<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: KiranPoudel98</title>
    <description>The latest articles on Forem by KiranPoudel98 (@kiranpoudel98).</description>
    <link>https://forem.com/kiranpoudel98</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F375269%2Ff8149893-ff1f-40c0-bb3b-2a80c151a15a.jpg</url>
      <title>Forem: KiranPoudel98</title>
      <link>https://forem.com/kiranpoudel98</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/kiranpoudel98"/>
    <language>en</language>
    <item>
      <title>11 Most Asked Swift Programming Questions</title>
      <dc:creator>KiranPoudel98</dc:creator>
      <pubDate>Fri, 13 Nov 2020 05:02:13 +0000</pubDate>
      <link>https://forem.com/truemark/11-most-asked-swift-programming-questions-4de5</link>
      <guid>https://forem.com/truemark/11-most-asked-swift-programming-questions-4de5</guid>
      <description>&lt;p&gt;Swift is a general-purpose programming language developed by Apple Inc. It is a powerful language developed for iOS, iPadOS, macOS, watchOS, tvOS, Linux, and z/OS. Swift is one of the popular languages and has a huge scope if you want to develop apps for Apple products. So, today we will be checking out the 11 most asked Swift programming questions.&lt;/p&gt;

&lt;h2&gt;
  
  
  11 Most Asked Swift Programming Questions
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1. How to call Objective-C code from Swift?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Using Objective-C Classes in Swift&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If you have an existing class that you’d like to use, perform &lt;strong&gt;Step 2&lt;/strong&gt; and then skip to &lt;strong&gt;Step 5&lt;/strong&gt;. (For some cases, add an explicit &lt;code&gt;#import &amp;lt;Foundation/Foundation.h&lt;/code&gt; to an older Objective-C File.)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1:&lt;/strong&gt; Add Objective-C Implementation — .m&lt;/p&gt;

&lt;p&gt;Add a &lt;code&gt;.m&lt;/code&gt; file to your class, and name it &lt;code&gt;CustomObject.m&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2:&lt;/strong&gt; Add Bridging Header&lt;/p&gt;

&lt;p&gt;When adding your &lt;code&gt;.m&lt;/code&gt; file, you’ll likely be hit with a prompt that looks like this: &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--hS9Zs8TF--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/j27hoog6n6gp5bn3a3db.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--hS9Zs8TF--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/j27hoog6n6gp5bn3a3db.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Click &lt;strong&gt;Yes!&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If you did not see the prompt or accidentally deleted your bridging header, add a new &lt;code&gt;.h&lt;/code&gt; file to your project and name it &lt;code&gt;&amp;lt;#YourProjectName#&amp;gt;-Bridging-Header.h&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;In some situations, particularly when working with Objective-C frameworks, you don’t add an Objective-C class explicitly and Xcode can’t find the linker. In this case, create your &lt;code&gt;.h&lt;/code&gt; file named as mentioned above, then make sure you link its path in your target’s project settings like so:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--TURLl2ei--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/cb4fqnpkv0o6fgf20p1l.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--TURLl2ei--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/cb4fqnpkv0o6fgf20p1l.gif" alt="An animation demonstrating the above paragraph"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It’s best practice to link your project using the &lt;code&gt;$(SRCROOT)&lt;/code&gt; macro so that if you move your project, or work on it with others using a remote repository, it will still work. &lt;code&gt;$(SRCROOT)&lt;/code&gt; can be thought of as the directory that contains your .xcodeproj file. It might look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$(SRCROOT)/Folder/Folder/&amp;lt;#YourProjectName#&amp;gt;-Bridging-Header.h
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 3:&lt;/strong&gt; Add Objective-C Header — .h&lt;/p&gt;

&lt;p&gt;Add another &lt;code&gt;.h&lt;/code&gt; file and name it &lt;code&gt;CustomObject.h&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 4:&lt;/strong&gt; Build your Objective-C Class&lt;/p&gt;

&lt;p&gt;In &lt;code&gt;CustomObject.h&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#import &amp;lt;Foundation/Foundation.h&amp;gt;

@interface CustomObject : NSObject

@property (strong, nonatomic) id someProperty;

- (void) someMethod;

@end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In &lt;code&gt;CustomObject.m&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#import "CustomObject.h"

@implementation CustomObject 

- (void) someMethod {
    NSLog(@"SomeMethod Ran");
}

@end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 5:&lt;/strong&gt; Add Class to Bridging-Header&lt;/p&gt;

&lt;p&gt;In &lt;code&gt;YourProject-Bridging-Header.h&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#import "CustomObject.h"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 6:&lt;/strong&gt; Use your Object&lt;/p&gt;

&lt;p&gt;In &lt;code&gt;SomeSwiftFile.swift&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var instanceOfCustomObject = CustomObject()
instanceOfCustomObject.someProperty = "Hello World"
print(instanceOfCustomObject.someProperty)
instanceOfCustomObject.someMethod()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There is no need to import explicitly; that’s what the bridging header is for.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Using Swift Classes in Objective-C&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1:&lt;/strong&gt; Create New Swift Class&lt;/p&gt;

&lt;p&gt;Add a &lt;code&gt;.swift&lt;/code&gt; file to your project, and name it &lt;code&gt;MySwiftObject.swift&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;In &lt;code&gt;MySwiftObject.swift&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import Foundation

@objc(MySwiftObject)
class MySwiftObject : NSObject {

    @objc
    var someProperty: AnyObject = "Some Initializer Val" as NSString

    init() {}

    @objc
    func someFunction(someArg: Any) -&amp;gt; NSString {
        return "You sent me \(someArg)"
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Step 2: Import Swift Files to ObjC Class&lt;/p&gt;

&lt;p&gt;In &lt;code&gt;SomeRandomClass.m&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#import "&amp;lt;#YourProjectName#&amp;gt;-Swift.h"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The file:&lt;code&gt;&amp;lt;#YourProjectName#&amp;gt;-Swift.h&lt;/code&gt; should already be created automatically in your project, even if you can not see it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 3:&lt;/strong&gt; Use your class&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;MySwiftObject * myOb = [MySwiftObject new];
NSLog(@"MyOb.someProperty: %@", myOb.someProperty);
myOb.someProperty = @"Hello World";
NSLog(@"MyOb.someProperty: %@", myOb.someProperty);

NSString * retString = [myOb someFunctionWithSomeArg:@"Arg"];

NSLog(@"RetString: %@", retString);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Notes:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;If Code Completion isn’t behaving as you expect, try running a quick build with &lt;code&gt;⌘⇧R&lt;/code&gt; to help Xcode find some of the Objective-C code from a Swift context and vice versa.&lt;/li&gt;
&lt;li&gt;If you add a &lt;code&gt;.swift&lt;/code&gt; file to an older project and get the error &lt;code&gt;dyld: Library not loaded: @rpath/libswift_stdlib_core.dylib&lt;/code&gt;, try completely &lt;a href="https://stackoverflow.com/questions/24002836/dyld-library-not-loaded-rpath-libswift-stdlib-core-dylib"&gt;restarting Xcode&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;While it was originally possible to use pure Swift classes (Not descendents of &lt;code&gt;NSObject&lt;/code&gt;) which are visible to Objective-C by using the &lt;code&gt;@objc&lt;/code&gt; prefix, this is no longer possible. Now, to be visible in Objective-C, the Swift object must either be a class conforming to &lt;code&gt;NSObjectProtocol&lt;/code&gt; (easiest way to do this is to inherit from &lt;code&gt;NSObject&lt;/code&gt;), or to be an &lt;code&gt;enum&lt;/code&gt; marked &lt;code&gt;@objc&lt;/code&gt; with a raw value of some integer type like &lt;code&gt;Int&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  2. Is there a stand-in for #pragma mark in Swift?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can use &lt;code&gt;// MARK&lt;/code&gt;:&lt;/p&gt;

&lt;p&gt;There has also been discussion that liberal use of class extensions might be a better practice anyway. Since extensions can implement protocols, you can e.g. put all of your table view delegate methods in an extension and group your code at a more semantic level than &lt;code&gt;#pragma mark&lt;/code&gt; is capable of.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Up to Xcode 5 the preprocessor directive &lt;code&gt;#pragma mark&lt;/code&gt; existed.&lt;/p&gt;

&lt;p&gt;From Xcode 6 on, you have to use &lt;code&gt;// MARK&lt;/code&gt;:&lt;/p&gt;

&lt;p&gt;These preprocessor features allow to bring some structure to the function drop down box of the source code editor.&lt;/p&gt;

&lt;p&gt;Some examples :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// MARK:
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;-&amp;gt; will be preceded by a horizontal divider&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// MARK: your text goes here
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;-&amp;gt; puts ‘your text goes here’ in bold in the drop down list&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// MARK: - your text goes here
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;-&amp;gt; puts ‘your text goes here’ in bold in the drop down list, preceded by a horizontal divider&lt;/p&gt;

&lt;p&gt;Added screenshot ’cause some people still seem to have issues with this:&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--MdPyyf5J--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/xvnbkrlkphb8ryx8upiq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--MdPyyf5J--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/xvnbkrlkphb8ryx8upiq.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  3. How to get the length of a &lt;code&gt;String&lt;/code&gt;?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;As of Swift 4&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It’s just:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;test1.count
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;As of Swift 2:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;With Swift 2, Apple has changed global functions to protocol extensions, extensions that match any type conforming to a protocol. Thus the new syntax is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;test1.characters.count
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;As of Swift 1&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Use the count characters method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let unusualMenagerie = "Koala &amp;amp;#128040;, Snail &amp;amp;#128012;, Penguin &amp;amp;#128039;, Dromedary &amp;amp;#128042;"
println("unusualMenagerie has \(count(unusualMenagerie)) characters")
// prints "unusualMenagerie has 40 characters"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;right from the Apple Swift Guide.&lt;/p&gt;

&lt;p&gt;(Note: For versions of Swift earlier than 1.2, this would be &lt;code&gt;countElements(unusualMenagerie)&lt;/code&gt; instead) for your variable, it would be&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;length = count(test1) // was countElements in earlier versions of Swift
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or you can use test1.utf16count&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;For &lt;strong&gt;Swift 2.0 and 3.0&lt;/strong&gt;, use &lt;code&gt;test1.characters.count&lt;/code&gt;. But, there are a few things you should know. So, read on.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Counting characters in Swift&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Before Swift 2.0, &lt;code&gt;count&lt;/code&gt; was a global function. As of Swift 2.0, it can be called as a member function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;test1.characters.count
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It will return the actual number of Unicode characters in a &lt;code&gt;String&lt;/code&gt;, so it’s the most correct alternative in the sense that, if you’d print the string and count characters by hand, you’d get the same result.&lt;/p&gt;

&lt;p&gt;However, because of the way &lt;code&gt;Strings&lt;/code&gt; are implemented in Swift, characters don’t always take up the same amount of memory, so be aware that this behaves quite differently than the usual character count methods in other languages.&lt;/p&gt;

&lt;p&gt;For example, you can also use &lt;code&gt;test1.utf16.count&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;But, as noted below, the returned value is not guaranteed to be the same as that of calling &lt;code&gt;count&lt;/code&gt; on &lt;code&gt;characters&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;From the language reference:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Extended grapheme clusters can be composed of one or more Unicode scalars. This means that different characters—and different representations of the same character—can require different amounts of memory to store. Because of this, characters in Swift do not each take up the same amount of memory within a string’s representation. As a result, the number of characters in a string cannot be calculated without iterating through the string to determine its extended grapheme cluster boundaries. If you are working with particularly long string values, be aware that the characters property must iterate over the Unicode scalars in the entire string in order to determine the characters for that string.&lt;/p&gt;

&lt;p&gt;The count of the characters returned by the characters property is not always the same as the length property of an NSString that contains the same characters. The length of an NSString is based on the number of 16-bit code units within the string’s UTF-16 representation and not the number of Unicode extended grapheme clusters within the string.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;An example that perfectly illustrates the situation described above is that of checking the length of a string containing a single emoji character.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var emoji = "👍"
emoji.characters.count             //returns 1
emoji.utf16.count                  //returns 2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  4. How to iterate a loop with index and element in Swift?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;As of Swift 3.0, if you need the index for each element along with its value, you can use the &lt;a href="https://docs.swift.org/swift-book/LanguageGuide/CollectionTypes.html#//apple_ref/doc/uid/TP40014097-CH8-XID_177"&gt;&lt;code&gt;enumerated()&lt;/code&gt; method&lt;/a&gt; to iterate over the array. It returns a sequence of pairs composed of the index and the value for each item in the array. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for (index, element) in list.enumerated() {
  print("Item \(index): \(element)")
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Before Swift 3.0 and after Swift 2.0, the function was called &lt;code&gt;enumerate()&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for (index, element) in list.enumerate() {
    print("Item \(index): \(element)")
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Prior to Swift 2.0, &lt;code&gt;enumerate&lt;/code&gt; was a global function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for (index, element) in enumerate(list) {
    println("Item \(index): \(element)")
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Swift 5 provides a method called &lt;a href="https://developer.apple.com/documentation/swift/array/1687832-enumerated"&gt;&lt;code&gt;enumerated()&lt;/code&gt;&lt;/a&gt; for &lt;code&gt;Array&lt;/code&gt;. &lt;code&gt;enumerated()&lt;/code&gt; has the following declaration:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func enumerated() -&amp;gt; EnumeratedSequence&amp;lt;Array&amp;lt;Element&amp;gt;&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero and x represents an element of the sequence.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In the simplest cases, you may use &lt;code&gt;enumerated()&lt;/code&gt; with a for loop. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let list = ["Car", "Bike", "Plane", "Boat"]
for (index, element) in list.enumerated() {
    print(index, ":", element)
}

/*
prints:
0 : Car
1 : Bike
2 : Plane
3 : Boat
*/
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; However that you’re not limited to use &lt;code&gt;enumerated()&lt;/code&gt; with a for loop. In fact, if you plan to use &lt;code&gt;enumerated()&lt;/code&gt; with a for loop for something similar to the following code, you’re doing it wrong:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let list = [Int](1...5)
var arrayOfTuples = [(Int, Int)]()

for (index, element) in list.enumerated() {
    arrayOfTuples += [(index, element)]
}

print(arrayOfTuples) // prints [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A swiftier way to do this is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let list = [Int](1...5)
let arrayOfTuples = Array(list.enumerated())
print(arrayOfTuples) // prints [(offset: 0, element: 1), (offset: 1, element: 2), (offset: 2, element: 3), (offset: 3, element: 4), (offset: 4, element: 5)]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As an alternative, you may also use &lt;code&gt;enumerated()&lt;/code&gt; with map:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let list = [Int](1...5)
let arrayOfDictionaries = list.enumerated().map { (a, b) in return [a : b] }
print(arrayOfDictionaries) // prints [[0: 1], [1: 2], [2: 3], [3: 4], [4: 5]]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Moreover, although it has some &lt;a href="https://developer.apple.com/documentation/swift/sequence/3018369-foreach"&gt;limitations&lt;/a&gt;, &lt;code&gt;forEach&lt;/code&gt; can be a good replacement to a for loop:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let list = [Int](1...5)
list.reversed().enumerated().forEach { print($0, ":", $1) }

/*
prints:
0 : 5
1 : 4
2 : 3
3 : 2
4 : 1
*/
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By using &lt;code&gt;enumerated()&lt;/code&gt; and &lt;code&gt;makeIterator()&lt;/code&gt;, you can even iterate manually on your &lt;code&gt;Array&lt;/code&gt;. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import UIKit
import PlaygroundSupport

class ViewController: UIViewController {

    var generator = ["Car", "Bike", "Plane", "Boat"].enumerated().makeIterator()

    override func viewDidLoad() {
        super.viewDidLoad()

        let button = UIButton(type: .system)
        button.setTitle("Tap", for: .normal)
        button.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
        button.addTarget(self, action: #selector(iterate(_:)), for: .touchUpInside)
        view.addSubview(button)
    }

    @objc func iterate(_ sender: UIButton) {
        let tuple = generator.next()
        print(String(describing: tuple))
    }

}

PlaygroundPage.current.liveView = ViewController()

/*
 Optional((offset: 0, element: "Car"))
 Optional((offset: 1, element: "Bike"))
 Optional((offset: 2, element: "Plane"))
 Optional((offset: 3, element: "Boat"))
 nil
 nil
 nil
 */
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  5. Is there a replacement/solution for #ifdef where you can define a macro using compiler preprocessors?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In Swift, you can still use the “#if/#else/#endif” preprocessor macros (although more constrained), as per &lt;a href="https://developer.apple.com/documentation/swift#2984801"&gt;Apple docs&lt;/a&gt;. Here’s an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#if DEBUG
    let a = 2
#else
    let a = 3
#endif
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, you must set the “DEBUG” symbol elsewhere, though. Set it in the “Swift Compiler – Custom Flags” section, “Other Swift Flags” line. You add the DEBUG symbol with the -D DEBUG entry.&lt;/p&gt;

&lt;p&gt;As usual, you can set a different value when in Debug or when in Release.&lt;/p&gt;

&lt;p&gt;It works, but it doesn’t seem to be recognized in a playground though.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Important Note:&lt;/strong&gt; &lt;code&gt;-DDEBUG=1&lt;/code&gt; doesn’t work. Only &lt;code&gt;-D DEBUG&lt;/code&gt; works. Seems the compiler is ignoring a flag with a specific value.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;As stated in &lt;a href="https://developer.apple.com/documentation/swift#2984801"&gt;Apple Docs&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The Swift compiler does not include a preprocessor. Instead, it takes advantage of compile-time attributes, build configurations, and language features to accomplish the same functionality. For this reason, preprocessor directives are not imported in Swift.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;By using custom Build Configurations:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Go to your project / select your target / Build Settings / search for Custom Flags&lt;/li&gt;
&lt;li&gt;For your chosen target set your custom flag using -D prefix (without white spaces), for both Debug and Release&lt;/li&gt;
&lt;li&gt;Do above steps for every target you have&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Here’s how you check for target:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#if BANANA
    print("We have a banana")
#elseif MELONA
    print("Melona")
#else
    print("Kiwi")
#endif
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--FbOabWVS--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/vji5ruqlv41zbh0c5das.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--FbOabWVS--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/vji5ruqlv41zbh0c5das.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Tested using Swift 2.2&lt;/p&gt;

&lt;h3&gt;
  
  
  6. How to split a string into an array in Swift?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The Swift way is to use the global &lt;code&gt;split&lt;/code&gt; function, like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var fullName = "First Last"
var fullNameArr = split(fullName) {$0 == " "}
var firstName: String = fullNameArr[0]
var lastName: String? = fullNameArr.count &amp;gt; 1 ? fullNameArr[1] : nilW
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With &lt;strong&gt;Swift 2&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In Swift 2 the use of split becomes a bit more complicated due to the introduction of the internal CharacterView type. This means that String no longer adopts the SequenceType or CollectionType protocols and you must instead use the &lt;code&gt;.characters&lt;/code&gt; property to access a CharacterView type representation of a String instance. (Note: CharacterView does adopt SequenceType and CollectionType protocols).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let fullName = "First Last"
let fullNameArr = fullName.characters.split{$0 == " "}.map(String.init)
// or simply:
// let fullNameArr = fullName.characters.split{" "}.map(String.init)

fullNameArr[0] // First
fullNameArr[1] // Last
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Just call &lt;code&gt;componentsSeparatedByString&lt;/code&gt; method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import Foundation

var fullName: String = "First Last"
let fullNameArr = fullName.componentsSeparatedByString(" ")

var firstName: String = fullNameArr[0]
var lastName: String = fullNameArr[1]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Update for Swift 3+&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import Foundation

let fullName    = "First Last"
let fullNameArr = fullName.components(separatedBy: " ")

let name    = fullNameArr[0]
let surname = fullNameArr[1]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  7. How to use @selector() in Swift?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Swift itself doesn’t use selectors — several design patterns that in Objective-C make use of selectors work differently in Swift. (For example, use optional chaining on protocol types or &lt;code&gt;is/as&lt;/code&gt; tests instead of &lt;code&gt;respondsToSelector:&lt;/code&gt;, and use closures wherever you can instead of &lt;code&gt;performSelector:&lt;/code&gt; for better type/memory safety.)&lt;/p&gt;

&lt;p&gt;But there are still a number of important ObjC-based APIs that use selectors, including timers and the target/action pattern. Swift provides the &lt;code&gt;Selector&lt;/code&gt; type for working with these. (Swift automatically uses this in place of ObjC’s SEL type.)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;In Swift 2.2 (Xcode 7.3) and later (including Swift 3 / Xcode 8 and Swift 4 / Xcode 9):&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can construct a &lt;code&gt;Selector&lt;/code&gt; from a Swift function type using the &lt;code&gt;#selector&lt;/code&gt; expression.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let timer = Timer(timeInterval: 1, target: object,
                  selector: #selector(MyClass.test),
                  userInfo: nil, repeats: false)
button.addTarget(object, action: #selector(MyClass.buttonTapped),
                 for: .touchUpInside)
view.perform(#selector(UIView.insertSubview(_:aboveSubview:)),
             with: button, with: otherButton)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The great thing about this approach? A function reference is checked by the Swift compiler, so you can use the &lt;code&gt;#selector&lt;/code&gt; expression only with class/method pairs that actually exist and are eligible for use as selectors (see “Selector availability” below). You’re also free to make your function reference only as specific as you need, as per &lt;a href="https://docs.swift.org/swift-book/ReferenceManual/Expressions.html#//apple_ref/doc/uid/TP40014097-CH32-ID400"&gt;the Swift 2.2+ rules for function-type naming.&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;(This is actually an improvement over ObjC’s &lt;code&gt;@selector()&lt;/code&gt; directive, because the compiler’s &lt;code&gt;-Wundeclared-selector&lt;/code&gt; check verifies only that the named selector exists. The Swift function reference you pass to &lt;code&gt;#selector&lt;/code&gt; checks existence, membership in a class, and type signature.) There are a couple of extra caveats for the function references you pass to the &lt;code&gt;#selector&lt;/code&gt; expression:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Multiple functions with the same base name can be differentiated by their parameter labels using the aforementioned &lt;a href="https://docs.swift.org/swift-book/ReferenceManual/Expressions.html#//apple_ref/doc/uid/TP40014097-CH32-ID400"&gt;syntax for function references&lt;/a&gt; (e.g. &lt;code&gt;insertSubview(_:at:)&lt;/code&gt; vs &lt;code&gt;insertSubview(_:aboveSubview:)&lt;/code&gt;). But if a function has no parameters, the only way to disambiguate it is to use an &lt;code&gt;as&lt;/code&gt; cast with the function’s type signature (e.g. &lt;code&gt;foo as () -&amp;gt; ()&lt;/code&gt; vs &lt;code&gt;foo(_:)&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;There’s a special syntax for property getter/setter pairs in Swift 3.0+. For example, given a &lt;code&gt;var foo: Int&lt;/code&gt;, you can use &lt;code&gt;#selector(getter: MyClass.foo)&lt;/code&gt; or &lt;code&gt;#selector(setter: MyClass.foo)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;General notes:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Cases where &lt;code&gt;#selector&lt;/code&gt; doesn’t work, and naming:&lt;/strong&gt; Sometimes you don’t have a function reference to make a selector with (for example, with methods dynamically registered in the ObjC runtime). In that case, you can construct a &lt;code&gt;Selector&lt;/code&gt; from a string: e.g. &lt;code&gt;Selector("dynamicMethod:")&lt;/code&gt; — though you lose the compiler’s validity checking. When you do that, you need to follow ObjC naming rules, including colons (:) for each parameter.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Selector availability:&lt;/strong&gt; The method referenced by the selector must be exposed to the ObjC runtime. In Swift 4, every method exposed to ObjC must have its declaration prefaced with the &lt;code&gt;@objc&lt;/code&gt; attribute. (In previous versions you got that attribute for free in some cases, but now you have to explicitly declare it.)&lt;/p&gt;

&lt;p&gt;Remember that &lt;code&gt;private&lt;/code&gt; symbols aren’t exposed to the runtime, too — your method needs to have at least &lt;code&gt;internal&lt;/code&gt; visibility.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key paths:&lt;/strong&gt; These are related to but not quite the same as selectors. There’s a special syntax for these in Swift 3, too: e.g. &lt;code&gt;chris.valueForKeyPath(#keyPath(Person.friends.firstName))&lt;/code&gt;. See &lt;a href="https://github.com/apple/swift-evolution/blob/master/proposals/0062-objc-keypaths.md"&gt;SE-0062&lt;/a&gt; for details. And even more &lt;a href="https://github.com/apple/swift-evolution/blob/master/proposals/0161-key-paths.md"&gt;&lt;code&gt;KeyPath&lt;/code&gt; stuff in Swift 4&lt;/a&gt;, so make sure you’re using the right KeyPath-based API instead of selectors if appropriate.&lt;/p&gt;

&lt;p&gt;You can read more about selectors under &lt;a href="https://developer.apple.com/documentation/swift#2984801"&gt;Interacting with Objective-C APIs&lt;/a&gt; in Using Swift with Cocoa and Objective-C.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; Before Swift 2.2, Selector conformed to &lt;code&gt;StringLiteralConvertible&lt;/code&gt;, so you might find old code where bare strings are passed to APIs that take selectors. You’ll want to run “Convert to Current Swift Syntax” in Xcode to get those using &lt;code&gt;#selector&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Here’s a quick example of how to use the &lt;code&gt;Selector&lt;/code&gt; class on Swift:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;override func viewDidLoad() {
    super.viewDidLoad()

    var rightButton = UIBarButtonItem(title: "Title", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("method"))
    self.navigationItem.rightBarButtonItem = rightButton
}

func method() {
    // Something cool here   
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that if the method passed as a string doesn’t work, it will fail at runtime, not compile time, and crash your app. Be careful.&lt;/p&gt;

&lt;h3&gt;
  
  
  8. Do Swift-based applications work on OS X 10.9/iOS 7 and lower?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Swift applications compile into standard binaries and can be run on OS X 10.9 and iOS 7. A simple Swift application used for testing:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -&amp;gt; Bool {
    self.window = UIWindow(frame: UIScreen.mainScreen().bounds)

    var controller = UIViewController()
    var view = UIView(frame: CGRectMake(0, 0, 320, 568))
    view.backgroundColor = UIColor.redColor()
    controller.view = view

    var label = UILabel(frame: CGRectMake(0, 0, 200, 21))
    label.center = CGPointMake(160, 284)
    label.textAlignment = NSTextAlignment.Center
    label.text = "I'am a test label"
    controller.view.addSubview(label)

    self.window!.rootViewController = controller
    self.window!.makeKeyAndVisible()
    return true
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  9. What is the proper usage of &lt;code&gt;dispatch_once&lt;/code&gt; singleton model in Swift?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Use the &lt;strong&gt;class constant&lt;/strong&gt; approach if you are using Swift 1.2 or above and the &lt;strong&gt;nested struct&lt;/strong&gt; approach if you need to support earlier versions.&lt;/p&gt;

&lt;p&gt;With Swift, there are three approaches to implement the Singleton pattern that support lazy initialization and thread-safety.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Class constant&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Singleton  {
   static let sharedInstance = Singleton()
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This approach supports lazy initialization because Swift lazily initializes class constants (and variables), and is thread safe by the definition of &lt;code&gt;let&lt;/code&gt;. This is now &lt;a href="https://developer.apple.com/documentation/swift/cocoa_design_patterns#//apple_ref/doc/uid/TP40014216-CH7-ID14"&gt;officially recommended way&lt;/a&gt; to instantiate a singleton.&lt;/p&gt;

&lt;p&gt;Class constants were introduced in Swift 1.2. If you need to support an earlier version of Swift, use the nested struct approach below or a global constant.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Nested struct&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Singleton {
    class var sharedInstance: Singleton {
        struct Static {
            static let instance: Singleton = Singleton()
        }
        return Static.instance
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we are using the static constant of a nested struct as a class constant. This is a workaround for the lack of static class constants in Swift 1.1 and earlier and still works as a workaround for the lack of static constants and variables in functions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;dispatch_once&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The traditional Objective-C approach ported to Swift.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Singleton {
    class var sharedInstance: Singleton {
        struct Static {
            static var onceToken: dispatch_once_t = 0
            static var instance: Singleton? = nil
        }
        dispatch_once(&amp;amp;Static.onceToken) {
            Static.instance = Singleton()
        }
        return Static.instance!
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;See this &lt;a href="https://github.com/hpique/SwiftSingleton"&gt;GitHub&lt;/a&gt; project for unit tests.&lt;/p&gt;

&lt;h3&gt;
  
  
  10. How to make a weak protocol reference in ‘pure’ Swift (without @objc)?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You need to declare the type of the protocol as &lt;code&gt;AnyObject&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;protocol ProtocolNameDelegate: AnyObject {
    // Protocol stuff goes here
}

class SomeClass {
    weak var delegate: ProtocolNameDelegate?
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using &lt;code&gt;AnyObject&lt;/code&gt; you say that only classes can conform to this protocol, whereas structs or enums can’t.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Supplemental Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The purpose of using the &lt;code&gt;weak&lt;/code&gt; keyword is to avoid &lt;a href="https://docs.swift.org/swift-book/LanguageGuide/AutomaticReferenceCounting.html#ID51"&gt;strong reference cycles&lt;/a&gt; (retain cycles). Strong reference cycles happen when two class instances have strong references to each other. Their reference counts never go to zero so they never get deallocated.&lt;/li&gt;
&lt;li&gt;You only need to use &lt;code&gt;weak&lt;/code&gt; if the delegate is a class. Swift structs and enums are value types (their values are copied when a new instance is made), not reference types, so they don’t make strong reference cycles.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;weak&lt;/code&gt; references are always optional (otherwise you would use &lt;code&gt;unowned&lt;/code&gt;) and always use &lt;code&gt;var&lt;/code&gt; (not &lt;code&gt;let&lt;/code&gt;) so that the optional can be set to &lt;code&gt;nil&lt;/code&gt; when it is deallocated.&lt;/li&gt;
&lt;li&gt;A parent class should naturally have a strong reference to its child classes and thus not use the &lt;code&gt;weak&lt;/code&gt; keyword. When a child wants a reference to its parent, though, it should make it a weak reference by using the &lt;code&gt;weak&lt;/code&gt; keyword.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;weak&lt;/code&gt; should be used when you want a reference to a class that you don’t own, not just for a child referencing its parent. When two non-hierarchical classes need to reference each other, choose one to be weak. The one you choose depends on the situation. See the answers to &lt;a href="https://stackoverflow.com/questions/34565760/two-weak-variables-referencing-each-other-in-swift"&gt;this question&lt;/a&gt; for more on this.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;As a general rule, delegates should be marked as &lt;code&gt;weak&lt;/code&gt;&lt;/strong&gt; because most delegates are referencing classes that they do not own. This is definitely true when a child is using a delegate to communicate with a parent. Using a weak reference for the delegate is what the &lt;a href="https://docs.swift.org/swift-book/LanguageGuide/Protocols.html#ID276"&gt;documentation&lt;/a&gt; recommends. (But see &lt;a href="https://stackoverflow.com/questions/17348523/is-it-ever-ok-to-have-a-strong-reference-for-a-delegate"&gt;this&lt;/a&gt;, too.)&lt;/li&gt;
&lt;li&gt;Protocols can be used for both &lt;a href="https://developer.apple.com/swift/blog/?id=10"&gt;reference types&lt;/a&gt; (classes) and &lt;a href="https://developer.apple.com/swift/blog/?id=10"&gt;value types&lt;/a&gt; (structs, enums). So in the likely case that you need to make a delegate weak, you have to make it an object-only protocol. The way to do that is to add &lt;code&gt;AnyObject&lt;/code&gt; to the protocol’s inheritance list. (In the past you did this using the &lt;code&gt;class&lt;/code&gt; keyword, but &lt;a href="https://stackoverflow.com/questions/30176814/whats-the-difference-between-a-protocol-extended-from-anyobject-and-a-class-onl/53395896#53395896"&gt;&lt;code&gt;AnyObject&lt;/code&gt; is preferred now&lt;/a&gt;.)
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    protocol MyClassDelegate: AnyObject {
        // ...
    }

    class SomeClass {
        weak var delegate: MyClassDelegate?
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  11. How to convert Int to String in Swift?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Converting &lt;code&gt;Int&lt;/code&gt; to &lt;code&gt;String&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x : Int = 42
var myString = String(x)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And the other way around – converting &lt;code&gt;String&lt;/code&gt; to &lt;code&gt;Int&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let myString : String = "42"
let x: Int? = myString.toInt()

if (x != nil) {
    // Successfully converted String to Int
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or if you’re using Swift 2 or 3:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x: Int? = Int(myString)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Check the Below Answer:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x : Int = 45
var stringValue = "\(x)"
print(stringValue)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;In Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;These are the 11 most commonly asked Swift programming questions. If you have any suggestions or any confusion, please comment below. If you need any help, we will be glad to help you.&lt;/p&gt;

&lt;p&gt;We, at &lt;a href="https://www.truemark.dev/"&gt;Truemark&lt;/a&gt;, provide services like web and mobile app development, digital marketing, and website development. So, if you need any help and want to work with us, please feel free to contact us.&lt;/p&gt;

&lt;p&gt;Hope this article helped you.&lt;/p&gt;

&lt;p&gt;This post was first published on &lt;a href="https://thedevpost.com/blog/11-most-asked-swift-programming-questions/"&gt;DevPostbyTruemark&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>swift</category>
    </item>
    <item>
      <title>10 Most Asked Scala Programming Questions</title>
      <dc:creator>KiranPoudel98</dc:creator>
      <pubDate>Fri, 06 Nov 2020 07:50:16 +0000</pubDate>
      <link>https://forem.com/truemark/10-most-asked-scala-programming-questions-1ldf</link>
      <guid>https://forem.com/truemark/10-most-asked-scala-programming-questions-1ldf</guid>
      <description>&lt;p&gt;Scala is a general-purpose programming language that is mainly used for functional programming. It is object-oriented and it runs on JVM (Java Virtual Machine). Scala provides language interoperability with Java. So, today we will be checking out the 10 most asked Scala programming questions.&lt;/p&gt;

&lt;h2&gt;
  
  
  10 Most Asked Scala Programming Questions
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1. Difference between object and class in Scala
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;class C&lt;/code&gt; defines a class, just as in Java or C++.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;object O&lt;/code&gt; creates a &lt;a href="https://en.wikipedia.org/wiki/Singleton_pattern"&gt;singleton&lt;/a&gt; object &lt;code&gt;O&lt;/code&gt; as instance of some anonymous class; it can be used to hold static members that are not associated with instances of some class.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;object O extends T&lt;/code&gt; makes the object &lt;code&gt;O&lt;/code&gt; an instance of &lt;code&gt;trait T;&lt;/code&gt; you can then pass &lt;code&gt;O&lt;/code&gt; anywhere, a &lt;code&gt;T&lt;/code&gt; is expected.&lt;/li&gt;
&lt;li&gt;if there is a &lt;code&gt;class C&lt;/code&gt;, then &lt;code&gt;object C&lt;/code&gt; is the &lt;a href="https://docs.scala-lang.org/tour/singleton-objects.html#companions"&gt;companion object&lt;/a&gt; of class &lt;code&gt;C&lt;/code&gt;; note that the companion object is &lt;strong&gt;not&lt;/strong&gt; automatically an instance of &lt;code&gt;C&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Also see Scala documentation for &lt;a href="https://docs.scala-lang.org/tour/singleton-objects.html"&gt;object&lt;/a&gt; and &lt;a href="https://docs.scala-lang.org/tour/classes.html"&gt;class&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;code&gt;object&lt;/code&gt; as host of static members&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Most often, you need an &lt;code&gt;object&lt;/code&gt; to hold methods and values/variables that shall be available without having to first instantiate an instance of some class. This use is closely related to &lt;code&gt;static&lt;/code&gt; members in Java.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;object A {
  def twice(i: Int): Int = 2*i
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can then call the above method using &lt;code&gt;A.twice(2)&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;If &lt;code&gt;twice&lt;/code&gt; were a member of some class &lt;code&gt;A&lt;/code&gt;, then you would need to make an instance first:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class A() {
  def twice(i: Int): Int = 2 * i
}

val a = new A()
a.twice(2)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can see how redundant this is, as &lt;code&gt;twice&lt;/code&gt; does not require any instance-specific data.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;code&gt;object&lt;/code&gt; as a special named instance&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can also use the &lt;code&gt;object&lt;/code&gt; itself as some special instance of a class or trait. When you do this, your object needs to extend some &lt;code&gt;trait&lt;/code&gt; in order to become an instance of a subclass of it.&lt;/p&gt;

&lt;p&gt;Consider the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;object A extends B with C {
  ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This declaration first declares an anonymous (inaccessible) class that extends both &lt;code&gt;B&lt;/code&gt; and &lt;code&gt;C&lt;/code&gt;, and instantiates a single instance of this class named &lt;code&gt;A&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This means &lt;code&gt;A&lt;/code&gt; can be passed to functions expecting objects of type &lt;code&gt;B&lt;/code&gt; or &lt;code&gt;C&lt;/code&gt;, or &lt;code&gt;B&lt;/code&gt; with &lt;code&gt;C&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Additional Features of &lt;code&gt;object&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;There also exist some special features of objects in Scala. You can read the &lt;a href="https://docs.scala-lang.org/tour/singleton-objects.html"&gt;official documentation&lt;/a&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;def apply(...)&lt;/code&gt; enables the usual method name-less syntax of &lt;code&gt;A(...)&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;def unapply(...)&lt;/code&gt; allows to create custom pattern matching &lt;a href="https://docs.scala-lang.org/tour/extractor-objects.html"&gt;extractors&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;if accompanying a class of the same name, the object assumes a special role when resolving &lt;a href="https://docs.scala-lang.org/tour/implicit-parameters.html"&gt;implicit parameters&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Additional Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A &lt;code&gt;class&lt;/code&gt; is a definition, a description. It defines a type in terms of methods and composition of other types.&lt;/p&gt;

&lt;p&gt;An &lt;code&gt;object&lt;/code&gt; is a singleton — an instance of a class that is guaranteed to be unique. For every &lt;code&gt;object&lt;/code&gt; in the code, an anonymous class is created, which inherits from whatever classes you declared &lt;code&gt;object&lt;/code&gt; to implement. This class cannot be seen from Scala source code — though you can get at it through reflection.&lt;/p&gt;

&lt;p&gt;There is a relationship between &lt;code&gt;object&lt;/code&gt; and &lt;code&gt;class&lt;/code&gt;. An object is said to be the companion-object of a class if they share the same name. When this happens, each has access to methods of &lt;code&gt;private&lt;/code&gt; visibility in the other. These methods are not automatically imported, though. You either have to import them explicitly or prefix them with the class/object name.&lt;/p&gt;

&lt;p&gt;For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class X {
  // class X can see private members of object X
  // Prefix to call
  def m(x: Int) = X.f(x)

  // Import and use
  import X._
  def n(x: Int) = f(x)

  private def o = 2
}

object X {
  private def f(x: Int) = x * x

  // object X can see private members of class X
  def g(x: X) = {
    import x._
    x.o * o // fully specified and imported
   }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2. What are all the uses of an underscore in Scala?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Existential types&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def foo(l: List[Option[_]]) = ...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Higher kinded type parameters&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;case class A[K[_],T](a: K[T])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Ignored variables&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;val _ = 5
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Ignored parameters&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;List(1, 2, 3) foreach { _ =&amp;gt; println("Hi") }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Ignored names of self types&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;trait MySeq { _: Seq[_] =&amp;gt; }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Wildcard patterns&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Some(5) match { case Some(_) =&amp;gt; println("Yes") }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Wildcard patterns in interpolations&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"abc" match { case s"a$_c" =&amp;gt; }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Sequence wildcard in patterns&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;C(1, 2, 3) match { case C(vs @ _*) =&amp;gt; vs.foreach(f(_)) }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Wildcard imports&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import java.util._
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Hiding imports&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import java.util.{ArrayList =&amp;gt; _, _}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Joining letters to operators&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def bang_!(x: Int) = 5
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Assignment operators&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def foo_=(x: Int) { ... }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Placeholder syntax&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;List(1, 2, 3) map (_ + 2)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Method values&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;List(1, 2, 3) foreach println _
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Converting call-by-name parameters to functions&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def toFunction(callByName: =&amp;gt; Int): () =&amp;gt; Int = callByName _
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Default initializer&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var x: String = _   // unloved syntax may be eliminated
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Example showing why &lt;code&gt;foo(_)&lt;/code&gt; and &lt;code&gt;foo _&lt;/code&gt; are different:&lt;/p&gt;

&lt;p&gt;This example &lt;a href="https://stackoverflow.com/questions/9610736/strange-type-mismatch-when-using-member-access-instead-of-extractor/9610961"&gt;comes from 0__&lt;/a&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;trait PlaceholderExample {
  def process[A](f: A =&amp;gt; Unit)

  val set: Set[_ =&amp;gt; Unit]

  set.foreach(process _) // Error 
  set.foreach(process(_)) // No Error
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the first case, &lt;code&gt;process _&lt;/code&gt; represents a method; Scala takes the polymorphic method and attempts to make it monomorphic by filling in the type parameter, but realizes that there is no type that can be filled in for &lt;code&gt;A&lt;/code&gt; that will give the type &lt;code&gt;(_ =&amp;gt; Unit) =&amp;gt; ?&lt;/code&gt; (Existential _ is not a type).&lt;/p&gt;

&lt;p&gt;In the second case, &lt;code&gt;process(_)&lt;/code&gt; is a lambda; when writing a lambda with no explicit argument type, Scala infers the type from the argument that &lt;code&gt;foreach&lt;/code&gt; expects, and &lt;code&gt;_ =&amp;gt; Unit&lt;/code&gt; is a type (whereas just plain _ isn’t), so it can be substituted and inferred.&lt;/p&gt;

&lt;p&gt;Note that this example compiles in 2.13. Ignore it like it was assigned to underscore.&lt;/p&gt;

&lt;h3&gt;
  
  
  3. What is the difference between Scala’s case class and class?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Case classes can be seen as plain and immutable data-holding objects that should exclusively depend on their constructor arguments.&lt;/p&gt;

&lt;p&gt;This functional concept allows us to&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;use a compact initialization syntax (&lt;code&gt;Node(1, Leaf(2), None))&lt;/code&gt;)&lt;/li&gt;
&lt;li&gt;decompose them using pattern matching&lt;/li&gt;
&lt;li&gt;have equality comparisons implicitly defined&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In combination with inheritance, case classes are used to mimic &lt;a&gt;algebraic datatypes&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;If an object performs stateful computations on the inside or exhibits other kinds of complex behavior, it should be an ordinary class.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Additional Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Technically, there is no difference between a class and a case class — even if the compiler does optimize some stuff when using case classes. However, a case class is used to do away with a boiler plate for a specific pattern, which is implementing &lt;a href="https://en.wikipedia.org/wiki/Algebraic_data_type"&gt;algebraic data types&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;A very simple example of such types are trees. A binary tree, for instance, can be implemented like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sealed abstract class Tree
case class Node(left: Tree, right: Tree) extends Tree
case class Leaf[A](value: A) extends Tree
case object EmptyLeaf extends Tree
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That enable us to do the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// DSL-like assignment:
val treeA = Node(EmptyLeaf, Leaf(5))
val treeB = Node(Node(Leaf(2), Leaf(3)), Leaf(5))

// On Scala 2.8, modification through cloning:
val treeC = treeA.copy(left = treeB.left)

// Pretty printing:
println("Tree A: "+treeA)
println("Tree B: "+treeB)
println("Tree C: "+treeC)

// Comparison:
println("Tree A == Tree B: %s" format (treeA == treeB).toString)
println("Tree B == Tree C: %s" format (treeB == treeC).toString)

// Pattern matching:
treeA match {
  case Node(EmptyLeaf, right) =&amp;gt; println("Can be reduced to "+right)
  case Node(left, EmptyLeaf) =&amp;gt; println("Can be reduced to "+left)
  case _ =&amp;gt; println(treeA+" cannot be reduced")
}

// Pattern matches can be safely done, because the compiler warns about
// non-exaustive matches:
def checkTree(t: Tree) = t match {
  case Node(EmptyLeaf, Node(left, right)) =&amp;gt;
  // case Node(EmptyLeaf, Leaf(el)) =&amp;gt;
  case Node(Node(left, right), EmptyLeaf) =&amp;gt;
  case Node(Leaf(el), EmptyLeaf) =&amp;gt;
  case Node(Node(l1, r1), Node(l2, r2)) =&amp;gt;
  case Node(Leaf(e1), Leaf(e2)) =&amp;gt;
  case Node(Node(left, right), Leaf(el)) =&amp;gt;
  case Node(Leaf(el), Node(left, right)) =&amp;gt;
  // case Node(EmptyLeaf, EmptyLeaf) =&amp;gt;
  case Leaf(el) =&amp;gt;
  case EmptyLeaf =&amp;gt;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that trees construct and deconstruct (through pattern match) with the same syntax, which is also exactly how they are printed (minus spaces).&lt;/p&gt;

&lt;p&gt;And they can also be used with hash maps or sets since they have a valid, stable hashCode.&lt;/p&gt;

&lt;h3&gt;
  
  
  4. What do all of Scala’s symbolic operators mean?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let’s divide operators into &lt;strong&gt;four categories&lt;/strong&gt; to make it easier to understand:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Keywords/reserved symbols&lt;/li&gt;
&lt;li&gt;Automatically imported methods&lt;/li&gt;
&lt;li&gt;Common methods&lt;/li&gt;
&lt;li&gt;Syntactic sugars/composition&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;It is fortunate, then, that most categories are represented in the question:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-&amp;gt;    // Automatically imported method
||=   // Syntactic sugar
++=   // Syntactic sugar/composition or common method
&amp;lt;=    // Common method
_._   // Typo, though it's probably based on Keyword/composition
::    // Common method
:+=   // Common method
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The exact meaning of most of these methods depends on the class that is defining them. For example, &lt;code&gt;&amp;lt;=&lt;/code&gt; on &lt;code&gt;Int&lt;/code&gt; means “less than or equal to”. The first one, &lt;code&gt;-&amp;gt;&lt;/code&gt;, let’s look at the example below. &lt;code&gt;::&lt;/code&gt; is probably the method defined on &lt;code&gt;List&lt;/code&gt; (though it could be the object of the same name), and &lt;code&gt;:+=&lt;/code&gt; is probably the method defined on various &lt;code&gt;Buffer&lt;/code&gt; classes.&lt;/p&gt;

&lt;p&gt;So, let’s see them.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Keywords/reserved symbols&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;There are some symbols in Scala that are special. Two of them are considered proper keywords, while others are just “reserved”. They are:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Keywords
&amp;lt;-  // Used on for-comprehensions, to separate pattern from generator
=&amp;gt;  // Used for function types, function literals and import renaming

// Reserved
( )        // Delimit expressions and parameters
[ ]        // Delimit type parameters
{ }        // Delimit blocks
.          // Method call and path separator
// /* */   // Comments
#          // Used in type notations
:          // Type ascription or context bounds
&amp;lt;: &amp;gt;: &amp;lt;%   // Upper, lower and view bounds
&amp;lt;? &amp;lt;!      // Start token for various XML elements
" """      // Strings
'          // Indicate symbols and characters
@          // Annotations and variable binding on pattern matching
`          // Denote constant or enable arbitrary identifiers
,          // Parameter separator
;          // Statement separator
_*         // vararg expansion
_          // Many different meanings
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;These are all part of the language, and, as such, can be found in any text that properly describes the language, such as Scala Specification(PDF) itself.&lt;/p&gt;

&lt;p&gt;The last one, the underscore, deserve a special description, because it is so widely used, and has so many different meanings. Here’s a sample:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import scala._    // Wild card -- all of Scala is imported
import scala.{ Predef =&amp;gt; _, _ } // Exception, everything except Predef
def f[M[_]]       // Higher kinded type parameter
def f(m: M[_])    // Existential type
_ + _             // Anonymous function placeholder parameter
m _               // Eta expansion of method into method value
m(_)              // Partial function application
_ =&amp;gt; 5            // Discarded parameter
case _ =&amp;gt;         // Wild card pattern -- matches anything
f(xs: _*)         // Sequence xs is passed as multiple parameters to f(ys: T*)
case Seq(xs @ _*) // Identifier xs is bound to the whole matched sequence
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Automatically imported methods&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;So, if you did not find the symbol you are looking for in the list above, then it must be a method or part of one. But, often, you’ll see some symbol, and the documentation for the class will not have that method. When this happens, either you are looking at a composition of one or more methods with something else, or the method has been imported into scope or is available through an imported implicit conversion.&lt;/p&gt;

&lt;p&gt;These can still be found on &lt;a href="https://www.scala-lang.org/api/current/index.html"&gt;ScalaDoc&lt;/a&gt;: you just have to know where to look for them. Or, failing that, look at the index (presently broken on 2.9.1, but available on nightly).&lt;/p&gt;

&lt;p&gt;Every Scala code has three automatic imports:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Not necessarily in this order
import _root_.java.lang._      // _root_ denotes an absolute path
import _root_.scala._
import _root_.scala.Predef._
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The first two only make classes and singleton objects available. The third one contains all implicit conversions and imported methods since &lt;a href="https://www.scala-lang.org/api/current/index.html#scala.Predef%24"&gt;&lt;code&gt;Predef&lt;/code&gt;&lt;/a&gt; is an object itself.&lt;/p&gt;

&lt;p&gt;Looking inside &lt;code&gt;Predef&lt;/code&gt; quickly show some symbols:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class &amp;lt;:&amp;lt;
class =:=
object &amp;lt;%&amp;lt;
object =:=
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Any other symbol will be made available through an implicit conversion. Just look at the methods tagged with &lt;code&gt;implicit&lt;/code&gt; that receive, as a parameter, an object of a type that is receiving the method. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"a" -&amp;gt; 1  // Look for an implicit from String, AnyRef, Any or type parameter
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above case, &lt;code&gt;-&amp;gt;&lt;/code&gt; is defined in the class &lt;a href="https://www.scala-lang.org/api/current/scala/Predef%24%24ArrowAssoc.html"&gt;&lt;code&gt;ArrowAssoc&lt;/code&gt;&lt;/a&gt; through the method &lt;code&gt;any2ArrowAssoc&lt;/code&gt; that takes an object of type &lt;code&gt;A&lt;/code&gt;, where &lt;code&gt;A&lt;/code&gt; is an unbounded type parameter to the same method.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Common methods&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;So, many symbols are simply methods of a class. For instance, if you do&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;List(1, 2) ++ List(3, 4)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You’ll find the method &lt;code&gt;++&lt;/code&gt; right on the ScalaDoc for &lt;a href="https://www.scala-lang.org/api/current/index.html#scala.collection.immutable.List"&gt;List&lt;/a&gt;. However, there’s one convention that you must be aware of when searching for methods. Methods ending in colon (&lt;code&gt;:&lt;/code&gt;) bind to the right instead of the left. In other words, while the above method call is equivalent to:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;List(1, 2).++(List(3, 4))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Instead &lt;code&gt;1 :: List(2, 3)&lt;/code&gt;, that would be equivalent to:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;List(2, 3).::(1)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So you need to look at the type found on the right when looking for methods ending in a colon. Consider, for instance:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;1 +: List(2, 3) :+ 4
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The first method (&lt;code&gt;+:&lt;/code&gt;) binds to the right and is found on &lt;code&gt;List&lt;/code&gt;. The second method (&lt;code&gt;:+&lt;/code&gt;) is just a normal method and binds to the left — again, on &lt;code&gt;List&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Syntactic sugars/composition&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;So, here’s a few syntactic sugars that may hide a method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Example(arr: Array[Int] = Array.fill(5)(0)) {
  def apply(n: Int) = arr(n)
  def update(n: Int, v: Int) = arr(n) = v
  def a = arr(0); def a_=(v: Int) = arr(0) = v
  def b = arr(1); def b_=(v: Int) = arr(1) = v
  def c = arr(2); def c_=(v: Int) = arr(2) = v
  def d = arr(3); def d_=(v: Int) = arr(3) = v
  def e = arr(4); def e_=(v: Int) = arr(4) = v
  def +(v: Int) = new Example(arr map (_ + v))
  def unapply(n: Int) = if (arr.indices contains n) Some(arr(n)) else None
}

val Ex = new Example // or var for the last example
println(Ex(0))  // calls apply(0)
Ex(0) = 2       // calls update(0, 2)
Ex.b = 3        // calls b_=(3)
// This requires Ex to be a "val"
val Ex(c) = 2   // calls unapply(2) and assigns result to c
// This requires Ex to be a "var"
Ex += 1         // substituted for Ex = Ex + 1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The last one is interesting because any symbolic method can be combined to form an assignment-like method that way.&lt;/p&gt;

&lt;p&gt;And, of course, there are various combinations that can appear in code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(_+_) // An expression, or parameter, that is an anonymous function with
      // two parameters, used exactly where the underscores appear, and
      // which calls the "+" method on the first parameter passing the
      // second parameter as argument.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  5. What is the difference between self-types and trait subclasses?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If you say &lt;code&gt;B extends A&lt;/code&gt;, then &lt;code&gt;B&lt;/code&gt; is an &lt;code&gt;A&lt;/code&gt;. When you use self-types, &lt;code&gt;B&lt;/code&gt; requires an &lt;code&gt;A&lt;/code&gt;. There are two specific requirements that are created with self-types:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If &lt;code&gt;B&lt;/code&gt; is extended, then you’re required to mix-in an &lt;code&gt;A&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;When a concrete class finally extends/mixes-in these traits, some class/trait must implement &lt;code&gt;A&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Consider the following examples:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;scala&amp;gt; trait User { def name: String }
defined trait User

scala&amp;gt; trait Tweeter {
     |   user: User =&amp;gt;
     |   def tweet(msg: String) = println(s"$name: $msg")
     | }
defined trait Tweeter

scala&amp;gt; trait Wrong extends Tweeter {
     |   def noCanDo = name
     | }
&amp;lt;console&amp;gt;:9: error: illegal inheritance;
 self-type Wrong does not conform to Tweeter's selftype Tweeter with User
       trait Wrong extends Tweeter {
                           ^
&amp;lt;console&amp;gt;:10: error: not found: value name
         def noCanDo = name
                       ^
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If &lt;code&gt;Tweeter&lt;/code&gt; was a subclass of &lt;code&gt;User&lt;/code&gt;, there would be no error. In the code above, we required a &lt;code&gt;User&lt;/code&gt; whenever &lt;code&gt;Tweeter&lt;/code&gt; is used, however, a &lt;code&gt;User&lt;/code&gt; wasn’t provided to &lt;code&gt;Wrong&lt;/code&gt;, so we got an error. Now, with the code above still in scope, consider:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;scala&amp;gt; trait DummyUser extends User {
     |   override def name: String = "foo"
     | }
defined trait DummyUser

scala&amp;gt; trait Right extends Tweeter with User {
     |   val canDo = name
     | }
defined trait Right 

scala&amp;gt; trait RightAgain extends Tweeter with DummyUser {
     |   val canDo = name
     | }
defined trait RightAgain
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With &lt;code&gt;Right&lt;/code&gt;, the requirement to mix-in a &lt;code&gt;User&lt;/code&gt; is satisfied. However, the second requirement mentioned above is not satisfied: the burden of implementing &lt;code&gt;User&lt;/code&gt; still remains for classes/traits which extend &lt;code&gt;Right&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;With &lt;code&gt;RightAgain&lt;/code&gt; both requirements are satisfied. A &lt;code&gt;User&lt;/code&gt; and implementation of &lt;code&gt;User&lt;/code&gt; are provided.&lt;/p&gt;

&lt;p&gt;For more practical use cases, please see the links at the start of this answer! But, hopefully, now you get it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Additional Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Self types allow you to define cyclical dependencies. For example, you can achieve this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;trait A { self: B =&amp;gt; }
trait B { self: A =&amp;gt; }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Inheritance using &lt;code&gt;extends&lt;/code&gt; does not allow that. Try:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;trait A extends B
trait B extends A
error:  illegal cyclic reference involving trait A
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the Odersky book, look at section 33.5 (Creating spreadsheet UI chapter) where it mentions:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;In the spreadsheet example, class Model inherits from Evaluator and thus gains access to its evaluation method. To go the other way, class Evaluator defines its self type to be Model, like this:&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package org.stairwaybook.scells
trait Evaluator { this: Model =&amp;gt; ...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  6. What is the advantage of using abstract classes instead of traits?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;There are two differences:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Abstract classes can have constructor parameters as well as type parameters. Traits can have only type parameters. There was some discussion that in future even traits can have constructor parameters.&lt;/li&gt;
&lt;li&gt;Abstract classes are fully interoperable with Java. You can call them from Java code without any wrappers. Traits are fully interoperable only if they do not contain any implementation code.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Additional Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Whenever you implement a reusable collection of behavior, you will have to decide whether you want to use a trait or an abstract class. There is no firm rule, but this section contains a few guidelines to consider.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;If the behavior will not be reused&lt;/em&gt;, then make it a concrete class. It is not reusable behavior after all.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;If it might be reused in multiple, unrelated classes&lt;/em&gt;, make it a trait. Only traits can be mixed into different parts of the class hierarchy.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;If you want to inherit from it in Java code&lt;/em&gt;, use an abstract class. Since traits with code do not have a close Java analog, it tends to be awkward to inherit from a trait in a Java class. Inheriting from a Scala class, meanwhile, is exactly like inheriting from a Java class. As one exception, a Scala trait with only abstract members translates directly to a Java interface, so you should feel free to define such traits even if you expect Java code to inherit from it.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;If you plan to distribute it in compiled form&lt;/em&gt;, and you expect outside groups to write classes inheriting from it, you might lean towards using an abstract class. The issue is that when a trait gains or loses a member, any classes that inherit from it must be recompiled, even if they have not changed. If outside clients will only call into the behavior, instead of inheriting from it, then using a trait is fine.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;If efficiency is very important&lt;/em&gt;, lean towards using a class. Most Java runtimes make a virtual method invocation of a class member a faster operation than an interface method invocation. Traits get compiled to interfaces and therefore may pay a slight performance overhead. However, you should make this choice only if you know that the trait in question constitutes a performance bottleneck and have evidence that using a class instead actually solves the problem.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;If you still do not know&lt;/em&gt;, after considering the above, then start by making it as a trait. You can always change it later, and in general, using a trait keeps more options open.&lt;/p&gt;

&lt;p&gt;The other difference between classes and traits is that whereas in classes, &lt;code&gt;super&lt;/code&gt; calls are statically bound, in traits, they are dynamically bound. If you write &lt;code&gt;super.toString&lt;/code&gt; in a class, you know exactly which method implementation will be invoked. When you write the same thing in a trait, however, the method implementation to invoke for the super call is undefined when you define the trait.&lt;/p&gt;

&lt;p&gt;There is also a subtle difference in the way abstract classes behave compared to traits. One of the linearization rules is that it preserves the inheritance hierarchy of the classes, which tends to push abstract classes later in the chain while traits can happily be mixed in. In certain circumstances, it’s actually preferable to be in the latter position of the class linearization, so abstract classes could be used for that. See &lt;a href="https://eed3si9n.com/constraining-class-linearization-in-Scala"&gt;constraining class linearization (mixin order) in Scala&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;As of Scala 2.12, the trait’s binary compatibility behavior has changed. Prior to 2.12, adding or removing a member to the trait required recompilation of all classes that inherit the trait, even if the classes have not changed. This is due to the way traits were encoded in JVM.&lt;/p&gt;

&lt;p&gt;As of Scala 2.12, traits &lt;a href="https://www.scala-lang.org/news/2.12.0/#traits-compile-to-interfaces"&gt;compile to Java interfaces&lt;/a&gt;, so the requirement has relaxed a bit. If the trait does any of the following, its subclasses still require recompilation:&lt;/p&gt;

&lt;blockquote&gt;
&lt;ul&gt;
&lt;li&gt;defining fields (&lt;code&gt;val&lt;/code&gt; or &lt;code&gt;var&lt;/code&gt;, but a constant is ok – &lt;code&gt;final val&lt;/code&gt; without result type)&lt;/li&gt;
&lt;li&gt;calling &lt;code&gt;super&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;initializer statements in the body&lt;/li&gt;
&lt;li&gt;extending a class&lt;/li&gt;
&lt;li&gt;relying on linearization to find implementations in the right supertrait&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;

&lt;p&gt;But if the trait does not, you can now update it without breaking binary compatibility.&lt;/p&gt;

&lt;h3&gt;
  
  
  7. What is a TypeTag and how to use it?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A &lt;code&gt;TypeTag&lt;/code&gt; solves the problem that Scala’s types are erased at runtime (type erasure). If we want to do&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Foo
class Bar extends Foo

def meth[A](xs: List[A]) = xs match {
  case _: List[String] =&amp;gt; "list of strings"
  case _: List[Foo] =&amp;gt; "list of foos"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;we will get warnings:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;console&amp;gt;:23: warning: non-variable type argument String in type pattern List[String]↩
is unchecked since it is eliminated by erasure
         case _: List[String] =&amp;gt; "list of strings"
                 ^
&amp;lt;console&amp;gt;:24: warning: non-variable type argument Foo in type pattern List[Foo]↩
is unchecked since it is eliminated by erasure
         case _: List[Foo] =&amp;gt; "list of foos"
                 ^
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To solve this problem, &lt;a href="https://www.scala-lang.org/api/current/index.html#scala.reflect.Manifest"&gt;Manifests&lt;/a&gt; were introduced to Scala. But they have the problem not being able to represent a lot of useful types, like path-dependent-types:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;scala&amp;gt; class Foo{class Bar}
defined class Foo

scala&amp;gt; def m(f: Foo)(b: f.Bar)(implicit ev: Manifest[f.Bar]) = ev
warning: there were 2 deprecation warnings; re-run with -deprecation for details
m: (f: Foo)(b: f.Bar)(implicit ev: Manifest[f.Bar])Manifest[f.Bar]

scala&amp;gt; val f1 = new Foo;val b1 = new f1.Bar
f1: Foo = Foo@681e731c
b1: f1.Bar = Foo$Bar@271768ab

scala&amp;gt; val f2 = new Foo;val b2 = new f2.Bar
f2: Foo = Foo@3e50039c
b2: f2.Bar = Foo$Bar@771d16b9

scala&amp;gt; val ev1 = m(f1)(b1)
warning: there were 2 deprecation warnings; re-run with -deprecation for details
ev1: Manifest[f1.Bar] = Foo@681e731c.type#Foo$Bar

scala&amp;gt; val ev2 = m(f2)(b2)
warning: there were 2 deprecation warnings; re-run with -deprecation for details
ev2: Manifest[f2.Bar] = Foo@3e50039c.type#Foo$Bar

scala&amp;gt; ev1 == ev2 // they should be different, thus the result is wrong
res28: Boolean = true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Thus, they are replaced by &lt;a href="https://www.scala-lang.org/api/current/scala-reflect/index.html#scala.reflect.api.TypeTags"&gt;TypeTags&lt;/a&gt;, which are both much simpler to use and well-integrated into the new Reflection API. With them we can solve the problem above about path-dependent-types elegantly:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;scala&amp;gt; def m(f: Foo)(b: f.Bar)(implicit ev: TypeTag[f.Bar]) = ev
m: (f: Foo)(b: f.Bar)(implicit ev: reflect.runtime.universe.TypeTag[f.Bar])↩
reflect.runtime.universe.TypeTag[f.Bar]

scala&amp;gt; val ev1 = m(f1)(b1)
ev1: reflect.runtime.universe.TypeTag[f1.Bar] = TypeTag[f1.Bar]

scala&amp;gt; val ev2 = m(f2)(b2)
ev2: reflect.runtime.universe.TypeTag[f2.Bar] = TypeTag[f2.Bar]

scala&amp;gt; ev1 == ev2 // the result is correct, the type tags are different
res30: Boolean = false

scala&amp;gt; ev1.tpe =:= ev2.tpe // this result is correct, too
res31: Boolean = false
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;They are also easy to use to check type parameters:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import scala.reflect.runtime.universe._

def meth[A : TypeTag](xs: List[A]) = typeOf[A] match {
  case t if t =:= typeOf[String] =&amp;gt; "list of strings"
  case t if t &amp;lt;:&amp;lt; typeOf[Foo] =&amp;gt; "list of foos"
}

scala&amp;gt; meth(List("string"))
res67: String = list of strings

scala&amp;gt; meth(List(new Bar))
res68: String = list of foos
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;At this point, it is extremely important to understand to use &lt;code&gt;=:=&lt;/code&gt; (type equality) and &lt;code&gt;&amp;lt;:&amp;lt;&lt;/code&gt; (subtype relation) for equality checks. Do never use &lt;code&gt;==&lt;/code&gt; or &lt;code&gt;!=&lt;/code&gt;, unless you absolutely know what you do:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;scala&amp;gt; typeOf[List[java.lang.String]] =:= typeOf[List[Predef.String]]
res71: Boolean = true

scala&amp;gt; typeOf[List[java.lang.String]] == typeOf[List[Predef.String]]
res72: Boolean = false
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The latter checks for structural equality, which often is not what should be done because it doesn’t care about things such as prefixes (like in the example).&lt;/p&gt;

&lt;p&gt;A &lt;code&gt;TypeTag&lt;/code&gt; is completely compiler-generated, that means that the compiler creates and fills in a &lt;code&gt;TypeTag&lt;/code&gt; when one calls a method expecting such a &lt;code&gt;TypeTag&lt;/code&gt;. There exist three different forms of tags:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.scala-lang.org/api/current/index.html#scala.reflect.ClassTag"&gt;scala.reflect.ClassTag&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.scala-lang.org/api/current/scala-reflect/index.html#scala.reflect.api.TypeTags%24TypeTag"&gt;scala.reflect.api.TypeTags#TypeTag&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.scala-lang.org/api/current/scala-reflect/index.html#scala.reflect.api.TypeTags"&gt;scala.reflect.api.TypeTags#WeakTypeTag&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;code&gt;ClassTag&lt;/code&gt; substitutes &lt;code&gt;ClassManifest&lt;/code&gt; whereas &lt;code&gt;TypeTag&lt;/code&gt; is more or less the replacement for &lt;code&gt;Manifest&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The former allows to fully work with generic arrays:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;scala&amp;gt; import scala.reflect._
import scala.reflect._

scala&amp;gt; def createArr[A](seq: A*) = Array[A](seq: _*)
&amp;lt;console&amp;gt;:22: error: No ClassTag available for A
       def createArr[A](seq: A*) = Array[A](seq: _*)
                                           ^

scala&amp;gt; def createArr[A : ClassTag](seq: A*) = Array[A](seq: _*)
createArr: [A](seq: A*)(implicit evidence$1: scala.reflect.ClassTag[A])Array[A]

scala&amp;gt; createArr(1,2,3)
res78: Array[Int] = Array(1, 2, 3)

scala&amp;gt; createArr("a","b","c")
res79: Array[String] = Array(a, b, c)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;ClassTag&lt;/code&gt; provides only the information needed to create types at runtime (which are type erased):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;scala&amp;gt; classTag[Int]
res99: scala.reflect.ClassTag[Int] = ClassTag[int]

scala&amp;gt; classTag[Int].runtimeClass
res100: Class[_] = int

scala&amp;gt; classTag[Int].newArray(3)
res101: Array[Int] = Array(0, 0, 0)

scala&amp;gt; classTag[List[Int]]
res104: scala.reflect.ClassTag[List[Int]] =↩
        ClassTag[class scala.collection.immutable.List]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As one can see above, they don’t care about type erasure, therefore if one wants “full” types &lt;code&gt;TypeTag&lt;/code&gt; should be used:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;scala&amp;gt; typeTag[List[Int]]
res105: reflect.runtime.universe.TypeTag[List[Int]] = TypeTag[scala.List[Int]]

scala&amp;gt; typeTag[List[Int]].tpe
res107: reflect.runtime.universe.Type = scala.List[Int]

scala&amp;gt; typeOf[List[Int]]
res108: reflect.runtime.universe.Type = scala.List[Int]

scala&amp;gt; res107 =:= res108
res109: Boolean = true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As one can see, the method &lt;code&gt;tpe&lt;/code&gt; of &lt;code&gt;TypeTag&lt;/code&gt; results in a full &lt;code&gt;Type&lt;/code&gt;, which is the same we get when &lt;code&gt;typeOf&lt;/code&gt; is called. Of course, it is possible to use both, &lt;code&gt;ClassTag&lt;/code&gt; and &lt;code&gt;TypeTag&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;scala&amp;gt; def m[A : ClassTag : TypeTag] = (classTag[A], typeTag[A])
m: [A](implicit evidence$1: scala.reflect.ClassTag[A],↩
       implicit evidence$2: reflect.runtime.universe.TypeTag[A])↩
      (scala.reflect.ClassTag[A], reflect.runtime.universe.TypeTag[A])

scala&amp;gt; m[List[Int]]
res36: (scala.reflect.ClassTag[List[Int]],↩
        reflect.runtime.universe.TypeTag[List[Int]]) =↩
       (scala.collection.immutable.List,TypeTag[scala.List[Int]])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The remaining question now is what is the sense of &lt;code&gt;WeakTypeTag&lt;/code&gt; ? In short, &lt;code&gt;TypeTag&lt;/code&gt; represents a concrete type (this means it only allows fully instantiated types) whereas &lt;code&gt;WeakTypeTag&lt;/code&gt; just allows any type. Most of the time one does not care which is what (which means &lt;code&gt;TypeTag&lt;/code&gt; should be used), but for example, when macros are used which should work with generic types they are needed:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;object Macro {
  import language.experimental.macros
  import scala.reflect.macros.Context

  def anymacro[A](expr: A): String = macro __anymacro[A]

  def __anymacro[A : c.WeakTypeTag](c: Context)(expr: c.Expr[A]): c.Expr[A] = {
    // to get a Type for A the c.WeakTypeTag context bound must be added
    val aType = implicitly[c.WeakTypeTag[A]].tpe
    ???
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If one replaces &lt;code&gt;WeakTypeTag&lt;/code&gt; with &lt;code&gt;TypeTag&lt;/code&gt; an error is thrown:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;console&amp;gt;:17: error: macro implementation has wrong shape:
 required: (c: scala.reflect.macros.Context)(expr: c.Expr[A]): c.Expr[String]
 found   : (c: scala.reflect.macros.Context)(expr: c.Expr[A])(implicit evidence$1: c.TypeTag[A]): c.Expr[A]
macro implementations cannot have implicit parameters other than WeakTypeTag evidences
             def anymacro[A](expr: A): String = macro __anymacro[A]
                                                      ^
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The official documentation site of Scala also contains a &lt;a href="https://docs.scala-lang.org/overviews/reflection/overview.html"&gt;guide for Reflection&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  8. Is there any difference between &lt;code&gt;:::&lt;/code&gt; and &lt;code&gt;++&lt;/code&gt; for concatenating lists in Scala?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The list was originally defined to be functional-languages-looking:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;1 :: 2 :: Nil // a list
list1 ::: list2  // concatenation of two lists

list match {
  case head :: tail =&amp;gt; "non-empty"
  case Nil          =&amp;gt; "empty"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Of course, Scala evolved other collections, in an ad-hoc manner. When 2.8 came out, the collections were redesigned for maximum code reuse and consistent API, so that you can use &lt;code&gt;++&lt;/code&gt; to concatenate any two collections — and even iterators. List, however, got to keep its original operators, aside from one or two which got deprecated.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Additional Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Always use &lt;code&gt;:::&lt;/code&gt;. There are two reasons: efficiency and type safety.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Efficiency&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;x ::: y ::: z&lt;/code&gt; is faster than &lt;code&gt;x ++ y ++ z&lt;/code&gt;, because &lt;code&gt;:::&lt;/code&gt; is right associative. &lt;code&gt;x ::: y ::: z&lt;/code&gt; is parsed as &lt;code&gt;x ::: (y ::: z)&lt;/code&gt;, which is algorithmically faster than &lt;code&gt;(x ::: y) ::: z&lt;/code&gt; (the latter requires O(|x|) more steps).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Type safety&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;With &lt;code&gt;:::&lt;/code&gt; you can only concatenate two &lt;code&gt;Lists&lt;/code&gt;. With &lt;code&gt;++&lt;/code&gt; you can append any collection to &lt;code&gt;List&lt;/code&gt;, which is terrible:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;scala&amp;gt; List(1, 2, 3) ++ "ab"
res0: List[AnyVal] = List(1, 2, 3, a, b)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;++&lt;/code&gt; is also easy to mix up with &lt;code&gt;+&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;scala&amp;gt; List(1, 2, 3) + "ab"
res1: String = List(1, 2, 3)ab
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  9. What is a sealed trait?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A &lt;code&gt;sealed&lt;/code&gt; trait can be extended only in the same file as its declaration.&lt;/p&gt;

&lt;p&gt;They are often used to provide an alternative to &lt;code&gt;enums&lt;/code&gt;. Since they can be only extended in a single file, the compiler knows every possible subtype and can reason about it.&lt;/p&gt;

&lt;p&gt;For instance with the declaration:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sealed trait Answer
case object Yes extends Answer
case object No extends Answer
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The compiler will emit a warning if a match is not exhaustive:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;scala&amp;gt; val x: Answer = Yes
x: Answer = Yes

scala&amp;gt; x match {
     |   case No =&amp;gt; println("No")
     | }
&amp;lt;console&amp;gt;:12: warning: match is not exhaustive!
missing combination            Yes
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So you should use sealed traits (or sealed abstract class) if the number of possible subtypes is finite and known in advance. For more examples, you can have a look at &lt;a href="https://github.com/scala/scala/blob/v2.9.2/src/library/scala/collection/immutable/List.scala#L76"&gt;list&lt;/a&gt; and &lt;a href="https://github.com/scala/scala/blob/v2.9.2/src/library/scala/Option.scala#L85"&gt;option&lt;/a&gt; implementations.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Additional Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A sealed trait is the same as a sealed class?&lt;/p&gt;

&lt;p&gt;As far as &lt;code&gt;sealed&lt;/code&gt; goes, yes. They share the normal differences between &lt;code&gt;trait&lt;/code&gt; and &lt;code&gt;class&lt;/code&gt;, of course.&lt;/p&gt;

&lt;p&gt;Or, if not, what are the differences ?&lt;/p&gt;

&lt;p&gt;When is it a good idea to use a sealed trait (and when not) ?&lt;/p&gt;

&lt;p&gt;If you have a &lt;code&gt;sealed class X&lt;/code&gt;, then you have to check for &lt;code&gt;X&lt;/code&gt; as well as any subclasses. The same is not true of &lt;code&gt;sealed abstract class X&lt;/code&gt; or &lt;code&gt;sealed trait X&lt;/code&gt;. So you could do &lt;code&gt;sealed abstract class X&lt;/code&gt;, but that’s way more verbose than just &lt;code&gt;trait&lt;/code&gt; and for little advantage.&lt;/p&gt;

&lt;p&gt;The main advantage of using an &lt;code&gt;abstract class&lt;/code&gt; over a &lt;code&gt;trait&lt;/code&gt; is that it can receive parameters. That advantage is particularly relevant when using type classes. Let’s say you want to build a sorted tree, for instance. You can write this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sealed abstract class Tree[T : Ordering]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;but you cannot do this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sealed trait Tree[T : Ordering]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;since context bounds (and view bounds) are implemented with implicit parameters. Given that traits can’t receive parameters, you can’t do that.&lt;/p&gt;

&lt;p&gt;You can prefer &lt;code&gt;sealed trait&lt;/code&gt; and use it unless some particular reason makes you use a &lt;code&gt;sealed abstract class&lt;/code&gt;. But in-your-face reasons you cannot ignore, such as using type classes.&lt;/p&gt;

&lt;h3&gt;
  
  
  10. How to use java.String.format in Scala?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Here’s a Scala example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;val placeholder = "Hello %s, isn't %s cool?"
val formatted = placeholder.format("Ivan", "Scala")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You don’t need to use numbers to indicate positioning. By default, the position of the argument is simply the order in which it appears in the string.&lt;/p&gt;

&lt;p&gt;Here’s an example of the proper way to use this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;String result = String.format("The format method is %s!", "great");
// result now equals  "The format method is great!".
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You will always use a &lt;code&gt;%&lt;/code&gt; followed by some other characters to let the method know how it should display the string. &lt;code&gt;%s&lt;/code&gt; is probably the most common, and it just means that the argument should be treated as a string.&lt;/p&gt;

&lt;p&gt;Here are a few examples just to give you an idea:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// we can specify the # of decimals we want to show for a floating point:
String result = String.format("10 / 3 = %.2f", 10.0 / 3.0);
// result now equals  "10 / 3 = 3.33"

// we can add commas to long numbers:
result = String.format("Today we processed %,d transactions.", 1000000);
// result now equals  "Today we processed 1,000,000 transactions."
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;String.format&lt;/code&gt; just uses a &lt;code&gt;java.util.Formatter&lt;/code&gt;, so for a full description of the options, you can see the &lt;a href="https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax"&gt;Formatter javadocs&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;And, you will see in the documentation that it is possible to change the default argument ordering if you need to. However, probably the only time you’d need/want to do this is if you are using the same argument more than once.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;In Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;These are the 10 most commonly asked questions about Scala. If you have any suggestions or any confusion, please comment below. If you need any help, we will be glad to help you.&lt;/p&gt;

&lt;p&gt;We, at &lt;a href="https://www.truemark.dev/"&gt;Truemark&lt;/a&gt;, provide services like web and mobile app development, digital marketing, and website development. So, if you need any help and want to work with us, please feel free to contact us.&lt;/p&gt;

&lt;p&gt;Hope this article helped you.&lt;/p&gt;

&lt;p&gt;This article was first published on &lt;a href="https://thedevpost.com/blog/10-most-asked-scala-programming-questions/"&gt;DevPostbyTruemark&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>scala</category>
    </item>
    <item>
      <title>13 Most Asked R Programming Questions</title>
      <dc:creator>KiranPoudel98</dc:creator>
      <pubDate>Fri, 30 Oct 2020 08:56:53 +0000</pubDate>
      <link>https://forem.com/truemark/13-most-asked-r-programming-questions-93m</link>
      <guid>https://forem.com/truemark/13-most-asked-r-programming-questions-93m</guid>
      <description>&lt;p&gt;R is an open-source programming language that is mainly used for statistical analysis, data analysis, graphical representation of data, and reporting. It a popular language among Data Scientists, Statisticians, researchers, and marketers to analyze and visualize the data. So, today we will be checking out the 13 most asked R programming questions.&lt;/p&gt;

&lt;h2&gt;
  
  
  13 Most Asked R Programming Questions
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1. How to make a great R reproducible example?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A &lt;a href="https://stackoverflow.com/help/minimal-reproducible-example"&gt;minimal reproducible example&lt;/a&gt; consists of the following items:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;a minimal dataset, necessary to demonstrate the problem&lt;/li&gt;
&lt;li&gt;the minimal &lt;strong&gt;runnable&lt;/strong&gt; code necessary to reproduce the error, which can be run on the given dataset&lt;/li&gt;
&lt;li&gt;the necessary information on the used packages, R version, and the system it is run on.&lt;/li&gt;
&lt;li&gt;in the case of random processes, a seed (set by &lt;code&gt;set.seed()&lt;/code&gt;) for reproducibility1&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For examples of good &lt;em&gt;minimal reproducible examples&lt;/em&gt;, see the help files of the function you are using. In general, all the code given there fulfills the requirements of a minimal reproducible example: data is provided, minimal code is provided, and everything is runnable. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Producing a minimal dataset&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In most cases, this can be easily done by just providing a vector/data frame with some values. Or you can use one of the built-in datasets, which are provided with most packages. A comprehensive list of built-in datasets can be seen with &lt;code&gt;library(help = "datasets")&lt;/code&gt;. There is a short description of every datasets and more information can be obtained for example with &lt;code&gt;?mtcars&lt;/code&gt; where ‘mtcars’ is one of the datasets in the list. Other packages might contain additional datasets.&lt;/p&gt;

&lt;p&gt;Making a vector is easy. Sometimes it is necessary to add some randomness to it, and there are a whole number of functions to make that. &lt;code&gt;sample()&lt;/code&gt; can randomize a vector, or give a random vector with only a few values. &lt;code&gt;letters&lt;/code&gt; is a useful vector containing the alphabet. This can be used for making factors.&lt;/p&gt;

&lt;p&gt;A few examples :&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;random values : &lt;code&gt;x &amp;lt;- rnorm(10)&lt;/code&gt; for normal distribution, &lt;code&gt;x &amp;lt;- runif(10)&lt;/code&gt; for uniform distribution, …&lt;/li&gt;
&lt;li&gt;a permutation of some values : &lt;code&gt;x &amp;lt;- sample(1:10)&lt;/code&gt; for vector 1:10 in random order.&lt;/li&gt;
&lt;li&gt;a random factor : &lt;code&gt;x &amp;lt;- sample(letters[1:4], 20, replace = TRUE)&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For matrices, one can use &lt;code&gt;matrix()&lt;/code&gt;, eg :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;matrix(1:10, ncol = 2)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Making data frames can be done using &lt;code&gt;data.frame()&lt;/code&gt;. One should pay attention to name the entries in the data frame, and to not make it overly complicated.&lt;/p&gt;

&lt;p&gt;An example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;set.seed(1)
Data &amp;lt;- data.frame(
    X = sample(1:10),
    Y = sample(c("yes", "no"), 10, replace = TRUE)
)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For some questions, specific formats can be needed. For these, one can use any of the provided &lt;code&gt;as.someType&lt;/code&gt; functions : &lt;code&gt;as.factor, as.Date, as.xts&lt;/code&gt;. These in combination with the vector and/or data frame tricks.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Copy your data&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If you have some data that would be too difficult to construct using these tips, then you can always make a subset of your original data, using &lt;code&gt;head()&lt;/code&gt;, &lt;code&gt;subset()&lt;/code&gt;, or the indices. Then use &lt;code&gt;dput()&lt;/code&gt; to give us something that can be put in R immediately:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt; dput(iris[1:4, ]) # first four rows of the iris data set
structure(list(Sepal.Length = c(5.1, 4.9, 4.7, 4.6), Sepal.Width = c(3.5, 
3, 3.2, 3.1), Petal.Length = c(1.4, 1.4, 1.3, 1.5), Petal.Width = c(0.2, 
0.2, 0.2, 0.2), Species = structure(c(1L, 1L, 1L, 1L), .Label = c("setosa", 
"versicolor", "virginica"), class = "factor")), .Names = c("Sepal.Length", 
"Sepal.Width", "Petal.Length", "Petal.Width", "Species"), row.names = c(NA, 
4L), class = "data.frame")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If your data frame has a factor with many levels, the &lt;code&gt;dput&lt;/code&gt; output can be unwieldy because it will still list all the possible factor levels even if they aren’t present in the subset of your data. To solve this issue, you can use the &lt;code&gt;droplevels()&lt;/code&gt; function. Notice below how species is a factor with only one level:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt; dput(droplevels(iris[1:4, ]))
structure(list(Sepal.Length = c(5.1, 4.9, 4.7, 4.6), Sepal.Width = c(3.5, 
3, 3.2, 3.1), Petal.Length = c(1.4, 1.4, 1.3, 1.5), Petal.Width = c(0.2, 
0.2, 0.2, 0.2), Species = structure(c(1L, 1L, 1L, 1L), .Label = "setosa",
class = "factor")), .Names = c("Sepal.Length", "Sepal.Width", 
"Petal.Length", "Petal.Width", "Species"), row.names = c(NA, 
4L), class = "data.frame")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When using &lt;code&gt;dput&lt;/code&gt;, you may also want to include only relevant columns:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt; dput(mtcars[1:3, c(2, 5, 6)]) # first three rows of columns 2, 5, and 6
structure(list(cyl = c(6, 6, 4), drat = c(3.9, 3.9, 3.85), wt = c(2.62, 
2.875, 2.32)), row.names = c("Mazda RX4", "Mazda RX4 Wag", "Datsun 710"
), class = "data.frame")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;One other caveat for &lt;code&gt;dput&lt;/code&gt; is that it will not work for keyed &lt;code&gt;data.table&lt;/code&gt; objects or for grouped &lt;code&gt;tbl_df&lt;/code&gt; (class &lt;code&gt;grouped_df&lt;/code&gt;) from &lt;code&gt;dplyr&lt;/code&gt;. In these cases you can convert back to a regular data frame before sharing, &lt;code&gt;dput(as.data.frame(my_data))&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Worst case scenario, you can give a text representation that can be read in using the &lt;code&gt;text&lt;/code&gt; parameter of &lt;code&gt;read.table&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;zz &amp;lt;- "Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa"

Data &amp;lt;- read.table(text=zz, header = TRUE)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Producing minimal code&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This should be the easy part but often isn’t. What you should not do, is:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;add all kind of data conversions. Make sure the provided data is already in the correct format (unless that is the problem of course)&lt;/li&gt;
&lt;li&gt;copy-paste a whole function/chunk of code that gives an error. First, try to locate which lines exactly result in the error. More often than not you’ll find out what the problem is yourself.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;What you should do, is:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;add which packages should be used if you use any (using &lt;code&gt;library()&lt;/code&gt;)&lt;/li&gt;
&lt;li&gt;if you open connections or create files, add some code to close them or delete the files (using &lt;code&gt;unlink()&lt;/code&gt;)&lt;/li&gt;
&lt;li&gt;if you change options, make sure the code contains a statement to revert them back to the original ones. (eg &lt;code&gt;op &amp;lt;- par(mfrow=c(1,2)) ...some code... par(op)&lt;/code&gt;)&lt;/li&gt;
&lt;li&gt;test run your code in a new, empty R session to make sure the code is runnable. People should be able to just copy-paste your data and your code in the console and get exactly the same as you have.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Give extra information&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In most cases, just the R version and the operating system will suffice. When conflicts arise with packages, giving the output of &lt;code&gt;sessionInfo()&lt;/code&gt; can really help. When talking about connections to other applications (be it through ODBC or anything else), one should also provide version numbers for those, and if possible also the necessary information on the setup.&lt;/p&gt;

&lt;p&gt;If you are running R in R Studio using &lt;code&gt;rstudioapi::versionInfo()&lt;/code&gt; can be helpful to report your RStudio version.&lt;/p&gt;

&lt;p&gt;If you have a problem with a specific package you may want to provide the version of the package by giving the output of &lt;code&gt;packageVersion("name of the package")&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; The output of &lt;code&gt;set.seed()&lt;/code&gt; differs between R &amp;gt;3.6.0 and previous versions. Do specify which R version you used for the random process, and don’t be surprised if you get slightly different results when following old questions. To get the same result in such cases, you can use the &lt;code&gt;RNGversion()&lt;/code&gt;-function before &lt;code&gt;set.seed()&lt;/code&gt; (e.g.: &lt;code&gt;RNGversion("3.5.2")&lt;/code&gt;).&lt;/p&gt;

&lt;h3&gt;
  
  
  2. How to sort a dataframe by multiple column(s)?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can use the &lt;a href="https://stat.ethz.ch/R-manual/R-devel/library/base/html/order.html"&gt;&lt;code&gt;order()&lt;/code&gt;&lt;/a&gt; function directly without resorting to add-on tools. See this simpler answer which uses a trick right from the top of the &lt;code&gt;example(order)&lt;/code&gt; code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;R&amp;gt; dd[with(dd, order(-z, b)), ]
    b x y z
4 Low C 9 2
2 Med D 3 1
1  Hi A 8 1
3  Hi A 9 1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you want to do this by column index, the answer is to simply pass the desired sorting column(s) to the &lt;code&gt;order()&lt;/code&gt; function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;R&amp;gt; dd[order(-dd[,4], dd[,1]), ]
    b x y z
4 Low C 9 2
2 Med D 3 1
1  Hi A 8 1
3  Hi A 9 1
R&amp;gt; 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;rather than using the name of the column (and &lt;code&gt;with()&lt;/code&gt; for easier/more direct access).&lt;/p&gt;

&lt;h3&gt;
  
  
  3. How to join (merge) data frames (inner, outer, left, right)?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;By using the &lt;code&gt;merge&lt;/code&gt; function and its optional parameters:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Inner join:&lt;/strong&gt; &lt;code&gt;merge(df1, df2)&lt;/code&gt; will work for these examples because R automatically joins the frames by common variable names, but you would most likely want to specify &lt;code&gt;merge(df1, df2, by = "CustomerId")&lt;/code&gt; to make sure that you were matching only the fields you desired. You can also use the &lt;code&gt;by.x&lt;/code&gt; and &lt;code&gt;by.y&lt;/code&gt; parameters if the matching variables have different names in the different data frames.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Outer join:&lt;/strong&gt; &lt;code&gt;merge(x = df1, y = df2, by = "CustomerId", all = TRUE)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Left outer:&lt;/strong&gt; &lt;code&gt;merge(x = df1, y = df2, by = "CustomerId", all.x = TRUE)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Right outer:&lt;/strong&gt; &lt;code&gt;merge(x = df1, y = df2, by = "CustomerId", all.y = TRUE)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Cross join:&lt;/strong&gt; &lt;code&gt;merge(x = df1, y = df2, by = NULL)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;It’s almost always best to explicitly state the identifiers on which you want to merge; it’s safer if the input data.frames change unexpectedly and easier to read later on.&lt;/p&gt;

&lt;p&gt;You can merge on multiple columns by giving &lt;code&gt;by&lt;/code&gt; a vector, e.g., &lt;code&gt;by = c("CustomerId", "OrderId")&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;If the column names to merge on are not the same, you can specify, e.g., &lt;code&gt;by.x = "CustomerId_in_df1"&lt;/code&gt;, &lt;code&gt;by.y = "CustomerId_in_df2"&lt;/code&gt; where &lt;code&gt;CustomerId_in_df1&lt;/code&gt; is the name of the column in the first data frame and &lt;code&gt;CustomerId_in_df2&lt;/code&gt; is the name of the column in the second data frame. (These can also be vectors if you need to merge on multiple columns.)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;There is the &lt;strong&gt;data.table&lt;/strong&gt; approach for an inner join, which is very time and memory-efficient (and necessary for some larger data.frames):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;library(data.table)

dt1 &amp;lt;- data.table(df1, key = "CustomerId") 
dt2 &amp;lt;- data.table(df2, key = "CustomerId")

joined.dt1.dt.2 &amp;lt;- dt1[dt2]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;merge&lt;/code&gt; also works on data.tables (as it is generic and calls &lt;code&gt;merge.data.table&lt;/code&gt;)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;merge(dt1, dt2)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Yet another option is the &lt;code&gt;join&lt;/code&gt; function found in the &lt;a href="https://cran.r-project.org/web/packages/plyr/index.html"&gt;plyr&lt;/a&gt; package.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;library(plyr)

join(df1, df2,
     type = "inner")

#   CustomerId Product   State
# 1          2 Toaster Alabama
# 2          4   Radio Alabama
# 3          6   Radio    Ohio
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Options for &lt;code&gt;type: inner&lt;/code&gt;, &lt;code&gt;left&lt;/code&gt;, &lt;code&gt;right&lt;/code&gt;, &lt;code&gt;full&lt;/code&gt;. From &lt;code&gt;?join:&lt;/code&gt; Unlike &lt;code&gt;merge, [join]&lt;/code&gt; preserves the order of x no matter what join type is used.&lt;/p&gt;

&lt;h3&gt;
  
  
  4. How and when to use grouping functions (tapply, by, aggregate) and the *apply family?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;R has many *apply functions which are ably described in the help files (e.g. &lt;code&gt;?apply&lt;/code&gt;). There are enough of them, though, that beginning users may have difficulty deciding which one is appropriate for their situation or even remember them all. They may have a general sense that “We should be using an *apply function here”, but it can be tough to keep them all straight at first.&lt;/p&gt;

&lt;p&gt;Despite the fact that much of the functionality of the *apply family is covered by the extremely popular &lt;code&gt;plyr&lt;/code&gt; package, the base functions remain useful and worth knowing.&lt;/p&gt;

&lt;p&gt;This answer is intended to act as a sort of &lt;strong&gt;signpost&lt;/strong&gt; for new users to help direct them to the correct &lt;em&gt;apply function for their particular problem. Note, this is **not&lt;/em&gt;* intended to simply regurgitate or replace the R documentation. The hope is that this answer helps you to decide which *apply function suits your situation and then it is up to you to research it further. With one exception, performance differences will not be addressed.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;apply&lt;/strong&gt; – When you want to apply a function to the rows or columns of a matrix (and higher-dimensional analogues); not generally advisable for data frames as it will coerce to a matrix first.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    # Two dimensional matrix
    M &amp;lt;- matrix(seq(1,16), 4, 4)

    # apply min to rows
    apply(M, 1, min)
    [1] 1 2 3 4

    # apply max to columns
    apply(M, 2, max)
    [1]  4  8 12 16

    # 3 dimensional array
    M &amp;lt;- array( seq(32), dim = c(4,4,2))

    # Apply sum across each M[*, , ] - i.e Sum across 2nd and 3rd dimension
    apply(M, 1, sum)
    # Result is one-dimensional
    [1] 120 128 136 144

    # Apply sum across each M[*, *, ] - i.e Sum across 3rd dimension
    apply(M, c(1,2), sum)
    # Result is two-dimensional
         [,1] [,2] [,3] [,4]
    [1,]   18   26   34   42
    [2,]   20   28   36   44
    [3,]   22   30   38   46
    [4,]   24   32   40   48
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you want row/column means or sums for a 2D matrix, be sure to investigate the highly optimized, lightning-quick &lt;code&gt;colMeans&lt;/code&gt;, &lt;code&gt;rowMeans&lt;/code&gt;, &lt;code&gt;colSums&lt;/code&gt;, &lt;code&gt;rowSums&lt;/code&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;lapply&lt;/strong&gt; – When you want to apply a function to each element of a list in turn and get a list back.This is the workhorse of many of the other *apply functions. Peel back their code and you will often find lapply underneath.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    x &amp;lt;- list(a = 1, b = 1:3, c = 10:100) 
    lapply(x, FUN = length) 
    $a 
    [1] 1
    $b 
    [1] 3
    $c 
    [1] 91
    lapply(x, FUN = sum) 
    $a 
    [1] 1
    $b 
    [1] 6
    $c 
    [1] 5005
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;sapply&lt;/strong&gt; – When you want to apply a function to each element of a list in turn, but you want a &lt;strong&gt;vector&lt;/strong&gt; back, rather than a list. If you find yourself typing &lt;code&gt;unlist(lapply(...))&lt;/code&gt;, stop and consider &lt;code&gt;sapply&lt;/code&gt;.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    x &amp;lt;- list(a = 1, b = 1:3, c = 10:100)
    # Compare with above; a named vector, not a list 
    sapply(x, FUN = length)  
    a  b  c   
    1  3 91

    sapply(x, FUN = sum)   
    a    b    c    
    1    6 5005 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In more advanced uses of &lt;code&gt;sapply&lt;/code&gt; it will attempt to coerce the result to a multi-dimensional array, if appropriate. For example, if our function returns vectors of the same length, &lt;code&gt;sapply&lt;/code&gt; will use them as columns of a matrix:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    sapply(1:5,function(x) rnorm(3,x))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If our function returns a 2 dimensional matrix, &lt;code&gt;sapply&lt;/code&gt; will do essentially the same thing, treating each returned matrix as a single long vector:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    sapply(1:5,function(x) matrix(x,2,2))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Unless we specify &lt;code&gt;simplify = "array"&lt;/code&gt;, in which case it will use the individual matrices to build a multi-dimensional array:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    sapply(1:5,function(x) matrix(x,2,2), simplify = "array")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each of these behaviors is of course contingent on our function returning vectors or matrices of the same length or dimension.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;vapply&lt;/strong&gt; – When you want to use &lt;code&gt;sapply&lt;/code&gt; but perhaps need to squeeze some more speed out of your code.For &lt;code&gt;vapply&lt;/code&gt;, you basically give R an example of what sort of thing your function will return, which can save some time coercing returned values to fit in a single atomic vector.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    x &amp;lt;- list(a = 1, b = 1:3, c = 10:100)
    #Note that since the advantage here is mainly speed, this
    # example is only for illustration. We're telling R that
    # everything returned by length() should be an integer of 
    # length 1. 
    vapply(x, FUN = length, FUN.VALUE = 0L) 
    a  b  c  
    1  3 91
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;mapply&lt;/strong&gt; – For when you have several data structures (e.g. vectors, lists) and you want to apply a function to the 1st elements of each, and then the 2nd elements of each, etc., coercing the result to a vector/array as in &lt;code&gt;sapply&lt;/code&gt;. This is multivariate in the sense that your function must accept multiple arguments.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    #Sums the 1st elements, the 2nd elements, etc. 
    mapply(sum, 1:5, 1:5, 1:5) 
    [1]  3  6  9 12 15
    #To do rep(1,4), rep(2,3), etc.
    mapply(rep, 1:4, 4:1)   
    [[1]]
    [1] 1 1 1 1

    [[2]]
    [1] 2 2 2

    [[3]]
    [1] 3 3

    [[4]]
    [1] 4
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Map&lt;/strong&gt; – A wrapper to &lt;code&gt;mapply&lt;/code&gt; with &lt;code&gt;SIMPLIFY = FALSE&lt;/code&gt;, so it is guaranteed to return a list.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    Map(sum, 1:5, 1:5, 1:5)
    [[1]]
    [1] 3

    [[2]]
    [1] 6

    [[3]]
    [1] 9

    [[4]]
    [1] 12

    [[5]]
    [1] 15
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;rapply&lt;/strong&gt; – For when you want to apply a function to each element of a &lt;strong&gt;nested list&lt;/strong&gt; structure, recursively.To give you some idea of how uncommon &lt;code&gt;rapply&lt;/code&gt; is. But YMMV. &lt;code&gt;rapply&lt;/code&gt; is best illustrated with a user-defined function to apply:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    # Append ! to string, otherwise increment
    myFun &amp;lt;- function(x){
        if(is.character(x)){
          return(paste(x,"!",sep=""))
        }
        else{
          return(x + 1)
        }
    }

    #A nested list structure
    l &amp;lt;- list(a = list(a1 = "Boo", b1 = 2, c1 = "Eeek"), 
              b = 3, c = "Yikes", 
              d = list(a2 = 1, b2 = list(a3 = "Hey", b3 = 5)))


    # Result is named vector, coerced to character          
    rapply(l, myFun)

    # Result is a nested list like l, with values altered
    rapply(l, myFun, how="replace")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;tapply&lt;/strong&gt; – For when you want to apply a function to &lt;strong&gt;subsets&lt;/strong&gt; of a vector and the subsets are defined by some other vector, usually a factor.The black sheep of the *apply family, of sorts. The help file’s use of the phrase “ragged array” can be a bit &lt;a href="https://stackoverflow.com/questions/6297201/explain-r-tapply-description/6297396#6297396"&gt;confusing&lt;/a&gt;, but it is actually quite simple. A vector:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    x &amp;lt;- 1:20
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A factor (of the same length!) defining groups:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    y &amp;lt;- factor(rep(letters[1:5], each = 4))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Add up the values in &lt;code&gt;x&lt;/code&gt; within each subgroup defined by &lt;code&gt;y&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    tapply(x, y, sum)  
     a  b  c  d  e  
    10 26 42 58 74 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;More complex examples can be handled where the subgroups are defined by the unique combinations of a list of several factors. &lt;code&gt;tapply&lt;/code&gt; is similar in spirit to the split-apply-combine functions that are common in R (&lt;code&gt;aggregate&lt;/code&gt;, &lt;code&gt;by&lt;/code&gt;, &lt;code&gt;ave&lt;/code&gt;, &lt;code&gt;ddply&lt;/code&gt;, etc.) Hence its black sheep status.&lt;/p&gt;

&lt;h3&gt;
  
  
  5. How to drop data frame columns by name?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can use a simple list of names:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DF &amp;lt;- data.frame(
  x=1:10,
  y=10:1,
  z=rep(5,10),
  a=11:20
)
drops &amp;lt;- c("x","z")
DF[ , !(names(DF) %in% drops)]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or, alternatively, you can make a list of those to keep and refer to them by name:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;keeps &amp;lt;- c("y", "a")
DF[keeps]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For those still not acquainted with the &lt;code&gt;drop&lt;/code&gt; argument of the indexing function, if you want to keep one column as a data frame, you do:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;keeps &amp;lt;- "y"
DF[ , keeps, drop = FALSE]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;drop=TRUE&lt;/code&gt; (or not mentioning it) will drop unnecessary dimensions, and hence return a vector with the values of column &lt;code&gt;y&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;There’s also the &lt;code&gt;subset&lt;/code&gt; command, useful if you know which columns you want:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;df &amp;lt;- data.frame(a = 1:10, b = 2:11, c = 3:12)
df &amp;lt;- subset(df, select = c(a, c))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To drop columns a,c you could do:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;df &amp;lt;- subset(df, select = -c(a, c))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  6. How to remove rows with all or some NAs (missing values) in data.frame?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Check &lt;a href="https://stat.ethz.ch/R-manual/R-patched/library/stats/html/complete.cases.html"&gt;&lt;code&gt;complete.cases&lt;/code&gt;&lt;/a&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt; final[complete.cases(final), ]
             gene hsap mmul mmus rnor cfam
2 ENSG00000199674    0    2    2    2    2
6 ENSG00000221312    0    1    2    3    2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;na.omit&lt;/code&gt; is nicer for just removing all &lt;code&gt;NA‘s. complete.cases&lt;/code&gt; allows partial selection by including only certain columns of the dataframe:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt; final[complete.cases(final[ , 5:6]),]
             gene hsap mmul mmus rnor cfam
2 ENSG00000199674    0    2    2    2    2
4 ENSG00000207604    0   NA   NA    1    2
6 ENSG00000221312    0    1    2    3    2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Your solution can’t work. If you insist on using &lt;code&gt;is.na&lt;/code&gt;, then you have to do something like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt; final[rowSums(is.na(final[ , 5:6])) == 0, ]
             gene hsap mmul mmus rnor cfam
2 ENSG00000199674    0    2    2    2    2
4 ENSG00000207604    0   NA   NA    1    2
6 ENSG00000221312    0    1    2    3    2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;but using &lt;code&gt;complete.cases&lt;/code&gt; is quite a lot more clear, and faster.&lt;/p&gt;

&lt;h3&gt;
  
  
  7. data.table vs dplyr: Can one do something well the other can’t or does poorly?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let’s cover these aspects to better understand: &lt;code&gt;Speed&lt;/code&gt;, &lt;code&gt;Memory&lt;/code&gt; &lt;code&gt;usage&lt;/code&gt;, &lt;code&gt;Syntax&lt;/code&gt;, and &lt;code&gt;Features&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; Unless explicitly mentioned otherwise, by referring to dplyr, we refer to dplyr’s data.frame interface whose internals are in C++ using Rcpp. The data.table syntax is consistent in its form – &lt;code&gt;DT[i, j, by]&lt;/code&gt;. To keep &lt;code&gt;i&lt;/code&gt;, &lt;code&gt;j&lt;/code&gt;, and &lt;code&gt;by&lt;/code&gt; together is by design. By keeping related operations together, it allows to easily optimize operations for speed and more importantly memory usage, and also provide some powerful features, all while maintaining the consistency in syntax.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;i. Speed&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Quite a few benchmarks (though mostly on grouping operations) have been added to the question already showing data.table gets faster than dplyr as the number of groups and/or rows to group by increase, including &lt;a href="https://github.com/Rdatatable/data.table/wiki/Benchmarks-%3A-Grouping"&gt;benchmarks by Matt&lt;/a&gt; on grouping from 10 million to 2 billion rows (100GB in RAM) on 100 – 10 million groups and varying grouping columns, which also compares &lt;code&gt;pandas&lt;/code&gt;. See also &lt;a href="https://h2oai.github.io/db-benchmark/"&gt;updated benchmarks&lt;/a&gt;, which include &lt;code&gt;Spark&lt;/code&gt; and &lt;code&gt;pydatatable&lt;/code&gt; as well. On benchmarks, it would be great to cover these remaining aspects as well:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Grouping operations involving a subset of rows – i.e., &lt;code&gt;DT[x &amp;gt; val, sum(y), by = z]&lt;/code&gt; type operations.&lt;/li&gt;
&lt;li&gt;Benchmark other operations such as update and joins.&lt;/li&gt;
&lt;li&gt;Also benchmark memory footprint for each operation in addition to runtime.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;ii. Memory usage&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Operations involving &lt;code&gt;filter()&lt;/code&gt; or &lt;code&gt;slice()&lt;/code&gt; in dplyr can be memory inefficient (on both data.frames and data.tables). &lt;a href="https://stackoverflow.com/questions/27511604/dplyr-on-data-table-am-i-really-using-data-table/27520688#27520688"&gt;See this post&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;data.table interface at the moment allows one to modify/update columns by reference (note that we don’t need to re-assign the result back to a variable).
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    # sub-assign by reference, updates 'y' in-place
    DT[x &amp;gt;= 1L, y := NA]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But dplyr will never update by reference. The dplyr equivalent would be (note that the result needs to be re-assigned):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    # copies the entire 'y' column
    ans &amp;lt;- DF %&amp;gt;% mutate(y = replace(y, which(x &amp;gt;= 1L), NA))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A concern for this is &lt;a href="https://en.wikipedia.org/wiki/Referential_transparency"&gt;referential transparency&lt;/a&gt;. Updating a data.table object by reference, especially within a function may not be always desirable. But this is an incredibly useful feature: see &lt;a href="https://stackoverflow.com/questions/24069491/direct-update-replace-of-sparse-data-frame-is-slow-and-inefficient/24070527#24070527"&gt;this&lt;/a&gt; and &lt;a href="https://stackoverflow.com/questions/7235657/fastest-way-to-replace-nas-in-a-large-data-table"&gt;this&lt;/a&gt; posts for interesting cases. And we want to keep it. Therefore we are working towards exporting &lt;code&gt;shallow()&lt;/code&gt; function in data.table that will provide the user with both possibilities. For example, if it is desirable to not modify the input data.table within a function, one can then do:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    foo &amp;lt;- function(DT) {
        DT = shallow(DT)          ## shallow copy DT
        DT[, newcol := 1L]        ## does not affect the original DT 
        DT[x &amp;gt; 2L, newcol := 2L]  ## no need to copy (internally), as this column exists only in shallow copied DT
        DT[x &amp;gt; 2L, x := 3L]       ## have to copy (like base R / dplyr does always); otherwise original DT will 
                                  ## also get modified.
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By not using &lt;code&gt;shallow()&lt;/code&gt;, the old functionality is retained:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    bar &amp;lt;- function(DT) {
        DT[, newcol := 1L]        ## old behaviour, original DT gets updated by reference
        DT[x &amp;gt; 2L, x := 3L]       ## old behaviour, update column x in original DT.
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By creating a shallow copy using &lt;code&gt;shallow()&lt;/code&gt;, we understand that you don’t want to modify the original object. We take care of everything internally to ensure that while also ensuring to copy columns you modify only when it is absolutely necessary. When implemented, this should settle the referential transparency issue altogether while providing the user with both possibilities.&lt;/p&gt;

&lt;p&gt;Also, once &lt;code&gt;shallow()&lt;/code&gt; is exported, dplyr’s data.table interface should avoid almost all copies. So those who prefer dplyr’s syntax can use it with data.tables. But it will still lack many features that data.table provides, including (sub)-assignment by reference.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Aggregate while joining:Suppose you have two data.tables as follows:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    DT1 = data.table(x=c(1,1,1,1,2,2,2,2), y=c("a", "a", "b", "b"), z=1:8, key=c("x", "y"))
    #    x y z
    # 1: 1 a 1
    # 2: 1 a 2
    # 3: 1 b 3
    # 4: 1 b 4
    # 5: 2 a 5
    # 6: 2 a 6
    # 7: 2 b 7
    # 8: 2 b 8
    DT2 = data.table(x=1:2, y=c("a", "b"), mul=4:3, key=c("x", "y"))
    #    x y mul
    # 1: 1 a   4
    # 2: 2 b   3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And you would like to get &lt;code&gt;sum(z) * mul&lt;/code&gt; for each row in &lt;code&gt;DT2&lt;/code&gt; while joining by columns &lt;code&gt;x&lt;/code&gt;,&lt;code&gt;y&lt;/code&gt;. We can either:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;1) aggregate &lt;code&gt;DT1&lt;/code&gt; to get &lt;code&gt;sum(z)&lt;/code&gt;, 2) perform a join and 3) multiply (or)
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;        # data.table way
        DT1[, .(z = sum(z)), keyby = .(x,y)][DT2][, z := z*mul][]

        # dplyr equivalent
        DF1 %&amp;gt;% group_by(x, y) %&amp;gt;% summarise(z = sum(z)) %&amp;gt;% 
            right_join(DF2) %&amp;gt;% mutate(z = z * mul)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;2) do it all in one go (using &lt;code&gt;by = .EACHI&lt;/code&gt; feature):
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;      DT1[DT2, list(z=sum(z) * mul), by = .EACHI]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What is the advantage?&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;We don’t have to allocate memory for the intermediate result.&lt;/li&gt;
&lt;li&gt;We don’t have to group/hash twice (one for aggregation and other for joining).&lt;/li&gt;
&lt;li&gt;And more importantly, the operation that we wanted to perform is clear by looking at &lt;code&gt;j&lt;/code&gt; in (2).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Check &lt;a href="https://stackoverflow.com/questions/27004002/eachi-in-data-table/27004566#27004566"&gt;this post&lt;/a&gt; for a detailed explanation of &lt;code&gt;by = .EACHI&lt;/code&gt;. No intermediate results are materialised, and the join+aggregate is performed all in one go. Have a look at &lt;a href="https://stackoverflow.com/questions/27059924/cartesian-product-with-filter-data-table/27061800#27061800"&gt;this&lt;/a&gt;, &lt;a href="https://stackoverflow.com/questions/26453288/check-frequency-of-data-table-value-in-other-data-table/26453795#26453795"&gt;this&lt;/a&gt; and this posts for real usage scenarios. In &lt;code&gt;dplyr&lt;/code&gt; you would have to &lt;a href="https://gist.github.com/arunsrinivasan/b14441829e7f484fdf58"&gt;join and aggregate or aggregate first and then join&lt;/a&gt;, neither of which are as efficient, in terms of memory (which in turn translates to speed).&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Update and joins:Consider the data.table code shown below:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    DT1[DT2, col := i.mul]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;adds/updates &lt;code&gt;DT1&lt;/code&gt;‘s column &lt;code&gt;col&lt;/code&gt; with &lt;code&gt;mul&lt;/code&gt; from &lt;code&gt;DT2&lt;/code&gt; on those rows where &lt;code&gt;DT2&lt;/code&gt;‘s key column matches &lt;code&gt;DT1&lt;/code&gt;. We don’t think there is an exact equivalent of this operation in &lt;code&gt;dplyr&lt;/code&gt;, i.e., without avoiding a &lt;code&gt;*_join&lt;/code&gt; operation, which would have to copy the entire &lt;code&gt;DT1&lt;/code&gt; just to add a new column to it, which is unnecessary. Check &lt;a href="https://stackoverflow.com/questions/26719940/how-to-merge-two-large-datasets-while-generate-new-column-with-different-repeat/26720434#26720434"&gt;this post&lt;/a&gt; for a real usage scenario.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;To summarise, it is important to realise that every bit of optimisation matters. As &lt;a href="https://en.wikipedia.org/wiki/Grace_Hopper"&gt;Grace Hopper&lt;/a&gt; would say, &lt;a href="http://highscalability.com/blog/2012/3/1/grace-hopper-to-programmers-mind-your-nanoseconds.html"&gt;Mind your nanoseconds&lt;/a&gt;!&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;iii. Syntax&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;What we can perhaps try is to contrast consistency in syntax. We will compare data.table and dplyr syntax side-by-side. We will work with the dummy data shown below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DT = data.table(x=1:10, y=11:20, z=rep(1:2, each=5))
DF = as.data.frame(DT)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Basic aggregation/update operations.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    # case (a)
    DT[, sum(y), by = z]                       ## data.table syntax
    DF %&amp;gt;% group_by(z) %&amp;gt;% summarise(sum(y)) ## dplyr syntax
    DT[, y := cumsum(y), by = z]
    ans &amp;lt;- DF %&amp;gt;% group_by(z) %&amp;gt;% mutate(y = cumsum(y))

    # case (b)
    DT[x &amp;gt; 2, sum(y), by = z]
    DF %&amp;gt;% filter(x&amp;gt;2) %&amp;gt;% group_by(z) %&amp;gt;% summarise(sum(y))
    DT[x &amp;gt; 2, y := cumsum(y), by = z]
    ans &amp;lt;- DF %&amp;gt;% group_by(z) %&amp;gt;% mutate(y = replace(y, which(x &amp;gt; 2), cumsum(y)))

    # case (c)
    DT[, if(any(x &amp;gt; 5L)) y[1L]-y[2L] else y[2L], by = z]
    DF %&amp;gt;% group_by(z) %&amp;gt;% summarise(if (any(x &amp;gt; 5L)) y[1L] - y[2L] else y[2L])
    DT[, if(any(x &amp;gt; 5L)) y[1L] - y[2L], by = z]
    DF %&amp;gt;% group_by(z) %&amp;gt;% filter(any(x &amp;gt; 5L)) %&amp;gt;% summarise(y[1L] - y[2L])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;data.table syntax is compact and dplyr’s quite verbose. Things are more or less equivalent in case (a).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;In case (b), we had to use &lt;code&gt;filter()&lt;/code&gt; in dplyr while summarising. But while updating, we had to move the logic inside &lt;code&gt;mutate()&lt;/code&gt;. In data.table however, we express both operations with the same logic – operate on rows where &lt;code&gt;x &amp;gt; 2&lt;/code&gt;, but in first case, get &lt;code&gt;sum(y)&lt;/code&gt;, whereas in the second case update those rows for &lt;code&gt;y&lt;/code&gt; with its cumulative sum.This is what we mean when we say the &lt;code&gt;DT[i, j, by]&lt;/code&gt; form is consistent.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Similarly in case (c), when we have &lt;code&gt;if-else&lt;/code&gt; condition, we are able to express the logic “as-is” in both data.table and dplyr. However, if we would like to return just those rows where the &lt;code&gt;if&lt;/code&gt; condition satisfies and skip otherwise, we cannot use &lt;code&gt;summarise()&lt;/code&gt; directly (AFAICT). We have to &lt;code&gt;filter()&lt;/code&gt; first and then summarise because &lt;code&gt;summarise()&lt;/code&gt; always expects a single value.While it returns the same result, using &lt;code&gt;filter()&lt;/code&gt; here makes the actual operation less obvious.It might very well be possible to use &lt;code&gt;filter()&lt;/code&gt; in the first case as well (does not seem obvious), but the point is that we should not have to.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Aggregation/update on multiple columns&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    # case (a)
    DT[, lapply(.SD, sum), by = z]                     ## data.table syntax
    DF %&amp;gt;% group_by(z) %&amp;gt;% summarise_each(funs(sum)) ## dplyr syntax
    DT[, (cols) := lapply(.SD, sum), by = z]
    ans &amp;lt;- DF %&amp;gt;% group_by(z) %&amp;gt;% mutate_each(funs(sum))

    # case (b)
    DT[, c(lapply(.SD, sum), lapply(.SD, mean)), by = z]
    DF %&amp;gt;% group_by(z) %&amp;gt;% summarise_each(funs(sum, mean))

    # case (c)
    DT[, c(.N, lapply(.SD, sum)), by = z]     
    DF %&amp;gt;% group_by(z) %&amp;gt;% summarise_each(funs(n(), mean))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;- In case (a), the codes are more or less equivalent. data.table uses familiar base function `lapply()`, whereas `dplyr` introduces `*_each()` along with a bunch of functions to `funs()`.

- data.table’s := requires column names to be provided, whereas dplyr generates it automatically.

- In case (b), dplyr’s syntax is relatively straightforward. Improving aggregations/updates on multiple functions is on data.table’s list.

- In case (c) though, dplyr would return `n()` as many times as many columns, instead of just once. In data.table, all we need to do is to return a list in `j`. Each element of the list will become a column in the result. So, we can use, once again, the familiar base function `c()` to concatenate `.N` to a `list` which returns a `list`.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;blockquote&gt;
&lt;p&gt;Note: Once again, in data.table, all we need to do is return a list in &lt;code&gt;j&lt;/code&gt;. Each element of the list will become a column in result. You can use &lt;code&gt;c()&lt;/code&gt;, &lt;code&gt;as.list()&lt;/code&gt;, &lt;code&gt;lapply()&lt;/code&gt;, &lt;code&gt;list()&lt;/code&gt; etc… base functions to accomplish this, without having to learn any new functions. You will need to learn just the special variables – &lt;code&gt;.N&lt;/code&gt; and &lt;code&gt;.SD&lt;/code&gt; at least. The equivalent in dplyr are &lt;code&gt;n()&lt;/code&gt; and &lt;code&gt;.&lt;/code&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;Joinsdplyr provides separate functions for each type of join where as data.table allows joins using the same syntax &lt;code&gt;DT[i, j, by]&lt;/code&gt; (and with reason). It also provides an equivalent &lt;code&gt;merge.data.table()&lt;/code&gt; function as an alternative.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    setkey(DT1, x, y)

    # 1. normal join
    DT1[DT2]            ## data.table syntax
    left_join(DT2, DT1) ## dplyr syntax

    # 2. select columns while join    
    DT1[DT2, .(z, i.mul)]
    left_join(select(DT2, x, y, mul), select(DT1, x, y, z))

    # 3. aggregate while join
    DT1[DT2, .(sum(z) * i.mul), by = .EACHI]
    DF1 %&amp;gt;% group_by(x, y) %&amp;gt;% summarise(z = sum(z)) %&amp;gt;% 
        inner_join(DF2) %&amp;gt;% mutate(z = z*mul) %&amp;gt;% select(-mul)

    # 4. update while join
    DT1[DT2, z := cumsum(z) * i.mul, by = .EACHI]
    ??

    # 5. rolling join
    DT1[DT2, roll = -Inf]
    ??

    # 6. other arguments to control output
    DT1[DT2, mult = "first"]
    ??
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Some might find a separate function for each joins much nicer (left, right, inner, anti, semi etc), whereas as others might like data.table’s &lt;code&gt;DT[i, j, by]&lt;/code&gt;, or &lt;code&gt;merge()&lt;/code&gt; which is similar to base R.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;However dplyr joins do just that. Nothing more. Nothing less.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;data.tables can select columns while joining (2), and in dplyr you will need to &lt;code&gt;select()&lt;/code&gt; first on both data.frames before to join as shown above. Otherwise you would materialiase the join with unnecessary columns only to remove them later and that is inefficient.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;data.tables can aggregate while joining (3) and also update while joining (4), using &lt;code&gt;by = .EACHI&lt;/code&gt; feature. Why materialse the entire join result to add/update just a few columns?&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;data.table is capable of rolling joins (5) – roll &lt;a href="https://stackoverflow.com/questions/18915219/r-update-with-value-of-previous-row-subject-to-condition/18915708#18915708"&gt;forward, LOCF&lt;/a&gt;, &lt;a href="https://stackoverflow.com/questions/23342647/how-to-match-by-nearest-date-from-two-data-frames/23342851#23342851"&gt;roll backward, NOCB&lt;/a&gt;, &lt;a href="https://stackoverflow.com/questions/27757220/creating-variable-in-r-data-frame-depending-on-another-data-frame/27763960#27763960"&gt;nearest&lt;/a&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;data.table also has &lt;code&gt;mult&lt;/code&gt; = argument which selects first, last or all matches (6).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;data.table has &lt;a href="https://stackoverflow.com/questions/23087358/why-is-allow-cartesian-required-at-times-when-when-joining-data-tables-with-dupl/23087759#23087759"&gt;&lt;code&gt;allow.cartesian = TRUE&lt;/code&gt;&lt;/a&gt; argument to protect from accidental invalid joins.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;Once again, the syntax is consistent with &lt;code&gt;DT[i, j, by]&lt;/code&gt; with additional arguments allowing for controlling the output further.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;do()&lt;/code&gt;…dplyr’s summarise is specially designed for functions that return a single value. If your function returns multiple/unequal values, you will have to resort to &lt;code&gt;do()&lt;/code&gt;. You have to know beforehand about all your functions return value.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    DT[, list(x[1], y[1]), by = z]                 ## data.table syntax
    DF %&amp;gt;% group_by(z) %&amp;gt;% summarise(x[1], y[1]) ## dplyr syntax
    DT[, list(x[1:2], y[1]), by = z]
    DF %&amp;gt;% group_by(z) %&amp;gt;% do(data.frame(.$x[1:2], .$y[1]))

    DT[, quantile(x, 0.25), by = z]
    DF %&amp;gt;% group_by(z) %&amp;gt;% summarise(quantile(x, 0.25))
    DT[, quantile(x, c(0.25, 0.75)), by = z]
    DF %&amp;gt;% group_by(z) %&amp;gt;% do(data.frame(quantile(.$x, c(0.25, 0.75))))

    DT[, as.list(summary(x)), by = z]
    DF %&amp;gt;% group_by(z) %&amp;gt;% do(data.frame(as.list(summary(.$x))))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;.SD&lt;/code&gt;‘s equivalent is .&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;In data.table, you can throw pretty much anything in &lt;code&gt;j&lt;/code&gt; – the only thing to remember is for it to return a list so that each element of the list gets converted to a column.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;In dplyr, cannot do that. Have to resort to &lt;code&gt;do()&lt;/code&gt; depending on how sure you are as to whether your function would always return a single value. And it is quite slow.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;Once again, data.table’s syntax is consistent with &lt;code&gt;DT[i, j, by]&lt;/code&gt;. We can just keep throwing expressions in &lt;code&gt;j&lt;/code&gt; without having to worry about these things.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;To summarise, we have particularly highlighted several instances where dplyr’s syntax is either inefficient, limited, or fails to make operations straightforward. This is, particularly because data.table gets quite a bit of backlash about “harder to read/learn” syntax.&lt;/p&gt;

&lt;p&gt;But it is important to realise its syntax and feature limitations as well. data.table has its quirks as well. We are also attempting to improve data.table’s joins as highlighted &lt;a href="https://stackoverflow.com/questions/27612859/joining-tables-based-on-different-column-names/27615377#27615377"&gt;here&lt;/a&gt;. But one should also consider the number of features that dplyr lacks in comparison to data.table.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;iv. Features&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We have pointed out most of the features &lt;a href="https://stackoverflow.com/questions/27511604/dplyr-on-data-table-am-i-really-using-data-table/27520688#27520688"&gt;here&lt;/a&gt; and also in this post. In addition:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;fread&lt;/strong&gt; – fast file reader has been available for a long time now.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;fwrite&lt;/strong&gt; – a parallelised fast file writer is now available. &lt;a href="https://www.h2o.ai/blog/fast-csv-writing-for-r/"&gt;See this&lt;/a&gt; post for a detailed explanation on the implementation and &lt;a href="https://github.com/Rdatatable/data.table/issues/1664"&gt;#1664&lt;/a&gt; for keeping track of further developments.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://gist.github.com/arunsrinivasan/dacb9d1cac301de8d9ff"&gt;Automatic indexing&lt;/a&gt; – another handy feature to optimise base R syntax as is, internally.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Ad-hoc grouping&lt;/strong&gt;: &lt;code&gt;dplyr&lt;/code&gt; automatically sorts the results by grouping variables during &lt;code&gt;summarise()&lt;/code&gt;, which may not be always desirable.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Numerous advantages in data.table joins (for speed / memory efficiency and syntax) mentioned above.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Non-equi joins&lt;/strong&gt;: Allows joins using other operators &lt;code&gt;&amp;lt;=&lt;/code&gt;, &lt;code&gt;&amp;lt;&lt;/code&gt;, &lt;code&gt;&amp;gt;&lt;/code&gt;, &lt;code&gt;&amp;gt;=&lt;/code&gt; along with all other advantages of data.table joins.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://raw.githubusercontent.com/wiki/Rdatatable/data.table/talks/EARL2014_OverlapRangeJoin_Arun.pdf"&gt;Overlapping range joins&lt;/a&gt; was implemented in data.table recently. Check &lt;a href="https://stackoverflow.com/questions/24480031/overlap-join-with-start-and-end-positions/25655497#25655497"&gt;this post&lt;/a&gt; for an overview with benchmarks.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;setorder()&lt;/code&gt; function in data.table that allows really fast reordering of data.tables by reference.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;dplyr provides interface to databases using the same syntax, which data.table does not at the moment.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;data.table&lt;/code&gt; provides faster equivalents of set operations (written by Jan Gorecki) – &lt;code&gt;fsetdiff&lt;/code&gt;, &lt;code&gt;fintersect&lt;/code&gt;, &lt;code&gt;funion&lt;/code&gt;, and &lt;code&gt;fsetequal&lt;/code&gt; with additional &lt;code&gt;all&lt;/code&gt; argument (as in SQL).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;data.table loads cleanly with no masking warnings and has a mechanism described &lt;a href="https://stackoverflow.com/questions/10527072/using-data-table-package-inside-my-own-package/10529888#10529888"&gt;here&lt;/a&gt; for &lt;code&gt;[.data.frame&lt;/code&gt; compatibility when passed to any R package. dplyr changes base functions &lt;code&gt;filter&lt;/code&gt;, &lt;code&gt;lag&lt;/code&gt;, and &lt;code&gt;[&lt;/code&gt; which can cause problems; e.g. &lt;a href="https://stackoverflow.com/questions/35022927/packages-with-the-same-function-name/35057612#35057612"&gt;here&lt;/a&gt; and &lt;a href="https://stackoverflow.com/questions/35327250/dplyr-masks-ggally-and-breaks-ggparcoord/35329418#35329418"&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Finally:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;On databases – there is no reason why data.table cannot provide similar interface, but this is not a priority now. It might get bumped up if users would very much like that feature, not sure.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;On parallelism – Everything is difficult, until someone goes ahead and does it. Of course it will take effort (being thread-safe).&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Progress is being made currently (in v1.9.7 devel) towards parallelising known time-consuming parts for incremental performance gains using &lt;code&gt;OpenMP&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  8. How to replace NA values with zeros in an R dataframe?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A simple example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt; m &amp;lt;- matrix(sample(c(NA, 1:10), 100, replace = TRUE), 10)
&amp;gt; d &amp;lt;- as.data.frame(m)
   V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1   4  3 NA  3  7  6  6 10  6   5
2   9  8  9  5 10 NA  2  1  7   2
3   1  1  6  3  6 NA  1  4  1   6
4  NA  4 NA  7 10  2 NA  4  1   8
5   1  2  4 NA  2  6  2  6  7   4
6  NA  3 NA NA 10  2  1 10  8   4
7   4  4  9 10  9  8  9  4 10  NA
8   5  8  3  2  1  4  5  9  4   7
9   3  9 10  1  9  9 10  5  3   3
10  4  2  2  5 NA  9  7  2  5   5

&amp;gt; d[is.na(d)] &amp;lt;- 0

&amp;gt; d
   V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1   4  3  0  3  7  6  6 10  6   5
2   9  8  9  5 10  0  2  1  7   2
3   1  1  6  3  6  0  1  4  1   6
4   0  4  0  7 10  2  0  4  1   8
5   1  2  4  0  2  6  2  6  7   4
6   0  3  0  0 10  2  1 10  8   4
7   4  4  9 10  9  8  9  4 10   0
8   5  8  3  2  1  4  5  9  4   7
9   3  9 10  1  9  9 10  5  3   3
10  4  2  2  5  0  9  7  2  5   5
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There’s no need to apply &lt;code&gt;apply&lt;/code&gt;. You should also take a look at &lt;code&gt;norm&lt;/code&gt; package. It has a lot of nice features for missing data analysis.&lt;/p&gt;

&lt;h3&gt;
  
  
  9. What are the differences between “=” and “&amp;lt;-” assignment operators in R?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The operator &lt;code&gt;&amp;lt;-&lt;/code&gt; can be used anywhere, whereas the operator &lt;code&gt;=&lt;/code&gt; is only allowed at the top level (e.g., in the complete expression typed at the command prompt) or as one of the subexpressions in a braced list of expressions. Let’s not put too fine a point on it: &lt;strong&gt;the R documentation is (subtly) wrong&lt;/strong&gt;. This is easy to show: we just need to find a counter-example of the &lt;code&gt;=&lt;/code&gt; operator that isn’t (a) at the top level, nor (b) a subexpression in a braced list of expressions (i.e. &lt;code&gt;{…; …}&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;Without further ado:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;x
# Error: object 'x' not found
sum((x = 1), 2)
# [1] 3
x
# [1] 1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Clearly we’ve performed an assignment, using &lt;code&gt;=&lt;/code&gt;, outside of contexts (a) and (b). So, why has the documentation of a core R language feature been wrong for decades? It’s because in R’s syntax the symbol = has two distinct meanings that get routinely conflated:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The first meaning is as an assignment operator. This is all we’ve talked about so far.&lt;/li&gt;
&lt;li&gt;The second meaning isn’t an operator but rather a syntax token that signals named argument passing in a function call. Unlike the &lt;code&gt;=&lt;/code&gt; operator it performs no action at runtime, it merely changes the way an expression is parsed.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let’s see. In any piece of code of the general form:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;‹function_name›(‹argname› = ‹value›, …)
‹function_name›(‹args›, ‹argname› = ‹value›, …)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;the &lt;code&gt;=&lt;/code&gt; is the token that defines named argument passing: it is not the assignment operator. Furthermore, &lt;code&gt;=&lt;/code&gt; is entirely forbidden in some syntactic contexts:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (‹var› = ‹value›) …
while (‹var› = ‹value›) …
for (‹var› = ‹value› in ‹value2›) …
for (‹var1› in ‹var2› = ‹value›) …
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Any of these will raise an error “unexpected ‘=’ in ‹bla›”. In any other context, &lt;code&gt;=&lt;/code&gt; refers to the assignment operator call. In particular, merely putting parentheses around the subexpression makes any of the above (a) valid, and (b) an assignment. For instance, the following performs assignment:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;median((x = 1 : 10))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But also:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (! (nf = length(from))) return()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now you might object that such code is atrocious (and you may be right). But this code is taken from the base::file.copy function (replacing &amp;lt;- with =) — it’s a pervasive pattern in much of the core R codebase.&lt;/p&gt;

&lt;p&gt;[= assignment is] allowed in only two places in the grammar: at the top level (as a complete program or user-typed expression); and when isolated from surrounding logical structure, by braces or an extra pair of parentheses. There is one additional difference between the &lt;code&gt;=&lt;/code&gt; and &lt;code&gt;&amp;lt;-&lt;/code&gt; operators: they call distinct functions. By default these functions do the same thing but you can override either of them separately to change the behaviour. By contrast, &lt;code&gt;&amp;lt;-&lt;/code&gt; and &lt;code&gt;-&amp;gt;&lt;/code&gt; (left-to-right assignment), though syntactically distinct, always call the same function. Overriding one also overrides the other. Knowing this is rarely practical &lt;a href="https://github.com/klmr/functional#a-concise-lambda-syntax"&gt;but it can be used for some fun shenanigans&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The difference in &lt;a href="https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/assignOps"&gt;assignment operators&lt;/a&gt; is clearer when you use them to set an argument value in a function call. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;median(x = 1:10)
x   
## Error: object 'x' not found
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this case, &lt;code&gt;x&lt;/code&gt; is declared within the scope of the function, so it does not exist in the user workspace.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;median(x &amp;lt;- 1:10)
x    
## [1]  1  2  3  4  5  6  7  8  9 10
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this case, &lt;code&gt;x&lt;/code&gt; is declared in the user workspace, so you can use it after the function call has been completed. There is a general preference among the R community for using &lt;code&gt;&amp;lt;-&lt;/code&gt; for assignment (other than in function signatures) for compatibility with (very) old versions of S-Plus. Note that the spaces help to clarify situations like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;x&amp;lt;-3
# Does this mean assignment?
x &amp;lt;- 3
# Or less than?
x &amp;lt; -3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Most R IDEs have keyboard shortcuts to make &lt;code&gt;&amp;lt;-&lt;/code&gt; easier to type. &lt;code&gt;Ctrl + =&lt;/code&gt; in Architect, &lt;code&gt;Alt + -&lt;/code&gt; in RStudio (&lt;code&gt;Option + -&lt;/code&gt; under macOS), &lt;code&gt;Shift + -&lt;/code&gt; (underscore) in emacs+ESS. If you prefer writing &lt;code&gt;=&lt;/code&gt; to &lt;code&gt;&amp;lt;-&lt;/code&gt; but want to use the more common assignment symbol for publicly released code (on CRAN, for example), then you can use one of the &lt;a href="https://www.rdocumentation.org/packages/formatR/versions/1.7/topics/tidy_source"&gt;&lt;code&gt;tidy_*&lt;/code&gt;&lt;/a&gt; functions in the &lt;code&gt;formatR&lt;/code&gt; package to automatically replace &lt;code&gt;=&lt;/code&gt; with &lt;code&gt;&amp;lt;-&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;library(formatR)
tidy_source(text = "x=1:5", arrow = TRUE)
## x &amp;lt;- 1:5
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The answer to the question “Why does &lt;code&gt;x &amp;lt;- y = 5&lt;/code&gt; throw an error but not &lt;code&gt;x &amp;lt;- y &amp;lt;- 5?&lt;/code&gt;” is “It’s down to the magic contained in the parser”. R’s syntax contains &lt;a href="http://shape-of-code.coding-guidelines.com/2012/02/29/parsing-r-code-freedom-of-expression-is-not-always-a-good-idea/"&gt;many ambiguous cases&lt;/a&gt; that have to be resolved one way or another. The parser chooses to resolve the bits of the expression in different orders depending on whether &lt;code&gt;=&lt;/code&gt; or &lt;code&gt;&amp;lt;-&lt;/code&gt; was used. To understand what is happening, you need to know that the assignment silently returns the value that was assigned. You can see that more clearly by explicitly printing, for example &lt;code&gt;print(x &amp;lt;- 2 + 3)&lt;/code&gt;. Secondly, it’s clearer if we use prefix notation for assignment. So&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;x &amp;lt;- 5
`&amp;lt;-`(x, 5)  #same thing

y = 5
`=`(y, 5)   #also the same thing
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The parser interprets &lt;code&gt;x &amp;lt;- y &amp;lt;- 5&lt;/code&gt; as&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;`&amp;lt;-`(x, `&amp;lt;-`(y, 5))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We might expect that &lt;code&gt;x &amp;lt;- y = 5&lt;/code&gt; would then be&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;`&amp;lt;-`(x, `=`(y, 5))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;but actually it gets interpreted as&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;`=`(`&amp;lt;-`(x, y), 5)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is because &lt;code&gt;=&lt;/code&gt; is lower precedence than &lt;code&gt;&amp;lt;-&lt;/code&gt;, as shown on the &lt;a href="https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/Syntax"&gt;&lt;code&gt;?Syntax&lt;/code&gt;&lt;/a&gt; help page.&lt;/p&gt;

&lt;h3&gt;
  
  
  10. How to convert a factor to integer\numeric without loss of information?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;See the Warning section of &lt;a href="https://mran.microsoft.com/"&gt;&lt;code&gt;?factor&lt;/code&gt;&lt;/a&gt;:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;In particular, &lt;code&gt;as.numeric&lt;/code&gt; applied to a factor is meaningless, and may happen by implicit coercion. To transform a factor &lt;code&gt;f&lt;/code&gt; to approximately its original numeric values, &lt;code&gt;as.numeric(levels(f))[f]&lt;/code&gt; is recommended and slightly more efficient than &lt;code&gt;as.numeric(as.character(f))&lt;/code&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The FAQ on R &lt;a href="https://cran.r-project.org/doc/FAQ/R-FAQ.html#How-do-I-convert-factors-to-numeric_003f"&gt;has similar advice&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why is &lt;code&gt;as.numeric(levels(f))[f]&lt;/code&gt; more efficent than &lt;code&gt;as.numeric(as.character(f))&lt;/code&gt;?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;as.numeric(as.character(f))&lt;/code&gt; is effectively &lt;code&gt;as.numeric(levels(f)[f])&lt;/code&gt;, so you are performing the conversion to numeric on &lt;code&gt;length(x)&lt;/code&gt; values, rather than on &lt;code&gt;nlevels(x)&lt;/code&gt; values. The speed difference will be most apparent for long vectors with few levels. If the values are mostly unique, there won’t be much difference in speed. However you do the conversion, this operation is unlikely to be the bottleneck in your code, so don’t worry too much about it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Some timings&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;library(microbenchmark)
microbenchmark(
  as.numeric(levels(f))[f],
  as.numeric(levels(f)[f]),
  as.numeric(as.character(f)),
  paste0(x),
  paste(x),
  times = 1e5
)
## Unit: microseconds
##                         expr   min    lq      mean median     uq      max neval
##     as.numeric(levels(f))[f] 3.982 5.120  6.088624  5.405  5.974 1981.418 1e+05
##     as.numeric(levels(f)[f]) 5.973 7.111  8.352032  7.396  8.250 4256.380 1e+05
##  as.numeric(as.character(f)) 6.827 8.249  9.628264  8.534  9.671 1983.694 1e+05
##                    paste0(x) 7.964 9.387 11.026351  9.956 10.810 2911.257 1e+05
##                     paste(x) 7.965 9.387 11.127308  9.956 11.093 2419.458 1e+05
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;R has a number of (undocumented) convenience functions for converting factors:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;as.character.factor&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;as.data.frame.factor&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;as.Date.factor&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;as.list.factor&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;as.vector.factor&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;…&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;But annoyingly, there is nothing to handle the factor -&amp;gt; numeric conversion. We would suggest overcoming this omission with the definition of your own idiomatic function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;as.numeric.factor &amp;lt;- function(x) {as.numeric(levels(x))[x]}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;that you can store at the beginning of your script, or even better in your &lt;a href="https://www.statmethods.net/interface/customizing.html"&gt;&lt;code&gt;.Rprofile&lt;/code&gt;&lt;/a&gt; file.&lt;/p&gt;

&lt;h3&gt;
  
  
  11. How to plot two graphs in the same plot in R?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;lines()&lt;/code&gt; or &lt;code&gt;points()&lt;/code&gt; will add to the existing graph, but will not create a new window. So you’d need to do&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;plot(x,y1,type="l",col="red")
lines(x,y2,col="green")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can also use &lt;code&gt;par&lt;/code&gt; and plot on the same graph but different axis. Something as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;plot( x, y1, type="l", col="red" )
par(new=TRUE)
plot( x, y2, type="l", col="green" )
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you read in detail about &lt;code&gt;par&lt;/code&gt; in &lt;code&gt;R&lt;/code&gt;, you will be able to generate really interesting graphs.&lt;/p&gt;

&lt;h3&gt;
  
  
  12. What is the difference between require() and library()?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It is probably best to avoid using &lt;code&gt;require()&lt;/code&gt; unless you actually will be using the value it returns e.g in some error checking loop such as given by Thierry.&lt;/p&gt;

&lt;p&gt;In most other cases it is better to use &lt;code&gt;library()&lt;/code&gt;, because this will give an error message at package loading time if the package is not available. &lt;code&gt;require()&lt;/code&gt; will just fail without an error if the package is not there. This is the best time to find out if the package needs to be installed (or perhaps doesn’t even exist because it is spelled wrong). Getting error feedback early and at the relevant time will avoid possible headaches with tracking down why later code fails when it attempts to use library routines.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;According to the documentation for both functions (accessed by putting a &lt;code&gt;?&lt;/code&gt; before the function name and hitting enter), &lt;code&gt;require&lt;/code&gt; is used inside functions, as it outputs a warning and continues if the package is not found, whereas &lt;code&gt;library&lt;/code&gt; will throw an error.&lt;/p&gt;

&lt;h3&gt;
  
  
  13. How to deal with “package ‘xxx’ is not available (for R version x.y.z)” warning?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;i. You can’t spell&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The first thing to test is have you spelled the name of the package correctly? Package names are case sensitive in R.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ii. You didn’t look in the right repository&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Next, you should check to see if the package is available. Type&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;setRepositories()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;See also &lt;a href="https://www.rdocumentation.org/packages/utils/versions/3.6.2/topics/setRepositories"&gt;?setRepositories&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;To see which repositories R will look in for your package, and optionally select some additional ones. At the very least, you will usually want &lt;code&gt;CRAN&lt;/code&gt; to be selected, and &lt;code&gt;CRAN (extras)&lt;/code&gt; if you use Windows, and the &lt;code&gt;Bioc*&lt;/code&gt; repositories if you do any biological analyses. To permanently change this, add a line like &lt;code&gt;setRepositories(ind = c(1:6, 8))&lt;/code&gt; to your &lt;a href="https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/Startup"&gt;&lt;code&gt;Rprofile.site&lt;/code&gt;&lt;/a&gt; file.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;iii. The package is not in the repositories you selected&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Return all the available packages using&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ap &amp;lt;- available.packages()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;See also &lt;a href="https://stackoverflow.com/questions/7381932/names-of-rs-available-packages"&gt;Names of R’s available packages&lt;/a&gt;, &lt;a href="https://www.rdocumentation.org/packages/utils/versions/3.6.2/topics/available.packages"&gt;?available.packages&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Since this is a large matrix, you may wish to use the data viewer to examine it. Alternatively, you can quickly check to see if the package is available by testing against the row names.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;View(ap)
"foobarbaz" %in% rownames(ap)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Alternatively, the list of available packages can be seen in a browser for &lt;a href="https://cran.r-project.org/web/packages/available_packages_by_name.html"&gt;CRAN&lt;/a&gt;, &lt;a href="http://www.stats.ox.ac.uk/pub/RWin/bin/windows/contrib/"&gt;CRAN (extras)&lt;/a&gt;, &lt;a href="https://www.bioconductor.org/packages/release/BiocViews.html#___Software"&gt;, &lt;/a&gt;&lt;a href="https://r-forge.r-project.org/softwaremap/full_list.php"&gt;R-forge&lt;/a&gt;, &lt;a href="http://rforge.net/"&gt;RForge&lt;/a&gt;, and &lt;a href="https://github.com/search?l=R&amp;amp;q=R&amp;amp;type=Repositories"&gt;github&lt;/a&gt;. Another possible warnings message you may get when interacting with CRAN mirrors is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Warning: unable to access index for repository
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Which may indicate the selected CRAN repository is currently be unavailable. You can select a different mirror with &lt;code&gt;chooseCRANmirror()&lt;/code&gt; and try the installation again. There are several reasons why a package may not be available.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;iv. You don’t want a package&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Perhaps you don’t really want a package. It is common to be confused about the difference between &lt;a href="https://cran.r-project.org/doc/FAQ/R-FAQ.html#What-is-the-difference-between-package-and-library_003f"&gt;a package and a library&lt;/a&gt;, or a package and a dataset.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;A package is a standardized collection of material extending R, e.g. providing code, data, or documentation. A library is a place (directory) where R knows to find packages it can use&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;To see available datasets, type&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;data()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;v. R or Bioconductor is out of date&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It may have a dependency on a more recent version of R (or one of the packages that it imports/depends upon does). Look at&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ap["foobarbaz", "Depends"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and consider updating your R installation to the current version. On Windows, this is most easily done via the &lt;a href="https://cran.r-project.org/web/packages/installr/index.html"&gt;&lt;code&gt;installr&lt;/code&gt;&lt;/a&gt; package.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;library(installr)
updateR()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;(Of course, you may need to &lt;code&gt;install.packages("installr")&lt;/code&gt; first.) Equivalently for Bioconductor packages, you may need to update your Bioconductor installation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;source("http://bioconductor.org/biocLite.R")
biocLite("BiocUpgrade")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;vi. The package is out of date&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It may have been &lt;a href="https://cran.r-project.org/src/contrib/Archive/"&gt;archived&lt;/a&gt; (if it is no longer maintained and no longer passes &lt;a href="https://www.rdocumentation.org/packages/utils/versions/3.6.2/topics/PkgUtils"&gt;&lt;code&gt;R CMD check&lt;/code&gt;&lt;/a&gt; tests). In this case, you can load an old version of the package using &lt;a href="https://www.rdocumentation.org/packages/remotes/versions/2.2.0/topics/install_version"&gt;&lt;code&gt;install_version()&lt;/code&gt;&lt;/a&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;library(remotes)
install_version("foobarbaz", "0.1.2")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;An alternative is to install from the github CRAN mirror.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;library(remotes)
install_github("cran/foobarbaz")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;vii. There is no Windows/OS X/Linux binary&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It may not have a &lt;a href="https://cran.r-project.org/bin/windows/contrib/3.2/ReadMe"&gt;Windows binary&lt;/a&gt; due to requiring additional software that CRAN does not have. Additionally, some packages are available only via the sources for some or all platforms. In this case, there may be a version in the &lt;code&gt;CRAN (extras)&lt;/code&gt; repository (see &lt;code&gt;setRepositories&lt;/code&gt; above). If the package requires compiling code (e.g. C, C++, FORTRAN) then on Windows install &lt;a href="https://cran.r-project.org/bin/windows/Rtools/"&gt;Rtools&lt;/a&gt; or on OS X install the &lt;a href="https://stackoverflow.com/questions/9329243/how-to-install-xcode-command-line-tools"&gt;developer tools&lt;/a&gt; accompanying XCode, and install the source version of the package via:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;install.packages("foobarbaz", type = "source")

# Or equivalently, for Bioconductor packages:
source("http://bioconductor.org/biocLite.R")
biocLite("foobarbaz", type = "source")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;On CRAN, you can tell if you’ll need special tools to build the package from source by looking at the &lt;code&gt;NeedsCompilation&lt;/code&gt; flag in the description. &lt;strong&gt;8. The package is on github/Bitbucket/Gitorious&lt;/strong&gt; It may have a repository on Github/Bitbucket/Gitorious. These packages require the &lt;a href="https://cran.r-project.org/web/packages/remotes/index.html"&gt;remotes&lt;/a&gt; package to install.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;library(remotes)
install_github("packageauthor/foobarbaz")
install_bitbucket("packageauthor/foobarbaz")
install_gitorious("packageauthor/foobarbaz")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;(As with &lt;code&gt;installr&lt;/code&gt;, you may need to &lt;code&gt;install.packages("remotes")&lt;/code&gt; first.)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;viii. There is no source version of the package&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Although the binary version of your package is available, the source version is not. You can turn off this check by setting&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;options(install.packages.check.source = "no")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;as described in &lt;a href="https://stackoverflow.com/questions/13132111/my-package-doesnt-work-for-r-2-15-2/13223715#13223715"&gt;this SO answer by imanuelc&lt;/a&gt; and the Details section of &lt;a href="https://www.rdocumentation.org/packages/utils/versions/3.6.2/topics/install.packages"&gt;&lt;code&gt;?install.packages&lt;/code&gt;&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ix. The package is in a non-standard repository&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Your package is in a non-standard repository (e.g. &lt;a href="https://stackoverflow.com/questions/13807729/package-rbbg-is-not-available-for-r-version-2-15-2"&gt;&lt;code&gt;Rbbg&lt;/code&gt;&lt;/a&gt;). Assuming that it is reasonably compliant with CRAN standards, you can still download it using &lt;code&gt;install.packages;&lt;/code&gt; you just have to specify the repository URL.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;install.packages("Rbbg", repos = "http://r.findata.org")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;RHIPE&lt;/code&gt; on the other hand isn’t in a CRAN-like repository and has its own installation instructions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;In Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;These are the 13 most commonly asked R programming questions. If you have any suggestions or any confusion, please comment below. If you need any help, we will be glad to help you.&lt;/p&gt;

&lt;p&gt;We, at &lt;a href="https://www.truemark.dev/"&gt;Truemark&lt;/a&gt;, provide services like web and mobile app development, digital marketing, and website development. So, if you need any help and want to work with us, please feel free to contact us.&lt;/p&gt;

&lt;p&gt;Hope this article helped you.&lt;/p&gt;

&lt;p&gt;This post was first published on &lt;a href="https://thedevpost.com/blog/13-most-asked-r-programming-questions/"&gt;DevpostbyTruemark&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>r</category>
    </item>
    <item>
      <title>10 Most Asked Questions About C++</title>
      <dc:creator>KiranPoudel98</dc:creator>
      <pubDate>Fri, 23 Oct 2020 07:50:55 +0000</pubDate>
      <link>https://forem.com/truemark/10-most-asked-questions-about-c-19a5</link>
      <guid>https://forem.com/truemark/10-most-asked-questions-about-c-19a5</guid>
      <description>&lt;p&gt;C++ is a general-purpose high-level programming language developed as an extension of C language. It is a cross-platform programming language used to create high-performance applications. And, here we have prepared a list of the most commonly asked questions about C++.&lt;/p&gt;

&lt;h2&gt;
  
  
  10 Most Asked Questions About C++
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1. What is the “–&amp;gt;” operator in C+ array?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;--&amp;gt;&lt;/code&gt; is not an operator. It is in fact two separate operators, &lt;code&gt;--&lt;/code&gt; and &lt;code&gt;&amp;gt;&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The conditional’s code decrements &lt;code&gt;x&lt;/code&gt;, while returning &lt;code&gt;x&lt;/code&gt;‘s original (not decremented) value, and then compares the original value with 0 using the &lt;code&gt;&amp;gt;&lt;/code&gt; operator.&lt;/p&gt;

&lt;p&gt;To better understand, the statement could be written as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;while( (x--) &amp;gt; 0 )
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;For something completely different… &lt;code&gt;x&lt;/code&gt; slides to &lt;code&gt;0&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;while (x --\
            \
             \
              \
               &amp;gt; 0)
     printf("%d ", x);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2. What are the differences between a pointer variable and a reference variable in C++?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A pointer can be re-assigned: &lt;code&gt;int x = 5; int y = 6; int *p; p = &amp;amp;x; p = &amp;amp;y; *p = 10; assert(x == 5); assert(y == 10);&lt;/code&gt; . A reference cannot, and must be assigned at initialization: &lt;code&gt;int x = 5; int y = 6; int &amp;amp;r = x;&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;A pointer has its own memory address and size on the stack (4 bytes on x86), whereas a reference shares the same memory address (with the original variable) but also takes up some space on the stack. Since a reference has the same address as the original variable itself, it is safe to think of a reference as another name for the same variable.&lt;/p&gt;

&lt;p&gt;Note: What a pointer points to can be on the stack or heap. But this doesn’t mean that a pointer must point to the stack. A pointer is just a variable that holds a memory address. This variable is on the stack. Since a reference has its own space on the stack, and since the address is the same as the variable it references. This implies that there is a real address of a reference that the compiler will not tell you. &lt;code&gt;int x = 0; int &amp;amp;r = x; int *p = &amp;amp;x; int *p2 = &amp;amp;r; assert(p == p2);&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;You can have pointers to pointers to pointers offering extra levels of indirection. Whereas references only offer one level of indirection. &lt;code&gt;int x = 0; int y = 0; int *p = &amp;amp;x; int *q = &amp;amp;y; int **pp = &amp;amp;p; pp = &amp;amp;q;//*pp = q **pp = 4; assert(y == 4); assert(x == 0);&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;A pointer can be assigned &lt;code&gt;nullptr&lt;/code&gt; directly, whereas reference cannot. If you try hard enough, and you know how, you can make the address of a reference &lt;code&gt;nullptr&lt;/code&gt;. Likewise, if you try hard enough, you can have a reference to a pointer, and then that reference can contain &lt;code&gt;nullptr&lt;/code&gt;. &lt;code&gt;int *p = nullptr; int &amp;amp;r = nullptr; &amp;lt;--- compiling error int &amp;amp;r = *p; &amp;lt;--- likely no compiling error, especially if the nullptr is hidden behind a function call, yet it refers to a non-existent int at address 0&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Pointers can iterate over an array; you can use &lt;code&gt;++&lt;/code&gt; to go to the next item that a pointer is pointing to, and &lt;code&gt;+ 4&lt;/code&gt; to go to the 5th element. This is no matter what size the object is that the pointer points to.&lt;/p&gt;

&lt;p&gt;A pointer needs to be de-referenced with &lt;code&gt;*&lt;/code&gt; to access the memory location it points to, whereas a reference can be used directly. A pointer to a class/struct uses &lt;code&gt;-&amp;gt;&lt;/code&gt; to access it’s members whereas a reference uses a ..&lt;/p&gt;

&lt;p&gt;References cannot be stuffed into an array, whereas pointers can be.&lt;/p&gt;

&lt;p&gt;Const references can be bound to temporaries. Pointers cannot (not without some indirection): &lt;code&gt;const int &amp;amp;x = int(12); //legal C++ int *y = &amp;amp;int(12); //illegal to dereference a temporary&lt;/code&gt;. This makes const&amp;amp; safer for use in argument lists and so forth.&lt;/p&gt;

&lt;h3&gt;
  
  
  3. How to iterate over the words of a string?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;For what it’s worth, here’s a way to extract tokens from an input string, relying only on standard library facilities. It’s an example of the power and elegance behind the design of the STL.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;string&amp;gt;
#include &amp;lt;sstream&amp;gt;
#include &amp;lt;algorithm&amp;gt;
#include &amp;lt;iterator&amp;gt;

int main() {
    using namespace std;
    string sentence = "And I feel fine...";
    istringstream iss(sentence);
    copy(istream_iterator&amp;lt;string&amp;gt;(iss),
         istream_iterator&amp;lt;string&amp;gt;(),
         ostream_iterator&amp;lt;string&amp;gt;(cout, "\n"));
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Instead of copying the extracted tokens to an output stream, one could insert them into a container, using the same generic &lt;a href="https://en.cppreference.com/w/cpp/algorithm/copy"&gt;&lt;code&gt;copy&lt;/code&gt;&lt;/a&gt; algorithm.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;vector&amp;lt;string&amp;gt; tokens;
copy(istream_iterator&amp;lt;string&amp;gt;(iss),
     istream_iterator&amp;lt;string&amp;gt;(),
     back_inserter(tokens));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;or create the &lt;code&gt;vector&lt;/code&gt; directly:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;vector&amp;lt;string&amp;gt; tokens{istream_iterator&amp;lt;string&amp;gt;{iss},
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Use this to split string by a delimiter. First put the results in a pre-constructed vector, the second returns a new vector.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#include &amp;lt;string&amp;gt;
#include &amp;lt;sstream&amp;gt;
#include &amp;lt;vector&amp;gt;
#include &amp;lt;iterator&amp;gt;

template &amp;lt;typename Out&amp;gt;
void split(const std::string &amp;amp;s, char delim, Out result) {
    std::istringstream iss(s);
    std::string item;
    while (std::getline(iss, item, delim)) {
        *result++ = item;
    }
}

std::vector&amp;lt;std::string&amp;gt; split(const std::string &amp;amp;s, char delim) {
    std::vector&amp;lt;std::string&amp;gt; elems;
    split(s, delim, std::back_inserter(elems));
    return elems;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that this solution does not skip empty tokens, so the following will find 4 items, one of which is empty:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;std::vector&amp;lt;std::string&amp;gt; x = split("one:two::three", ':');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  4. What does the explicit keyword mean?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The compiler is allowed to make one implicit conversion to resolve the parameters to a function. What this means is that the compiler can use constructors callable with a &lt;strong&gt;single parameter&lt;/strong&gt; to convert from one type to another in order to get the right type for a parameter.&lt;/p&gt;

&lt;p&gt;Here’s an example class with a constructor that can be used for implicit conversions:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Foo
{
public:
  // single parameter constructor, can be used as an implicit conversion
  Foo (int foo) : m_foo (foo) 
  {
  }

  int GetFoo () { return m_foo; }

private:
  int m_foo;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here’s a simple function that takes a &lt;code&gt;Foo&lt;/code&gt; object:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;void DoBar (Foo foo)
{
  int i = foo.GetFoo ();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and here’s where the &lt;code&gt;DoBar&lt;/code&gt; function is called.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int main ()
{
  DoBar (42);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The argument is not a &lt;code&gt;Foo&lt;/code&gt; object, but an &lt;code&gt;int&lt;/code&gt;. However, there exists a constructor for &lt;code&gt;Foo&lt;/code&gt; that takes an &lt;code&gt;int&lt;/code&gt; so this constructor can be used to convert the parameter to the correct type.&lt;/p&gt;

&lt;p&gt;The compiler is allowed to do this once for each parameter.&lt;/p&gt;

&lt;p&gt;Prefixing the &lt;code&gt;explicit&lt;/code&gt; keyword to the constructor prevents the compiler from using that constructor for implicit conversions. Adding it to the above class will create a compiler error at the function call &lt;code&gt;DoBar (42)&lt;/code&gt;. It is now necessary to call for conversion explicitly with &lt;code&gt;DoBar (Foo (42))&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The reason you might want to do this is to avoid accidental construction that can hide bugs. Contrived example:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;You have a &lt;code&gt;MyString(int size)&lt;/code&gt; class with a constructor that constructs a string of the given size. You have a function &lt;code&gt;print(const MyString&amp;amp;)&lt;/code&gt;, and you call &lt;code&gt;print(3)&lt;/code&gt; (when you actually intended to call &lt;code&gt;print("3")&lt;/code&gt;). You expect it to print “3”, but it prints an empty string of length 3 instead.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Suppose, you have a class &lt;code&gt;String&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class String {
public:
    String(int n); // allocate n bytes to the String object
    String(const char *p); // initializes object with char *p
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, if you try:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;String mystring = 'x';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The character &lt;code&gt;'x'&lt;/code&gt; will be implicitly converted to &lt;code&gt;int&lt;/code&gt; and then the &lt;code&gt;String(int)&lt;/code&gt; constructor will be called. But, this is not what the user might have intended. So, to prevent such conditions, we shall define the constructor as &lt;code&gt;explicit&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class String {
public:
    explicit String (int n); //allocate n bytes
    String(const char *p); // initialize sobject with string p
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  5. Why is “using namespace std;” considered bad practice?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This is not related to performance at all. But consider this: you are using two libraries called Foo and Bar:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using namespace foo;
using namespace bar;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Everything works fine, and you can call &lt;code&gt;Blah()&lt;/code&gt; from Foo and &lt;code&gt;Quux()&lt;/code&gt; from Bar without problems. But one day you upgrade to a new version of Foo 2.0, which now offers a function called &lt;code&gt;Quux()&lt;/code&gt;. Now you’ve got a conflict: Both Foo 2.0 and Bar import &lt;code&gt;Quux()&lt;/code&gt; into your global namespace. This is going to take some effort to fix, especially if the function parameters happen to match.&lt;/p&gt;

&lt;p&gt;If you had used &lt;code&gt;foo::Blah()&lt;/code&gt; and &lt;code&gt;bar::Quux()&lt;/code&gt;, then the introduction of foo::Quux() would have been a non-event.&lt;/p&gt;

&lt;h3&gt;
  
  
  6. How do you set, clear, and toggle a single bit?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Setting a bit&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Use the bitwise OR operator (|) to set a bit.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;number |= 1UL &amp;lt;&amp;lt; n;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That will set the &lt;code&gt;n&lt;/code&gt;th bit of &lt;code&gt;number&lt;/code&gt;. &lt;code&gt;n&lt;/code&gt; should be zero, if you want to set the 1st bit and so on upto &lt;code&gt;n-1&lt;/code&gt;, if you want to set the &lt;code&gt;n&lt;/code&gt;th bit.&lt;/p&gt;

&lt;p&gt;Use &lt;code&gt;1ULL&lt;/code&gt; if &lt;code&gt;number&lt;/code&gt; is wider than &lt;code&gt;unsigned long;&lt;/code&gt; promotion of &lt;code&gt;1UL &amp;lt;&amp;lt; n&lt;/code&gt; doesn’t happen until after evaluating &lt;code&gt;1UL &amp;lt;&amp;lt; n&lt;/code&gt; where it’s undefined behaviour to shift by more than the width of a &lt;code&gt;long&lt;/code&gt;. The same applies to all the rest of the examples.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Clearing a bit&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Use the bitwise AND operator (&amp;amp;) to clear a bit.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;number &amp;amp;= ~(1UL &amp;lt;&amp;lt; n);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That will clear the &lt;code&gt;n&lt;/code&gt;th bit of &lt;code&gt;number&lt;/code&gt;. You must invert the bit string with the bitwise NOT operator (~), then AND it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Toggling a bit&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The XOR operator (^) can be used to toggle a bit.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;number ^= 1UL &amp;lt;&amp;lt; n;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That will toggle the &lt;code&gt;n&lt;/code&gt;th bit of &lt;code&gt;number&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Checking a bit&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;To check a bit, shift the number n to the right, then bitwise AND it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;bit = (number &amp;gt;&amp;gt; n) &amp;amp; 1U;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That will put the value of the &lt;code&gt;n&lt;/code&gt;th bit of &lt;code&gt;number&lt;/code&gt; into the variable &lt;code&gt;bit&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Changing the nth bit to x&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Setting the &lt;code&gt;n&lt;/code&gt;th bit to either &lt;code&gt;1&lt;/code&gt; or &lt;code&gt;0&lt;/code&gt; can be achieved with the following on a 2’s complement C++ implementation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;number ^= (-x ^ number) &amp;amp; (1UL &amp;lt;&amp;lt; n);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Bit &lt;code&gt;n&lt;/code&gt; will be set if &lt;code&gt;x&lt;/code&gt; is &lt;code&gt;1&lt;/code&gt;, and cleared if &lt;code&gt;x&lt;/code&gt; is &lt;code&gt;0&lt;/code&gt;. If &lt;code&gt;x&lt;/code&gt; has some other value, you get garbage. &lt;code&gt;x = !!x&lt;/code&gt; will booleanize it to 0 or 1.&lt;/p&gt;

&lt;p&gt;To make this independent of 2’s complement negation behaviour (where &lt;code&gt;-1&lt;/code&gt; has all bits set, unlike on a 1’s complement or sign/magnitude C++ implementation), use unsigned negation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;number ^= (-(unsigned long)x ^ number) &amp;amp; (1UL &amp;lt;&amp;lt; n);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;or&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;unsigned long newbit = !!x;    // Also booleanize to force 0 or 1
number ^= (-newbit ^ number) &amp;amp; (1UL &amp;lt;&amp;lt; n);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It’s generally a good idea to use unsigned types for portable bit manipulation.&lt;/p&gt;

&lt;p&gt;or&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;number = (number &amp;amp; ~(1UL &amp;lt;&amp;lt; n)) | (x &amp;lt;&amp;lt; n);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;(number &amp;amp; ~(1UL &amp;lt;&amp;lt; n))&lt;/code&gt; will clear the &lt;code&gt;n&lt;/code&gt;th bit and &lt;code&gt;(x &amp;lt;&amp;lt; n)&lt;/code&gt; will set the &lt;code&gt;n&lt;/code&gt;th bit to &lt;code&gt;x&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;It’s also generally a good idea not to copy/paste code in general and so many people use preprocessor macros or some sort of encapsulation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Using the Standard C++ Library: &lt;a href="https://en.cppreference.com/w/cpp/utility/bitset"&gt;&lt;code&gt;std::bitset&amp;lt;N&amp;gt;&lt;/code&gt;&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Or the &lt;a href="https://en.wikipedia.org/wiki/Boost_%28C%2B%2B_libraries%29"&gt;Boost&lt;/a&gt; version: &lt;a href="https://www.boost.org/doc/libs/1_74_0/libs/dynamic_bitset/dynamic_bitset.html"&gt;boost::dynamic_bitset&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;There is no need to roll your own:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#include &amp;lt;bitset&amp;gt;
#include &amp;lt;iostream&amp;gt;

int main()
{
    std::bitset&amp;lt;5&amp;gt; x;

    x[1] = 1;
    x[2] = 0;
    // Note x[0-4]  valid

    std::cout &amp;lt;&amp;lt; x &amp;lt;&amp;lt; std::endl;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[Alpha:] &amp;gt; ./a.out
00010
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The Boost version allows a runtime sized bitset compared with a &lt;a href="https://en.wikipedia.org/wiki/C%2B%2B_Standard_Library"&gt;standard library&lt;/a&gt; compile-time sized bitset.&lt;/p&gt;

&lt;h3&gt;
  
  
  7. When should static_cast, dynamic_cast, const_cast, and reinterpret_cast be used?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;static_cast&lt;/code&gt; is the first cast you should attempt to use. It does things like implicit conversions between types (such as &lt;code&gt;int&lt;/code&gt; to &lt;code&gt;float&lt;/code&gt; or pointer to &lt;code&gt;void*&lt;/code&gt;), and it can also call explicit conversion functions (or implicit ones). In many cases, explicitly stating &lt;code&gt;static_cast&lt;/code&gt; isn’t necessary, but it’s important to note that the &lt;code&gt;T(something)&lt;/code&gt; syntax is equivalent to &lt;code&gt;(T)something&lt;/code&gt; and should be avoided (more on that later). A &lt;code&gt;T(something, something_else)&lt;/code&gt; is safe, however, and guaranteed to call the constructor.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;static_cast&lt;/code&gt; can also cast through inheritance hierarchies. It is unnecessary when casting upwards (towards a base class), but when casting downwards it can be used as long as it doesn’t cast through &lt;code&gt;virtual&lt;/code&gt; inheritance. It does not do checking, however, and it is undefined behavior to &lt;code&gt;static_cast&lt;/code&gt; down a hierarchy to a type that isn’t actually the type of the object.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;const_cast&lt;/code&gt; can be used to remove or add &lt;code&gt;const&lt;/code&gt; to a variable; no other C++ cast is capable of removing it (not even &lt;code&gt;reinterpret_cast&lt;/code&gt;). It is important to note that modifying a formerly &lt;code&gt;const&lt;/code&gt; value is only undefined if the original variable is &lt;code&gt;const;&lt;/code&gt; if you use it to take the &lt;code&gt;const&lt;/code&gt; off a reference to something that wasn’t declared with &lt;code&gt;const&lt;/code&gt;, it is safe. This can be useful when overloading member functions based on &lt;code&gt;const&lt;/code&gt;, for instance. It can also be used to add const to an object, such as to call a member function overload.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;const_cast&lt;/code&gt; also works similarly on &lt;code&gt;volatile&lt;/code&gt;, though that’s less common.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;dynamic_cast&lt;/code&gt; is exclusively used for handling polymorphism. You can cast a pointer or reference to any polymorphic type to any other class type (a polymorphic type has at least one virtual function, declared or inherited). You can use it for more than just casting downwards – you can cast sideways or even up another chain. The &lt;code&gt;dynamic_cast&lt;/code&gt; will seek out the desired object and return it if possible. If it can’t, it will return &lt;code&gt;nullptr&lt;/code&gt; in the case of a pointer, or throw &lt;code&gt;std::bad_cast&lt;/code&gt; in the case of a reference.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;dynamic_cast&lt;/code&gt; has some limitations, though. It doesn’t work if there are multiple objects of the same type in the inheritance hierarchy (the so-called ‘dreaded diamond’) and you aren’t using &lt;code&gt;virtual&lt;/code&gt; inheritance. It also can only go through public inheritance – it will always fail to travel through &lt;code&gt;protected&lt;/code&gt; or &lt;code&gt;private&lt;/code&gt; inheritance. This is rarely an issue, however, as such forms of inheritance are rare.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;reinterpret_cast&lt;/code&gt; is the most dangerous cast, and should be used very sparingly. It turns one type directly into another — such as casting the value from one pointer to another, or storing a pointer in an &lt;code&gt;int&lt;/code&gt;, or all sorts of other nasty things.&lt;/p&gt;

&lt;p&gt;Largely, the only guarantee you get with reinterpret_cast is that normally if you cast the result back to the original type, you will get the exact same value (but not if the intermediate type is smaller than the original type). There are a number of conversions that reinterpret_cast cannot do, too. It’s used primarily for particularly weird conversions and bit manipulations, like turning a raw data stream into actual data or storing data in the low bits of a pointer to aligned data.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;C-style cast&lt;/strong&gt; and &lt;strong&gt;function-style&lt;/strong&gt; cast are casts using &lt;code&gt;(type)object or type(object),&lt;/code&gt; respectively, and are functionally equivalent. They are defined as the first of the following which succeeds:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;const_cast&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;static_cast&lt;/code&gt; (though ignoring access restrictions)&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;static_cast&lt;/code&gt; (see above), then &lt;code&gt;const_cast&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;&lt;code&gt;reinterpret_cast&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;reinterpret_cast&lt;/code&gt;, then &lt;code&gt;const_cast&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;It can therefore be used as a replacement for other casts in some instances, but can be extremely dangerous because of the ability to devolve into a &lt;code&gt;reinterpret_cast&lt;/code&gt;, and the latter should be preferred when explicit casting is needed, unless you are sure &lt;code&gt;static_cast&lt;/code&gt; will succeed or &lt;code&gt;reinterpret_cast&lt;/code&gt; will fail. Even then, consider the longer, more explicit option.&lt;/p&gt;

&lt;p&gt;C-style casts also ignore access control when performing a &lt;code&gt;static_cast&lt;/code&gt;, which means that they have the ability to perform an operation that no other cast can. This is mostly a kludge, though, and is just another reason to avoid C-style casts.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Additional Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Use &lt;code&gt;dynamic_cast&lt;/code&gt; for converting pointers/references within an inheritance hierarchy.&lt;/p&gt;

&lt;p&gt;Use &lt;code&gt;static_cast&lt;/code&gt; for ordinary type conversions.&lt;/p&gt;

&lt;p&gt;Use &lt;code&gt;reinterpret_cast&lt;/code&gt; for low-level reinterpreting of bit patterns. Use with extreme caution.&lt;/p&gt;

&lt;p&gt;Use &lt;code&gt;const_cast&lt;/code&gt; for casting away &lt;code&gt;const/volatile&lt;/code&gt;. Avoid this unless you are stuck using a const-incorrect API.&lt;/p&gt;

&lt;h3&gt;
  
  
  8. What is the difference between #include  and #include “filename”?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In practice, the difference is in the location where the preprocessor searches for the included file.&lt;/p&gt;

&lt;p&gt;For &lt;code&gt;#include &amp;lt;filename&amp;gt;&lt;/code&gt;, the preprocessor searches in an implementation-dependent manner, normally in search directories pre-designated by the compiler/IDE. This method is normally used to include standard library header files.&lt;/p&gt;

&lt;p&gt;For &lt;code&gt;#include "filename"&lt;/code&gt;, the preprocessor searches first in the same directory as the file containing the directive and then follows the search path used for the &lt;code&gt;#include &amp;lt;filename&amp;gt;&lt;/code&gt; form. This method is normally used to include programmer-defined header files.&lt;/p&gt;

&lt;h3&gt;
  
  
  9. Why is reading lines from stdin much slower in C++ than Python?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;By default, &lt;code&gt;cin&lt;/code&gt; is synchronized with stdio, which causes it to avoid any input buffering. If you add this to the top of your main, you should see much better performance:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;std::ios_base::sync_with_stdio(false);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Normally, when an input stream is buffered, instead of reading one character at a time, the stream will be read in larger chunks. This reduces the number of system calls, which are typically relatively expensive. However, since the &lt;code&gt;FILE*&lt;/code&gt; based &lt;code&gt;stdio&lt;/code&gt; and &lt;code&gt;iostreams&lt;/code&gt; often have separate implementations and therefore separate buffers, this could lead to a problem if both were used together. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int myvalue1;
cin &amp;gt;&amp;gt; myvalue1;
int myvalue2;
scanf("%d",&amp;amp;myvalue2);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If more input was read by &lt;code&gt;cin&lt;/code&gt; than it actually needed, then the second integer value wouldn’t be available for the &lt;code&gt;scanf&lt;/code&gt; function, which has its own independent buffer. This would lead to unexpected results.&lt;/p&gt;

&lt;p&gt;To avoid this, by default, streams are synchronized with &lt;code&gt;stdio&lt;/code&gt;. One common way to achieve this is to have &lt;code&gt;cin&lt;/code&gt; read each character one at a time as needed using &lt;code&gt;stdio&lt;/code&gt; functions. Unfortunately, this introduces a lot of overhead. For small amounts of input, this isn’t a big problem, but when you are reading millions of lines, the performance penalty is significant.&lt;/p&gt;

&lt;p&gt;Fortunately, the library designers decided that you should also be able to disable this feature to get improved performance if you knew what you were doing, so they provided the &lt;a href="https://en.cppreference.com/w/cpp/io/ios_base/sync_with_stdio"&gt;&lt;code&gt;sync_with_stdio&lt;/code&gt; method&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can also use &lt;a href="https://en.wikipedia.org/wiki/Strace"&gt;dtruss/strace&lt;/a&gt; on each test.&lt;/p&gt;

&lt;p&gt;C++&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;./a.out &amp;lt; in
Saw 6512403 lines in 8 seconds.  Crunch speed: 814050
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;syscalls &lt;code&gt;sudo dtruss -c ./a.out &amp;lt; in&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CALL                                        COUNT
__mac_syscall                                   1
&amp;lt;snip&amp;gt;
open                                            6
pread                                           8
mprotect                                       17
mmap                                           22
stat64                                         30
read_nocancel                               25958
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Python&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;./a.py &amp;lt; in
Read 6512402 lines in 1 seconds. LPS: 6512402
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;syscalls &lt;code&gt;sudo dtruss -c ./a.py &amp;lt; in&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CALL                                        COUNT
__mac_syscall                                   1
&amp;lt;snip&amp;gt;
open                                            5
pread                                           8
mprotect                                       17
mmap                                           21
stat64                                         29
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  10. Why can templates only be implemented in the header file?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It is not necessary to put the implementation in the header file, see the alternative solution at the end of this answer.&lt;/p&gt;

&lt;p&gt;Anyway, the reason your code is failing is that, when instantiating a template, the compiler creates a new class with the given template argument. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;template&amp;lt;typename T&amp;gt;
struct Foo
{
    T bar;
    void doSomething(T param) {/* do stuff using T */}
};

// somewhere in a .cpp
Foo&amp;lt;int&amp;gt; f; 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When reading this line, the compiler will create a new class (let’s call it &lt;code&gt;FooInt&lt;/code&gt;), which is equivalent to the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;struct FooInt
{
    int bar;
    void doSomething(int param) {/* do stuff using int */}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Consequently, the compiler needs to have access to the implementation of the methods, to instantiate them with the template argument (in this case int). If these implementations were not in the header, they wouldn’t be accessible, and therefore the compiler wouldn’t be able to instantiate the template.&lt;/p&gt;

&lt;p&gt;A common solution to this is to write the template declaration in a header file, then implement the class in an implementation file (for example .tpp), and include this implementation file at the end of the header.&lt;/p&gt;

&lt;p&gt;Foo.h&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;template &amp;lt;typename T&amp;gt;
struct Foo
{
    void doSomething(T param);
};

#include "Foo.tpp"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Foo.tpp&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;template &amp;lt;typename T&amp;gt;
void Foo&amp;lt;T&amp;gt;::doSomething(T param)
{
    //implementation
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This way, implementation is still separated from declaration, but is accessible to the compiler.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Another solution is to keep the implementation separated, and explicitly instantiate all the template instances you’ll need:&lt;/p&gt;

&lt;p&gt;Foo.h&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// no implementation
template &amp;lt;typename T&amp;gt; struct Foo { ... };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Foo.cpp&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// implementation of Foo's methods

// explicit instantiations
template class Foo&amp;lt;int&amp;gt;;
template class Foo&amp;lt;float&amp;gt;;
// You will only be able to use Foo with int or float
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;In Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;These are the top 10 most commonly asked questions about C++. If you have any suggestions or any confusion, please comment below. If you need any help, we will be glad to help you.&lt;/p&gt;

&lt;p&gt;We, at &lt;a href="https://www.truemark.dev/hire/resources/"&gt;Truemark&lt;/a&gt;, provide services like web and mobile app development, digital marketing, and website development. So, if you need any help and want to work with us, please feel free to contact us.&lt;/p&gt;

&lt;p&gt;Hope this article helped you.&lt;/p&gt;

&lt;p&gt;This post was first published on &lt;a href="https://thedevpost.com/blog/10-most-asked-questions-about-cplusplus//"&gt;DevPostbyTruemark&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>cpp</category>
    </item>
    <item>
      <title>13 Most Asked Questions About C Programming</title>
      <dc:creator>KiranPoudel98</dc:creator>
      <pubDate>Fri, 16 Oct 2020 07:48:20 +0000</pubDate>
      <link>https://forem.com/truemark/13-most-asked-questions-about-c-programming-3oc4</link>
      <guid>https://forem.com/truemark/13-most-asked-questions-about-c-programming-3oc4</guid>
      <description>&lt;p&gt;C is a general-purpose programming language developed by Dennis Ritchie and Bell Labs. It is mainly used in advanced scientific systems and operating systems. C is one of the oldest programming languages, but still it is one of the popular languages. So, today we will be checking out the 13 most asked questions about C programming.&lt;/p&gt;

&lt;h2&gt;
  
  
  13 Most Asked Questions About C Programming
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1. Do we cast the result of malloc?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;No&lt;/strong&gt;, you don’t cast the result, since:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;It is unnecessary, as &lt;code&gt;void *&lt;/code&gt;  is automatically and safely promoted to any other pointer type in this case.&lt;/li&gt;
&lt;li&gt;It adds clutter to the code, casts are not very easy to read (especially if the pointer type is long).&lt;/li&gt;
&lt;li&gt;It makes you repeat yourself, which is generally bad.&lt;/li&gt;
&lt;li&gt;It can hide an error if you forgot to include &lt;code&gt;&amp;lt;stdlib.h&amp;gt;&lt;/code&gt;. This can cause crashes (or, worse, not cause a crash until way later in some totally different part of the code). Consider what happens if pointers and integers are differently sized; then you’re hiding a warning by casting and might lose bits of your returned address.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; As of C99 implicit functions are gone from C, and this point is no longer relevant since there’s no automatic assumption that undeclared functions return &lt;code&gt;int&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;There are simply no benefits to doing it, but a bunch of potential risks, and including the cast indicates that you don’t know about the risks. To add further, your code needlessly shouldn’t repeat the type information (&lt;code&gt;int&lt;/code&gt;) which can cause errors. It’s better to de-reference the pointer being used to store the return value, to “lock” the two together:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int *sieve = malloc(length * sizeof *sieve);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This also moves the &lt;code&gt;length&lt;/code&gt; to the front for increased visibility, and drops the redundant parentheses with &lt;code&gt;sizeof&lt;/code&gt;; they are only needed when the argument is a type name. Many people seem to not know (or ignore) this, which makes their code more verbose. Remember: &lt;code&gt;sizeof&lt;/code&gt; is not a function. While moving &lt;code&gt;length&lt;/code&gt; to the front may increase visibility in some rare cases, one should also pay attention that in the general case, it should be better to write the expression as:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int *sieve = malloc(sizeof *sieve * length);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Since keeping the &lt;code&gt;sizeof&lt;/code&gt; first, in this case, ensures multiplication is done with at least &lt;code&gt;size_t&lt;/code&gt; math.&lt;/p&gt;

&lt;p&gt;Compare: &lt;code&gt;malloc(sizeof *sieve * length * width)&lt;/code&gt; vs. &lt;code&gt;malloc(length * width * sizeof *sieve)&lt;/code&gt;, the second may overflow the &lt;code&gt;length * width&lt;/code&gt; when &lt;code&gt;width&lt;/code&gt; and &lt;code&gt;length&lt;/code&gt; are smaller types than &lt;code&gt;size_t&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In C, you don’t need to cast the return value of &lt;code&gt;malloc&lt;/code&gt;. The pointer to void returned by &lt;code&gt;malloc&lt;/code&gt; is automagically converted to the correct type. However, if you want your code to compile with a C++ compiler, a cast is needed. A preferred alternative among the community is to use the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int *sieve = malloc(sizeof *sieve * length);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;which additionally frees you from having to worry about changing the right-hand side of the expression if ever you change the type of &lt;code&gt;sieve&lt;/code&gt;. Casts are bad, especially pointer casts.&lt;/p&gt;

&lt;h3&gt;
  
  
  2. What does the ??!??! operator do in C?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;??!&lt;/code&gt; is a &lt;a href="https://en.wikipedia.org/wiki/Digraphs_and_trigraphs#C"&gt;trigraph&lt;/a&gt; that translates to |. So it says:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;!ErrorHasOccured() || HandleError();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;which, due to short circuiting, is equivalent to:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (ErrorHasOccured())
    HandleError();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="http://www.gotw.ca/gotw/086.htm"&gt;Guru of the Week&lt;/a&gt; (deals with C++ but relevant here). Possible origin of trigraphs, it’s more likely due to EBCDIC being difficult (again). &lt;a href="https://community.ibm.com/community/user/legacy?messageID=14505849"&gt;This&lt;/a&gt; discussion on the IBM developerworks board seems to support that theory. From ISO/IEC 9899:1999 §5.2.1.1, footnote 12 (h/t @Random832):&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The trigraph sequences enable the input of characters that are not defined in the Invariant Code Set as described in ISO/IEC 646, which is a subset of the seven-bit US ASCII code set.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  3. What is “:-!!” in C code?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This is, in effect, &lt;strong&gt;a way to check whether the expression e can be evaluated to be 0, and if not, to fail the build&lt;/strong&gt;. The macro is somewhat misnamed; it should be something more like &lt;code&gt;BUILD_BUG_OR_ZERO&lt;/code&gt;, rather than &lt;code&gt;...ON_ZERO&lt;/code&gt;. (There have been &lt;a href="http://lkml.iu.edu/hypermail/linux/kernel/0703.1/1546.html"&gt;occasional discussions about whether this is a confusing name&lt;/a&gt;.) You should read the expression like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sizeof(struct { int: -!!(e); }))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;(e)&lt;/code&gt;: Compute expression &lt;code&gt;e&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;!!(e)&lt;/code&gt;: Logically negate twice: &lt;code&gt;0&lt;/code&gt; if &lt;code&gt;e == 0&lt;/code&gt;; otherwise &lt;code&gt;1&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;-!!(e)&lt;/code&gt;: Numerically negate the expression from step 2: &lt;code&gt;0&lt;/code&gt; if it was &lt;code&gt;0&lt;/code&gt;; otherwise &lt;code&gt;-1&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;struct{int: -!!(0);} --&amp;gt; struct{int: 0;}&lt;/code&gt;: If it was zero, then we declare a struct with an anonymous integer bitfield that has width zero. Everything is fine and we proceed as normal.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;struct{int: -!!(1);} --&amp;gt; struct{int: -1;}&lt;/code&gt;: On the other hand, if it isn’t zero, then it will be some negative number. Declaring any bitfield with negative width is a compilation error.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So we’ll either wind up with a bitfield that has width 0 in a struct, which is fine, or a bitfield with negative width, which is a compilation error. Then we take &lt;code&gt;sizeof&lt;/code&gt; that field, so we get a &lt;code&gt;size_t&lt;/code&gt; with the appropriate width (which will be zero in the case where &lt;code&gt;e&lt;/code&gt; is zero). You don’t want to detect problems in your kernel at runtime that could have been caught earlier. It’s a critical piece of the operating system. To whatever extent problems can be detected at compile-time, so much the better.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;:&lt;/code&gt; is a bitfield. As for &lt;code&gt;!!&lt;/code&gt;, that is &lt;a href="https://stackoverflow.com/questions/248693/double-negation-in-c"&gt;logical double negation&lt;/a&gt; and so returns &lt;code&gt;0&lt;/code&gt; for false or &lt;code&gt;1&lt;/code&gt; for true. And the &lt;code&gt;-&lt;/code&gt; is a minus sign, i.e. arithmetic negation. It’s all just a trick to get the compiler to barf on invalid inputs. Consider &lt;code&gt;BUILD_BUG_ON_ZERO&lt;/code&gt;. When &lt;code&gt;-!!(e)&lt;/code&gt; evaluates to a negative value, that produces a compile error. Otherwise &lt;code&gt;-!!(e)&lt;/code&gt; evaluates to 0, and a 0 width bitfield has size of 0. And hence the macro evaluates to a &lt;code&gt;size_t&lt;/code&gt; with value 0. The name is weak in my view because the build, in fact fails when the input is not zero. &lt;code&gt;BUILD_BUG_ON_NULL&lt;/code&gt; is very similar, but yields a pointer rather than an &lt;code&gt;int&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  4. With arrays, why is it the case that a[5] == 5[a]?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The C standard defines the &lt;code&gt;[]&lt;/code&gt; operator as follows: &lt;code&gt;a[b] == *(a + b)&lt;/code&gt; Therefore &lt;code&gt;a[5]&lt;/code&gt; will evaluate to:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;*(a + 5)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and &lt;code&gt;5[a]&lt;/code&gt; will evaluate to:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;*(5 + a)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;a&lt;/code&gt; is a pointer to the first element of the array. &lt;code&gt;a[5]&lt;/code&gt; is the value that’s 5 &lt;strong&gt;elements&lt;/strong&gt; further from &lt;code&gt;a&lt;/code&gt;, which is the same as &lt;code&gt;*(a + 5)&lt;/code&gt;, and from elementary school math we know those are equal (addition is &lt;a href="https://en.wikipedia.org/wiki/Commutative_property"&gt;commutative&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Because array access is defined in terms of pointers. &lt;code&gt;a[i]&lt;/code&gt; is defined to mean &lt;code&gt;*(a + i)&lt;/code&gt;, which is commutative.&lt;/p&gt;

&lt;h3&gt;
  
  
  5. How do function pointers in C work?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let’s start with a basic function which we will be pointing to:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int addInt(int n, int m) {
    return n+m;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;First thing, let’s define a pointer to a function which receives 2 &lt;code&gt;int&lt;/code&gt;s and returns an &lt;code&gt;int&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int (*functionPtr)(int,int);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we can safely point to our function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;functionPtr = &amp;amp;addInt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now that we have a pointer to the function, let’s use it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int sum = (*functionPtr)(2, 3); // sum == 5
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Passing the pointer to another function is basically the same:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int add2to3(int (*functionPtr)(int, int)) {
    return (*functionPtr)(2, 3);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can use function pointers in return values as well (try to keep up, it gets messy):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// this is a function called functionFactory which receives parameter n
// and returns a pointer to another function which receives two ints
// and it returns another int
int (*functionFactory(int n))(int, int) {
    printf("Got parameter %d", n);
    int (*functionPtr)(int,int) = &amp;amp;addInt;
    return functionPtr;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But it’s much nicer to use a &lt;code&gt;typedef&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;typedef int (*myFuncDef)(int, int);
// note that the typedef name is indeed myFuncDef

myFuncDef functionFactory(int n) {
    printf("Got parameter %d", n);
    myFuncDef functionPtr = &amp;amp;addInt;
    return functionPtr;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Function pointers in C can be used to perform object-oriented programming in C. For example, the following lines is written in C:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;String s1 = newString();
s1-&amp;gt;set(s1, "hello");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Yes, the &lt;code&gt;-&amp;gt;&lt;/code&gt; and the lack of a &lt;code&gt;new&lt;/code&gt; operator is a dead give away, but it sure seems to imply that we’re setting the text of some &lt;code&gt;String&lt;/code&gt; class to be &lt;code&gt;"hello"&lt;/code&gt;. By using function pointers, &lt;strong&gt;it is possible to emulate methods in C&lt;/strong&gt;. How is this accomplished? The &lt;code&gt;String&lt;/code&gt; class is actually a &lt;code&gt;struct&lt;/code&gt; with a bunch of function pointers which act as a way to simulate methods. The following is a partial declaration of the &lt;code&gt;String&lt;/code&gt; class:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;typedef struct String_Struct* String;

struct String_Struct
{
    char* (*get)(const void* self);
    void (*set)(const void* self, char* value);
    int (*length)(const void* self);
};

char* getString(const void* self);
void setString(const void* self, char* value);
int lengthString(const void* self);

String newString();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As can be seen, the methods of the &lt;code&gt;String&lt;/code&gt; class are actually function pointers to the declared function. In preparing the instance of the &lt;code&gt;String&lt;/code&gt;, the &lt;code&gt;newString&lt;/code&gt; function is called in order to set up the function pointers to their respective functions:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;String newString()
{
    String self = (String)malloc(sizeof(struct String_Struct));

    self-&amp;gt;get = &amp;amp;getString;
    self-&amp;gt;set = &amp;amp;setString;
    self-&amp;gt;length = &amp;amp;lengthString;

    self-&amp;gt;set(self, "");

    return self;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For example, the &lt;code&gt;getString&lt;/code&gt; function that is called by invoking the &lt;code&gt;get&lt;/code&gt; method is defined as the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;char* getString(const void* self_obj)
{
    return ((String)self_obj)-&amp;gt;internal-&amp;gt;value;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;One thing that can be noticed is that there is no concept of an instance of an object and having methods that are actually a part of an object, so a “self object” must be passed in on each invocation. (And the &lt;code&gt;internal&lt;/code&gt; is just a hidden &lt;code&gt;struct&lt;/code&gt; which was omitted from the code listing earlier — it is a way of performing information hiding, but that is not relevant to function pointers.) So, rather than being able to do &lt;code&gt;s1-&amp;gt;set("hello");&lt;/code&gt;, one must pass in the object to perform the action on &lt;code&gt;s1-&amp;gt;set(s1, "hello")&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;With that minor explanation having to pass in a reference to yourself out of the way, we’ll move to the next part, which is &lt;strong&gt;inheritance in C&lt;/strong&gt;. Let’s say we want to make a subclass of &lt;code&gt;String&lt;/code&gt;, say an &lt;code&gt;ImmutableString&lt;/code&gt;. In order to make the string immutable, the &lt;code&gt;set&lt;/code&gt; method will not be accessible, while maintaining access to &lt;code&gt;get&lt;/code&gt; and &lt;code&gt;length&lt;/code&gt;, and force the “constructor” to accept a &lt;code&gt;char*&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;typedef struct ImmutableString_Struct* ImmutableString;

struct ImmutableString_Struct
{
    String base;

    char* (*get)(const void* self);
    int (*length)(const void* self);
};

ImmutableString newImmutableString(const char* value);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Basically, for all subclasses, the available methods are once again function pointers. This time, the declaration for the &lt;code&gt;set&lt;/code&gt; method is not present, therefore, it cannot be called in a &lt;code&gt;ImmutableString&lt;/code&gt;. As for the implementation of the &lt;code&gt;ImmutableString&lt;/code&gt;, the only relevant code is the “constructor” function, the &lt;code&gt;newImmutableString&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ImmutableString newImmutableString(const char* value)
{
    ImmutableString self = (ImmutableString)malloc(sizeof(struct ImmutableString_Struct));

    self-&amp;gt;base = newString();

    self-&amp;gt;get = self-&amp;gt;base-&amp;gt;get;
    self-&amp;gt;length = self-&amp;gt;base-&amp;gt;length;

    self-&amp;gt;base-&amp;gt;set(self-&amp;gt;base, (char*)value);

    return self;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In instantiating the &lt;code&gt;ImmutableString&lt;/code&gt;, the function pointers to the &lt;code&gt;get&lt;/code&gt; and &lt;code&gt;length&lt;/code&gt; methods actually refer to the &lt;code&gt;String.get&lt;/code&gt; and &lt;code&gt;String.length&lt;/code&gt; method, by going through the &lt;code&gt;base&lt;/code&gt; variable which is an internally stored &lt;code&gt;String&lt;/code&gt; object. The use of a function pointer can achieve the inheritance of a method from a superclass. We can further continue to &lt;strong&gt;polymorphism in C&lt;/strong&gt;. If for example we wanted to change the behavior of the &lt;code&gt;length&lt;/code&gt; method to return &lt;code&gt;0&lt;/code&gt; all the time in the &lt;code&gt;ImmutableString&lt;/code&gt; class for some reason, all that would have to be done is to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Add a function that is going to serve as the overriding &lt;code&gt;length&lt;/code&gt; method.&lt;/li&gt;
&lt;li&gt;Go to the “constructor” and set the function pointer to the overriding &lt;code&gt;length&lt;/code&gt; method.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Adding an overriding &lt;code&gt;length&lt;/code&gt; method in &lt;code&gt;ImmutableString&lt;/code&gt; may be performed by adding an &lt;code&gt;lengthOverrideMethod&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int lengthOverrideMethod(const void* self)
{
    return 0;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then, the function pointer for the &lt;code&gt;length&lt;/code&gt; method in the constructor is hooked up to the&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;lengthOverrideMethod:

ImmutableString newImmutableString(const char* value)
{
    ImmutableString self = (ImmutableString)malloc(sizeof(struct ImmutableString_Struct));

    self-&amp;gt;base = newString();

    self-&amp;gt;get = self-&amp;gt;base-&amp;gt;get;
    self-&amp;gt;length = &amp;amp;lengthOverrideMethod;

    self-&amp;gt;base-&amp;gt;set(self-&amp;gt;base, (char*)value);

    return self;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, rather than having an identical behavior for the &lt;code&gt;length&lt;/code&gt; method in &lt;code&gt;ImmutableString&lt;/code&gt; class as the &lt;code&gt;String&lt;/code&gt; class, now the &lt;code&gt;length&lt;/code&gt; method will refer to the behavior defined in the &lt;code&gt;lengthOverrideMethod&lt;/code&gt; function. For more information on how to perform object-oriented programming in C, please refer to the following questions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://stackoverflow.com/questions/415452/object-orientation-in-c"&gt;Object-Orientation in C?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://stackoverflow.com/questions/351733/how-would-one-write-object-oriented-code-in-c"&gt;Can you write object oriented code in C?&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  6. What does “static” mean in C?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A static variable inside a function keeps its value between invocations.&lt;/li&gt;
&lt;li&gt;A static global variable or a function is “seen” only in the file it’s declared in&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;(1) is the more foreign topic if you’re a newbie, so here’s an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#include &amp;lt;stdio.h&amp;gt;

void foo()
{
    int a = 10;
    static int sa = 10;

    a += 5;
    sa += 5;

    printf("a = %d, sa = %d\n", a, sa);
}


int main()
{
    int i;

    for (i = 0; i &amp;lt; 10; ++i)
        foo();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This prints:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;a = 15, sa = 15
a = 15, sa = 20
a = 15, sa = 25
a = 15, sa = 30
a = 15, sa = 35
a = 15, sa = 40
a = 15, sa = 45
a = 15, sa = 50
a = 15, sa = 55
a = 15, sa = 60
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is useful for cases where a function needs to keep some state between invocations, and you don’t want to use global variables. Beware, however, this feature should be used very sparingly – it makes your code not thread-safe and harder to understand.&lt;/p&gt;

&lt;p&gt;(2) Is used widely as an “access control” feature. If you have a .c file implementing some functionality, it usually exposes only a few “public” functions to users. The rest of its functions should be made &lt;code&gt;static&lt;/code&gt;, so that the user won’t be able to access them. This is encapsulation, a good practice.&lt;/p&gt;

&lt;p&gt;Quoting &lt;a href="https://en.wikipedia.org/wiki/Static_variable"&gt;Wikipedia&lt;/a&gt;:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;In the C programming language, static is used with global variables and functions to set their scope to the containing file. In local variables, static is used to store the variable in the statically allocated memory instead of the automatically allocated memory. While the language does not dictate the implementation of either type of memory, statically allocated memory is typically reserved in data segment of the program at compile time, while the automatically allocated memory is normally implemented as a transient call stack.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In C++, however, &lt;code&gt;static&lt;/code&gt; is also used to define class attributes (shared between all objects of the same class) and methods. In C there are no classes, so this feature is irrelevant.&lt;/p&gt;

&lt;h3&gt;
  
  
  7. How to determine the size of an array in C?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Executive summary:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int a[17];
size_t n = sizeof(a)/sizeof(a[0]);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Full answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;To determine the size of your array in bytes, you can use the &lt;code&gt;sizeof&lt;/code&gt; operator:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int a[17];
size_t n = sizeof(a);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To determine the number of elements in the array, we can divide the total size of the array by the size of the array element. You could do this with the type, like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int a[17];
size_t n = sizeof(a) / sizeof(int);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and get the proper answer (68 / 4 = 17), but if the type of &lt;code&gt;a&lt;/code&gt; changed you would have a nasty bug if you forgot to change the &lt;code&gt;sizeof(int)&lt;/code&gt; as well. So the preferred divisor is &lt;code&gt;sizeof(a[0])&lt;/code&gt; or the equivalent &lt;code&gt;sizeof(*a)&lt;/code&gt;, the size of the first element of the array.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int a[17];
size_t n = sizeof(a) / sizeof(a[0]);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Another advantage is that you can now easily parameterize the array name in a macro and get:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#define NELEMS(x)  (sizeof(x) / sizeof((x)[0]))

int a[17];
size_t n = NELEMS(a);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;sizeof&lt;/code&gt; way is the right way &lt;a href="https://en.wikipedia.org/wiki/If_and_only_if"&gt;if&lt;/a&gt; you are dealing with arrays not received as parameters. An array sent as a parameter to a function is treated as a pointer, so &lt;code&gt;sizeof&lt;/code&gt; will return the pointer’s size, instead of the array’s. Thus, inside functions this method does not work. Instead, always pass an additional parameter &lt;code&gt;size_t size&lt;/code&gt; indicating the number of elements in the array. Test:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#include &amp;lt;stdio.h&amp;gt;
#include &amp;lt;stdlib.h&amp;gt;

void printSizeOf(int intArray[]);
void printLength(int intArray[]);

int main(int argc, char* argv[])
{
    int array[] = { 0, 1, 2, 3, 4, 5, 6 };

    printf("sizeof of array: %d\n", (int) sizeof(array));
    printSizeOf(array);

    printf("Length of array: %d\n", (int)( sizeof(array) / sizeof(array[0]) ));
    printLength(array);
}

void printSizeOf(int intArray[])
{
    printf("sizeof of parameter: %d\n", (int) sizeof(intArray));
}

void printLength(int intArray[])
{
    printf("Length of parameter: %d\n", (int)( sizeof(intArray) / sizeof(intArray[0]) ));
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output (in a 64-bit Linux OS):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sizeof of array: 28
sizeof of parameter: 8
Length of array: 7
Length of parameter: 2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output (in a 32-bit windows OS):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sizeof of array: 28
sizeof of parameter: 4
Length of array: 7
Length of parameter: 1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  8. Why does the C preprocessor interpret the word “linux” as the constant “1”?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In the Old Days (pre-ANSI), predefining symbols such as &lt;code&gt;unix&lt;/code&gt; and &lt;code&gt;vax&lt;/code&gt; was a way to allow code to detect at compile time what system it was being compiled for. There was no official language standard back then (beyond the reference material at the back of the first edition of K&amp;amp;R), and the C code of any complexity was typically a complex maze of &lt;code&gt;#ifdefs&lt;/code&gt; to allow for differences between systems. These macro definitions were generally set by the compiler itself, not defined in a library header file. Since there were no real rules about which identifiers could be used by the implementation and which were reserved for programmers, compiler writers felt free to use simple names like &lt;code&gt;unix&lt;/code&gt; and assumed that programmers would simply avoid using those names for their own purposes.&lt;/p&gt;

&lt;p&gt;The 1989 ANSI C standard introduced rules restricting what symbols an implementation could legally predefine. A macro predefined by the compiler could only have a name starting with two underscores, or with an underscore followed by an uppercase letter, leaving programmers free to use identifiers not matching that pattern and not used in the standard library.&lt;/p&gt;

&lt;p&gt;As a result, any compiler that predefines &lt;code&gt;unix&lt;/code&gt; or &lt;code&gt;linux&lt;/code&gt; is non-conforming, since it will fail to compile perfectly legal code that uses something like &lt;code&gt;int linux = 5;&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;As it happens, gcc is non-conforming by default — but it can be made to conform (reasonably well) with the right command-line options:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;gcc -std=c90 -pedantic ... # or -std=c89 or -ansi
gcc -std=c99 -pedantic
gcc -std=c11 -pedantic
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;See &lt;a href="https://gcc.gnu.org/onlinedocs/gcc-4.8.1/gcc/Standards.html"&gt;the GCC manual&lt;/a&gt; for more details.&lt;/p&gt;

&lt;p&gt;GCC will be phasing out these definitions in future releases, so you shouldn’t write code that depends on them. If your program needs to know whether it’s being compiled for a Linux target or not it can check whether &lt;code&gt;__linux__&lt;/code&gt; is defined (assuming you’re using GCC or a compiler that’s compatible with it). See &lt;a href="https://gcc.gnu.org/onlinedocs/cpp/System-specific-Predefined-Macros.html"&gt;the GNU C preprocessor manual&lt;/a&gt; for more information.&lt;/p&gt;

&lt;p&gt;A largely irrelevant aside: the “Best One Liner” winner of the 1987 &lt;a href="http://www.ioccc.org/"&gt;International Obfuscated C Code Contest&lt;/a&gt;, by David Korn (yes, the author of the Korn Shell) took advantage of the predefined &lt;code&gt;unix&lt;/code&gt; macro:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;main() { printf(&amp;amp;unix["\021%six\012\0"],(unix)["have"]+"fun"-0x60);}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It prints &lt;code&gt;"unix"&lt;/code&gt;, but for reasons that have absolutely nothing to do with the spelling of the macro name.&lt;/p&gt;

&lt;h3&gt;
  
  
  9. How to initialize all members of an array to the same value?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Unless that value is 0 (in which case you can omit some part of the initializer and the corresponding elements will be initialized to 0), there’s no easy way. Don’t overlook the obvious solution, though:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Elements with missing values will be initialized to 0:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int myArray[10] = { 1, 2 }; // initialize to 1,2,0,0,0...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So this will initialize all elements to 0:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int myArray[10] = { 0 }; // all elements 0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In C++, an empty initialization list will also initialize every element to 0. This is &lt;a href="https://stackoverflow.com/questions/17589533/is-an-empty-initializer-list-valid-c-code/17589839#17589839"&gt;not allowed&lt;/a&gt; with C:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int myArray[10] = {}; // all elements 0 in C++
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Remember that objects with static storage duration will initialize to 0 if no initializer is specified:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;static int myArray[10]; // all elements 0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And that “0” doesn’t necessarily mean “all-bits-zero”, so using the above is better and more portable than memset(). (Floating point values will be initialized to +0, pointers to null value, etc.)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If your compiler is GCC you can use following syntax:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int array[1024] = {[0 ... 1023] = 5};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Check out detailed description: &lt;a href="http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Designated-Inits.html"&gt;http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Designated-Inits.html&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  10. What is the difference between ++i and i++?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;++i&lt;/code&gt; will increment the value of &lt;code&gt;i&lt;/code&gt;, and then return the incremented value.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;i = 1;
j = ++i;
(i is 2, j is 2)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;i++&lt;/code&gt; will increment the value of &lt;code&gt;i&lt;/code&gt;, but return the original value that &lt;code&gt;i&lt;/code&gt; held before being incremented.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;     i = 1;
     j = i++;
     (i is 2, j is 1)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For a &lt;code&gt;for&lt;/code&gt; loop, either works. &lt;code&gt;++i&lt;/code&gt; seems more common, perhaps because that is what is used in &lt;a href="https://en.wikipedia.org/wiki/The_C_Programming_Language"&gt;K&amp;amp;R&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;In any case, follow the guideline “prefer &lt;code&gt;++i&lt;/code&gt; over &lt;code&gt;i++&lt;/code&gt;” and you won’t go wrong.&lt;/p&gt;

&lt;p&gt;In any non-student-project compiler, there will be no performance difference. You can verify this by looking at the generated code, which will be identical.&lt;/p&gt;

&lt;p&gt;It’s different for a C++ object, since &lt;code&gt;operator++()&lt;/code&gt; is a function and the compiler can’t know to optimize away the creation of a temporary object to hold the intermediate value.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;i++&lt;/strong&gt; is known as &lt;strong&gt;Post Increment&lt;/strong&gt; whereas &lt;strong&gt;++i&lt;/strong&gt; is called &lt;strong&gt;Pre Increment&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;i++
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;i++&lt;/code&gt; is post increment because it increments &lt;code&gt;i&lt;/code&gt;‘s value by 1 after the operation is over.&lt;/p&gt;

&lt;p&gt;Lets see the following example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int i = 1, j;
j = i++;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here value of &lt;code&gt;j = 1&lt;/code&gt; but &lt;code&gt;i = 2&lt;/code&gt;. Here value of &lt;code&gt;i&lt;/code&gt; will be assigned to &lt;code&gt;j&lt;/code&gt; first then &lt;code&gt;i&lt;/code&gt; will be incremented.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;++i
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;++i&lt;/code&gt; is pre increment because it increments &lt;code&gt;i&lt;/code&gt;‘s value by 1 before the operation. It means &lt;code&gt;j = i&lt;/code&gt;; will execute after &lt;code&gt;i++&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Lets see the following example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int i = 1, j;
j = ++i;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here value of &lt;code&gt;j = 2&lt;/code&gt; but &lt;code&gt;i = 2&lt;/code&gt;. Here value of &lt;code&gt;i&lt;/code&gt; will be assigned to &lt;code&gt;j&lt;/code&gt; after the &lt;code&gt;i&lt;/code&gt; incremention of &lt;code&gt;i&lt;/code&gt;. Similarly &lt;code&gt;++i&lt;/code&gt; will be executed before &lt;code&gt;j=i;&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;For the question like &lt;strong&gt;which should be used in the incrementation block of a for loop?&lt;/strong&gt; The answer is, you can use any one, it doesn’t matter. It will execute your for loop the same no. of times.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for(i=0; i&amp;lt;5; i++)
   printf("%d ",i);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for(i=0; i&amp;lt;5; ++i)
   printf("%d ",i);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Both the loops will produce same output i.e. &lt;code&gt;0 1 2 3 4&lt;/code&gt;. It only matters where you are using it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for(i = 0; i&amp;lt;5;)
    printf("%d ",++i);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this case output will be &lt;code&gt;1 2 3 4 5&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  11. What is the difference between a definition and a declaration?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A &lt;strong&gt;declaration&lt;/strong&gt; introduces an identifier and describes its type, be it a type, object, or function. A declaration is &lt;strong&gt;what the compiler needs&lt;/strong&gt; to accept references to that identifier. These are declarations:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;extern int bar;
extern int g(int, int);
double f(int, double); // extern can be omitted for function declarations
class foo; // no extern allowed for type declarations
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A &lt;strong&gt;definition&lt;/strong&gt; actually instantiates/implements this identifier. It’s &lt;strong&gt;what the linker needs&lt;/strong&gt; in order to link references to those entities. These are definitions corresponding to the above declarations:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int bar;
int g(int lhs, int rhs) {return lhs*rhs;}
double f(int i, double d) {return i+d;}
class foo {};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A definition can be used in the place of a declaration.&lt;/p&gt;

&lt;p&gt;An identifier can be declared as often as you want. Thus, the following is legal in C and C++:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;double f(int, double);
double f(int, double);
extern double f(int, double); // the same as the two above
extern double f(int, double);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However, it must be defined exactly once. If you forget to define something that’s been declared and referenced somewhere, then the linker doesn’t know what to link references to and complains about missing symbols. If you define something more than once, then the linker doesn’t know which of the definitions to link references to and complains about duplicated symbols.&lt;/p&gt;

&lt;p&gt;Since the debate what is a class declaration vs. a class definition in C++ keeps coming up, here is a quote from the C++ standard here. At 3.1/2, C++03 says:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;A declaration is a definition unless it […] is a class name declaration […].&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;3.1/3 then gives a few examples. Amongst them:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[Example: [...]
struct S { int a; int b; }; // defines S, S::a, and S::b [...]
struct S; // declares S
—end example
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To sum it up: The C++ standard considers &lt;code&gt;struct x&lt;/code&gt;; to be a declaration and &lt;code&gt;struct x {};&lt;/code&gt; a definition. (In other words, &lt;strong&gt;“forward declaration” a misnomer&lt;/strong&gt;, since there are no other forms of class declarations in C++.)&lt;/p&gt;

&lt;h3&gt;
  
  
  12. What is the strict aliasing rule?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A typical situation where you encounter strict aliasing problems is when overlaying a struct (like a device/network msg) onto a buffer of the word size of your system (like a pointer to &lt;code&gt;uint32_ts&lt;/code&gt; or &lt;code&gt;uint16_ts&lt;/code&gt;). When you overlay a struct onto such a buffer, or a buffer onto such a struct through pointer casting you can easily violate strict aliasing rules.&lt;/p&gt;

&lt;p&gt;So in this kind of setup, if you want to send a message to something you would have to have two incompatible pointers pointing to the same chunk of memory. You might then naively code something like this (on a system with &lt;code&gt;sizeof(int) == 2&lt;/code&gt;):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;typedef struct Msg
{
    unsigned int a;
    unsigned int b;
} Msg;

void SendWord(uint32_t);

int main(void)
{
    // Get a 32-bit buffer from the system
    uint32_t* buff = malloc(sizeof(Msg));

    // Alias that buffer through message
    Msg* msg = (Msg*)(buff);

    // Send a bunch of messages    
    for (int i =0; i &amp;lt; 10; ++i)
    {
        msg-&amp;gt;a = i;
        msg-&amp;gt;b = i+1;
        SendWord(buff[0]);
        SendWord(buff[1]);   
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The strict aliasing rule makes this setup illegal: dereferencing a pointer that aliases an object that is not of a &lt;a href="https://en.cppreference.com/w/c/language/type"&gt;compatible type&lt;/a&gt; or one of the other types allowed by C 2011 6.5 paragraph 7 is undefined behavior. Unfortunately, you can still code this way, maybe get some warnings, have it compile fine, only to have weird unexpected behavior when you run the code.&lt;/p&gt;

&lt;p&gt;(GCC appears somewhat inconsistent in its ability to give aliasing warnings, sometimes giving us a friendly warning and sometimes not.)&lt;/p&gt;

&lt;p&gt;To see why this behavior is undefined, we have to think about what the strict aliasing rule buys the compiler. Basically, with this rule, it doesn’t have to think about inserting instructions to refresh the contents of &lt;code&gt;buff&lt;/code&gt; every run of the loop. Instead, when optimizing, with some annoyingly unenforced assumptions about aliasing, it can omit those instructions, load &lt;code&gt;buff[0]&lt;/code&gt; and &lt;code&gt;buff[1]&lt;/code&gt; into CPU registers once before the loop is run, and speed up the body of the loop. Before strict aliasing was introduced, the compiler had to live in a state of paranoia that the contents of &lt;code&gt;buff&lt;/code&gt; could change at any time from anywhere by anybody. So to get an extra performance edge, and assuming most people don’t type-pun pointers, the strict aliasing rule was introduced.&lt;/p&gt;

&lt;p&gt;Keep in mind, if you think the example is contrived, this might even happen if you’re passing a buffer to another function doing the sending for you, if instead, you have.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;void SendMessage(uint32_t* buff, size_t size32)
{
    for (int i = 0; i &amp;lt; size32; ++i) 
    {
        SendWord(buff[i]);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And rewrote our earlier loop to take advantage of this convenient function&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for (int i = 0; i &amp;lt; 10; ++i)
{
    msg-&amp;gt;a = i;
    msg-&amp;gt;b = i+1;
    SendMessage(buff, 2);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The compiler may or may not be able to or smart enough to try to inline SendMessage and it may or may not decide to load or not load buff again. If &lt;code&gt;SendMessage&lt;/code&gt; is part of another API that’s compiled separately, it probably has instructions to load buff’s contents. Then again, maybe you’re in C++ and this is some templated header only implementation that the compiler thinks it can inline. Or maybe it’s just something you wrote in your .c file for your own convenience. Anyway undefined behavior might still ensue. Even when we know some of what’s happening under the hood, it’s still a violation of the rule so no well-defined behavior is guaranteed. So just by wrapping in a function that takes our word delimited buffer doesn’t necessarily help.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;So how to get around this?&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Use a union. Most compilers support this without complaining about strict aliasing. This is allowed in C99 and explicitly allowed in C11.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    union {
        Msg msg;
        unsigned int asBuffer[sizeof(Msg)/sizeof(unsigned int)];
    };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;You can disable strict aliasing in your compiler (&lt;a href="https://gcc.gnu.org/onlinedocs/gcc-4.6.1/gcc/Optimize-Options.html#index-fstrict_002daliasing-825"&gt;f[no-]strict-aliasing&lt;/a&gt; in gcc))&lt;/li&gt;
&lt;li&gt;You can use &lt;code&gt;char*&lt;/code&gt; for aliasing instead of your system’s word. The rules allow an exception for &lt;code&gt;char*&lt;/code&gt; (including &lt;code&gt;signed char&lt;/code&gt; and &lt;code&gt;unsigned char&lt;/code&gt;). It’s always assumed that &lt;code&gt;char*&lt;/code&gt; aliases other types. However this won’t work the other way: there’s no assumption that your struct aliases a buffer of chars.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Beginner beware&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This is only one potential minefield when overlaying two types onto each other. You should also learn about &lt;a href="https://en.wikipedia.org/wiki/Endianness"&gt;endianness&lt;/a&gt;, &lt;a href="https://web.archive.org/web/20170708093042/http://www.cs.umd.edu:80/class/sum2003/cmsc311/Notes/Data/aligned.html"&gt;word alignment&lt;/a&gt;, and how to deal with alignment issues through &lt;a href="http://grok2.com/structure_packing.html"&gt;packing structs&lt;/a&gt; correctly.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Footnote&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The types that C 2011 6.5 7 allows an lvalue to access are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;a type compatible with the effective type of the object,&lt;/li&gt;
&lt;li&gt;a qualified version of a type compatible with the effective type of the object,&lt;/li&gt;
&lt;li&gt;a type that is the signed or unsigned type corresponding to the effective type of the object,&lt;/li&gt;
&lt;li&gt;a type that is the signed or unsigned type corresponding to a qualified version of the effective type of the object,&lt;/li&gt;
&lt;li&gt;an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or&lt;/li&gt;
&lt;li&gt;a character type.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  13. Difference between malloc and calloc?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;calloc()&lt;/code&gt; gives you a zero-initialized buffer, while &lt;code&gt;malloc()&lt;/code&gt; leaves the memory uninitialized.&lt;/p&gt;

&lt;p&gt;For large allocations, most &lt;code&gt;calloc&lt;/code&gt; implementations under mainstream OSes will get known-zeroed pages from the OS (e.g. via POSIX &lt;code&gt;mmap(MAP_ANONYMOUS)&lt;/code&gt; or Windows &lt;code&gt;VirtualAlloc&lt;/code&gt;) so it doesn’t need to write them in user-space. This is how normal &lt;code&gt;malloc&lt;/code&gt; gets more pages from the OS as well; &lt;code&gt;calloc&lt;/code&gt; just takes advantage of the OS’s guarantee.&lt;/p&gt;

&lt;p&gt;This means &lt;code&gt;calloc&lt;/code&gt; memory can still be “clean” and lazily-allocated, and copy-on-write mapped to a system-wide shared physical page of zeros. (Assuming a system with virtual memory.)&lt;/p&gt;

&lt;p&gt;Some compilers even can optimize malloc + memset(0) into calloc for you, but you should use calloc explicitly if you want the memory to read as 0.&lt;/p&gt;

&lt;p&gt;If you aren’t going to ever read memory before writing it, use &lt;code&gt;malloc&lt;/code&gt; so it can (potentially) give you dirty memory from its internal free list instead of getting new pages from the OS. (Or instead of zeroing a block of memory on the free list for a small allocation).&lt;/p&gt;

&lt;p&gt;Embedded implementations of &lt;code&gt;calloc&lt;/code&gt; may leave it up to &lt;code&gt;calloc&lt;/code&gt; itself to zero memory if there’s no OS, or it’s not a fancy multi-user OS that zeros pages to stop information leaks between processes.&lt;/p&gt;

&lt;p&gt;On embedded Linux, malloc could &lt;code&gt;map(MAP_UNINITIALIZED|MAP_ANONYMOUS)&lt;/code&gt;, which is only enabled for some embedded kernels because it’s insecure on a multi-user system.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;In Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;These are the 13 most commonly asked questions about C programming. If you have any suggestions or any confusion, please comment below. If you need any help, we will be glad to help you.&lt;/p&gt;

&lt;p&gt;We, at &lt;a href="https://www.truemark.dev/"&gt;Truemark&lt;/a&gt;, provide services like web and mobile app development, digital marketing, and website development. So, if you need any help and want to work with us, please feel free to contact us.&lt;/p&gt;

&lt;p&gt;Hope this article helped you.&lt;/p&gt;

&lt;p&gt;This post was first published on &lt;a href="https://thedevpost.com/blog/13-most-asked-questions-about-c/"&gt;DevPostbyTruemark&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>c</category>
    </item>
    <item>
      <title>10 Most Asked MongoDB Questions</title>
      <dc:creator>KiranPoudel98</dc:creator>
      <pubDate>Fri, 09 Oct 2020 06:49:18 +0000</pubDate>
      <link>https://forem.com/truemark/10-most-asked-mongodb-questions-4jm6</link>
      <guid>https://forem.com/truemark/10-most-asked-mongodb-questions-4jm6</guid>
      <description>&lt;p&gt;MongoDB is a cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with the schema. The database’s ability to scale up with ease and hold very large amounts of data. MongoDB stores documents in collections within databases. And, it is one of the popular DBMS used by developers today. So, today we will be checking out the 10 most asked MongoDB questions.&lt;/p&gt;

&lt;h2&gt;
  
  
  10 Most Asked MongoDB Questions
&lt;/h2&gt;

&lt;p&gt;Here is the list of MongoDB questions asked frequently by database engineers and developers. We came up with this list to make it easy for developers to solve their problems if they have any questions mentioned in the list. So, let’s begin.&lt;/p&gt;

&lt;h3&gt;
  
  
  1. How to query MongoDB with “like”?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;For this problem, you need to have the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;db.users.find({"name": /.*m.*/})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;or, similar:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;db.users.find({"name": /m/})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You’re looking for something that contains “m” somewhere (SQL’s ‘&lt;code&gt;%&lt;/code&gt;‘ operator is equivalent to Regexp’s ‘&lt;code&gt;.*&lt;/code&gt;‘), not something that has “m” anchored to the beginning of the string.&lt;/p&gt;

&lt;p&gt;Note: MongoDB uses regular expressions which are more powerful than “LIKE” in SQL. With regular expressions, you can create any pattern that you imagine.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;PyMongo&lt;/strong&gt; using &lt;strong&gt;Python&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Mongoose&lt;/strong&gt; using &lt;strong&gt;Node.js&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Jongo&lt;/strong&gt;, using &lt;strong&gt;Java&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;mgo&lt;/strong&gt;, using &lt;strong&gt;Go&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;you can do:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;db.users.find({'name': {'$regex': 'sometext'}})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2. How to drop a MongoDB database from the command line?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can drop a MongoDB database from the command line, like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mongo &amp;lt;dbname&amp;gt; --eval "db.dropDatabase()"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;More info on scripting the shell from the command line here: &lt;a href="https://docs.mongodb.com/manual/tutorial/write-scripts-for-the-mongo-shell/#scripting"&gt;https://docs.mongodb.com/manual/tutorial/write-scripts-for-the-mongo-shell/#scripting&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;From the mongodb console:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt; use mydb; 
&amp;gt; db.dropDatabase();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Alternatively, you can stop &lt;code&gt;mongod&lt;/code&gt; and delete the data files from your data directory, then restart.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint&lt;/strong&gt;: You can also move the data files to a sub folder, and delete them if you’re sure you no longer need them.&lt;/p&gt;

&lt;h3&gt;
  
  
  3. How to list all collections in the MongoDB shell?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can do as given below:&lt;/p&gt;

&lt;p&gt;JavaScript (shell):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;db.getCollectionNames()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Node.js:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;db.listCollections()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Non-JavaScript (shell only):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;show collections
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The reason to call it non-JavaScript is because :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ mongo prodmongo/app --eval "show collections"
MongoDB shell version: 3.2.10
connecting to: prodmongo/app
2016-10-26T19:34:34.886-0400 E QUERY    [thread1] SyntaxError: missing ; before statement @(shell eval):1:5

$ mongo prodmongo/app --eval "db.getCollectionNames()"
MongoDB shell version: 3.2.10
connecting to: prodmongo/app
[
    "Profiles",
    "Unit_Info"
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you really want that sweet, sweet &lt;code&gt;show collections&lt;/code&gt; output, you can:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ mongo prodmongo/app --eval "db.getCollectionNames().join('\n')"
MongoDB shell version: 3.2.10
connecting to: prodmongo/app
Profiles
Unit_Info
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Other methods:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;show collections&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;show tables&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;db.getCollectionNames()&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;To list all databases:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;show dbs
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;To enter or use a given database:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use databasename
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;To list all collections:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;show collections
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Output:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;collection1
collection2
system.indexes
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;(or)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;show tables
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;collection1
collection2
system.indexes
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;(or)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;db.getCollectionNames()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[ "collection1", "collection2", "system.indexes" ]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;To enter or use given collection&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use collectionname
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  4. How to use embed or reference in relationships?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This is more an art than a science. The &lt;a href="https://docs.mongodb.com/manual/data-modeling/"&gt;Mongo Documentation on Schemas&lt;/a&gt; is a good reference, but here are some things to consider:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Put as much in as possible The joy of a Document database is that it eliminates lots of Joins. Your first instinct should be to place as much in a single document as you can. Because MongoDB documents have structure, and because you can efficiently query within that structure (this means that you can take the part of the document that you need, so document size shouldn’t worry you much) there is no immediate need to normalize data like you would in SQL. In particular, any data that is not useful apart from its parent document should be part of the same document.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Separate data that can be referred to from multiple places into its own collection. This is not so much a “storage space” issue as it is a “data consistency” issue. If many records will refer to the same data it is more efficient and less error-prone to update a single record and keep references to it in other places.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Document size considerations MongoDB imposes a 4MB (16MB with 1.8) size limit on a single document. In a world of GB of data, this sounds small, but it is also 30 thousand tweets or 250 typical Stack Overflow answers or 20 flicker photos. On the other hand, this is far more information than one might want to present at one time on a typical web page. First, consider what will make your queries easier. In many cases, concern about document sizes will be premature optimization.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Complex data structures: MongoDB can store arbitrary deep nested data structures, but cannot search them efficiently. If your data forms a tree, forest, or graph, you effectively need to store each node and its edges in a separate document. (Note that there are data stores specifically designed for this type of data that one should consider as well) It has also been pointed out than it is impossible to return a subset of elements in a document. If you need to pick-and-choose a few bits of each document, it will be easier to separate them out.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Data Consistency MongoDB makes a trade-off between efficiency and consistency. The rule changes to a single document are always atomic, while updates to multiple documents should never be assumed to be atomic. There is also no way to “lock” a record on the server (you can build this into the client’s logic using, for example, a “lock” field). When you design your schema consider how you will keep your data consistent. Generally, the more that you keep in a document the better.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Additional Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In general, embed is good if you have one-to-one or one-to-many relationships between entities, and reference is good if you have many-to-many relationships.&lt;/p&gt;

&lt;h3&gt;
  
  
  5. How to get the last N records in MongoDB?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Assuming you have some id or date field called “x” you would do:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;.sort()&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;db.foo.find().sort({x:1});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;strong&gt;1&lt;/strong&gt; will sort ascending (oldest to newest) and &lt;strong&gt;-1&lt;/strong&gt; will sort descending (newest to oldest.)&lt;/p&gt;

&lt;p&gt;If you use the auto-created &lt;strong&gt;_id&lt;/strong&gt; field it has a date embedded in it, so you can use that to order by:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;db.foo.find().sort({_id:1});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That will return back all your documents sorted from oldest to newest.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Natural Order&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can also use a &lt;a href="https://docs.mongodb.com/manual/reference/glossary/#term-natural-order"&gt;Natural Order&lt;/a&gt; mentioned above …&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;db.foo.find().sort({$natural:1});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Again, using &lt;strong&gt;1&lt;/strong&gt; or &lt;strong&gt;-1&lt;/strong&gt; depending on the order you want.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use .limit()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Lastly, it’s good practice to add a limit when doing this sort of wide-open query so you could do either.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;db.foo.find().sort({_id:1}).limit(50);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;or&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;db.foo.find().sort({$natural:1}).limit(50);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  6. Is there a way to tell Mongo to pretty print output?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can ask it to be pretty by following command.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;db.collection.find().pretty()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Also you can add&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DBQuery.prototype._prettyShell = true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;to your file in &lt;code&gt;$HOME/.mongorc.js&lt;/code&gt; to enable pretty print globally by default.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can just do this on the CLI:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;echo DBQuery.prototype._prettyShell = true &amp;gt;&amp;gt; ~/.mongorc.js
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And it’s always going to output pretty results.&lt;/p&gt;

&lt;h3&gt;
  
  
  7. How to find MongoDB records where array field is not empty?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If you have documents that don’t have the key, you can use:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ME.find({ pictures: { $exists: true, $not: {$size: 0} } })
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;MongoDB don’t use indexes if $size is involved, so here is a better solution:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ME.find({ pictures: { $exists: true, $ne: [] } })
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Since MongoDB 2.6 release, you can compare with the operator &lt;code&gt;$gt&lt;/code&gt; but could lead to unexpected results.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ME.find({ pictures: { $gt: [] } }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can also do as given below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ME.find({pictures: {$exists: true, $not: {$size: 0}}})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  8. How to find document with array that contains a specific value?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;As &lt;code&gt;favouriteFoods&lt;/code&gt; is a simple array of strings, you can just query that field directly:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;PersonModel.find({ favouriteFoods: "sushi" }, ...);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But it is also recommended to make the string array explicit in your schema:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;person = {
    name : String,
    favouriteFoods : [String]
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The relevant documentation can be found here: &lt;a href="https://docs.mongodb.com/manual/tutorial/query-arrays/"&gt;https://docs.mongodb.com/manual/tutorial/query-arrays/&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  9. How do you rename a MongoDB database?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Unfortunately, this is not a simple feature for us to implement due to the way that database metadata is stored in the original (default) storage engine. In MMAPv1 files, the namespace (e.g.: dbName.collection) that describes every single collection and index includes the database name, so to rename a set of database files, every single namespace string would have to be rewritten. This impacts:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;the .ns file&lt;/li&gt;
&lt;li&gt;every single numbered file for the collection&lt;/li&gt;
&lt;li&gt;the namespace for every index&lt;/li&gt;
&lt;li&gt;internal unique names of each collection and index&lt;/li&gt;
&lt;li&gt;contents of system.namespaces and system.indexes (or their equivalents in the future)&lt;/li&gt;
&lt;li&gt;other locations that may be missing&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This is just to accomplish a rename of a single database in a standalone mongod instance. For replica sets the above would need to be done on every replica node, plus on each node every single oplog entry that refers this database would have to be somehow invalidated or rewritten, and then if it’s a sharded cluster, one also needs to add these changes to every shard if the DB is sharded, plus the config servers have all the shard metadata in terms of namespaces with their full names.&lt;/p&gt;

&lt;p&gt;There would be absolutely no way to do this on a live system.&lt;/p&gt;

&lt;p&gt;To do it offline, it would require re-writing every single database file to accommodate the new name, and at that point, it would be as slow as the current “copydb” command.&lt;/p&gt;

&lt;p&gt;For more see See &lt;a href="https://jira.mongodb.org/browse/SERVER-7"&gt;https://jira.mongodb.org/browse/SERVER-7&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You could do this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;db.copyDatabase("db_to_rename","db_renamed","localhost")
use db_to_rename
db.dropDatabase();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Also, try this method&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The following shows you how to rename&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt; show dbs;
testing
games
movies
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To rename you use the following syntax&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;db.copyDatabase("old db name","new db name")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;db.copyDatabase('testing','newTesting')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now you can safely delete the old db by the following way&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use testing;

db.dropDatabase(); //Here the db **testing** is deleted successfully
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Now just think what happens if you try renaming the new database name with an existing database name&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;db.copyDatabase('testing','movies'); 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So in this context, all the collections (tables) of &lt;strong&gt;testing&lt;/strong&gt; will be copied to &lt;strong&gt;movies&lt;/strong&gt; database.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ALERT&lt;/strong&gt;: Just be careful while copying the database, if you don’t want to mess up the different collections under a single database.&lt;/p&gt;

&lt;h3&gt;
  
  
  10. How to fix error “&lt;code&gt;sudo chown mongod:mongod /data/db&lt;/code&gt;“?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;You might have created the directory in the wrong place&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;/data/db means that it’s directly under the ‘/’ root directory, whereas you might have created ‘data/db’ (without the leading /) probably just inside another directory, such as the ‘/root’ homedirectory.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;You need to create this directory as root&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Either you need to use &lt;code&gt;sudo&lt;/code&gt;, e.g. &lt;code&gt;sudo mkdir -p /data/db&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Or you need to do &lt;code&gt;su -&lt;/code&gt; to become superuser, and then create the directory with &lt;code&gt;mkdir -p /data/db&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Note:&lt;/p&gt;

&lt;p&gt;MongoDB also has an option where you can create the data directory in another location, but that’s generally not a good idea, because it just slightly complicates things such as DB recovery, because you always have to specify the db-path manually. It is not recommended to do that.&lt;/p&gt;

&lt;p&gt;If the error message you’re getting is &lt;strong&gt;“Unable to create/open lock file: /data/db/mongod.lock errno:13 Permission denied”&lt;/strong&gt;. The directory you created doesn’t seem to have the correct permissions and ownership -it needs to be writable by the user who runs the MongoDB process.&lt;/p&gt;

&lt;p&gt;To see the permissions and ownership of the ‘/data/db/’ directory, do this: (this is what the permissions and ownership should look like)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ ls -ld /data/db/
drwxr-xr-x 4 mongod mongod 4096 Oct 26 10:31 /data/db/
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The left side ‘drwxr-xr-x’ shows the permissions for the User, Group, and Others. ‘mongod mongod’ shows who owns the directory, and which group that directory belongs to. Both are called ‘mongod’ in this case.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;If your ‘/data/db’ directory doesn’t have the permissions and ownership above, do this:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;First, check what user and group your mongo user have:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# grep mongo /etc/passwd
mongod:x:498:496:mongod:/var/lib/mongo:/bin/false
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You should have an entry for mongod in /etc/passwd , as it’s a daemon.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sudo chmod 0755 /data/db
sudo chown -R 498:496 /data/db    # using the user-id , group-id
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can also use the user-name and group-name, as follows: (they can be found in /etc/passwd and /etc/group )&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sudo chown -R mongod:mongod /data/db 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;that should make it work.&lt;/p&gt;

&lt;p&gt;Some people use this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sudo chown -R `id -u` /data/db
sudo chmod -R go+w /data/db
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;or&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sudo chown -R $USER /data/db 
sudo chmod -R go+w /data/db
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The disadvantage is that $USER is an account that has a login shell. Daemons should ideally not have a shell for security reasons, that’s why you see /bin/false in the grep of the password file above.&lt;/p&gt;

&lt;p&gt;Maybe also check out one of the tutorials you can find via Google: “UNIX for beginners”.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;In Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This is the list for 10 most asked MongoDB questions. Hope you are clear about your query regarding MongoDB. If you haven’t found exactly what you have been looking for, please drop your comment. We will get in touch with you as soon as possible.&lt;/p&gt;

&lt;p&gt;This post was first published on &lt;a href="https://thedevpost.com/blog/10-most-asked-mongodb-questions/"&gt;DevPostbyTruemark&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>mongodb</category>
    </item>
    <item>
      <title>12 Most Asked Questions On Python</title>
      <dc:creator>KiranPoudel98</dc:creator>
      <pubDate>Fri, 02 Oct 2020 08:50:11 +0000</pubDate>
      <link>https://forem.com/truemark/12-most-asked-questions-on-python-5dnh</link>
      <guid>https://forem.com/truemark/12-most-asked-questions-on-python-5dnh</guid>
      <description>&lt;p&gt;Python is an open-source high level programming language that is easy to learn and user-friendly. It is one of the first choice of many programmers be it beginner or experienced. So, today we have prepared a list of most asked questions on Python programming language.&lt;/p&gt;

&lt;h2&gt;
  
  
  12 Most Asked Questions On Python
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1. What does the “yield” keyword do?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;yield&lt;/code&gt; is a keyword that is used like &lt;code&gt;return&lt;/code&gt;, except the function will return a generator.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; def createGenerator():
...    mylist = range(3)
...    for i in mylist:
...        yield i*i
...
&amp;gt;&amp;gt;&amp;gt; mygenerator = createGenerator() # create a generator
&amp;gt;&amp;gt;&amp;gt; print(mygenerator) # mygenerator is an object!
&amp;lt;generator object createGenerator at 0xb7555c34&amp;gt;
&amp;gt;&amp;gt;&amp;gt; for i in mygenerator:
...     print(i)
0
1
4
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It’s handy when you know your function will return a huge set of values that you will only need to read once.&lt;/p&gt;

&lt;p&gt;To master &lt;code&gt;yield&lt;/code&gt;, you must understand that &lt;strong&gt;when you call the function, the code you have written in the function body does not run&lt;/strong&gt;. The function only returns the generator object.&lt;/p&gt;

&lt;p&gt;Then, your code will continue from where it left off each time &lt;code&gt;for&lt;/code&gt; uses the generator.&lt;/p&gt;

&lt;p&gt;Now the hard part:&lt;/p&gt;

&lt;p&gt;The first time the &lt;code&gt;for&lt;/code&gt; calls the generator object created from your function, it will run the code in your function from the beginning until it hits &lt;code&gt;yield&lt;/code&gt;, then it’ll return the first value of the loop. Then, each subsequent call will run another iteration of the loop you have written in the function and return the next value. This will continue until the generator is considered empty, which happens when the function runs without hitting &lt;code&gt;yield&lt;/code&gt;. That can be because the loop has come to an end, or because you no longer satisfy an &lt;code&gt;"if/else"&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can also think of it this way.&lt;/p&gt;

&lt;p&gt;An iterator is just a fancy sounding term for an object that has a &lt;code&gt;next()&lt;/code&gt; method. So a yield-ed function ends up being something like this:&lt;/p&gt;

&lt;p&gt;Original version:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def some_function():
    for i in xrange(4):
        yield i

for i in some_function():
    print i
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is basically what the Python interpreter does with the above code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class it:
    def __init__(self):
        # Start at -1 so that we get 0 when we add 1 below.
        self.count = -1

    # The __iter__ method will be called once by the 'for' loop.
    # The rest of the magic happens on the object returned by this method.
    # In this case it is the object itself.
    def __iter__(self):
        return self

    # The next method will be called repeatedly by the 'for' loop
    # until it raises StopIteration.
    def next(self):
        self.count += 1
        if self.count &amp;lt; 4:
            return self.count
        else:
            # A StopIteration exception is raised
            # to signal that the iterator is done.
            # This is caught implicitly by the 'for' loop.
            raise StopIteration

def some_func():
    return it()

for i in some_func():
    print i
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For more insight as to what’s happening behind the scenes, the &lt;code&gt;for&lt;/code&gt; loop can be rewritten to this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;iterator = some_func()
try:
    while 1:
        print iterator.next()
except StopIteration:
    pass
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2. Does Python have a ternary conditional operator?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Yes, it was &lt;a href="https://mail.python.org/pipermail/python-dev/2005-September/056846.html"&gt;added&lt;/a&gt; in version 2.5. The expression syntax is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;a if condition else b
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;First &lt;code&gt;condition&lt;/code&gt; is evaluated, then exactly one of either &lt;code&gt;a&lt;/code&gt; or &lt;code&gt;b&lt;/code&gt; is evaluated and returned based on the &lt;a href="https://en.wikipedia.org/wiki/Boolean_data_type"&gt;Boolean&lt;/a&gt; value of &lt;code&gt;condition&lt;/code&gt;. If &lt;code&gt;condition&lt;/code&gt; evaluates to &lt;code&gt;True&lt;/code&gt;, then &lt;code&gt;a&lt;/code&gt; is evaluated and returned but &lt;code&gt;b&lt;/code&gt; is ignored, or else when &lt;code&gt;b&lt;/code&gt; is evaluated and returned but &lt;code&gt;a&lt;/code&gt; is ignored.&lt;/p&gt;

&lt;p&gt;This allows short-circuiting because when &lt;code&gt;condition&lt;/code&gt; is true only &lt;code&gt;a&lt;/code&gt; is evaluated and &lt;code&gt;b&lt;/code&gt; is not evaluated at all, but when &lt;code&gt;condition&lt;/code&gt; is false only &lt;code&gt;b&lt;/code&gt; is evaluated and &lt;code&gt;a&lt;/code&gt; is not evaluated at all.&lt;/p&gt;

&lt;p&gt;For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; 'true' if True else 'false'
'true'
&amp;gt;&amp;gt;&amp;gt; 'true' if False else 'false'
'false'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that conditionals are an &lt;em&gt;expression&lt;/em&gt;, not a statement. This means you can’t use assignment statements or &lt;code&gt;pass&lt;/code&gt; or other &lt;strong&gt;statements&lt;/strong&gt; within a conditional &lt;strong&gt;expression&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; pass if False else x = 3
  File "&amp;lt;stdin&amp;gt;", line 1
    pass if False else x = 3
          ^
SyntaxError: invalid syntax
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can, however, use conditional expressions to assign a variable like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;x = a if True else b
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Think of the conditional expression as switching between two values. It is very useful when you’re in a ‘one value or another’ situation, it but doesn’t do much else.&lt;/p&gt;

&lt;p&gt;If you need to use statements, you have to use a normal &lt;code&gt;if&lt;/code&gt; &lt;strong&gt;statement&lt;/strong&gt; instead of a &lt;strong&gt;conditional expression&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Keep in mind that it’s frowned upon by some Pythonistas for several reasons:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The order of the arguments is different from those of the classic &lt;code&gt;condition ? a : b&lt;/code&gt; ternary operator from many other languages (such as C, C++, Go, Perl, Ruby, Java, Javascript, etc.), which may lead to bugs when people unfamiliar with Python’s “surprising” behavior use it (they may reverse the argument order).&lt;/li&gt;
&lt;li&gt;Some find it “unwieldy”, since it goes contrary to the normal flow of thought (thinking of the condition first and then the effects).&lt;/li&gt;
&lt;li&gt;Stylistic reasons. (Although the ‘inline &lt;code&gt;if&lt;/code&gt;‘ can be really useful, and make your script more concise, it really does complicate your code)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you’re having trouble remembering the order, then remember that when read aloud, you (almost) say what you mean. For example, &lt;code&gt;x = 4 if b &amp;gt; 8 else 9&lt;/code&gt; is read aloud as &lt;code&gt;x will be 4 if b is greater than 8 otherwise 9&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can index into a tuple:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(falseValue, trueValue)[test]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;test&lt;/code&gt; needs to return True or False.&lt;br&gt;
It might be safer to always implement it as:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(falseValue, trueValue)[test == True]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;or you can use the built-in &lt;a href="https://docs.python.org/3.3/library/functions.html#bool"&gt;&lt;code&gt;bool()&lt;/code&gt;&lt;/a&gt; to assure a Boolean value:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(falseValue, trueValue)[bool(&amp;lt;expression&amp;gt;)]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  3. What are metaclasses in Python?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A metaclass is the class of a class. A class defines how an instance of the class (i.e. an object) behaves while a metaclass defines how a class behaves. A class is an instance of a metaclass.&lt;/p&gt;

&lt;p&gt;While in Python you can use arbitrary callables for metaclasses, the better approach is to make it an actual class itself. &lt;code&gt;type&lt;/code&gt; is the usual metaclass in Python. &lt;code&gt;type&lt;/code&gt; is itself a class, and it is its own type. You won’t be able to recreate something like &lt;code&gt;type&lt;/code&gt; purely in Python, but Python cheats a little. To create your own metaclass in Python you really just want to subclass &lt;code&gt;type&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;A metaclass is most commonly used as a class-factory. When you create an object by calling the class, Python creates a new class (when it executes the ‘class’ statement) by calling the metaclass. Combined with the normal &lt;code&gt;__init__&lt;/code&gt; and &lt;code&gt;__new__&lt;/code&gt; methods, metaclasses therefore allow you to do ‘extra things’ when creating a class, like registering the new class with some registry or replace the class with something else entirely.&lt;/p&gt;

&lt;p&gt;When the &lt;code&gt;class&lt;/code&gt; statement is executed, Python first executes the body of the &lt;code&gt;class&lt;/code&gt; statement as a normal block of code. The resulting namespace (a dict) holds the attributes of the class-to-be. The metaclass is determined by looking at the baseclasses of the class-to-be (metaclasses are inherited), at the &lt;code&gt;__metaclass__&lt;/code&gt; attribute of the class-to-be (if any) or the &lt;code&gt;__metaclass__&lt;/code&gt; global variable. The metaclass is then called with the name, bases and attributes of the class to instantiate it.&lt;/p&gt;

&lt;p&gt;However, metaclasses actually define the type of a class, not just a factory for it, so you can do much more with them. You can, for instance, define normal methods on the metaclass. These metaclass-methods are like classmethods in that they can be called on the class without an instance, but they are also not like classmethods in that they cannot be called on an instance of the class. &lt;code&gt;type&lt;/code&gt;.&lt;code&gt;__subclasses__()&lt;/code&gt; is an example of a method on the &lt;code&gt;type&lt;/code&gt; metaclass. You can also define the normal ‘magic’ methods, like &lt;code&gt;__add__&lt;/code&gt;, &lt;code&gt;__iter__&lt;/code&gt; and &lt;code&gt;__getattr__&lt;/code&gt;, to implement or change how the class behaves.&lt;/p&gt;

&lt;p&gt;Here’s an aggregated example of the bits and pieces:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def make_hook(f):
    """Decorator to turn 'foo' method into '__foo__'"""
    f.is_hook = 1
    return f

class MyType(type):
    def __new__(mcls, name, bases, attrs):

        if name.startswith('None'):
            return None

        # Go over attributes and see if they should be renamed.
        newattrs = {}
        for attrname, attrvalue in attrs.iteritems():
            if getattr(attrvalue, 'is_hook', 0):
                newattrs['__%s__' % attrname] = attrvalue
            else:
                newattrs[attrname] = attrvalue

        return super(MyType, mcls).__new__(mcls, name, bases, newattrs)

    def __init__(self, name, bases, attrs):
        super(MyType, self).__init__(name, bases, attrs)

        # classregistry.register(self, self.interfaces)
        print "Would register class %s now." % self

    def __add__(self, other):
        class AutoClass(self, other):
            pass
        return AutoClass
        # Alternatively, to autogenerate the classname as well as the class:
        # return type(self.__name__ + other.__name__, (self, other), {})

    def unregister(self):
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  4. How to check whether a file exists without exceptions?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If the reason you’re checking is so you can do something like &lt;code&gt;if file_exists: open_it()&lt;/code&gt;, it’s safer to use a &lt;code&gt;try&lt;/code&gt; around the attempt to open it. Checking and then opening risks the file being deleted or moved or something between when you check and when you try to open it.&lt;/p&gt;

&lt;p&gt;If you’re not planning to open the file immediately, you can use &lt;a href="https://docs.python.org/3/library/os.path.html#os.path.isfile"&gt;&lt;code&gt;os.path.isfile&lt;/code&gt;&lt;/a&gt;.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Return &lt;code&gt;True&lt;/code&gt; if path is an existing regular file. This follows symbolic links, so both &lt;a href="https://docs.python.org/3/library/os.path.html#os.path.islink"&gt;islink()&lt;/a&gt; and &lt;a href="https://docs.python.org/3/library/os.path.html#os.path.isfile"&gt;isfile()&lt;/a&gt; can be true for the same path.&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import os.path
os.path.isfile(fname) 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;if you need to be sure it’s a file.&lt;/p&gt;

&lt;p&gt;Starting with Python 3.4, the &lt;a href="https://docs.python.org/3/library/pathlib.html#pathlib.Path.is_file"&gt;&lt;code&gt;pathlib&lt;/code&gt; module&lt;/a&gt; offers an object-oriented approach (backported to &lt;code&gt;pathlib2&lt;/code&gt; in Python 2.7):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from pathlib import Path

my_file = Path("/path/to/file")
if my_file.is_file():
    # file exists
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To check a directory, do:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if my_file.is_dir():
    # directory exists
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To check whether a &lt;code&gt;Path&lt;/code&gt; object exists independently of whether is it a file or directory, use &lt;code&gt;exists()&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if my_file.exists():
    # path exists
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can also use &lt;code&gt;resolve(strict=True)&lt;/code&gt; in a &lt;code&gt;try&lt;/code&gt; block:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;try:
    my_abs_path = my_file.resolve(strict=True)
except FileNotFoundError:
    # doesn't exist
else:
    # exists
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You have the &lt;a href="https://docs.python.org/2/library/os.path.html#os.path.exists"&gt;&lt;code&gt;os.path.exists&lt;/code&gt;&lt;/a&gt; function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import os.path
os.path.exists(file_path)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This returns &lt;code&gt;True&lt;/code&gt; for both files and directories but you can instead use&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;os.path.isfile(file_path)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;to test if it’s a file specifically. It follows symlinks.&lt;/p&gt;

&lt;h3&gt;
  
  
  5. How to call an external command from within a Python script?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Look at the &lt;a href="https://docs.python.org/3/library/subprocess.html"&gt;subprocess&lt;/a&gt; module in the standard library:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import subprocess
subprocess.run(["ls", "-l"])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The advantage of &lt;code&gt;subprocess&lt;/code&gt; vs. &lt;code&gt;system&lt;/code&gt; is that it is more flexible (you can get the &lt;code&gt;stdout&lt;/code&gt;, &lt;code&gt;stderr&lt;/code&gt;, the “real” status code, better error handling, etc.).&lt;/p&gt;

&lt;p&gt;The &lt;a href="https://docs.python.org/3/library/os.html#os.system"&gt;official documentation&lt;/a&gt; recommends the &lt;code&gt;subprocess&lt;/code&gt; module over the alternative &lt;code&gt;os.system()&lt;/code&gt;:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The &lt;code&gt;subprocess&lt;/code&gt; module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function [&lt;a href="https://docs.python.org/3/library/os.html#os.system"&gt;&lt;code&gt;os.system()&lt;/code&gt;&lt;/a&gt;].&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The &lt;a href="https://docs.python.org/3/library/subprocess.html#replacing-older-functions-with-the-subprocess-module"&gt;Replacing Older Functions with the subprocess Module&lt;/a&gt; section in the &lt;code&gt;subprocess&lt;/code&gt; documentation may have some helpful recipes.&lt;/p&gt;

&lt;p&gt;For versions of Python before 3.5, use &lt;code&gt;call&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import subprocess
subprocess.call(["ls", "-l"])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Here’s a summary of the ways to call external programs and the advantages and disadvantages of each:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;os.system("some_command with args")&lt;/code&gt; passes the command and arguments to your system’s shell. This is nice because you can actually run multiple commands at once in this manner and set up pipes and input/output redirection. For example: &lt;code&gt;os.system("some_command &amp;lt; input_file | another_command &amp;gt; output_file")&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;However, while this is convenient, you have to manually handle the escaping of shell characters such as spaces, etc. On the other hand, this also lets you run commands which are simply shell commands and not actually external programs. See &lt;a href="https://docs.python.org/2/library/os.html#os.system"&gt;the documentation&lt;/a&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;stream = os.popen("some_command with args")&lt;/code&gt; will do the same thing as &lt;code&gt;os.system&lt;/code&gt; except that it gives you a file-like object that you can use to access standard input/output for that process. There are 3 other variants of popen that all handle the i/o slightly differently. If you pass everything as a string, then your command is passed to the shell; if you pass them as a list then you don’t need to worry about escaping anything. See &lt;a href="https://docs.python.org/2/library/os.html#os.popen"&gt;the documentation&lt;/a&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The &lt;code&gt;Popen&lt;/code&gt; class of the &lt;code&gt;subprocess&lt;/code&gt; module. This is intended as a replacement for &lt;code&gt;os.popen&lt;/code&gt; but has the downside of being slightly more complicated by virtue of being so comprehensive. For example, you’d say: &lt;code&gt;print subprocess.Popen("echo Hello World", shell=True, stdout=subprocess.PIPE).stdout.read()&lt;/code&gt; instead of: &lt;code&gt;print os.popen("echo Hello World").read()&lt;/code&gt; but it is nice to have all of the options there in one unified class instead of 4 different popen functions. See &lt;a href="https://docs.python.org/2/library/subprocess.html#popen-constructor"&gt;the documentation&lt;/a&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The &lt;code&gt;call&lt;/code&gt; function from the &lt;code&gt;subprocess&lt;/code&gt; module. This is basically just like the &lt;code&gt;Popen&lt;/code&gt; class and takes all of the same arguments, but it simply waits until the command completes and gives you the return code. For example: &lt;code&gt;return_code = subprocess.call("echo Hello World", shell=True)&lt;/code&gt;. See &lt;a href="https://docs.python.org/2/library/subprocess.html#subprocess.call"&gt;the documentation&lt;/a&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If you’re on Python 3.5 or later, you can use the new &lt;a href="https://docs.python.org/3.5/library/subprocess.html#subprocess.run"&gt;&lt;code&gt;subprocess.run&lt;/code&gt;&lt;/a&gt; function, which is a lot like the above but even more flexible and returns a &lt;a href="https://docs.python.org/3.5/library/subprocess.html#subprocess.CompletedProcess"&gt;&lt;code&gt;CompletedProcess&lt;/code&gt;&lt;/a&gt; object when the command finishes executing.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The os module also has all of the fork/exec/spawn functions that you’d have in a C program, but we don’t recommend using them directly.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The &lt;code&gt;subprocess&lt;/code&gt; module should probably be what you use.&lt;/p&gt;

&lt;p&gt;Finally please be aware that for all methods where you pass the final command to be executed by the shell as a string and you are responsible for escaping it. &lt;strong&gt;There are serious security implications&lt;/strong&gt; if any part of the string that you pass can not be fully trusted. For example, if a user is entering some/any part of the string. If you are unsure, only use these methods with constants. To give you a hint of the implications consider this code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print subprocess.Popen("echo %s " % user_input, stdout=PIPE).stdout.read()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and imagine that the user enters something “my mama didnt love me &amp;amp;&amp;amp; rm -rf /” which could erase the whole filesystem.&lt;/p&gt;

&lt;h3&gt;
  
  
  6. How to create a nested directory safely?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;On Python ≥ 3.5, use &lt;a href="https://docs.python.org/3/library/pathlib.html#pathlib.Path.mkdir"&gt;&lt;code&gt;pathlib.Path.mkdir&lt;/code&gt;&lt;/a&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from pathlib import Path
Path("/my/directory").mkdir(parents=True, exist_ok=True)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For older versions of Python, we see two answers with good qualities, each with a small flaw, so we will give our take on it:&lt;/p&gt;

&lt;p&gt;Try &lt;a href="https://docs.python.org/3/library/os.path.html#os.path.exists"&gt;&lt;code&gt;os.path.exists&lt;/code&gt;&lt;/a&gt; and consider &lt;a href="https://docs.python.org/3/library/os.html#os.makedirs"&gt;&lt;code&gt;os.makedirs&lt;/code&gt;&lt;/a&gt; for the creation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import os
if not os.path.exists(directory):
    os.makedirs(directory)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As noted, there’s a race condition – if the directory is created between the &lt;code&gt;os.path.exists&lt;/code&gt; and the &lt;code&gt;os.makedirs&lt;/code&gt; calls, the &lt;code&gt;os.makedirs&lt;/code&gt; will fail with an &lt;code&gt;OSError&lt;/code&gt;. Unfortunately, blanket-catching &lt;code&gt;OSError&lt;/code&gt; and continuing is not foolproof, as it will ignore a failure to create the directory due to other factors, such as insufficient permissions, full disk, etc.&lt;/p&gt;

&lt;p&gt;One option would be to trap the &lt;code&gt;OSError&lt;/code&gt; and examine the embedded error code (see &lt;a href="https://stackoverflow.com/questions/273698/is-there-a-cross-platform-way-of-getting-information-from-pythons-oserror"&gt;Is there a cross-platform way of getting information from Python’s OSError&lt;/a&gt;):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import os, errno

try:
    os.makedirs(directory)
except OSError as e:
    if e.errno != errno.EEXIST:
        raise
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Alternatively, there could be a second &lt;code&gt;os.path.exists&lt;/code&gt;, but suppose another created the directory after the first check, then removed it before the second one – we could still be fooled.&lt;/p&gt;

&lt;p&gt;Depending on the application, the danger of concurrent operations may be more or less than the danger posed by other factors such as file permissions. The developer would have to know more about the particular application being developed and its expected environment before choosing an implementation.&lt;/p&gt;

&lt;p&gt;Modern versions of Python improve this code quite a bit, both by exposing &lt;a href="https://docs.python.org/3.3/library/exceptions.html?#FileExistsError"&gt;&lt;code&gt;FileExistsError&lt;/code&gt;&lt;/a&gt; (in 3.3+).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;try:
    os.makedirs("path/to/directory")
except FileExistsError:
    # directory already exists
    pass
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and by allowing &lt;a href="https://docs.python.org/3.2/library/os.html#os.makedirs"&gt;a keyword argument to &lt;code&gt;os.makedirs&lt;/code&gt; called &lt;code&gt;exist_ok&lt;/code&gt;&lt;/a&gt; (in 3.2+).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;os.makedirs("path/to/directory", exist_ok=True)  # succeeds even if directory exists.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Python 3.5+:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import pathlib
pathlib.Path('/my/directory').mkdir(parents=True, exist_ok=True) 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://docs.python.org/3/library/pathlib.html#pathlib.Path.mkdir"&gt;&lt;code&gt;pathlib.Path.mkdir&lt;/code&gt;&lt;/a&gt; as used above recursively creates the directory and does not raise an exception if the directory already exists. If you don’t need or want the parents to be created, skip the &lt;code&gt;parents&lt;/code&gt; argument.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Python 3.2+:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Using &lt;code&gt;pathlib&lt;/code&gt;:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If you can, install the current &lt;code&gt;pathlib&lt;/code&gt; backport named &lt;a href="https://pypi.org/project/pathlib2/"&gt;pathlib2&lt;/a&gt;. Do not install the older unmaintained backport named &lt;a href="https://pypi.org/project/pathlib/"&gt;&lt;code&gt;pathlib&lt;/code&gt;&lt;/a&gt;. Next, refer to the Python 3.5+ section above and use it the same.&lt;/p&gt;

&lt;p&gt;If using Python 3.4, even though it comes with &lt;code&gt;pathlib&lt;/code&gt;, it is missing the useful &lt;code&gt;exist_ok&lt;/code&gt; option. The backport is intended to offer a newer and superior implementation of &lt;code&gt;mkdir&lt;/code&gt; which includes this missing option.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Using &lt;code&gt;os&lt;/code&gt;:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import os
os.makedirs(path, exist_ok=True)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://docs.python.org/3/library/os.html#os.makedirs"&gt;&lt;code&gt;os.makedirs&lt;/code&gt;&lt;/a&gt; as used above recursively creates the directory and does not raise an exception if the directory already exists. It has the optional &lt;code&gt;exist_ok&lt;/code&gt; argument only if using Python 3.2+, with a default value of &lt;code&gt;False&lt;/code&gt;. This argument does not exist in Python 2.x up to 2.7. As such, there is no need for manual exception handling as with Python 2.7.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Python 2.7+:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Using pathlib:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If you can, install the current &lt;code&gt;pathlib&lt;/code&gt; backport named &lt;code&gt;pathlib2&lt;/code&gt;. Do not install the older unmaintained backport named &lt;code&gt;pathlib&lt;/code&gt;. Next, refer to the Python 3.5+ section above and use it the same.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Using &lt;code&gt;os&lt;/code&gt;:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import os
try: 
    os.makedirs(path)
except OSError:
    if not os.path.isdir(path):
        raise
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;While a naive solution may first use &lt;a href="https://docs.python.org/2/library/os.path.html#os.path.isdir"&gt;&lt;code&gt;os.path.isdir&lt;/code&gt;&lt;/a&gt; followed by &lt;a href="https://docs.python.org/2/library/os.html#os.makedirs"&gt;&lt;code&gt;os.makedirs&lt;/code&gt;&lt;/a&gt;, the solution above reverses the order of the two operations. In doing so, it prevents a common race condition having to do with a duplicated attempt at creating the directory, and also disambiguates files from directories.&lt;/p&gt;

&lt;p&gt;Note that capturing the exception and using &lt;code&gt;errno&lt;/code&gt; is of limited usefulness because &lt;code&gt;OSError: [Errno 17] File exists, i.e. errno.EEXIST,&lt;/code&gt; is raised for both files and directories. It is more reliable simply to check if the directory exists.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://docs.python.org/3/distutils/apiref.html#distutils.dir_util.mkpath"&gt;&lt;code&gt;mkpath&lt;/code&gt;&lt;/a&gt; creates the nested directory, and does nothing if the directory already exists. This works in both Python 2 and 3.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import distutils.dir_util
distutils.dir_util.mkpath(path)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Per &lt;a href="https://bugs.python.org/issue10948"&gt;Bug 10948&lt;/a&gt;, a severe limitation of this alternative is that it works only once per python process for a given path. In other words, if you use it to create a directory, then delete the directory from inside or outside Python, then use &lt;code&gt;mkpath&lt;/code&gt; again to recreate the same directory, &lt;code&gt;mkpath&lt;/code&gt; will simply silently use its invalid cached info of having previously created the directory, and will not actually make the directory again. In contrast, &lt;code&gt;os.makedirs&lt;/code&gt; doesn’t rely on any such cache. This limitation may be okay for some applications.&lt;/p&gt;

&lt;h3&gt;
  
  
  7. Does Python have a string ‘contains’ substring method?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can use the &lt;a href="https://docs.python.org/3/reference/expressions.html#membership-test-details"&gt;&lt;code&gt;in&lt;/code&gt; operator&lt;/a&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if "blah" not in somestring: 
    continue
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If it’s just a substring search you can use &lt;code&gt;string.find("substring")&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;You do have to be a little careful with &lt;a href="https://docs.python.org/3/library/stdtypes.html#str.find"&gt;&lt;code&gt;find&lt;/code&gt;&lt;/a&gt;, &lt;a href="https://docs.python.org/3/library/stdtypes.html#str.index"&gt;&lt;code&gt;index&lt;/code&gt;&lt;/a&gt;, and &lt;a href="https://docs.python.org/3/reference/expressions.html#membership-test-operations"&gt;&lt;code&gt;in&lt;/code&gt;&lt;/a&gt; though, as they are substring searches. In other words, this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;s = "This be a string"
if s.find("is") == -1:
    print("No 'is' here!")
else:
    print("Found 'is' in the string.")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It would print &lt;code&gt;Found 'is' in the string&lt;/code&gt;. Similarly, if &lt;code&gt;"is"&lt;/code&gt; in &lt;code&gt;s:&lt;/code&gt; would evaluate to &lt;code&gt;True&lt;/code&gt;. This may or may not be what you want.&lt;/p&gt;

&lt;h3&gt;
  
  
  8. How to access the index in ‘for’ loops?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Using an additional state variable, such as an index variable (which you would normally use in languages such as C or PHP), is considered non-pythonic.&lt;/p&gt;

&lt;p&gt;The better option is to use the built-in function &lt;a href="https://docs.python.org/3/library/functions.html#enumerate"&gt;&lt;code&gt;enumerate()&lt;/code&gt;&lt;/a&gt;, available in both Python 2 and 3:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for idx, val in enumerate(ints):
    print(idx, val)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Check out &lt;a href="https://www.python.org/dev/peps/pep-0279/"&gt;PEP 279&lt;/a&gt; for more.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Use &lt;code&gt;enumerate&lt;/code&gt; to get the index with the element as you iterate:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for index, item in enumerate(items):
    print(index, item)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And note that Python’s indexes start at zero, so you would get 0 to 4 with the above. If you want the count, 1 to 5, do this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for count, item in enumerate(items, start=1):
    print(count, item)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  9. What is the difference between staticmethod and classmethod?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Maybe a bit of example code will help. Notice the difference in the call signatures of &lt;code&gt;foo&lt;/code&gt;, &lt;code&gt;class_foo&lt;/code&gt; and &lt;code&gt;static_foo&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class A(object):
    def foo(self, x):
        print "executing foo(%s, %s)" % (self, x)

    @classmethod
    def class_foo(cls, x):
        print "executing class_foo(%s, %s)" % (cls, x)

    @staticmethod
    def static_foo(x):
        print "executing static_foo(%s)" % x    

a = A()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Below is the usual way an object instance calls a method. The object instance, &lt;code&gt;a&lt;/code&gt;, is implicitly passed as the first argument.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;a.foo(1)
# executing foo(&amp;lt;__main__.A object at 0xb7dbef0c&amp;gt;,1)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;With classmethods&lt;/strong&gt;, the class of the object instance is implicitly passed as the first argument instead of &lt;code&gt;self&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;a.class_foo(1)
# executing class_foo(&amp;lt;class '__main__.A'&amp;gt;,1)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can also call &lt;code&gt;class_foo&lt;/code&gt; using the class. In fact, if you define something to be a classmethod, it is probably because you intend to call it from the class rather than from a class instance. &lt;code&gt;A.foo(1)&lt;/code&gt; would have raised a TypeError, but &lt;code&gt;A.class_foo(1)&lt;/code&gt; works just fine:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;A.class_foo(1)
# executing class_foo(&amp;lt;class '__main__.A'&amp;gt;,1)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;One use people have found for class methods is to create &lt;a href="https://stackoverflow.com/questions/1950414/what-does-classmethod-do-in-this-code/1950927#1950927"&gt;inheritable alternative constructors&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;With staticmethods&lt;/strong&gt;, neither &lt;code&gt;self&lt;/code&gt; (the object instance) nor &lt;code&gt;cls&lt;/code&gt; (the class) is implicitly passed as the first argument. They behave like plain functions except that you can call them from an instance or the class:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;a.static_foo(1)
# executing static_foo(1)

A.static_foo('hi')
# executing static_foo(hi)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Staticmethods are used to group functions which have some logical connection with a class to the class.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;foo&lt;/code&gt; is just a function, but when you call &lt;code&gt;a.foo&lt;/code&gt; you don’t just get the function, you get a “partially applied” version of the function with the object instance &lt;code&gt;a&lt;/code&gt; bound as the first argument to the function. &lt;code&gt;foo&lt;/code&gt; expects 2 arguments, while &lt;code&gt;a.foo&lt;/code&gt; only expects 1 argument.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;a&lt;/code&gt; is bound to &lt;code&gt;foo&lt;/code&gt;. That is what is meant by the term “bound” below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print(a.foo)
# &amp;lt;bound method A.foo of &amp;lt;__main__.A object at 0xb7d52f0c&amp;gt;&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With &lt;code&gt;a.class_foo&lt;/code&gt;, a is not bound to &lt;code&gt;class_foo&lt;/code&gt;, rather the class &lt;code&gt;A&lt;/code&gt; is bound to &lt;code&gt;class_foo&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print(a.class_foo)
# &amp;lt;bound method type.class_foo of &amp;lt;class '__main__.A'&amp;gt;&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, with a staticmethod, even though it is a method, &lt;code&gt;a.static_foo&lt;/code&gt; just returns a good old function with no arguments bound. &lt;code&gt;static_foo&lt;/code&gt; expects 1 argument, and &lt;code&gt;a.static_foo&lt;/code&gt; expects 1 argument too.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print(a.static_foo)
# &amp;lt;function static_foo at 0xb7d479cc&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And of course the same thing happens when you call &lt;code&gt;static_foo&lt;/code&gt; with the class A instead.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print(A.static_foo)
# &amp;lt;function static_foo at 0xb7d479cc&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Additional Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A &lt;strong&gt;staticmethod&lt;/strong&gt; is a method that knows nothing about the class or instance it was called on. It just gets the arguments that were passed, no implicit first argument. It is basically useless in Python — you can just use a module function instead of a staticmethod.&lt;/p&gt;

&lt;p&gt;A &lt;strong&gt;classmethod&lt;/strong&gt;, on the other hand, is a method that gets passed the class it was called on, or the class of the instance it was called on, as first argument. This is useful when you want the method to be a factory for the class: since it gets the actual class it was called on as first argument, you can always instantiate the right class, even when subclasses are involved. Observe for instance how &lt;code&gt;dict.fromkeys()&lt;/code&gt;, a classmethod, returns an instance of the subclass when called on a subclass:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; class DictSubclass(dict):
...     def __repr__(self):
...         return "DictSubclass"
... 
&amp;gt;&amp;gt;&amp;gt; dict.fromkeys("abc")
{'a': None, 'c': None, 'b': None}
&amp;gt;&amp;gt;&amp;gt; DictSubclass.fromkeys("abc")
DictSubclass
&amp;gt;&amp;gt;&amp;gt; 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  10. How to list all files of a directory?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://docs.python.org/2/library/os.html#os.listdir"&gt;&lt;code&gt;os.listdir()&lt;/code&gt;&lt;/a&gt; will get you everything that’s in a directory – &lt;strong&gt;files&lt;/strong&gt; and &lt;strong&gt;directories&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;If you want just files, you could either filter this down using &lt;a href="https://docs.python.org/2/library/os.path.html#module-os.path"&gt;&lt;code&gt;os.path&lt;/code&gt;&lt;/a&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;or you could use &lt;a href="https://docs.python.org/2/library/os.html#os.walk"&gt;&lt;code&gt;os.walk()&lt;/code&gt;&lt;/a&gt; which will &lt;strong&gt;yield two lists&lt;/strong&gt; for each directory it visits – splitting into &lt;strong&gt;files&lt;/strong&gt; and &lt;strong&gt;dirs&lt;/strong&gt; for you. If you only want the top directory you can just break the first time it yields&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from os import walk

f = []
for (dirpath, dirnames, filenames) in walk(mypath):
    f.extend(filenames)
    break
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can also prefer using the &lt;a href="https://docs.python.org/3/library/glob.html"&gt;&lt;code&gt;glob&lt;/code&gt;&lt;/a&gt; module, as it does pattern matching and expansion.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import glob
print(glob.glob("/home/adam/*.txt"))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It will return a list with the queried files:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;['/home/adam/file1.txt', '/home/adam/file2.txt', .... ]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  11. How to make a flat list out of list of lists?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Given a list of lists l,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;flat_list = [item for sublist in l for item in sublist]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;which means:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;flat_list = []
for sublist in l:
    for item in sublist:
        flat_list.append(item)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;is faster than the shortcuts posted so far. (l is the list to flatten.)&lt;/p&gt;

&lt;p&gt;Here is the corresponding function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;flatten = lambda l: [item for sublist in l for item in sublist]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As evidence, you can use the &lt;code&gt;timeit&lt;/code&gt; module in the standard library:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' '[item for sublist in l for item in sublist]'
10000 loops, best of 3: 143 usec per loop
$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'sum(l, [])'
1000 loops, best of 3: 969 usec per loop
$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'reduce(lambda x,y: x+y,l)'
1000 loops, best of 3: 1.1 msec per loop
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Explanation:&lt;/strong&gt; The shortcuts based on &lt;code&gt;+&lt;/code&gt; (including the implied use in &lt;code&gt;sum&lt;/code&gt;) are, of necessity, &lt;code&gt;O(L**2)&lt;/code&gt; when there are L sublists — as the intermediate result list keeps getting longer, at each step a new intermediate result list object gets allocated, and all the items in the previous intermediate result must be copied over (as well as a few new ones added at the end). So, for simplicity and without actual loss of generality, say you have L sublists of I items each: the first I items are copied back and forth L-1 times, the second I items L-2 times, and so on; total number of copies is I times the sum of x for x from 1 to L excluded, i.e., &lt;code&gt;I * (L**2)/2&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The list comprehension just generates one list, once, and copies each item over (from its original place of residence to the result list) also exactly once.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can use &lt;a href="https://docs.python.org/3/library/itertools.html#itertools.chain"&gt;itertools.chain()&lt;/a&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import itertools
list2d = [[1,2,3], [4,5,6], [7], [8,9]]
merged = list(itertools.chain(*list2d))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or you can use &lt;a href="https://docs.python.org/3/library/itertools.html#itertools.chain.from_iterable"&gt;&lt;code&gt;itertools.chain.from_iterable()&lt;/code&gt;&lt;/a&gt; which doesn’t require unpacking the list with the &lt;a href="https://docs.python.org/3/tutorial/controlflow.html#tut-unpacking-arguments"&gt;&lt;code&gt;*&lt;/code&gt; operator&lt;/a&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import itertools
list2d = [[1,2,3], [4,5,6], [7], [8,9]]
merged = list(itertools.chain.from_iterable(list2d))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  12. How to check if a list is empty?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if not a:
  print("List is empty")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using the &lt;a href="https://docs.python.org/3/library/stdtypes.html#truth-value-testing"&gt;implicit booleanness&lt;/a&gt; of the empty &lt;code&gt;list&lt;/code&gt; is quite pythonic.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The pythonic way to do it is from the &lt;a href="https://www.python.org/dev/peps/pep-0008/"&gt;PEP 8 style guide&lt;/a&gt; (where &lt;strong&gt;Yes&lt;/strong&gt; means “recommended” and &lt;strong&gt;No&lt;/strong&gt; means “not recommended”):&lt;/p&gt;

&lt;p&gt;For sequences, (strings, lists, tuples), use the fact that empty sequences are false.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Yes: if not seq:
     if seq:

No:  if len(seq):
     if not len(seq):
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;In Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;These are the 12 most commonly asked questions about Python. If you have any suggestions regarding the article, please feel free to comment below. If you need any help, then we would be glad to help you.&lt;/p&gt;

&lt;p&gt;We, at &lt;a href="https://www.truemark.dev/"&gt;Truemark&lt;/a&gt;, provide services like web and mobile app development, digital marketing, and website development. So, if you want to work with us, please feel free to contact us.&lt;/p&gt;

&lt;p&gt;Hope this article helped you.&lt;/p&gt;

&lt;p&gt;This article was first published on &lt;a href="https://thedevpost.com/blog/12-most-asked-questions-on-python/"&gt;DevPostbyTruemark&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>python</category>
    </item>
    <item>
      <title>10 Most Asked Questions On Node.js</title>
      <dc:creator>KiranPoudel98</dc:creator>
      <pubDate>Fri, 25 Sep 2020 07:53:06 +0000</pubDate>
      <link>https://forem.com/truemark/10-most-asked-questions-on-node-js-4lpf</link>
      <guid>https://forem.com/truemark/10-most-asked-questions-on-node-js-4lpf</guid>
      <description>&lt;p&gt;Node.js is the server-side JavaScript runtime environment that executes JavaScript outside of the browser. So, today we have brought a list of most frequently asked questions on Node.js.&lt;/p&gt;

&lt;h2&gt;
  
  
  10 Most Asked Questions on Node.js
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1. How to update npm on Windows?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This is the new best way to &lt;a href="https://github.com/felixrieseberg/npm-windows-upgrade"&gt;upgrade npm on Windows&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Run PowerShell as Administrator&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force
npm install -g npm-windows-upgrade
npm-windows-upgrade
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note: Do not run &lt;code&gt;npm i -g npm&lt;/code&gt;. Instead, use &lt;code&gt;npm-windows-upgrade&lt;/code&gt; to update npm going forward. Also if you run the NodeJS installer, it will replace the node version.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Upgrades npm in-place, where node installed it.&lt;/li&gt;
&lt;li&gt;Easy updating, update to the latest by running &lt;code&gt;npm-windows-upgrade -p -v latest&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Does not modify the default path.&lt;/li&gt;
&lt;li&gt;Does not change the default global package location.&lt;/li&gt;
&lt;li&gt;Allows easy upgrades and downgrades.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://github.com/npm/npm#upgrading-on-windows"&gt;Officially recommended by the NPM team&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;A list of versions matched between NPM and NODE (&lt;a href="https://nodejs.org/en/download/releases/"&gt;https://nodejs.org/en/download/releases/&lt;/a&gt;) – but you will need to download NODE INSTALLER and run that to update node (&lt;a href="https://nodejs.org/en/"&gt;https://nodejs.org/en/&lt;/a&gt;)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://nodejs.org/en/download/"&gt;Download&lt;/a&gt; and run the latest MSI. The MSI will update your installed node and npm.&lt;/p&gt;

&lt;h3&gt;
  
  
  2. How to measure the time taken by a function to execute?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Using &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Performance/now"&gt;performance.now()&lt;/a&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var t0 = performance.now()

doSomething()   // &amp;lt;---- The function you're measuring time for 

var t1 = performance.now()
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;NodeJs: it is required to &lt;a href="https://nodejs.org/api/perf_hooks.html#perf_hooks_class_performance"&gt;import the performance&lt;/a&gt; class.&lt;/p&gt;

&lt;p&gt;Using &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Console/time"&gt;console.time&lt;/a&gt;: (&lt;a href="https://console.spec.whatwg.org/#time"&gt;living standard&lt;/a&gt;)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.time('someFunction')

someFunction() // Whatever is timed goes between the two "console.time"

console.timeEnd('someFunction')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt;&lt;br&gt;
The string being pass to the &lt;code&gt;time()&lt;/code&gt; and &lt;code&gt;timeEnd()&lt;/code&gt; methods must match&lt;br&gt;
(for the timer to finish as expected).&lt;/p&gt;

&lt;p&gt;&lt;code&gt;console.time()&lt;/code&gt; documentations:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://nodejs.org/api/console.html#console_console_timeend_label"&gt;NodeJS documentation regarding&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Console/time"&gt;MDN (client-side) documentation&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;use &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime"&gt;new Date().getTime()&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The getTime() method returns the number of milliseconds since midnight of January 1, 1970.&lt;/p&gt;

&lt;p&gt;example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var start = new Date().getTime();

for (i = 0; i &amp;lt; 50000; ++i) {
// do something
}

var end = new Date().getTime();
var time = end - start;
alert('Execution time: ' + time);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  3. How to update NodeJS and NPM to the next versions?
&lt;/h3&gt;

&lt;p&gt;Answer:&lt;/p&gt;

&lt;p&gt;You can see the docs for the &lt;a href="https://docs.npmjs.com/cli/update"&gt;&lt;code&gt;update&lt;/code&gt;&lt;/a&gt; command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm update [-g] [&amp;lt;pkg&amp;gt;...]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This command will update all the packages listed to the latest version (specified by the tag config), respecting semver.&lt;/p&gt;

&lt;p&gt;Additionally, see the documentation on &lt;a href="https://docs.npmjs.com/downloading-and-installing-node-js-and-npm"&gt;Node.js and NPM installation&lt;/a&gt; and &lt;a href="https://docs.npmjs.com/try-the-latest-stable-version-of-npm"&gt;Upgrading NPM&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The following answer should work for Linux and Mac:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install -g npm
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Please note that this command will remove your current version of npm. Make sure to use &lt;code&gt;sudo npm install -g npm&lt;/code&gt; if on a Mac.&lt;/p&gt;

&lt;p&gt;You can also update all outdated local packages by doing &lt;code&gt;npm update&lt;/code&gt; without any arguments, or global packages by doing &lt;code&gt;npm update -g&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Occasionally, the version of npm will progress such that the current version cannot be properly installed with the version that you have installed already. (Consider, if there is ever a bug in the update command.) In those cases, you can do this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;curl https://www.npmjs.com/install.sh | sh
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To update Node.js itself, we recommend you use &lt;a href="https://github.com/nvm-sh/nvm"&gt;nvm, the Node Version Manager&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We found this really neat way of updating node on &lt;a href="https://davidwalsh.name/upgrade-nodejs"&gt;David Walsh’s blog&lt;/a&gt;, you can do it by installing &lt;a href="https://www.npmjs.com/package/n"&gt;&lt;code&gt;n&lt;/code&gt;&lt;/a&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sudo npm cache clean -f
sudo npm install -g n
sudo n stable
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It will install the current stable version of &lt;code&gt;node&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Please don’t use n anymore. We recommend using &lt;a href="https://github.com/nvm-sh/nvm"&gt;nvm&lt;/a&gt;. You can simply install stable by following the commands below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;nvm ls-remote
nvm install &amp;lt;version&amp;gt; 
nvm use &amp;lt;version&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  4. How to upgrade Node.js to the latest version on Mac OS?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Here’s how to successfully upgrade from &lt;code&gt;v0.8.18&lt;/code&gt; to &lt;code&gt;v0.10.20&lt;/code&gt; &lt;strong&gt;without any other requirements&lt;/strong&gt; like brew etc. (type these commands in the terminal):&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;sudo npm cache clean -f&lt;/code&gt; (force) clear you npm cache&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;sudo npm install -g n&lt;/code&gt; install &lt;a href="https://www.npmjs.com/package/n"&gt;n&lt;/a&gt; (this might take a while)&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;sudo n stable&lt;/code&gt; upgrade to the current stable version&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Note that &lt;code&gt;sudo&lt;/code&gt; might prompt your password.&lt;/p&gt;

&lt;p&gt;Additional note regarding step 3: &lt;code&gt;stable&lt;/code&gt; can be exchanged for &lt;code&gt;latest&lt;/code&gt;, &lt;code&gt;lts&lt;/code&gt; (long term support) or any specific version number such as &lt;code&gt;0.10.20&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;If the version number doesn’t show up when typing &lt;code&gt;node -v&lt;/code&gt;, you might have to reboot.&lt;/p&gt;

&lt;p&gt;These instructions are found here as well: &lt;a href="https://davidwalsh.name/upgrade-nodejs"&gt;davidwalsh.name/upgrade-nodejs&lt;/a&gt;&lt;br&gt;
More info about the &lt;strong&gt;n&lt;/strong&gt; package found here: &lt;a href="https://www.npmjs.com/package/n"&gt;npmjs.com/package/n&lt;/a&gt;&lt;br&gt;
More info about Node.js’ release schedule: &lt;a href="https://github.com/nodejs/Release#release-schedule"&gt;github.com/nodejs/Release&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If you initially installed &lt;a href="https://nodejs.org/en/"&gt;Node.js&lt;/a&gt; with &lt;a href="https://brew.sh/"&gt;Homebrew&lt;/a&gt;, run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;brew update
brew upgrade node
npm install -g npm
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or as a one-liner:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;brew update &amp;amp;&amp;amp; brew upgrade node &amp;amp;&amp;amp; npm install -g npm
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A convenient way to change versions is to use &lt;a href="https://github.com/nvm-sh/nvm"&gt;nvm&lt;/a&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;brew install nvm
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To install the latest version of Node.js with nvm:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;nvm install node
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you installed via a package, then download the latest version from &lt;a href="https://docs.npmjs.com/downloading-and-installing-node-js-and-npm"&gt;nodejs.org&lt;/a&gt;. See Installing Node.js and updating npm.&lt;/p&gt;

&lt;h3&gt;
  
  
  5. How to completely uninstall Node.js and reinstall from the beginning (Mac OS X)?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Apparently, there was a &lt;code&gt;/Users/myusername/local&lt;/code&gt; folder that contained a &lt;code&gt;include&lt;/code&gt; with &lt;code&gt;node&lt;/code&gt; and &lt;code&gt;lib&lt;/code&gt; with &lt;code&gt;node&lt;/code&gt; and &lt;code&gt;node_modules&lt;/code&gt;. Don’t know how and why this was created instead of in &lt;code&gt;/usr/local&lt;/code&gt; folder.&lt;/p&gt;

&lt;p&gt;Deleting these local references fixed the phantom v0.6.1-pre.&lt;/p&gt;

&lt;p&gt;You may need to do the additional instructions as well:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sudo rm -rf /usr/local/{lib/node{,/.npm,_modules},bin,share/man}/{npm*,node*,man1/node*}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;which is the equivalent of (same as above)…&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sudo rm -rf /usr/local/bin/npm /usr/local/share/man/man1/node* /usr/local/lib/dtrace/node.d ~/.npm ~/.node-gyp 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;or (same as above) broken down.&lt;/p&gt;

&lt;p&gt;To completely uninstall node + npm is to do the following:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;go to &lt;strong&gt;/usr/local/lib&lt;/strong&gt; and delete any &lt;strong&gt;node&lt;/strong&gt; and &lt;strong&gt;node_modules&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;go to &lt;strong&gt;/usr/local/include&lt;/strong&gt; and delete any &lt;strong&gt;node&lt;/strong&gt; and &lt;strong&gt;node_modules&lt;/strong&gt; directory&lt;/li&gt;
&lt;li&gt;if you installed with &lt;strong&gt;brew install node&lt;/strong&gt;, then run &lt;strong&gt;brew uninstall node&lt;/strong&gt; in your terminal&lt;/li&gt;
&lt;li&gt;check your Home directory for any &lt;strong&gt;local&lt;/strong&gt; or &lt;strong&gt;lib&lt;/strong&gt; or &lt;strong&gt;include&lt;/strong&gt; folders, and delete any &lt;strong&gt;node&lt;/strong&gt; or &lt;strong&gt;node_modules&lt;/strong&gt; from there&lt;/li&gt;
&lt;li&gt;go to &lt;strong&gt;/usr/local/bin&lt;/strong&gt; and delete any &lt;strong&gt;node&lt;/strong&gt; executable&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You may also need to do:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sudo rm -rf /opt/local/bin/node /opt/local/include/node /opt/local/lib/node_modules
sudo rm -rf /usr/local/bin/npm /usr/local/share/man/man1/node.1 /usr/local/lib/dtrace/node.d
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Additionally, NVM modifies the PATH variable in &lt;code&gt;$HOME/.bashrc&lt;/code&gt;, which must be &lt;a href="https://github.com/nvm-sh/nvm#removal"&gt;reverted manually&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Then download &lt;strong&gt;nvm&lt;/strong&gt; and follow the instructions to install node. The latest versions of node come with &lt;strong&gt;npm&lt;/strong&gt;, we believe, but you can also reinstall that as well.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;For brew users, OSX:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;To remove:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;brew uninstall node; 
# or `brew uninstall --force node` which removes all versions
brew cleanup;
rm -f /usr/local/bin/npm /usr/local/lib/dtrace/node.d;
rm -rf ~/.npm;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To install:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;brew install node;
which node # =&amp;gt; /usr/local/bin/node
export NODE_PATH='/usr/local/lib/node_modules' # &amp;lt;--- add this ~/.bashrc
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can run &lt;code&gt;brew&lt;/code&gt; info node for more details regarding your node installs.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Consider using NVM instead of brew&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;NVM (Node version manager) is a portable solution for managing multiple versions of node&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/nvm-sh/nvm"&gt;https://github.com/nvm-sh/nvm&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt; nvm uninstall v4.1.0
&amp;gt; nvm install v8.1.2
&amp;gt; nvm use v8.1.2
&amp;gt; nvm list
         v4.2.0
         v5.8.0
        v6.11.0
-&amp;gt;       v8.1.2
         system
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://github.com/wbyoung/avn"&gt;You can use this with AVN&lt;/a&gt; to automatically switch versions as you hop between different projects with different node dependencies.&lt;/p&gt;

&lt;h3&gt;
  
  
  6. How to get GET (query string) variables in Express.js on Node.js?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In Express it’s already done for you and you can simply use &lt;a href="https://expressjs.com/en/api.html#req.query"&gt;req.query&lt;/a&gt; for that:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var id = req.query.id; // $_GET["id"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Otherwise, in NodeJS, you can access &lt;a href="https://nodejs.org/api/http.html#http_message_url"&gt;req.url&lt;/a&gt; and the builtin &lt;code&gt;url&lt;/code&gt; module to &lt;a href="https://nodejs.org/api/url.html#url_url_parse_urlstring_parsequerystring_slashesdenotehost"&gt;url.parse&lt;/a&gt; it manually:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var url = require('url');
var url_parts = url.parse(request.url, true);
var query = url_parts.query;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  7. How to send command-line arguments to npm script?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/npm/npm/pull/5518"&gt;It’s possible to pass args to &lt;code&gt;npm run&lt;/code&gt; as of npm 2.0.0&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The syntax is as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm run &amp;lt;command&amp;gt; [-- &amp;lt;args&amp;gt;]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note- It is needed to separate the params passed to &lt;code&gt;npm&lt;/code&gt; command itself and params passed to your script.&lt;/p&gt;

&lt;p&gt;So if you have in &lt;code&gt;package.json&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"scripts": {
    "grunt": "grunt",
    "server": "node server.js"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then the following commands would be equivalent:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;grunt task:target =&amp;gt; npm run grunt -- task:target

node server.js --port=1337 =&amp;gt; npm run server -- --port=1337
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To get the parameter value, &lt;a href="https://stackoverflow.com/questions/4351521/how-do-i-pass-command-line-arguments-to-a-node-js-program"&gt;see this question&lt;/a&gt;. For reading named parameters, it’s probably best to use a parsing library like &lt;a href="https://github.com/yargs/yargs"&gt;yargs&lt;/a&gt; or &lt;a href="https://github.com/substack/minimist"&gt;minimist&lt;/a&gt;; nodejs exposes &lt;code&gt;process.argv&lt;/code&gt; globally, containing command line parameter values, but this is a low-level API (whitespace-separated array of strings, as provided by the operating system to the node executable).&lt;/p&gt;

&lt;p&gt;Like some kind of workaround (though not very handy), you can do as follows:&lt;/p&gt;

&lt;p&gt;Say your package name from &lt;code&gt;package.json&lt;/code&gt; is &lt;code&gt;myPackage&lt;/code&gt; and you have also&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"scripts": {
    "start": "node ./script.js server"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then add in &lt;code&gt;package.json&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"config": {
    "myPort": "8080"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And in your &lt;code&gt;script.js&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// defaulting to 8080 in case if script invoked not via "npm run-script" but directly
var port = process.env.npm_package_config_myPort || 8080
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That way, by default &lt;code&gt;npm start&lt;/code&gt; will use 8080. You can, however, configure it (the value will be stored by &lt;code&gt;npm&lt;/code&gt; in its internal storage):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm config set myPackage:myPort 9090
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then, when invoking &lt;code&gt;npm start&lt;/code&gt;, 9090 will be used (the default from &lt;code&gt;package.json&lt;/code&gt; gets overridden).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If you want to run something like &lt;code&gt;npm start 8080&lt;/code&gt;. This is possible without needing to modify &lt;code&gt;script.js&lt;/code&gt; or configuration files as follows.&lt;/p&gt;

&lt;p&gt;For example, in your &lt;code&gt;"scripts"&lt;/code&gt; JSON value, include–&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"start": "node ./script.js server $PORT"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And then from the command-line:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ PORT=8080 npm start
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It is confirmed that this works using bash and npm 1.4.23. Note that this workaround does not require GitHub npm &lt;a href="https://github.com/npm/npm/issues/3494"&gt;issue #3494&lt;/a&gt; to be resolved.&lt;/p&gt;

&lt;h3&gt;
  
  
  8. How to install packages using node package manager in Ubuntu?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sudo apt-get install nodejs-legacy
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;First of all, lets clarify the situation a bit. In summer 2012 Debian maintainers decided to rename Node.js executable to prevent some kind of namespace collision with another package. It was very hard decision for Debian Technical Committee, because it breaks backward compatibility.&lt;/p&gt;

&lt;p&gt;The following is a quote from Committee resolution draft, published in Debian &lt;a href="https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=614907#108"&gt;mailing list&lt;/a&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The nodejs package shall be changed to provide /usr/bin/nodejs, not /usr/bin/node. The package should declare a Breaks: relationship with any packages in Debian that reference /usr/bin/node.&lt;/li&gt;
&lt;li&gt;The nodejs source package shall also provide a nodejs-legacy binary package at Priority: extra that contains /usr/bin/node as a symlink to /usr/bin/nodejs. No package in the archive may depend on or recommend the nodejs-legacy package, which is provided solely for upstream compatibility. This package declares shall also declare a Conflicts: relationship with the node package.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Paragraph 2 is the actual solution for OP’s issue. OP should try to install this package instead of doing symlink by hand. Here is a link to this package in Debian package index &lt;a href="&amp;lt;br&amp;gt;%0Ahttps://packages.debian.org/sid/nodejs-legacy"&gt;website&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;It can be installed using &lt;code&gt;sudo apt-get install nodejs-legacy&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;We have not found any information about adopting the whole thing by NPM developers, but we think &lt;code&gt;npm&lt;/code&gt; package will be fixed on some point and &lt;code&gt;nodejs-legacy&lt;/code&gt; become really legacy.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Try linking node to nodejs. First, find out where nodejs is&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;whereis nodejs
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then soft link node to nodejs&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ln -s [the path of nodejs] /usr/bin/node 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;/usr/bin might be in your execution path. Then you can test by typing node or npm into your command line, and everything should work now.&lt;/p&gt;

&lt;h3&gt;
  
  
  9. How to check Node.js version on the command line? (not the REPL)
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The command line for that is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;node -v
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;node --version
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note:&lt;/p&gt;

&lt;p&gt;If &lt;code&gt;node -v&lt;/code&gt; doesn’t work, but &lt;code&gt;nodejs -v&lt;/code&gt; does, then something’s not set up quite right on your system. See &lt;a href="https://stackoverflow.com/questions/18130164/nodejs-vs-node-on-ubuntu-12-04"&gt;this other question&lt;/a&gt; for ways to fix it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If you’re referring to the shell command line, either of the following will work:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;node -v

node --version
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Just typing &lt;code&gt;node version&lt;/code&gt; will cause node.js to attempt loading a module named version, which doesn’t exist unless you like working with confusing module names.&lt;/p&gt;

&lt;h3&gt;
  
  
  10. How to use node.js as a simple webserver?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Simplest Node.js server is just:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ npm install http-server -g
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now you can run a server via the following commands:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ cd MyApp

$ http-server
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you’re using NPM 5.2.0 or newer, you can use &lt;code&gt;http-server&lt;/code&gt; without installing it with &lt;code&gt;npx&lt;/code&gt;. This isn’t recommended for use in production but is a great way to quickly get a server running on localhost.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ npx http-server
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or, you can try this, which opens your web browser and enables CORS requests:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ http-server -o --cors
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For more options, check out the &lt;a href="https://github.com/http-party/http-server"&gt;documentation for &lt;code&gt;http-server&lt;/code&gt; on GitHub&lt;/a&gt;, or run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ http-server --help
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Lots of other nice features and brain-dead-simple deployment to NodeJitsu.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Feature Forks&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Of course, you can easily top up the features with your own fork. You might find it’s already been done in one of the existing 800+ forks of this project:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://github.com/nodeapps/http-server/network"&gt;https://github.com/nodeapps/http-server/network&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Light Server: An Auto Refreshing Alternative&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A nice alternative to &lt;code&gt;http-server&lt;/code&gt; is &lt;a href="https://www.npmjs.com/package/light-server"&gt;&lt;code&gt;light-server&lt;/code&gt;&lt;/a&gt;. It supports file watching and auto-refreshing and many other features.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install -g light-server 
$ light-server
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Add to your directory context menu in Windows Explorer&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;reg.exe add HKCR\Directory\shell\LightServer\command /ve /t REG_EXPAND_SZ /f /d "\"C:\nodejs\light-server.cmd\" \"-o\" \"-s\" \"%V\""
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Simple JSON REST server&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If you need to create a simple REST server for a prototype project then &lt;a href="https://github.com/typicode/json-server"&gt;json-server&lt;/a&gt; might be what you’re looking for.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Auto Refreshing Editors&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Most web page editors and IDE tools now include a web server that will watch your source files and auto-refresh your web page when they change.&lt;/p&gt;

&lt;p&gt;You can use &lt;a href="https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer"&gt;Live Server&lt;/a&gt; with Visual Studio Code.&lt;/p&gt;

&lt;p&gt;The &lt;a href="https://github.com/adobe/brackets/"&gt;open source&lt;/a&gt; text editor &lt;a href="http://brackets.io/"&gt;Brackets&lt;/a&gt; also includes a NodeJS static web server. Just open any HTML file in Brackets, press “Live Preview” and it starts a static server and opens your browser at the page. The browser will auto-refresh whenever you edit and save the HTML file. This especially useful when testing adaptive web sites. Open your HTML page on multiple browsers/window sizes/devices. Save your HTML page and instantly see if your adaptive stuff is working as they all auto-refresh.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;PhoneGap Developers&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If you’re coding a hybrid mobile app, you may be interested to know that the &lt;a href="https://phonegap.com/"&gt;PhoneGap&lt;/a&gt; team took this auto-refresh concept on board with their new &lt;a href="https://phonegap.com/products/"&gt;PhoneGap App&lt;/a&gt;. This is a generic mobile app that can load the HTML5 files from a server during development. This is a very slick trick since now you can skip the slow compile/deploy steps in your development cycle for hybrid mobile apps if you’re changing JS/CSS/HTML files — which is what you’re doing most of the time. They also provide the static NodeJS webserver (run &lt;code&gt;phonegap&lt;/code&gt; serve) that detects file changes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;PhoneGap + Sencha Touch Developers&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We have now extensively adapted the PhoneGap static server &amp;amp; PhoneGap Developer App for Sencha Touch &amp;amp; jQuery Mobile developers. Check it out at &lt;a href="https://github.com/tohagan/stlive"&gt;Sencha Touch Live&lt;/a&gt;. Supports –qr QR Codes and –localtunnel that proxies your static server from your desktop computer to a URL outside your firewall! Tons of uses. Massive speedup for hybrid mobile devs.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Cordova + Ionic Framework Developers&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Local server and auto refresh features are baked into the &lt;code&gt;ionic&lt;/code&gt; tool. Just run &lt;code&gt;ionic serve&lt;/code&gt; from your app folder. Even better &lt;a href="https://blog.ionicframework.com/ionic-lab/"&gt;&lt;code&gt;…ionic serve --lab&lt;/code&gt;&lt;/a&gt; to view auto-refreshing side by side views of both iOS and Android.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can use &lt;a href="https://www.npmjs.com/package/connect"&gt;Connect&lt;/a&gt; and &lt;a href="https://github.com/expressjs/serve-static"&gt;ServeStatic&lt;/a&gt; with Node.js for this:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Install connect and serve-static with NPM &lt;code&gt;$ npm install connect serve-static&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Create server.js file with this content: &lt;code&gt;var connect = require('connect'); var serveStatic = require('serve-static'); connect() .use(serveStatic(__dirname)) .listen(8080, () =&amp;gt; console.log('Server running on 8080...'));&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Run with Node.js &lt;code&gt;$ node server.js&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You can now go to &lt;code&gt;http://localhost:8080/yourfile.html&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;In Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;These are the 10 most commonly asked questions on Node.js. If you have any suggestions regarding the article, please feel free to comment below. If you need any help, then we would be glad to help you.&lt;/p&gt;

&lt;p&gt;We, at &lt;a href="https://www.truemark.dev/"&gt;Truemark&lt;/a&gt;, provide services like web and mobile app development, digital marketing, and website development. So, if you want to work with us, please feel free to contact us.&lt;/p&gt;

&lt;p&gt;Hope this article helped you.&lt;/p&gt;

&lt;p&gt;This post was originally posted on &lt;a href="https://thedevpost.com/blog/10-most-asked-questions-on-nodejs/"&gt;DevPostbyTruemark&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>node</category>
    </item>
    <item>
      <title>12 Most Asked ReactJS Questions</title>
      <dc:creator>KiranPoudel98</dc:creator>
      <pubDate>Fri, 18 Sep 2020 08:09:24 +0000</pubDate>
      <link>https://forem.com/truemark/12-most-asked-reactjs-questions-1gb8</link>
      <guid>https://forem.com/truemark/12-most-asked-reactjs-questions-1gb8</guid>
      <description>&lt;p&gt;ReactJS, also known as React.js or simply React, is a JavaScript library used for building user interfaces and is maintained by Facebook. It is one of the new technology built in 2011 by Jordan Walke, a software engineer at Facebook. So, today we will be talking about the 12 most asked ReactJS questions.&lt;/p&gt;

&lt;h2&gt;
  
  
  12 Most Asked ReactJS Questions
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1. How to programmatically navigate using React Router?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;React Router v5.1.0 with hooks&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;There is a new &lt;code&gt;useHistory&lt;/code&gt; hook in React Router &amp;gt;5.1.0. If you are using React &amp;gt;16.8.0 and functional components.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useHistory } from "react-router-dom";

function HomeButton() {
  const history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    &amp;lt;button type="button" onClick={handleClick}&amp;gt;
      Go home
    &amp;lt;/button&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;React Router v4&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;With v4 of React Router, there are three approaches that you can take to programmatic routing within components.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Use the &lt;code&gt;withRouter&lt;/code&gt; higher-order component.&lt;/li&gt;
&lt;li&gt;Use composition and render a &lt;code&gt;&amp;lt;Route&amp;gt;&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Use the context.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;React Router is mostly a wrapper around the &lt;a href="https://github.com/ReactTraining/history"&gt;&lt;code&gt;history&lt;/code&gt;&lt;/a&gt;library. &lt;code&gt;history&lt;/code&gt; handles interaction with the browser’s &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/history"&gt;&lt;code&gt;window.history&lt;/code&gt;&lt;/a&gt; for you with its browser and hash histories. It also provides a memory history which is useful for environments that don’t have a global history. This is particularly useful in mobile app development (&lt;code&gt;react-native&lt;/code&gt;) and unit testing with Node.&lt;/p&gt;

&lt;p&gt;A &lt;code&gt;history&lt;/code&gt; instance has two methods for navigating: &lt;code&gt;push&lt;/code&gt; and &lt;code&gt;replace&lt;/code&gt;. If you think of the &lt;code&gt;history&lt;/code&gt; as an array of visited locations, &lt;code&gt;push&lt;/code&gt; will add a new location to the array and &lt;code&gt;replace&lt;/code&gt; will replace the current location in the array with the new one. Typically you will want to use the &lt;code&gt;push&lt;/code&gt; method when you are navigating.&lt;/p&gt;

&lt;p&gt;In earlier versions of React Router, you had to create your own &lt;code&gt;history&lt;/code&gt; instance, but in v4 the &lt;code&gt;&amp;lt;BrowserRouter&amp;gt;&lt;/code&gt;, &lt;code&gt;&amp;lt;HashRouter&amp;gt;&lt;/code&gt;, and &lt;code&gt;&amp;lt;MemoryRouter&amp;gt;&lt;/code&gt; components will create a browser, hash, and memory instances for you. React Router makes the properties and methods of the &lt;code&gt;history&lt;/code&gt; instance associated with your router available through the context, under the &lt;code&gt;router&lt;/code&gt; object.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;a. Use the &lt;code&gt;withRouter&lt;/code&gt; higher-order component&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;withRouter&lt;/code&gt; higher-order component will inject the &lt;code&gt;history&lt;/code&gt; object as a prop of the component. This allows you to access the &lt;code&gt;push&lt;/code&gt; and &lt;code&gt;replace&lt;/code&gt; methods without having to deal with the &lt;code&gt;context&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { withRouter } from 'react-router-dom'
// this also works with react-router-native

const Button = withRouter(({ history }) =&amp;gt; (
  &amp;lt;button
    type='button'
    onClick={() =&amp;gt; { history.push('/new-location') }}
  &amp;gt;
    Click Me!
  &amp;lt;/button&amp;gt;
))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;b. Use composition and render a &lt;code&gt;&amp;lt;Route&amp;gt;&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;&amp;lt;Route&amp;gt;&lt;/code&gt; component isn’t just for matching locations. You can render a pathless route and &lt;strong&gt;it will always match the current location&lt;/strong&gt;. The &lt;code&gt;&amp;lt;Route&amp;gt;&lt;/code&gt; component passes the same props as &lt;code&gt;withRouter&lt;/code&gt;, so you will be able to access the &lt;code&gt;history&lt;/code&gt; methods through the &lt;code&gt;history&lt;/code&gt; prop.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Route } from 'react-router-dom'

const Button = () =&amp;gt; (
  &amp;lt;Route render={({ history}) =&amp;gt; (
    &amp;lt;button
      type='button'
      onClick={() =&amp;gt; { history.push('/new-location') }}
    &amp;gt;
      Click Me!
    &amp;lt;/button&amp;gt;
  )} /&amp;gt;
)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;c. Use the context&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;But you probably should not.&lt;/p&gt;

&lt;p&gt;The last option is one that you should only use if you feel comfortable working with React’s &lt;a href="https://reactjs.org/docs/context.html"&gt;context&lt;/a&gt; model (React’s Context API is stable as of v16).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Button = (props, context) =&amp;gt; (
  &amp;lt;button
    type='button'
    onClick={() =&amp;gt; {
      // context.history.push === history.push
      context.history.push('/new-location')
    }}
  &amp;gt;
    Click Me!
  &amp;lt;/button&amp;gt;
)

// you need to specify the context type so that it
// is available within the component
Button.contextTypes = {
  history: React.PropTypes.shape({
    push: React.PropTypes.func.isRequired
  })
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;a and b are the simplest choices to implement, so for most use cases, they are your best bets.&lt;/p&gt;

&lt;h3&gt;
  
  
  2. How to loop inside React JSX?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Think of it like you’re just calling JavaScript functions. You can’t use a &lt;code&gt;for&lt;/code&gt; loop where the arguments to a function call would go:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;return tbody(
    for (var i = 0; i &amp;lt; numrows; i++) {
        ObjectRow()
    } 
)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;See how the function &lt;code&gt;tbody&lt;/code&gt; is being passed a &lt;code&gt;for&lt;/code&gt; loop as an argument, and of course that’s a syntax error.&lt;/p&gt;

&lt;p&gt;But you can make an array, and then pass that in as an argument:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var rows = [];
for (var i = 0; i &amp;lt; numrows; i++) {
    rows.push(ObjectRow());
}
return tbody(rows);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can use basically the same structure when working with JSX:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var rows = [];
for (var i = 0; i &amp;lt; numrows; i++) {
    // note: we add a key prop here to allow react to uniquely identify each
    // element in this array. see: https://reactjs.org/docs/lists-and-keys.html
    rows.push(&amp;lt;ObjectRow key={i} /&amp;gt;);
}
return &amp;lt;tbody&amp;gt;{rows}&amp;lt;/tbody&amp;gt;;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Incidentally, the above JavaScript example is almost exactly what that example of JSX transforms into. Play around with &lt;a href="https://babeljs.io/repl#?browsers=defaults%2C%20not%20ie%2011%2C%20not%20ie_mob%2011&amp;amp;build=&amp;amp;builtIns=false&amp;amp;spec=false&amp;amp;loose=false&amp;amp;code_lz=Q&amp;amp;debug=false&amp;amp;forceAllTransforms=false&amp;amp;shippedProposals=false&amp;amp;circleciRepo=&amp;amp;evaluate=false&amp;amp;fileSize=false&amp;amp;timeTravel=false&amp;amp;sourceType=module&amp;amp;lineWrap=true&amp;amp;presets=env%2Creact%2Cstage-2%2Cenv&amp;amp;prettier=false&amp;amp;targets=&amp;amp;version=7.11.6&amp;amp;externalPlugins="&gt;Babel REPL&lt;/a&gt; to get a feel for how JSX works.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Often &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map"&gt;map&lt;/a&gt; is a good answer.&lt;/p&gt;

&lt;p&gt;If this was your code with the for loop:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;tbody&amp;gt;
    for (var i=0; i &amp;lt; objects.length; i++) {
        &amp;lt;ObjectRow obj={objects[i]} key={i}&amp;gt;
    } 
&amp;lt;/tbody&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You could write it like this with map:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;tbody&amp;gt;
    {objects.map(function(object, i){
        return &amp;lt;ObjectRow obj={object} key={i} /&amp;gt;;
    })}
&amp;lt;/tbody&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;ES6 syntax:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;tbody&amp;gt;
    {objects.map((object, i) =&amp;gt; &amp;lt;ObjectRow obj={object} key={i} /&amp;gt;)}
&amp;lt;/tbody&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  3. What do these three dots … in React do?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;That’s &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax"&gt;property spread notation&lt;/a&gt;. It was added in ES2018 (spread for arrays/iterables was earlier, ES2015), but it’s been supported in React projects for a long time via transpilation (as “&lt;a href="https://reactjs.org/docs/jsx-in-depth.html#spread-attributes"&gt;JSX spread attributes&lt;/a&gt;” even though you could do it elsewhere, too, not just attributes).&lt;/p&gt;

&lt;p&gt;&lt;code&gt;{...this.props}&lt;/code&gt; spreads out the “own” enumerable properties in &lt;code&gt;props&lt;/code&gt; as discrete properties on the &lt;code&gt;Modal&lt;/code&gt; element you’re creating. For instance, if &lt;code&gt;this.props&lt;/code&gt; contained &lt;code&gt;a: 1&lt;/code&gt; and &lt;code&gt;b: 2&lt;/code&gt;, then&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;Modal {...this.props} title='Modal heading' animation={false}&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;would be the same as&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;Modal a={this.props.a} b={this.props.b} title='Modal heading' animation={false}&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But it’s dynamic, so whatever “own” properties are in &lt;code&gt;props&lt;/code&gt; are included.&lt;/p&gt;

&lt;p&gt;Since &lt;code&gt;children&lt;/code&gt; is an “own” property in &lt;code&gt;props&lt;/code&gt;, spread will include it. So if the component where this appears had child elements, they’ll be passed on to &lt;code&gt;Modal&lt;/code&gt;. Putting child elements between the opening tag and closing tags is just syntactic sugar — the good kind — for putting a &lt;code&gt;children&lt;/code&gt; property in the opening tag. Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Example extends React.Component {
  render() {
    const { className, children } = this.props;
    return (
      &amp;lt;div className={className}&amp;gt;
      {children}
      &amp;lt;/div&amp;gt;
    );
  }
}
ReactDOM.render(
  [
    &amp;lt;Example className="first"&amp;gt;
      &amp;lt;span&amp;gt;Child in first&amp;lt;/span&amp;gt;
    &amp;lt;/Example&amp;gt;,
    &amp;lt;Example className="second" children={&amp;lt;span&amp;gt;Child in second&amp;lt;/span&amp;gt;} /&amp;gt;
  ],
  document.getElementById("root")
);

.first {
  color: green;
}
.second {
  color: blue;
}

&amp;lt;div id="root"&amp;gt;&amp;lt;/div&amp;gt;

&amp;lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"&amp;gt;&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The spread notation is handy not only for that use case, but for creating a new object with most (or all) of the properties of an existing object — which comes up a lot when you’re updating state, since you can’t modify state directly:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;this.setState(prevState =&amp;gt; {
    return {foo: {...prevState.foo, a: "updated"}};
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That replaces &lt;code&gt;this.state.foo&lt;/code&gt; with a new object with all the same properties as &lt;code&gt;foo&lt;/code&gt; except the a property, which becomes &lt;code&gt;"updated"&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const obj = {
  foo: {
    a: 1,
    b: 2,
    c: 3
  }
};
console.log("original", obj.foo);
// Creates a NEW object and assigns it to `obj.foo`
obj.foo = {...obj.foo, a: "updated"};
console.log("updated", obj.foo);

.as-console-wrapper {
  max-height: 100% !important;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;As you know &lt;code&gt;...&lt;/code&gt; are called &lt;strong&gt;Spread Attributes&lt;/strong&gt; which the name represents it allows an expression to be expanded.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var parts = ['two', 'three'];
var numbers = ['one', ...parts, 'four', 'five']; // ["one", "two", "three", "four", "five"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And in this case, let’s simplify it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//just assume we have an object like this:
var person= {
    name: 'Alex',
    age: 35 
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;Modal {...person} title='Modal heading' animation={false} /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;is equal to&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;Modal name={person.name} age={person.age} title='Modal heading' animation={false} /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So in short, it’s a &lt;strong&gt;neat&lt;/strong&gt; short-cut, we can say.&lt;/p&gt;

&lt;h3&gt;
  
  
  4. How to pass props to {this.props.children}?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The answer is simple, cloning children with new props.&lt;/p&gt;

&lt;p&gt;You can use &lt;a href="https://reactjs.org/docs/react-api.html#reactchildren"&gt;React.Children&lt;/a&gt; to iterate over the children, and then clone each element with new props (shallow merged) using &lt;a href="https://reactjs.org/docs/react-api.html#cloneelement"&gt;React.cloneElement&lt;/a&gt; e.g:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { Children, isValidElement, cloneElement } from 'react';

const Child = ({ doSomething, value }) =&amp;gt; (
  &amp;lt;div onClick={() =&amp;gt; doSomething(value)}&amp;gt;Click Me&amp;lt;/div&amp;gt;
);

function Parent({ children }) {
  function doSomething(value) {
    console.log('doSomething called by child with value:', value);
  }

  render() {
    const childrenWithProps = Children.map(children, child =&amp;gt; {
      // Checking isValidElement is the safe way and avoids a TS error too.
      if (isValidElement(child)) {
        return cloneElement(child, { doSomething })
      }

      return child;
    });

    return &amp;lt;div&amp;gt;{childrenWithProps}&amp;lt;/div&amp;gt;
  }
};

ReactDOM.render(
  &amp;lt;Parent&amp;gt;
    &amp;lt;Child value="1" /&amp;gt;
    &amp;lt;Child value="2" /&amp;gt;
  &amp;lt;/Parent&amp;gt;,
  document.getElementById('container')
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Fiddle: &lt;a href="https://jsfiddle.net/2q294y43/2/"&gt;https://jsfiddle.net/2q294y43/2/&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Calling children as a function&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can also pass props to children with &lt;a href="https://reactjs.org/docs/render-props.html"&gt;render props&lt;/a&gt;. In this approach the children (which can be &lt;code&gt;children&lt;/code&gt; or any other prop name) is a function which can accept any arguments you want to pass and returns the children:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Child = ({ doSomething, value }) =&amp;gt; (
  &amp;lt;div onClick={() =&amp;gt;  doSomething(value)}&amp;gt;Click Me&amp;lt;/div&amp;gt;
);

function Parent({ children }) {
  function doSomething(value) {
    console.log('doSomething called by child with value:', value);
  }

  render() {
    // Note that children is called as a function and we can pass args to it
    return &amp;lt;div&amp;gt;{children(doSomething)}&amp;lt;/div&amp;gt;
  }
};

ReactDOM.render(
  &amp;lt;Parent&amp;gt;
    {doSomething =&amp;gt; (
      &amp;lt;React.Fragment&amp;gt;
        &amp;lt;Child doSomething={doSomething} value="1" /&amp;gt;
        &amp;lt;Child doSomething={doSomething} value="2" /&amp;gt;
      &amp;lt;/React.Fragment&amp;gt;
    )}
  &amp;lt;/Parent&amp;gt;,
  document.getElementById('container')
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Instead of &lt;code&gt;&amp;lt;React.Fragment&amp;gt;&lt;/code&gt; or simply &lt;code&gt;&amp;lt;&amp;gt;&lt;/code&gt; you can also return an array if you prefer.&lt;/p&gt;

&lt;p&gt;Fiddle: &lt;a href="https://jsfiddle.net/ferahl/y5pcua68/7/"&gt;https://jsfiddle.net/ferahl/y5pcua68/7/&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;For a slightly cleaner way to do it, try:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div&amp;gt;
    {React.cloneElement(this.props.children, { loggedIn: this.state.loggedIn })}
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To use with multiple individual children (the child must itself be a component) you can do. Tested in 16.8.6&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div&amp;gt;
    {React.cloneElement(props.children[0], { loggedIn: true, testingTwo: true })}
    {React.cloneElement(props.children[1], { loggedIn: true, testProp: false })}
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  5. What is the difference between React Native and React?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://reactjs.org/"&gt;ReactJS&lt;/a&gt; is a JavaScript library, supporting both front-end web and being run on a server, for building user interfaces and web applications.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://reactnative.dev/"&gt;React Native&lt;/a&gt; is a mobile framework that compiles to native app components, allowing you to build native mobile applications for different platforms (iOS, Android, and Windows Mobile) in JavaScript that allows you to use ReactJS to build your components, and implements ReactJS under the hood.&lt;/p&gt;

&lt;p&gt;Both are open-sourced by Facebook.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Here is the &lt;a href="https://github.com/facebook/react"&gt;React project&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;At Facebook, they invented &lt;strong&gt;React&lt;/strong&gt; so JavaScript can manipulate the website DOM faster using the virtual DOM model.&lt;/p&gt;

&lt;p&gt;DOM full refresh is slower compared to the &lt;a href="https://stackoverflow.com/questions/21109361/why-is-reacts-concept-of-virtual-dom-said-to-be-more-performant-than-dirty-mode"&gt;React virtual-dom model&lt;/a&gt;, which refreshes only parts of the page (read: partial refresh).&lt;/p&gt;

&lt;p&gt;As you may understand from this &lt;a href="https://www.youtube.com/watch?v=oWPoW0gIzvs"&gt;video&lt;/a&gt;, Facebook did not invent React because they understood immediately that the partial refresh would be faster than the conventional one. Originally they needed a way to reduce Facebook application re-build time and luckily this brought the partial DOM refresh to life.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/facebook/react-native"&gt;React native&lt;/a&gt; is just a consequence of React. It is a platform to build native apps using JavaScript.&lt;/p&gt;

&lt;p&gt;Prior to &lt;strong&gt;React native&lt;/strong&gt;, you needed to know Java for Android or Objective-C for iPhone and iPad to create native apps.&lt;/p&gt;

&lt;p&gt;With React Native it is possible to mimic the behavior of the native app in JavaScript and in the end, you will get platform-specific code as the output. You may even mix the &lt;strong&gt;native code&lt;/strong&gt; with JavaScript if you need to optimize your application further.&lt;/p&gt;

&lt;p&gt;As Olivia Bishop said in the video, 85% of the &lt;strong&gt;React native&lt;/strong&gt; code base can be shared among platforms. These would be the components applications typically use and the common logic.&lt;/p&gt;

&lt;p&gt;15% of the code is platform-specific. The platform-specific JavaScript is what gives the platform flavor ( and makes the difference in the experience).&lt;/p&gt;

&lt;p&gt;The cool thing is this platform-specific code — is already written, so you just need to use it.&lt;/p&gt;

&lt;h3&gt;
  
  
  6. Understanding unique keys for array children in React.js
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You should add a key to each child &lt;strong&gt;as well as each element inside children&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;This way React can handle the minimal DOM change.&lt;/p&gt;

&lt;p&gt;Check &lt;a href="https://jsfiddle.net/1khqfLgr/2/"&gt;this example&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Try removing the &lt;code&gt;key={i}&lt;/code&gt; from the &lt;code&gt;&amp;lt;b&amp;gt;&amp;lt;/b&amp;gt;&lt;/code&gt; element inside the div’s (and check the console).&lt;/p&gt;

&lt;p&gt;In the sample, if we don’t give a key to the &lt;code&gt;&amp;lt;b&amp;gt;&lt;/code&gt; element and we want to update &lt;strong&gt;only&lt;/strong&gt; the &lt;code&gt;object.city&lt;/code&gt;, React needs to re-render the whole row vs just the element.&lt;/p&gt;

&lt;p&gt;Here is the code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var data = [{name:'Jhon', age:28, city:'HO'},
            {name:'Onhj', age:82, city:'HN'},
            {name:'Nohj', age:41, city:'IT'}
           ];

var Hello = React.createClass({

    render: function() {

      var _data = this.props.info;
      console.log(_data);
      return(
        &amp;lt;div&amp;gt;
            {_data.map(function(object, i){
               return &amp;lt;div className={"row"} key={i}&amp;gt; 
                          {[ object.name ,
                             // remove the key
                             &amp;lt;b className="fosfo" key={i}&amp;gt; {object.city} &amp;lt;/b&amp;gt; , 
                             object.age
                          ]}
                      &amp;lt;/div&amp;gt;; 
             })}
        &amp;lt;/div&amp;gt;
       );
    }
});

React.render(&amp;lt;Hello info={data} /&amp;gt;, document.body);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  7. How can you pass a value to the &lt;code&gt;onClick&lt;/code&gt; event in React js?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Easy Way&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Use an arrow function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;return (
  &amp;lt;th value={column} onClick={() =&amp;gt; this.handleSort(column)}&amp;gt;{column}&amp;lt;/th&amp;gt;
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will create a new function that calls handleSort with the right params.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Better Way&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-bind.md#protips"&gt;Extract it into a sub-component&lt;/a&gt;. The problem with using an arrow function in the render call is it will create a new function every time, which ends up causing unneeded re-renders.&lt;/p&gt;

&lt;p&gt;If you create a sub-component, you can pass handler and use props as the arguments, which will then re-render only when the props change (because the handler reference now never changes):&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Sub-component&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class TableHeader extends Component {
  handleClick = () =&amp;gt; {
    this.props.onHeaderClick(this.props.value);
  }

  render() {
    return (
      &amp;lt;th onClick={this.handleClick}&amp;gt;
        {this.props.column}
      &amp;lt;/th&amp;gt;
    );
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Main component&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{this.props.defaultColumns.map((column) =&amp;gt; (
  &amp;lt;TableHeader
    value={column}
    onHeaderClick={this.handleSort}
  /&amp;gt;
))}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Old Easy Way (ES5)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Use &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind"&gt;&lt;code&gt;.bind&lt;/code&gt;&lt;/a&gt; to pass the parameter you want:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;return (
  &amp;lt;th value={column} onClick={that.handleSort.bind(that, column)}&amp;gt;{column}&amp;lt;/th&amp;gt;
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;There is another way like, &lt;a href="https://www.sitepoint.com/currying-in-functional-javascript/"&gt;currying&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;What you can do is create a function that accepts a parameter (your parameter) and returns another function that accepts another parameter (the click event in this case). Then you are free to do with it whatever you want.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ES5:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;handleChange(param) { // param is the argument you passed to the function
    return function (e) { // e is the event object that returned

    };
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;ES6:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;handleChange = param =&amp;gt; e =&amp;gt; {
    // param is the argument you passed to the function
    // e is the event object that returned
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And you will use it this way:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;input 
    type="text" 
    onChange={this.handleChange(someParam)} 
/&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here is a full example of such usage:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const someArr = ["A", "B", "C", "D"];

class App extends React.Component {
  state = {
    valueA: "",
    valueB: "some initial value",
    valueC: "",
    valueD: "blah blah"
  };

  handleChange = param =&amp;gt; e =&amp;gt; {
    const nextValue = e.target.value;
    this.setState({ ["value" + param]: nextValue });
  };

  render() {
    return (
      &amp;lt;div&amp;gt;
        {someArr.map(obj =&amp;gt; {
          return (
            &amp;lt;div&amp;gt;
              &amp;lt;label&amp;gt;
                {`input ${obj}   `}
              &amp;lt;/label&amp;gt;
              &amp;lt;input
                type="text"
                value={this.state["value" + obj]}
                onChange={this.handleChange(obj)}
              /&amp;gt;
              &amp;lt;br /&amp;gt;
              &amp;lt;br /&amp;gt;
            &amp;lt;/div&amp;gt;
          );
        })}
      &amp;lt;/div&amp;gt;
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(&amp;lt;App /&amp;gt;, rootElement);

&amp;lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;div id="root"&amp;gt;&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that this approach doesn’t solve the creation of a new instance on each render.&lt;/p&gt;

&lt;p&gt;You can also cache/memoize the result of the function.&lt;/p&gt;

&lt;p&gt;Here is a naive implementation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let memo = {};

const someArr = ["A", "B", "C", "D"];

class App extends React.Component {
  state = {
    valueA: "",
    valueB: "some initial value",
    valueC: "",
    valueD: "blah blah"
  };

  handleChange = param =&amp;gt; {
    const handler = e =&amp;gt; {
      const nextValue = e.target.value;
      this.setState({ ["value" + param]: nextValue });
    }
    if (!memo[param]) {
      memo[param] = e =&amp;gt; handler(e)
    }
    return memo[param]
  };

  render() {
    return (
      &amp;lt;div&amp;gt;
        {someArr.map(obj =&amp;gt; {
          return (
            &amp;lt;div key={obj}&amp;gt;
              &amp;lt;label&amp;gt;
                {`input ${obj}   `}
              &amp;lt;/label&amp;gt;
              &amp;lt;input
                type="text"
                value={this.state["value" + obj]}
                onChange={this.handleChange(obj)}
              /&amp;gt;
              &amp;lt;br /&amp;gt;
              &amp;lt;br /&amp;gt;
            &amp;lt;/div&amp;gt;
          );
        })}
      &amp;lt;/div&amp;gt;
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(&amp;lt;App /&amp;gt;, rootElement);

&amp;lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;div id="root" /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  8. How to set focus on an input field after rendering?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You should do it in &lt;code&gt;componentDidMount&lt;/code&gt; and &lt;a href="https://reactjs.org/docs/refs-and-the-dom.html"&gt;&lt;code&gt;refs callback&lt;/code&gt;&lt;/a&gt; instead. Something like this&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;componentDidMount(){
   this.nameInput.focus(); 
}

class App extends React.Component{
  componentDidMount(){
    this.nameInput.focus();
  }
  render() {
    return(
      &amp;lt;div&amp;gt;
        &amp;lt;input 
          defaultValue="Won't focus" 
        /&amp;gt;
        &amp;lt;input 
          ref={(input) =&amp;gt; { this.nameInput = input; }} 
          defaultValue="will focus"
        /&amp;gt;
      &amp;lt;/div&amp;gt;
    );
  }
}

ReactDOM.render(&amp;lt;App /&amp;gt;, document.getElementById('app'));

&amp;lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react.js"&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-dom.js"&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;div id="app"&amp;gt;&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;For convenience you can use the autoFocus prop to have an input automatically focus when mounted:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;input autoFocus name=...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that in JSX it’s &lt;code&gt;autoFocus&lt;/code&gt; (capital F) unlike plain old HTML which is case-insensitive.&lt;/p&gt;

&lt;h3&gt;
  
  
  9. What is the difference between using constructor vs getInitialState in React / React Native?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The two approaches are not interchangeable. You should initialize state in the constructor when using ES6 classes, and define the &lt;code&gt;getInitialState&lt;/code&gt; method when using &lt;code&gt;React.createClass&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://reactjs.org/docs/components-and-props.html#es6-classes"&gt;See the official React doc on the subject of ES6 classes.&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { /* initial state */ };
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;is equivalent to&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var MyComponent = React.createClass({
  getInitialState() {
    return { /* initial state */ };
  },
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The difference between &lt;code&gt;constructor&lt;/code&gt; and &lt;code&gt;getInitialState&lt;/code&gt; is the difference between &lt;strong&gt;ES6&lt;/strong&gt; and &lt;strong&gt;ES5&lt;/strong&gt; itself.&lt;br&gt;
&lt;code&gt;getInitialState&lt;/code&gt; is used with &lt;code&gt;React.createClass&lt;/code&gt; and &lt;code&gt;constructor&lt;/code&gt; is used with &lt;code&gt;React.Component&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Hence the question boils down to the advantages/disadvantages of using &lt;strong&gt;ES6&lt;/strong&gt; or &lt;strong&gt;ES5&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Let’s look at the difference in code&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ES5&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var TodoApp = React.createClass({ 
  propTypes: {
    title: PropTypes.string.isRequired
  },
  getInitialState () { 
    return {
      items: []
    }; 
  }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;ES6&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class TodoApp extends React.Component {
  constructor () {
    super()
    this.state = {
      items: []
    }
  }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There is an interesting &lt;a href="https://www.reddit.com/r/reactjs/comments/35ed7s/es6_or_es5_in_reactjs/"&gt;reddit thread&lt;/a&gt; regarding this.&lt;/p&gt;

&lt;p&gt;React community is moving closer to &lt;strong&gt;ES6&lt;/strong&gt;. Also, it is considered as the best practice.&lt;/p&gt;

&lt;p&gt;There are some differences between &lt;code&gt;React.createClass&lt;/code&gt; and &lt;code&gt;React.Component&lt;/code&gt;. For instance, &lt;code&gt;how&lt;/code&gt; this is handled in these cases. Read more about such differences &lt;a href="https://ultimatecourses.com/blog/react-create-class-versus-component"&gt;in this blogpost&lt;/a&gt; and facebook’s &lt;a href="https://reactjs.org/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding"&gt;content on autobinding&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;constructor&lt;/code&gt; can also be used to handle such situations. To bind methods to a component instance, it can be prebinded in the &lt;code&gt;constructor&lt;/code&gt;. &lt;a href="https://www.newmediacampaigns.com/blog/refactoring-react-components-to-es6-classes"&gt;This&lt;/a&gt; is a good material to do such cool stuff.&lt;/p&gt;

&lt;p&gt;Some more good material on best practices&lt;br&gt;
&lt;a href="http://brewhouse.io/blog/2015/03/24/best-practices-for-component-state-in-reactjs.html"&gt;Best Practices for Component State in React.js&lt;/a&gt;&lt;br&gt;
&lt;a href="http://cheng.logdown.com/posts/2015/09/29/converting-es5-react-to-es6"&gt;Converting React project from ES5 to ES6&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;April 9 2019:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;With the new changes in Javascript class API, you don’t need constructor.&lt;/p&gt;

&lt;p&gt;You could do&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class TodoApp extends React.Component {

    this.state = {items: []}
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will still get transpiled to constructor format, but you won’t have to worry about it. You can use this format that is more readable.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;With React Hooks&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;From React version 16.8, there’s a new API Called hooks.&lt;/p&gt;

&lt;p&gt;Now, you don’t even need a class component to have state. It can even be done in a functional component.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useState } from 'react';

function TodoApp () {
  const items = useState([]);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that the initial state is passed as an argument to &lt;code&gt;useState; useState([])&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Read more about React Hooks &lt;a href="https://reactjs.org/docs/hooks-state.html"&gt;from the official docs&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  10. What is the difference between state and props in React?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Props and state are related. The state of one component will often become the props of a child component. Props are passed to the child within the render method of the parent as the second argument to &lt;code&gt;React.createElement()&lt;/code&gt; or, if you’re using JSX, the more familiar tag attributes.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;MyChild name={this.state.childsName} /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The parent’s state value of &lt;code&gt;childsName&lt;/code&gt; becomes the child’s &lt;code&gt;this.props.name&lt;/code&gt;. From the child’s perspective, the name prop is immutable. If it needs to be changed, the parent should just change its internal state:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;this.setState({ childsName: 'New name' });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and React will propagate it to the child for you. A natural follow-on question is: what if the child needs to change its name prop? This is usually done through child events and parent callbacks. The child might expose an event called, for example, &lt;code&gt;onNameChanged&lt;/code&gt;. The parent would then subscribe to the event by passing a callback handler.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;MyChild name={this.state.childsName} onNameChanged={this.handleName} /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The child would pass its requested new name as an argument to the event callback by calling, e.g., &lt;code&gt;this.props.onNameChanged('New name')&lt;/code&gt;, and the parent would use the name in the event handler to update its state.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;handleName: function(newName) {
   this.setState({ childsName: newName });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;For parent-child communication, simply pass props.&lt;/p&gt;

&lt;p&gt;Use &lt;strong&gt;state&lt;/strong&gt; to store the data your current page needs in your controller-view.&lt;/p&gt;

&lt;p&gt;Use &lt;strong&gt;props&lt;/strong&gt; to pass data &amp;amp; event handlers down to your child components.&lt;/p&gt;

&lt;p&gt;These lists should help guide you when working with data in your components.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Props&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;are immutable

&lt;ul&gt;
&lt;li&gt;which lets React do fast reference checks&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;are used to pass data down from your view-controller

&lt;ul&gt;
&lt;li&gt;your top-level component&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;have better performance

&lt;ul&gt;
&lt;li&gt;use this to pass data to child components&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;State&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;should be managed in your view-controller

&lt;ul&gt;
&lt;li&gt;your top-level component&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;is mutable&lt;/li&gt;
&lt;li&gt;has worse performance&lt;/li&gt;
&lt;li&gt;should not be accessed from child components

&lt;ul&gt;
&lt;li&gt;pass it down with props instead&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For communication between two components that don’t have a parent-child relationship, you can set up your own global event system. Subscribe to events in componentDidMount(), unsubscribe in componentWillUnmount(), and call setState() when you receive an event. Flux pattern is one of the possible ways to arrange this. – &lt;a href="https://facebook.github.io/react/tips/communicate-between-components.html"&gt;https://facebook.github.io/react/tips/communicate-between-components.html&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What Components Should Have State?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Most of your components should simply take some data from props and render it. However, sometimes you need to respond to user input, a server request, or the passage of time. For this you use state.&lt;/p&gt;

&lt;p&gt;Try to keep as many of your components as possible &lt;strong&gt;stateless&lt;/strong&gt;. By doing this you’ll isolate the state to its most logical place and minimize redundancy, making it easier to reason about your application.&lt;/p&gt;

&lt;p&gt;A common pattern is to create several &lt;strong&gt;stateless&lt;/strong&gt; components that just render data, and have a stateful component above them in the hierarchy that passes its state to its children via props. The stateful component encapsulates all of the interaction logic, while the stateless components take care of rendering data in a declarative way. – &lt;a href="https://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html#what-components-should-have-state"&gt;https://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html#what-components-should-have-state&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What Should Go in State?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The state should contain data that a component’s event handlers may change to trigger a UI update. In real apps, this data tends to be very small and JSON-serializable. When building a stateful component, think about the minimal possible representation of its state, and only store those properties in this.state. Inside of render() simply compute any other information you need based on this state. You’ll find that thinking about and writing applications in this way tends to lead to the most correct application, since adding redundant or computed values to state means that you need to explicitly keep them in sync rather than rely on React computing them for you. – &lt;a href="https://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html#what-should-go-in-state"&gt;https://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html#what-should-go-in-state&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  11. How to use radio buttons in ReactJS?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Any changes to the rendering should be change via the &lt;code&gt;state&lt;/code&gt; or &lt;code&gt;props&lt;/code&gt; (&lt;a href="https://reactjs.org/docs/state-and-lifecycle.html"&gt;react doc&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;So here register the event of the input, and then change the &lt;code&gt;state&lt;/code&gt;, which will then trigger the render to show on the footer.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var SearchResult = React.createClass({
  getInitialState: function () {
    return {
      site: '',
      address: ''
    };
  },
  onSiteChanged: function (e) {
    this.setState({
      site: e.currentTarget.value
      });
  },

  onAddressChanged: function (e) {
    this.setState({
      address: e.currentTarget.value
      });
  },

  render: function(){
       var resultRows = this.props.data.map(function(result){
           return (
               &amp;lt;tbody&amp;gt;
                    &amp;lt;tr&amp;gt;
                        &amp;lt;td&amp;gt;&amp;lt;input type="radio" name="site_name" 
                                   value={result.SITE_NAME} 
                                   checked={this.state.site === result.SITE_NAME} 
                                   onChange={this.onSiteChanged} /&amp;gt;{result.SITE_NAME}&amp;lt;/td&amp;gt;
                        &amp;lt;td&amp;gt;&amp;lt;input type="radio" name="address" 
                                   value={result.ADDRESS}  
                                   checked={this.state.address === result.ADDRESS} 
                                   onChange={this.onAddressChanged} /&amp;gt;{result.ADDRESS}&amp;lt;/td&amp;gt;
                    &amp;lt;/tr&amp;gt;
               &amp;lt;/tbody&amp;gt;
           );
       }, this);
       return (
           &amp;lt;table className="table"&amp;gt;
               &amp;lt;thead&amp;gt;
                   &amp;lt;tr&amp;gt;
                       &amp;lt;th&amp;gt;Name&amp;lt;/th&amp;gt;
                       &amp;lt;th&amp;gt;Address&amp;lt;/th&amp;gt;
                   &amp;lt;/tr&amp;gt;
               &amp;lt;/thead&amp;gt;
                {resultRows}
               &amp;lt;tfoot&amp;gt;
                   &amp;lt;tr&amp;gt;
                       &amp;lt;td&amp;gt;chosen site name {this.state.site} &amp;lt;/td&amp;gt;
                       &amp;lt;td&amp;gt;chosen address {this.state.address} &amp;lt;/td&amp;gt;
                   &amp;lt;/tr&amp;gt;
               &amp;lt;/tfoot&amp;gt;
           &amp;lt;/table&amp;gt;
       );
  }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Here is the simplest way of implementing radio buttons in ReactJS.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class App extends React.Component {

  setGender(event) {
    console.log(event.target.value);
  }

  render() {
    return ( 
      &amp;lt;div onChange={this.setGender.bind(this)}&amp;gt;
        &amp;lt;input type="radio" value="MALE" name="gender"/&amp;gt; Male
        &amp;lt;input type="radio" value="FEMALE" name="gender"/&amp;gt; Female
      &amp;lt;/div&amp;gt;
     )
  }
}

ReactDOM.render(&amp;lt;App/&amp;gt;, document.getElementById('app'));

&amp;lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;div id="app"&amp;gt;&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  12. How to include bootstrap CSS and JS in the ReactJS app?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If you are new to React and using &lt;code&gt;create-react-app&lt;/code&gt; cli setup, run the &lt;strong&gt;npm&lt;/strong&gt; command below to include the latest version of bootstrap.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install --save bootstrap
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;or&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install --save bootstrap@latest
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then add the following import statement to index.js file&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;or&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import 'bootstrap/dist/css/bootstrap.min.css';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;don’t forget to use &lt;code&gt;className&lt;/code&gt; as attribute on target elements (react uses &lt;code&gt;className&lt;/code&gt; as an attribute instead of &lt;code&gt;class&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Via &lt;strong&gt;npm&lt;/strong&gt;, you would run the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install bootstrap jquery --save
npm install css-loader style-loader --save-dev
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If bootstrap 4, also add popper.js&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install popper.js --save
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Add the following (as a new object) to your webpack config &lt;code&gt;loaders:&lt;/code&gt; [ array&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  test: /\.css$/,
  loader: 'style-loader!css-loader'
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Add the following to your &lt;strong&gt;index&lt;/strong&gt;, or &lt;strong&gt;layout&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/js/bootstrap.js';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;In Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;These are the most commonly asked questions about ReactJS. If you have any suggestions regarding the article, please feel free to comment below. If you need any help, then we would be glad to help you.&lt;/p&gt;

&lt;p&gt;We, at &lt;a href="https://www.truemark.dev/"&gt;Truemark&lt;/a&gt;, provide services like web and mobile app development, digital marketing, and website development. So, if you want to work with us, please feel free to contact us.&lt;/p&gt;

&lt;p&gt;Hope this article helped you.&lt;/p&gt;

&lt;p&gt;This post was first published on &lt;a href="https://thedevpost.com/blog/12-most-asked-reactjs-questions/"&gt;DevPostbyTruemark&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>react</category>
    </item>
    <item>
      <title>11 Most Asked Questions About Laravel</title>
      <dc:creator>KiranPoudel98</dc:creator>
      <pubDate>Fri, 11 Sep 2020 07:37:31 +0000</pubDate>
      <link>https://forem.com/truemark/11-most-asked-questions-about-laravel-5hii</link>
      <guid>https://forem.com/truemark/11-most-asked-questions-about-laravel-5hii</guid>
      <description>&lt;p&gt;Laravel is a free open-source PHP framework that helps to develop web apps easily. There are several PHP frameworks but among them, Laravel is the most popular one. Being the popular one, users have many questions. So, today we will be talking about the most asked questions about Laravel.&lt;/p&gt;

&lt;h2&gt;
  
  
  11 Most Asked Questions About Laravel
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1. What are the best practices for custom helpers in Laravel 5?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Create a &lt;code&gt;helpers.php&lt;/code&gt; file in your app folder and load it up with composer:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"autoload": {
    "classmap": [
        ...
    ],
    "psr-4": {
        "App\\": "app/"
    },
    "files": [
        "app/helpers.php" // &amp;lt;---- ADD THIS
    ]
},
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After adding that to your &lt;code&gt;composer.json&lt;/code&gt; file, run the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;composer dump-autoload
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you don’t like keeping your &lt;code&gt;helpers.php&lt;/code&gt; file in your &lt;code&gt;app&lt;/code&gt; directory (because it’s not a PSR-4 namespaced class file), you can do what the &lt;code&gt;laravel.com&lt;/code&gt; website does: store the &lt;code&gt;helpers.php&lt;/code&gt; in the bootstrap directory. Remember to set it in your &lt;code&gt;composer.json&lt;/code&gt; file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"files": [
    "bootstrap/helpers.php"
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This answer is applicable to general custom classes within Laravel.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1:&lt;/strong&gt; Create your Helpers (or other custom class) file and give it a matching namespace. Write your class and method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php // Code within app\Helpers\Helper.php

namespace App\Helpers;

class Helper
{
    public static function shout(string $string)
    {
        return strtoupper($string);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 2:&lt;/strong&gt; Create an alias:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php // Code within config/app.php

    'aliases' =&amp;gt; [
     ...
        'Helper' =&amp;gt; App\Helpers\Helper::class,
     ...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 3:&lt;/strong&gt; Run &lt;code&gt;composer dump-autoload&lt;/code&gt; in the project root&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 4:&lt;/strong&gt; Use it in your Blade template:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!-- Code within resources/views/template.blade.php --&amp;gt;

{!! Helper::shout('this is how to use autoloading correctly!!') !!}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Extra Credit:&lt;/strong&gt; Use this class anywhere in your Laravel app:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php // Code within app/Http/Controllers/SomeController.php

namespace App\Http\Controllers;

use Helper;

class SomeController extends Controller
{

    public function __construct()
    {
        Helper::shout('now i\'m using my helper class in a controller!!');
    }
    ...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Source: &lt;a href="http://www.php-fig.org/psr/psr-4/"&gt;http://www.php-fig.org/psr/psr-4/&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Where autoloading originates from: &lt;a href="http://php.net/manual/en/language.oop5.autoload.php"&gt;http://php.net/manual/en/language.oop5.autoload.php&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  2. How to fix error “Laravel requires the Mcrypt PHP extension”?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The web-enabled extensions and command-line enabled extensions can differ. Run &lt;code&gt;php -m&lt;/code&gt; in your terminal and check to see if &lt;code&gt;mcrypt&lt;/code&gt; is listed. If it does not then check where the command line is loading your &lt;code&gt;php.ini&lt;/code&gt; file from by running php &lt;code&gt;--ini&lt;/code&gt; from your terminal.&lt;/p&gt;

&lt;p&gt;In this &lt;code&gt;php.ini&lt;/code&gt; file you can enable the extension.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;OSX&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Many people on OSX run into problems due to the terminal pointing to the native PHP shipped with OSX. You should instead update your bash profile to include the actual path to your PHP. Something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export PATH=/usr/local/php5/bin:$PATH
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Ubuntu&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;On earlier versions of Ubuntu (prior to 14.04) when you run &lt;code&gt;sudo apt-get install php5-mcrypt&lt;/code&gt; it doesn’t actually install the extension into the &lt;code&gt;mods-available&lt;/code&gt;. You’ll need to symlink it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sudo ln -s /etc/php5/conf.d/mcrypt.ini /etc/php5/mods-available/mcrypt.ini
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;On all Ubuntu versions you’ll need to enable the mod once it’s installed. You can do that with &lt;code&gt;php5enmod&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sudo php5enmod mcrypt
sudo service apache2 restart
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;NOTES&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;PHP 7.1 deprecated mcrypt and 7.2 has &lt;a href="https://wiki.php.net/rfc/mcrypt-viking-funeral"&gt;removed the mcrypt extension entirely&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Laravel 5.1 and later &lt;a href="https://github.com/laravel/framework/issues/9020"&gt;removed the need for mcrypt&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  3. How to create multiple where clause query using Laravel Eloquent?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In &lt;a href="https://laravel.com/docs/5.3/queries#where-clauses"&gt;Laravel 5.3&lt;/a&gt; (and still true as of &lt;a href="https://laravel.com/docs/6.x/queries#where-clauses"&gt;6.x&lt;/a&gt;) you can use more granular wheres passed as an array:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$query-&amp;gt;where([
    ['column_1', '=', 'value_1'],
    ['column_2', '&amp;lt;&amp;gt;', 'value_2'],
    [COLUMN, OPERATOR, VALUE],
    ...
])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Personally we haven’t found use-case for this over just multiple where calls, but fact is you can use it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Since June 2014 you can pass an array to &lt;code&gt;where&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;As long as you want all the &lt;code&gt;wheres&lt;/code&gt; use &lt;code&gt;and&lt;/code&gt; operator, you can group them this way:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$matchThese = ['field' =&amp;gt; 'value', 'another_field' =&amp;gt; 'another_value', ...];

// if you need another group of wheres as an alternative:
$orThose = ['yet_another_field' =&amp;gt; 'yet_another_value', ...];
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$results = User::where($matchThese)-&amp;gt;get();

// with another group
$results = User::where($matchThese)
    -&amp;gt;orWhere($orThose)
    -&amp;gt;get();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above will result in such query:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT * FROM users
  WHERE (field = value AND another_field = another_value AND ...)
  OR (yet_another_field = yet_another_value AND ...)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Query scopes can help you to let your code more readable.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://laravel.com/docs/eloquent#query-scopes"&gt;http://laravel.com/docs/eloquent#query-scopes&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In your model, create scopes methods like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public function scopeActive($query)
{
    return $query-&amp;gt;where('active', '=', 1);
}

public function scopeThat($query)
{
    return $query-&amp;gt;where('that', '=', 1);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then, you can call this scopes while building your query:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$users = User::active()-&amp;gt;that()-&amp;gt;get();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  4. How to get the last inserted id using Laravel Eloquent?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;For updated Laravel version try this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;return response()-&amp;gt;json(array('success' =&amp;gt; true, 'last_insert_id' =&amp;gt; $data-&amp;gt;id), 200);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;For those who might be using &lt;code&gt;DB::statement or DB::insert&lt;/code&gt;, there is another way:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DB::getPdo()-&amp;gt;lastInsertId();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  5. How to display HTML with Blade in Laravel 5?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You need to use&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{!! $text !!}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The string will auto escape when using &lt;code&gt;{{ $text }}&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;For Laravel 5&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{!!html_entity_decode($text)!!}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  6. How to say &lt;code&gt;WHERE (a = 1 OR b =1 ) AND (c = 1 OR d = 1)&lt;/code&gt;?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Make use of &lt;a href="https://laravel.com/docs/master/queries#parameter-grouping"&gt;Parameter Grouping&lt;/a&gt; (&lt;a href="https://laravel.com/docs/4.2/queries#advanced-wheres"&gt;Laravel 4.2&lt;/a&gt;). For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Model::where(function ($query) {
    $query-&amp;gt;where('a', '=', 1)
          -&amp;gt;orWhere('b', '=', 1);
})-&amp;gt;where(function ($query) {
    $query-&amp;gt;where('c', '=', 1)
          -&amp;gt;orWhere('d', '=', 1);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If you want to use parameters for a,b,c,d in Laravel 4&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Model::where(function ($query) use ($a,$b) {
    $query-&amp;gt;where('a', '=', $a)
          -&amp;gt;orWhere('b', '=', $b);
})
-&amp;gt;where(function ($query) use ($c,$d) {
    $query-&amp;gt;where('c', '=', $c)
          -&amp;gt;orWhere('d', '=', $d);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  7.  Is there a way to check whether an Eloquent collection returned from &lt;code&gt;$result = Model::where(...)-&amp;gt;get()&lt;/code&gt; is empty, as well as counting the number of elements?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When using &lt;code&gt;-&amp;gt;get()&lt;/code&gt; you cannot simply use any of the below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (empty($result)) { }
if (!$result) { }
if ($result) { }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Because if you &lt;code&gt;dd($result);&lt;/code&gt; you’ll notice an instance of &lt;code&gt;Illuminate\Support\Collection&lt;/code&gt; is always returned, even when there are no results. Essentially what you’re checking is &lt;code&gt;$a = new stdClass;&lt;/code&gt; if &lt;code&gt;($a) { ... }&lt;/code&gt; which will always return true.&lt;/p&gt;

&lt;p&gt;To determine if there are any results you can do any of the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if ($result-&amp;gt;first()) { } 
if (!$result-&amp;gt;isEmpty()) { }
if ($result-&amp;gt;count()) { }
if (count($result)) { }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You could also use &lt;code&gt;-&amp;gt;first()&lt;/code&gt; instead of &lt;code&gt;-&amp;gt;get()&lt;/code&gt; on the query builder which will return an instance of the first found model, or &lt;code&gt;null&lt;/code&gt; otherwise. This is useful if you need or are expecting only one result from the database.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$result = Model::where(...)-&amp;gt;first();
if ($result) { ... }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Bonus Information&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The Collection and the Query Builder differences can be a bit confusing to newcomers of Laravel because the method names are often the same between the two. For that reason, it can be confusing to know what one you’re working on.&lt;/p&gt;

&lt;p&gt;The Query Builder essentially builds a query until you call a method where it will execute the query and hit the database (e.g. when you call certain methods like &lt;code&gt;-&amp;gt;all() -&amp;gt;first() -&amp;gt;lists()&lt;/code&gt; and others). Those methods also exist on the &lt;code&gt;Collection&lt;/code&gt; object, which can get returned from the Query Builder if there are multiple results. If you’re not sure what class you’re actually working with, try doing &lt;code&gt;var_dump(User::all())&lt;/code&gt; and experimenting to see what classes it’s actually returning (with help of &lt;code&gt;get_class(...)&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;We highly recommend you check out the source code for the Collection class, it’s pretty simple. Then check out the Query Builder and see the similarities in function names and find out when it actually hits the database.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://github.com/laravel/framework/blob/5.2/src/Illuminate/Support/Collection.php"&gt;Laravel 5.2 Collection Class&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://github.com/laravel/framework/blob/5.2/src/Illuminate/Database/Query/Builder.php"&gt;Laravel 5.2 Query Builder&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  8. How to add a new column to existing table in a migration?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;To create a migration, you may use the migrate:make command on the Artisan CLI. Use a specific name to avoid clashing with existing models&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;For Laravel 3:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan migrate:make add_paid_to_users
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;For Laravel 5+:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan make:migration add_paid_to_users_table --table=users
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You then need to use the &lt;code&gt;Schema::table()&lt;/code&gt; method (as you’re accessing an existing table, not creating a new one). And you can add a column like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public function up()
{
    Schema::table('users', function($table) {
        $table-&amp;gt;integer('paid');
    });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and don’t forget to add the rollback option:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public function down()
{
    Schema::table('users', function($table) {
        $table-&amp;gt;dropColumn('paid');
    });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then you can run your migrations:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan migrate
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is all well covered in the documentation for both Laravel 3:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://laravel3.veliovgroup.com/docs/database/schema"&gt;Schema Builder&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://laravel3.veliovgroup.com/docs/database/migrations"&gt;Migrations&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;And for Laravel 4 / Laravel 5:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://laravel.com/docs/5.0/schema"&gt;Schema Builder&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://laravel.com/docs/5.0/migrations"&gt;Migrations&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Also,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use $table-&amp;gt;integer('paid')-&amp;gt;after('whichever_column'); to add this field after a specific column.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;To make things quicker, you can use the flag “–table” like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan make:migration add_paid_to_users --table="users"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will add the &lt;code&gt;up&lt;/code&gt; and &lt;code&gt;down&lt;/code&gt; method content automatically:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::table('users', function (Blueprint $table) {
        //
    });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Similarly, you can use the &lt;code&gt;--create["table_name"]&lt;/code&gt; option when creating new migrations which will add more boilerplate to your migrations.&lt;/p&gt;

&lt;h3&gt;
  
  
  9. How to get the current URL inside @if statement (Blade) in Laravel 4?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can use: &lt;code&gt;Request::url()&lt;/code&gt; to obtain the current URL, here is an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@if(Request::url() === 'your url here')
    // code
@endif
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Laravel offers a method to find out, whether the URL matches a pattern or not&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (Request::is('admin/*'))
{
    // code
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Check the related documentation to obtain different request information: &lt;a href="http://laravel.com/docs/requests#request-information"&gt;http://laravel.com/docs/requests#request-information&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can also use &lt;code&gt;Route::current()-&amp;gt;getName()&lt;/code&gt; to check your route name.&lt;/p&gt;

&lt;p&gt;Example: routes.php&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Route::get('test', ['as'=&amp;gt;'testing', function() {
    return View::make('test');
}]);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;View:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@if(Route::current()-&amp;gt;getName() == 'testing')
    Hello This is testing
@endif
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  10.. What to do to see if &lt;code&gt;$user&lt;/code&gt; has a record?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It depends if you want to work with the user afterward or only check if one exists.&lt;/p&gt;

&lt;p&gt;If you want to use the user object if it exists:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$user = User::where('email', '=', Input::get('email'))-&amp;gt;first();
if ($user === null) {
   // user doesn't exist
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And if you only want to check&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (User::where('email', '=', Input::get('email'))-&amp;gt;count() &amp;gt; 0) {
   // user found
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or even nicer&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (User::where('email', '=', Input::get('email'))-&amp;gt;exists()) {
   // user found
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;One of the best solutions is to use the &lt;code&gt;firstOrNew&lt;/code&gt; or &lt;code&gt;firstOrCreate&lt;/code&gt; method. The &lt;a href="https://laravel.com/docs/5.7/eloquent#other-creation-methods"&gt;documentation&lt;/a&gt; has more details on both.&lt;/p&gt;

&lt;h3&gt;
  
  
  11.  How to fix error “Allowed memory size of 536870912 bytes exhausted” in Laravel?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can try editing /etc/php5/fpm/php.ini:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;; Old Limit
; memory_limit = 512M

; New Limit
memory_limit = 2048M
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You may need to restart Nginx.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The solution is to change memory_limit in php.ini but it should be the correct one. So you need one responsible for the server, located there:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/etc/php/7.0/cli/php.ini
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;so you need a line with&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;memory_limit
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After that, you need to restart PHP service&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sudo service php7.0-fpm restart
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;to check if it was changed successfully you need to use the command line to run this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php -i
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;the report contained following line&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;memory_limit =&amp;gt; 2048M =&amp;gt; 2048M
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now test cases are fine.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;In Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;These are the 11 most asked questions about the Laravel. If you have any suggestions or any confusion, please comment below. If you need any help, we will be glad to help you.&lt;/p&gt;

&lt;p&gt;We, at &lt;a href="https://www.truemark.dev/"&gt;Truemark&lt;/a&gt;, provide services like web and mobile app development, digital marketing, and website development. So, if you need any help and want to work with us, please feel free to contact us.&lt;/p&gt;

&lt;p&gt;Hope this article helped you.&lt;/p&gt;

&lt;p&gt;This post was first published on &lt;a href="https://thedevpost.com/blog/11-most-asked-questions-about-laravel/"&gt;DevPostbyTruemark&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>laravel</category>
      <category>php</category>
    </item>
    <item>
      <title>11 Most Asked C# Questions</title>
      <dc:creator>KiranPoudel98</dc:creator>
      <pubDate>Fri, 04 Sep 2020 08:40:18 +0000</pubDate>
      <link>https://forem.com/truemark/11-most-asked-c-questions-1c65</link>
      <guid>https://forem.com/truemark/11-most-asked-c-questions-1c65</guid>
      <description>&lt;p&gt;C# is a general-purpose and object-oriented programming language developed by Microsoft. It is mostly used for developing desktop and web applications. So, today we will be talking about the 11 frequently asked questions about C# programming language.&lt;/p&gt;

&lt;h2&gt;
  
  
  11 Frequently Asked C# Questions
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1. What is the difference between String and string in C#?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/reference-types"&gt;&lt;code&gt;string&lt;/code&gt;&lt;/a&gt; is an alias in C# for &lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.string?view=netcore-3.1"&gt;&lt;code&gt;System.String&lt;/code&gt;.&lt;/a&gt;&lt;br&gt;
So technically, there is no difference. It’s like &lt;a href="https://stackoverflow.com/questions/62503/should-i-use-int-or-int32"&gt;int vs. System.Int32&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;As far as guidelines, it’s generally recommended to use string any time you’re referring to an object.&lt;/p&gt;

&lt;p&gt;e.g.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;string place = "world";
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Likewise, it’s generally recommended to use &lt;code&gt;String&lt;/code&gt; if you need to refer specifically to the class.&lt;/p&gt;

&lt;p&gt;e.g.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;string greet = String.Format("Hello {0}!", place);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is the style that Microsoft tends to use in &lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.string.format?view=netcore-3.1#examples"&gt;their examples&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;It appears that the guidance in this area may have changed, as &lt;a href="https://github.com/StyleCop"&gt;StyleCop&lt;/a&gt; now enforces the use of the C# specific aliases.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;string&lt;/code&gt; is an alias for &lt;code&gt;System.String&lt;/code&gt;. They compile to the same code, so at execution time there is no difference whatsoever. This is just one of the aliases in C#. The complete list is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;object:  System.Object
string:  System.String
bool:    System.Boolean
byte:    System.Byte
sbyte:   System.SByte
short:   System.Int16
ushort:  System.UInt16
int:     System.Int32
uint:    System.UInt32
long:    System.Int64
ulong:   System.UInt64
float:   System.Single
double:  System.Double
decimal: System.Decimal
char:    System.Char
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Apart from &lt;code&gt;string&lt;/code&gt; and &lt;code&gt;object&lt;/code&gt;, the aliases are all to value types. &lt;code&gt;decimal&lt;/code&gt; is a value type, but not a primitive type in the CLR. The only primitive type which doesn’t have an alias is &lt;code&gt;System.IntPtr&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;In the spec, the value type aliases are known as “simple types”. Literals can be used for constant values of every simple type; no other value types have literal forms available. (Compare this with VB, which allows &lt;code&gt;DateTime&lt;/code&gt; literals, and has an alias for it too.)&lt;/p&gt;

&lt;p&gt;There is one circumstance in which you have to use the aliases: when explicitly specifying an enum’s underlying type. For instance:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public enum Foo : UInt32 {} // Invalid
public enum Bar : uint   {} // Valid
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That’s just a matter of the way the spec defines enum declarations – the part after the colon has to be the integral-type production, which is one token of &lt;code&gt;sbyte&lt;/code&gt;, &lt;code&gt;byte&lt;/code&gt;, &lt;code&gt;short&lt;/code&gt;, &lt;code&gt;ushort&lt;/code&gt;, &lt;code&gt;int&lt;/code&gt;, &lt;code&gt;uint&lt;/code&gt;, &lt;code&gt;long&lt;/code&gt;, &lt;code&gt;ulong&lt;/code&gt;, &lt;code&gt;char…&lt;/code&gt; as opposed to a type production as used by variable declarations for example. It doesn’t indicate any other difference.&lt;/p&gt;

&lt;p&gt;Finally, when it comes to which to use: the CLR type is for any APIs. It really doesn’t matter too much which you use in terms of implementation – consistency among your team is nice, but no-one else is going to care. On the other hand, it’s genuinely important that if you refer to a type in an API, you do so in a language-neutral way. A method called &lt;code&gt;ReadInt32&lt;/code&gt; is unambiguous, whereas a method called &lt;code&gt;ReadInt&lt;/code&gt; requires interpretation. The caller could be using a language that defines an &lt;code&gt;int&lt;/code&gt; alias for &lt;code&gt;Int16&lt;/code&gt;, for example. The .NET framework designers have followed this pattern, good examples being in the &lt;code&gt;BitConverter&lt;/code&gt;, &lt;code&gt;BinaryReader&lt;/code&gt;, and &lt;code&gt;Convert&lt;/code&gt; classes.&lt;/p&gt;

&lt;h3&gt;
  
  
  2. How to cast an int to enum?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;From a string:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;YourEnum foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString);

// The foo.ToString().Contains(",") check is necessary for enumerations marked with an [Flags] attribute
if (!Enum.IsDefined(typeof(YourEnum), foo) &amp;amp;&amp;amp; !foo.ToString().Contains(","))
{
    throw new InvalidOperationException($"{yourString} is not an underlying value of the YourEnum enumeration.")
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;From an int:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;YourEnum foo = (YourEnum)yourInt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;From the number also you can&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;YourEnum foo = (YourEnum)Enum.ToObject(typeof(YourEnum) , yourInt);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Just cast it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;MyEnum e = (MyEnum)3;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can check if it’s in range using &lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.enum.isdefined?redirectedfrom=MSDN&amp;amp;view=netcore-3.1#System_Enum_IsDefined_System_Type_System_Object_"&gt;Enum.IsDefined&lt;/a&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (Enum.IsDefined(typeof(MyEnum), 3)) { ... }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  3. What is the best way to iterate over a dictionary?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The best way to do is&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;foreach(KeyValuePair&amp;lt;string, string&amp;gt; entry in myDictionary)
{
    // do something with entry.Value or entry.Key
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If you are trying to use a generic Dictionary in C# like you would use an associative array in another language:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;foreach(var item in myDictionary)
{
  foo(item.Key);
  bar(item.Value);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or, if you only need to iterate over the collection of keys, use&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;foreach(var item in myDictionary.Keys)
{
  foo(item);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And lastly, if you’re only interested in the values:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;foreach(var item in myDictionary.Values)
{
  foo(item);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;(Take note that the &lt;code&gt;var&lt;/code&gt; keyword is an optional C# 3.0 and above feature, you could also use the exact type of your keys/values here)&lt;/p&gt;

&lt;h3&gt;
  
  
  4. What are the correct version numbers for C#?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;C# language version history:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;These are the &lt;a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-version-history"&gt;versions of C#&lt;/a&gt; known about at the time of this writing:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;C# 1.0&lt;/strong&gt; released with .NET 1.0 and VS2002 (January 2002)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;C# 1.2&lt;/strong&gt; (bizarrely enough); released with .NET 1.1 and VS2003 (April 2003). First version to call &lt;code&gt;Dispose&lt;/code&gt; on &lt;code&gt;IEnumerators&lt;/code&gt; which implemented &lt;code&gt;IDisposable&lt;/code&gt;. A few other small features.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;C# 2.0&lt;/strong&gt; released with .NET 2.0 and VS2005 (November 2005). Major new features: generics, anonymous methods, nullable types, iterator blocks&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;C# 3.0&lt;/strong&gt; released with .NET 3.5 and VS2008 (November 2007). Major new features: lambda expressions, extension methods, expression trees, anonymous types, implicit typing (&lt;code&gt;var&lt;/code&gt;), query expressions&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;C# 4.0&lt;/strong&gt; released with .NET 4 and VS2010 (April 2010). Major new features: late binding (&lt;code&gt;dynamic&lt;/code&gt;), delegate and interface generic variance, more COM support, named arguments, tuple data type, and optional parameters&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;C# 5.0&lt;/strong&gt; released with .NET 4.5 and VS2012 (August 2012). &lt;a href="https://docs.microsoft.com/en-us/archive/blogs/csharpfaq/visual-studio-11-beta-is-here"&gt;Major features&lt;/a&gt;: async programming, caller info attributes. Breaking change: &lt;a href="https://ericlippert.com/2009/11/16/closing-over-the-loop-variable-considered-harmful-part-two/"&gt;loop variable closure&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;C# 6.0&lt;/strong&gt; released with .NET 4.6 and VS2015 (July 2015). Implemented by &lt;a href="https://github.com/dotnet/roslyn"&gt;Roslyn&lt;/a&gt;. &lt;a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-6"&gt;Features&lt;/a&gt;: initializers for automatically implemented properties, using directives to import static members, exception filters, element initializers, &lt;code&gt;await&lt;/code&gt; in &lt;code&gt;catch&lt;/code&gt; and &lt;code&gt;finally&lt;/code&gt;, extension &lt;code&gt;Add&lt;/code&gt; methods in collection initializers.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;C# 7.0&lt;/strong&gt; released with .NET 4.7 and VS2017 (March 2017) Major &lt;a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7"&gt;new features&lt;/a&gt;: &lt;a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#tuples"&gt;tuples&lt;/a&gt;, &lt;a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#ref-locals-and-returns"&gt;ref locals and ref return&lt;/a&gt;, &lt;a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#pattern-matching"&gt;pattern matching&lt;/a&gt; (including pattern-based switch statements), &lt;a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#out-variables"&gt;inline &lt;code&gt;out&lt;/code&gt; parameter declarations&lt;/a&gt;, &lt;a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#local-functions"&gt;local functions&lt;/a&gt;, &lt;a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#numeric-literal-syntax-improvements"&gt;binary literals, digit separators&lt;/a&gt;, and &lt;a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#generalized-async-return-types"&gt;arbitrary async returns&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;C# 7.1&lt;/strong&gt; released with VS2017 v15.3 (August 2017) New features: &lt;a href="https://github.com/dotnet/csharplang/issues/97"&gt;async main&lt;/a&gt;, &lt;a href="https://github.com/dotnet/csharplang/issues/415"&gt;tuple member name inference&lt;/a&gt;, &lt;a href="https://github.com/dotnet/csharplang/issues/102"&gt;default expression&lt;/a&gt;, &lt;a href="https://github.com/dotnet/csharplang/issues/154"&gt;pattern matching with generics&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;C# 7.2&lt;/strong&gt; released with VS2017 v15.5 (November 2017) New features: &lt;a href="https://github.com/dotnet/csharplang/issues/37"&gt;private protected access modifier&lt;/a&gt;, &lt;a href="https://github.com/dotnet/csharplang/issues/666"&gt;Span, aka interior pointer, aka stack only struct&lt;/a&gt;, &lt;a href="https://github.com/dotnet/csharplang/milestone/6"&gt;everything else&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;C# 7.3&lt;/strong&gt; released with VS2017 v15.7 (May 2018). New features: &lt;a href="https://devblogs.microsoft.com/premier-developer/dissecting-new-generics-constraints-in-c-7-3/"&gt;enum, delegate and &lt;code&gt;unmanaged&lt;/code&gt; generic type constraints&lt;/a&gt;. &lt;code&gt;ref&lt;/code&gt; reassignment. Unsafe improvements: &lt;code&gt;stackalloc&lt;/code&gt; initialization, unpinned indexed &lt;code&gt;fixed&lt;/code&gt; buffers, custom &lt;code&gt;fixed&lt;/code&gt; statements. Improved overloading resolution. Expression variables in initializers and queries. &lt;code&gt;==&lt;/code&gt; and &lt;code&gt;!=&lt;/code&gt; defined for tuples. Auto-properties’ backing fields can now be targeted by attributes.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;C# 8.0&lt;/strong&gt; released with .Net Core 3.0 and VS2019 v16.3 (September 2019). Major &lt;a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8"&gt;new features&lt;/a&gt;: &lt;a href="https://docs.microsoft.com/en-us/dotnet/csharp/nullable-references"&gt;nullable reference-types&lt;/a&gt;, &lt;a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#asynchronous-streams"&gt;Asynchronous streams&lt;/a&gt;, &lt;a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#indices-and-ranges"&gt;Indices and Ranges&lt;/a&gt;, &lt;a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#readonly-members"&gt;Readonly members&lt;/a&gt;, &lt;a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#using-declarations"&gt;using declarations&lt;/a&gt;, &lt;a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#default-interface-methods"&gt;default interface methods&lt;/a&gt;, &lt;a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#static-local-functions"&gt;Static local functions&lt;/a&gt;, and &lt;a&gt;Enhancement of interpolated verbatim strings&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  5. How to clone or deep copy an object so that the cloned object can be modified without any changes being reflected in the original object?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Whilst the standard practice is to implement the &lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.icloneable?redirectedfrom=MSDN&amp;amp;view=netcore-3.1"&gt;&lt;code&gt;ICloneable&lt;/code&gt;&lt;/a&gt; interface, here’s a nice deep clone object copier found on &lt;a href="https://www.codeproject.com/Articles/23832/Implementing-Deep-Cloning-via-Serializing-objects"&gt;The Code Project&lt;/a&gt; and incorporated it.&lt;/p&gt;

&lt;p&gt;As mentioned, it does require your objects to be serializable.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

/// &amp;lt;summary&amp;gt;
/// Reference Article http://www.codeproject.com/KB/tips/SerializedObjectCloner.aspx
/// Provides a method for performing a deep copy of an object.
/// Binary Serialization is used to perform the copy.
/// &amp;lt;/summary&amp;gt;
public static class ObjectCopier
{
    /// &amp;lt;summary&amp;gt;
    /// Perform a deep Copy of the object.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;typeparam name="T"&amp;gt;The type of object being copied.&amp;lt;/typeparam&amp;gt;
    /// &amp;lt;param name="source"&amp;gt;The object instance to copy.&amp;lt;/param&amp;gt;
    /// &amp;lt;returns&amp;gt;The copied object.&amp;lt;/returns&amp;gt;
    public static T Clone&amp;lt;T&amp;gt;(T source)
    {
        if (!typeof(T).IsSerializable)
        {
            throw new ArgumentException("The type must be serializable.", nameof(source));
        }

        // Don't serialize a null object, simply return the default for that object
        if (Object.ReferenceEquals(source, null))
        {
            return default(T);
        }

        IFormatter formatter = new BinaryFormatter();
        Stream stream = new MemoryStream();
        using (stream)
        {
            formatter.Serialize(stream, source);
            stream.Seek(0, SeekOrigin.Begin);
            return (T)formatter.Deserialize(stream);
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The idea is that it serializes your object and then deserializes it into a fresh object. The benefit is that you don’t have to concern yourself about cloning everything when an object gets too complex.&lt;/p&gt;

&lt;p&gt;And with the use of extension methods (also from the originally referenced source):&lt;/p&gt;

&lt;p&gt;In case you prefer to use the new &lt;a href="https://en.wikipedia.org/wiki/Extension_method"&gt;extension methods&lt;/a&gt; of C# 3.0, change the method to have the following signature:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public static T Clone&amp;lt;T&amp;gt;(this T source)
{
   //...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now the method call simply becomes &lt;code&gt;objectBeingCloned.Clone();&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;You can also use JSON to do this, it &lt;a href="https://maxondev.com/serialization-performance-comparison-c-net-formats-frameworks-xmldatacontractserializer-xmlserializer-binaryformatter-json-newtonsoft-servicestack-text/"&gt;should be &lt;/a&gt;lighter, and avoids the overhead of [Serializable] tags.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/// &amp;lt;summary&amp;gt;
/// Perform a deep Copy of the object, using Json as a serialisation method. NOTE: Private members are not cloned using this method.
/// &amp;lt;/summary&amp;gt;
/// &amp;lt;typeparam name="T"&amp;gt;The type of object being copied.&amp;lt;/typeparam&amp;gt;
/// &amp;lt;param name="source"&amp;gt;The object instance to copy.&amp;lt;/param&amp;gt;
/// &amp;lt;returns&amp;gt;The copied object.&amp;lt;/returns&amp;gt;
public static T CloneJson&amp;lt;T&amp;gt;(this T source)
{            
    // Don't serialize a null object, simply return the default for that object
    if (Object.ReferenceEquals(source, null))
    {
        return default(T);
    }

    // initialize inner objects individually
    // for example in default constructor some list property initialized with some values,
    // but in 'source' these items are cleaned -
    // without ObjectCreationHandling.Replace default constructor values will be added to result
    var deserializeSettings = new JsonSerializerSettings {ObjectCreationHandling = ObjectCreationHandling.Replace};

    return JsonConvert.DeserializeObject&amp;lt;T&amp;gt;(JsonConvert.SerializeObject(source), deserializeSettings);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If your object is out of the box JSON serializable then this method will do the trick. This requires no modification or implementation of interfaces on the cloned class, just a JSON serializer like JSON.NET.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public static T Clone&amp;lt;T&amp;gt;(T source)
{
    var serialized = JsonConvert.SerializeObject(source);
    return JsonConvert.DeserializeObject&amp;lt;T&amp;gt;(serialized);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Also, you can use this extension method&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public static class SystemExtension
{
    public static T Clone&amp;lt;T&amp;gt;(this T source)
    {
        var serialized = JsonConvert.SerializeObject(source);
        return JsonConvert.DeserializeObject&amp;lt;T&amp;gt;(serialized);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  6. How to get a consistent byte representation of strings in C# without manually specifying an encoding?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can just do this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;static byte[] GetBytes(string str)
{
    byte[] bytes = new byte[str.Length * sizeof(char)];
    System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
    return bytes;
}

// Do NOT use on arbitrary bytes; only use on GetBytes's output on the SAME system
static string GetString(byte[] bytes)
{
    char[] chars = new char[bytes.Length / sizeof(char)];
    System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
    return new string(chars);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It also depends on the encoding of your string (&lt;a href="https://en.wikipedia.org/wiki/ASCII"&gt;ASCII&lt;/a&gt;, &lt;a href="https://en.wikipedia.org/wiki/UTF-8"&gt;UTF-8&lt;/a&gt;, …).&lt;/p&gt;

&lt;p&gt;For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;byte[] b1 = System.Text.Encoding.UTF8.GetBytes (myString);
byte[] b2 = System.Text.Encoding.ASCII.GetBytes (myString);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A small sample of why encoding matters:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;string pi = "\u03a0";
byte[] ascii = System.Text.Encoding.ASCII.GetBytes (pi);
byte[] utf8 = System.Text.Encoding.UTF8.GetBytes (pi);

Console.WriteLine (ascii.Length); //Will print 1
Console.WriteLine (utf8.Length); //Will print 2
Console.WriteLine (System.Text.Encoding.ASCII.GetString (ascii)); //Will print '?'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;ASCII simply isn’t equipped to deal with special characters.&lt;/p&gt;

&lt;p&gt;Internally, the .NET framework uses &lt;a href="https://en.wikipedia.org/wiki/UTF-16"&gt;UTF-16&lt;/a&gt; to represent strings, so if you simply want to get the exact bytes that .NET uses, use &lt;code&gt;System.Text.Encoding.Unicode.GetBytes (...)&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;See &lt;a href="https://docs.microsoft.com/en-us/dotnet/standard/base-types/character-encoding?redirectedfrom=MSDN"&gt;Character Encoding in the .NET Framework&lt;/a&gt; (MSDN) for more information.&lt;/p&gt;

&lt;h3&gt;
  
  
  7. Should ‘using’ directives be inside or outside the namespace?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;There is actually a (subtle) difference between the two. Imagine you have the following code in File1.cs:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// File1.cs
using System;
namespace Outer.Inner
{
    class Foo
    {
        static void Bar()
        {
            double d = Math.PI;
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now imagine that someone adds another file (File2.cs) to the project that looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// File2.cs
namespace Outer
{
    class Math
    {
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The compiler searches &lt;code&gt;Outer&lt;/code&gt; before looking at those &lt;code&gt;using&lt;/code&gt; directives outside the namespace, so it finds &lt;code&gt;Outer.Math&lt;/code&gt; instead of &lt;code&gt;System.Math&lt;/code&gt;. Unfortunately (or perhaps fortunately?), &lt;code&gt;Outer.Math&lt;/code&gt; has no &lt;code&gt;PI&lt;/code&gt; member, so File1 is now broken.&lt;/p&gt;

&lt;p&gt;This changes if you put the &lt;code&gt;using&lt;/code&gt; inside your namespace declaration, as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// File1b.cs
namespace Outer.Inner
{
    using System;
    class Foo
    {
        static void Bar()
        {
            double d = Math.PI;
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now the compiler searches &lt;code&gt;System&lt;/code&gt; before searching &lt;code&gt;Outer&lt;/code&gt;, finds &lt;code&gt;System.Math&lt;/code&gt;, and all is well.&lt;/p&gt;

&lt;p&gt;Some would argue that &lt;code&gt;Math&lt;/code&gt; might be a bad name for a user-defined class since there’s already one in &lt;code&gt;System&lt;/code&gt;; the point here is just that there is a difference, and it affects the maintainability of your code.&lt;/p&gt;

&lt;p&gt;It’s also interesting to note what happens if &lt;code&gt;Foo&lt;/code&gt; is in the namespace &lt;code&gt;Outer&lt;/code&gt;, rather than &lt;code&gt;Outer.Inner&lt;/code&gt;. In that case, adding &lt;code&gt;Outer.Math&lt;/code&gt; in File2 breaks File1 regardless of where the &lt;code&gt;using&lt;/code&gt; goes. This implies that the compiler searches the innermost enclosing namespace before it looks at any &lt;code&gt;using&lt;/code&gt; directive.&lt;/p&gt;

&lt;h3&gt;
  
  
  8. How to generate a random int number?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The &lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.random?view=netcore-3.1"&gt;&lt;code&gt;Random&lt;/code&gt; class&lt;/a&gt; is used to create random numbers. (Pseudo-random that is of course.).&lt;/p&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Random rnd = new Random();
int month  = rnd.Next(1, 13);  // creates a number between 1 and 12
int dice   = rnd.Next(1, 7);   // creates a number between 1 and 6
int card   = rnd.Next(52);     // creates a number between 0 and 51
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you are going to create more than one random number, you should keep the &lt;code&gt;Random&lt;/code&gt; instance and reuse it. If you create new instances too close in time, they will produce the same series of random numbers as the random generator is seeded from the system clock.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Every time you do new Random() it is initialized . This means that in a tight loop you get the same value lots of times. You should keep a single Random instance and keep using Next on the same instance.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//Function to get random number
private static readonly Random getrandom = new Random();

public static int GetRandomNumber(int min, int max)
{
    lock(getrandom) // synchronize
    {
        return getrandom.Next(min, max);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  9. How to create an Excel (.XLS and .XLSX) file in C# without installing Microsoft Office?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can use a library called ExcelLibrary. It’s a free, open-source library posted on Google Code: &lt;a href="https://code.google.com/archive/p/excellibrary/"&gt;ExcelLibrary&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It will not write to the new .xlsx format yet, but they are working on adding that functionality in.&lt;/p&gt;

&lt;p&gt;It’s very simple, small, and easy to use. Plus it has a DataSetHelper that lets you use DataSets and DataTables to easily work with Excel data.&lt;/p&gt;

&lt;p&gt;ExcelLibrary seems to still only work for the older Excel format (.xls files), but maybe adding support in the future for newer 2007/2010 formats.&lt;/p&gt;

&lt;p&gt;You can also use &lt;a href="https://github.com/JanKallman/EPPlus"&gt;EPPlus&lt;/a&gt;, which works only for Excel 2007/2010 format files (.xlsx files). There’s also &lt;a href="https://github.com/tonyqus/npoi"&gt;NPOI&lt;/a&gt; which works with both.&lt;/p&gt;

&lt;p&gt;There are a few known bugs with each library. In all, EPPlus seems to be the best choice as time goes on. It seems to be more actively updated and documented as well.&lt;/p&gt;

&lt;p&gt;Also, EPPlus has support for Pivot Tables and ExcelLibrary may have some support (&lt;a href="https://code.google.com/archive/p/excellibrary/issues/98"&gt;Pivot table issue in ExcelLibrary&lt;/a&gt;)&lt;/p&gt;

&lt;p&gt;Here are a couple of links for quick reference:&lt;br&gt;
&lt;a href="https://code.google.com/archive/p/excellibrary/"&gt;ExcelLibrary&lt;/a&gt; – &lt;a href="https://www.gnu.org/licenses/lgpl-3.0.html"&gt;GNU Lesser GPL&lt;/a&gt;&lt;br&gt;
EPPlus – GNU Lesser General Public License (LGPL)&lt;br&gt;
NPOI – &lt;a href="https://github.com/tonyqus/npoi/blob/master/LICENSE"&gt;Apache License&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Here some example code for ExcelLibrary:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Here is an example of taking data from a database and creating a workbook from it. Note that the ExcelLibrary code is the single line at the bottom:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//Create the data set and table
DataSet ds = new DataSet("New_DataSet");
DataTable dt = new DataTable("New_DataTable");

//Set the locale for each
ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;

//Open a DB connection (in this example with OleDB)
OleDbConnection con = new OleDbConnection(dbConnectionString);
con.Open();

//Create a query and fill the data table with the data from the DB
string sql = "SELECT Whatever FROM MyDBTable;";
OleDbCommand cmd = new OleDbCommand(sql, con);
OleDbDataAdapter adptr = new OleDbDataAdapter();

adptr.SelectCommand = cmd;
adptr.Fill(dt);
con.Close();

//Add the table to the data set
ds.Tables.Add(dt);

//Here's the easy part. Create the Excel worksheet from the data set
ExcelLibrary.DataSetHelper.CreateWorkbook("MyExcelFile.xls", ds);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Creating the Excel file is as easy as that. You can also manually create Excel files.&lt;/p&gt;

&lt;h3&gt;
  
  
  10. What is the best way to give a C# auto-property an initial value?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In C# 5 and earlier, to give auto-implemented properties an initial value, you have to do it in a constructor.&lt;/p&gt;

&lt;p&gt;Since C# 6.0, you can specify the initial value in-line. The syntax is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public int X { get; set; } = x; // C# 6 or higher
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.componentmodel.defaultvalueattribute?view=netframework-4.8"&gt;&lt;code&gt;DefaultValueAttributeis&lt;/code&gt;&lt;/a&gt; intended to be used by the VS designer (or any other consumer) to specify a default value, not an initial value. (Even if in the designed object, the initial value is the default value).&lt;/p&gt;

&lt;p&gt;At compile time &lt;code&gt;DefaultValueAttribute&lt;/code&gt; will not impact the generated IL and it will not be read to initialize the property to that value.&lt;/p&gt;

&lt;p&gt;Example of attributes that impact the IL are &lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.threadstaticattribute?view=netframework-4.8"&gt;&lt;code&gt;ThreadStaticAttribute&lt;/code&gt;&lt;/a&gt;, &lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callermembernameattribute?view=netframework-4.8"&gt;&lt;code&gt;CallerMemberNameAttribute&lt;/code&gt;&lt;/a&gt;, …&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;C# 6 :&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;With C# 6 you can initialize auto-properties directly.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;C# 5 and below:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Though the intended use of the attribute is not to actually set the values of the properties, you can use reflection to always set them anyway.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class DefaultValuesTest
{    
    public DefaultValuesTest()
    {               
        foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(this))
        {
            DefaultValueAttribute myAttribute = (DefaultValueAttribute)property.Attributes[typeof(DefaultValueAttribute)];

            if (myAttribute != null)
            {
                property.SetValue(this, myAttribute.Value);
            }
        }
    }

    public void DoTest()
    {
        var db = DefaultValueBool;
        var ds = DefaultValueString;
        var di = DefaultValueInt;
    }

    [System.ComponentModel.DefaultValue(true)]
    public bool DefaultValueBool { get; set; }

    [System.ComponentModel.DefaultValue("Good")]
    public string DefaultValueString { get; set; }

    [System.ComponentModel.DefaultValue(27)]
    public int DefaultValueInt { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  11. How to Sort a List by a property in the object?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The easiest way is to use Linq:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;List&amp;lt;Order&amp;gt; SortedList = objListOrder.OrderBy(o=&amp;gt;o.OrderDate).ToList();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If you need to sort the list in-place then you can use the &lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.sort?view=netcore-3.1#System_Collections_Generic_List_1_Sort_System_Comparison__0__"&gt;&lt;code&gt;Sort&lt;/code&gt;&lt;/a&gt; method, passing a &lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.comparison-1?view=netcore-3.1"&gt;&lt;code&gt;Comparison&amp;lt;T&amp;gt;&lt;/code&gt;&lt;/a&gt; delegate:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;objListOrder.Sort((x, y) =&amp;gt; x.OrderDate.CompareTo(y.OrderDate));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you prefer to create a new, sorted sequence rather than sort in-place then you can use LINQ’s &lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.orderby?view=netcore-3.1"&gt;&lt;code&gt;OrderBy&lt;/code&gt;&lt;/a&gt; method.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;In Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;These are the 11 most asked C# questions. If you have any suggestions or any confusion, please comment below. If you need any help, we will be glad to help you.&lt;/p&gt;

&lt;p&gt;We, at &lt;a href="https://www.truemark.dev/"&gt;Truemark&lt;/a&gt;, provide services like web and mobile app development, digital marketing, and website development. So, if you need any help and want to work with us, please feel free to contact us.&lt;/p&gt;

&lt;p&gt;Hope this article helped you.&lt;/p&gt;

&lt;p&gt;This article was first published on &lt;a href="https://thedevpost.com/blog/11-most-asked-csharp-questions/"&gt;DevPost&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>csharp</category>
    </item>
    <item>
      <title>11 Most Asked Questions About PHP</title>
      <dc:creator>KiranPoudel98</dc:creator>
      <pubDate>Fri, 28 Aug 2020 07:56:27 +0000</pubDate>
      <link>https://forem.com/truemark/11-most-asked-questions-about-php-4p1f</link>
      <guid>https://forem.com/truemark/11-most-asked-questions-about-php-4p1f</guid>
      <description>&lt;p&gt;PHP (Hypertext Pre-processor) is a popular server-side scripting language mainly used for developing websites and web applications. It can be used to build either static or dynamic websites. It is very simple and easy to learn. So, today we will be checking out the 11 most frequently asked questions about PHP.&lt;/p&gt;

&lt;h2&gt;
  
  
  11 Most Asked Questions About PHP
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1. How to prevent SQL injection in PHP?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use prepared statements and parameterized queries.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.&lt;/p&gt;

&lt;p&gt;You basically have two options to achieve this:&lt;/p&gt;

&lt;p&gt;i. Using &lt;a href="https://www.php.net/manual/en/book.pdo.php"&gt;PDO&lt;/a&gt; (for any supported database driver):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$stmt = $pdo-&amp;gt;prepare('SELECT * FROM employees WHERE name = :name');

$stmt-&amp;gt;execute([ 'name' =&amp;gt; $name ]);

foreach ($stmt as $row) {
    // Do something with $row
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;ii. Using &lt;a href="https://www.php.net/manual/en/book.mysqli.php"&gt;MySQLi&lt;/a&gt; (for MySQL):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$stmt = $dbConnection-&amp;gt;prepare('SELECT * FROM employees WHERE name = ?');
$stmt-&amp;gt;bind_param('s', $name); // 's' specifies the variable type =&amp;gt; 'string'

$stmt-&amp;gt;execute();

$result = $stmt-&amp;gt;get_result();
while ($row = $result-&amp;gt;fetch_assoc()) {
    // Do something with $row
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you’re connecting to a database other than MySQL, there is a driver-specific second option that you can refer to (for example, &lt;code&gt;pg_prepare()&lt;/code&gt; and &lt;code&gt;pg_execute()&lt;/code&gt; for PostgreSQL). PDO is the universal option.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Correctly setting up the connection&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Note that when using &lt;code&gt;PDO&lt;/code&gt; to access a MySQL database real prepared statements are &lt;strong&gt;not used by default&lt;/strong&gt;. To fix this you have to disable the emulation of prepared statements. An example of creating a connection using PDO is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'password');

$dbConnection-&amp;gt;setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection-&amp;gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example the error mode isn’t strictly necessary, &lt;strong&gt;but it is advised to add it&lt;/strong&gt;. This way the script will not stop with a &lt;code&gt;Fatal Error&lt;/code&gt; when something goes wrong. And it gives the developer the chance to &lt;code&gt;catch&lt;/code&gt; any error(s) which are &lt;code&gt;throw&lt;/code&gt;n as &lt;code&gt;PDOExceptions&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;What is &lt;strong&gt;mandatory&lt;/strong&gt;, however, is the first &lt;code&gt;setAttribute()&lt;/code&gt; line, which tells PDO to disable emulated prepared statements and use &lt;em&gt;real&lt;/em&gt; prepared statements. This makes sure the statement and the values aren’t parsed by PHP before sending it to the MySQL server (giving a possible attacker no chance to inject malicious SQL).&lt;/p&gt;

&lt;p&gt;Although you can set the &lt;code&gt;charset&lt;/code&gt; in the options of the constructor, it’s important to note that ‘older’ versions of PHP (before 5.3.6) &lt;a href="https://www.php.net/manual/en/ref.pdo-mysql.connection.php"&gt;silently ignored the charset parameter&lt;/a&gt; in the DSN.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Explanation&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The SQL statement you pass to &lt;code&gt;prepare&lt;/code&gt; is parsed and compiled by the database server. By specifying parameters (either a &lt;code&gt;?&lt;/code&gt; or a named parameter like &lt;code&gt;:name&lt;/code&gt; in the example above) you tell the database engine where you want to filter on. Then when you call &lt;code&gt;execute&lt;/code&gt;, the prepared statement is combined with the parameter values you specify.&lt;/p&gt;

&lt;p&gt;The important thing here is that the parameter values are combined with the compiled statement, not an SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters, you limit the risk of ending up with something you didn’t intend.&lt;/p&gt;

&lt;p&gt;Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the &lt;code&gt;$name&lt;/code&gt; variable contains &lt;code&gt;'Sarah'; DELETE FROM employees&lt;/code&gt; the result would simply be a search for the string &lt;code&gt;"'Sarah'; DELETE FROM employees"&lt;/code&gt;, and you will not end up with an empty table.&lt;/p&gt;

&lt;p&gt;Another benefit of using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains. Oh, and about how to do it for an insert, here’s an example (using PDO):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$preparedStatement = $db-&amp;gt;prepare('INSERT INTO table (column) VALUES (:column)');

$preparedStatement-&amp;gt;execute([ 'column' =&amp;gt; $unsafeValue ]);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Can prepared statements be used for dynamic queries?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;While you can still use prepared statements for the query parameters, the structure of the dynamic query itself cannot be parametrized and certain query features cannot be parametrized.&lt;/p&gt;

&lt;p&gt;For these specific scenarios, the best thing to do is use a whitelist filter that restricts the possible values.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Value whitelist
// $dir can only be 'DESC', otherwise it will be 'ASC'
if (empty($dir) || $dir !== 'DESC') {
   $dir = 'ASC';
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2. How to check if a string contains a specific word?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can use the &lt;a href="https://www.php.net/manual/en/function.strpos.php"&gt;&lt;code&gt;strpos()&lt;/code&gt;&lt;/a&gt; function which is used to find the occurrence of one string inside another one:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$a = 'How are you?';

if (strpos($a, 'are') !== false) {
    echo 'true';
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that the use of &lt;code&gt;!== false&lt;/code&gt; is deliberate (neither &lt;code&gt;!= false&lt;/code&gt; nor &lt;code&gt;=== true&lt;/code&gt; will return the desired result); &lt;code&gt;strpos()&lt;/code&gt; returns either the offset at which the needle string begins in the haystack string, or the boolean &lt;code&gt;false&lt;/code&gt; if the needle isn’t found. Since 0 is a valid offset and 0 is “falsey”, we can’t use simpler constructs like &lt;code&gt;!strpos($a, 'are')&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You could use regular expressions, it’s better for word matching compared to &lt;code&gt;strpos&lt;/code&gt; as it will also return true for strings such as fare, care, stare, etc. This can simply be avoided in regular expression by using word boundaries. A simple match for are could look something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$a = 'How are you?';

if (preg_match('/\bare\b/', $a)) {
    echo 'true';
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;On the performance side, &lt;code&gt;strpos&lt;/code&gt; is about three times faster and have in mind, when we did one million compares at once, it took &lt;a href="https://www.php.net/manual/en/function.preg-match.php"&gt;&lt;code&gt;preg_match&lt;/code&gt;&lt;/a&gt; 1.5 seconds to finish and for &lt;code&gt;strpos&lt;/code&gt; it took 0.5 seconds.&lt;/p&gt;

&lt;p&gt;In order to search any part of the string, not just word by word, we would recommend using a regular expression like&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$a = 'How are you?';
$search = 'are y';
if(preg_match("/{$search}/i", $a)) {
    echo 'true';
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;i&lt;/code&gt; at the end of regular expression changes regular expression to be case-insensitive, if you do not want that, you can leave it out.&lt;/p&gt;

&lt;p&gt;Now, this can be quite problematic in some cases as the $search string isn’t sanitized in any way, meaning, it might not pass the check-in some cases as if &lt;code&gt;$search&lt;/code&gt; is a user input they can add some string that might behave like some different regular expression.&lt;/p&gt;

&lt;p&gt;Also, here’s a great tool for testing and seeing explanations of various regular expressions &lt;a href="https://regex101.com/"&gt;Regex101&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;To combine both sets of functionality into a single multi-purpose function (including with selectable case sensitivity), you could use something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function FindString($needle,$haystack,$i,$word)
{   // $i should be "" or "i" for case insensitive
    if (strtoupper($word)=="W")
    {   // if $word is "W" then word search instead of string in string search.
        if (preg_match("/\b{$needle}\b/{$i}", $haystack)) 
        {
            return true;
        }
    }
    else
    {
        if(preg_match("/{$needle}/{$i}", $haystack)) 
        {
            return true;
        }
    }
    return false;
    // Put quotes around true and false above to return them as strings instead of as bools/ints.
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  3. Why not to use mysql_* functions in PHP?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The MySQL extension:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Is not under active development&lt;/li&gt;
&lt;li&gt;Is officially &lt;a href="https://wiki.php.net/rfc/mysql_deprecation"&gt;deprecated&lt;/a&gt; as of PHP 5.5 (released June 2013).&lt;/li&gt;
&lt;li&gt;Has been &lt;a href="https://wiki.php.net/rfc/remove_deprecated_functionality_in_php7#extmysql"&gt;removed&lt;/a&gt; entirely as of PHP 7.0 (released December 2015)

&lt;ul&gt;
&lt;li&gt;This means that as of &lt;a href="https://www.php.net/eol.php"&gt;31 Dec 2018&lt;/a&gt; it does not exist in any supported version of PHP. If you are using a version of PHP which supports it, you are using a version that doesn’t get security problems fixed.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;Lacks an OO interface&lt;/li&gt;
&lt;li&gt;Doesn’t support:

&lt;ul&gt;
&lt;li&gt;Non-blocking, asynchronous queries&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php"&gt;Prepared statements&lt;/a&gt; or &lt;strong&gt;parameterized queries&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;Stored procedures&lt;/li&gt;
&lt;li&gt;Multiple Statements&lt;/li&gt;
&lt;li&gt;Transactions&lt;/li&gt;
&lt;li&gt;The “new” password authentication method (on by default in MySQL 5.6; required in 5.7)&lt;/li&gt;
&lt;li&gt;Any of the new functionality in MySQL 5.1 or later&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Since it is deprecated, using it makes your code less future proof. Lack of support for prepared statements is particularly important as they provide a clearer, less error-prone method of escaping and quoting external data than manually escaping it with a separate function call.&lt;/p&gt;

&lt;p&gt;See &lt;a href="https://www.php.net/manual/en/mysqlinfo.api.choosing.php"&gt;the comparison of SQL extensions&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  4. How to delete an element from an array in PHP?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;There are different ways to delete an array element, where some are more useful for some specific tasks than others.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Delete one array element&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If you want to delete just one array element you can use &lt;a href="https://www.php.net/manual/en/function.unset.php"&gt;&lt;code&gt;unset()&lt;/code&gt;&lt;/a&gt; or alternatively &lt;a href="https://www.php.net/manual/en/function.array-splice.php"&gt;&lt;code&gt;\array_splice()&lt;/code&gt;&lt;/a&gt;. Also if you have the value and don’t know the key to delete the element you can use &lt;a href="https://www.php.net/manual/en/function.array-search.php"&gt;&lt;code&gt;\array_search()&lt;/code&gt;&lt;/a&gt; to get the key.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;i. &lt;code&gt;unset()&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Note that when you use &lt;code&gt;unset()&lt;/code&gt; the array keys won’t change/reindex. If you want to reindex the keys you can use &lt;a href="https://www.php.net/manual/en/function.array-values.php"&gt;&lt;code&gt;\array_values()&lt;/code&gt;&lt;/a&gt; after &lt;code&gt;unset()&lt;/code&gt; which will convert all keys to numerical enumerated keys starting from 0.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Code&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

    $array = [0 =&amp;gt; "a", 1 =&amp;gt; "b", 2 =&amp;gt; "c"];
    unset($array[1]);
                //↑ Key which you want to delete

?&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[
    [0] =&amp;gt; a
    [2] =&amp;gt; c
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;ii. &lt;code&gt;\array_splice()&lt;/code&gt; method&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If you use &lt;code&gt;\array_splice()&lt;/code&gt; the keys will be automatically reindexed, but the associative keys won’t change as opposed to &lt;code&gt;\array_values()&lt;/code&gt; which will convert all keys to numerical keys.&lt;br&gt;
Also &lt;code&gt;\array_splice()&lt;/code&gt; needs the offset, not the key! as the second parameter.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Code&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

    $array = [0 =&amp;gt; "a", 1 =&amp;gt; "b", 2 =&amp;gt; "c"];
    \array_splice($array, 1, 1);
                        //↑ Offset which you want to delete

?&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[
    [0] =&amp;gt; a
    [1] =&amp;gt; c
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;array_splice()&lt;/code&gt; same as &lt;code&gt;unset()&lt;/code&gt; take the array by reference, and this means you don’t want to assign the return values of those functions back to the array.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Delete multiple array elements&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If you want to delete multiple array elements and don’t want to call &lt;code&gt;unset()&lt;/code&gt; or &lt;code&gt;\array_splice()&lt;/code&gt; multiple times you can use the functions &lt;code&gt;\array_diff()&lt;/code&gt; or &lt;code&gt;\array_diff_key()&lt;/code&gt; depending on if you know the values or the keys of the elements which you want to delete.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;i. &lt;a href="https://www.php.net/manual/en/function.array-diff.php"&gt;&lt;code&gt;\array_diff()&lt;/code&gt;&lt;/a&gt; method&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If you know the values of the array elements which you want to delete, then you can use &lt;code&gt;\array_diff()&lt;/code&gt;. As before with &lt;code&gt;unset()&lt;/code&gt; it won’t change/reindex the keys of the array.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Code&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

    $array = [0 =&amp;gt; "a", 1 =&amp;gt; "b", 2 =&amp;gt; "c"];
    $array = \array_diff($array, ["a", "c"]);
                               //└────────┘→ Array values which you want to delete

?&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[
    [1] =&amp;gt; b
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;ii. &lt;a href="https://www.php.net/manual/en/function.array-diff-key.php"&gt;&lt;code&gt;\array_diff_key()&lt;/code&gt;&lt;/a&gt; method&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If you know the keys of the elements which you want to delete, then you want to use &lt;code&gt;\array_diff_key()&lt;/code&gt;. Here you have to make sure you pass the keys as keys in the second parameter and not as values. Otherwise, you have to flip the array with &lt;a href="https://www.php.net/manual/en/function.array-flip.php"&gt;&lt;code&gt;\array_flip()&lt;/code&gt;&lt;/a&gt;. And also here the keys won’t change/reindex.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Code&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

    $array = [0 =&amp;gt; "a", 1 =&amp;gt; "b", 2 =&amp;gt; "c"];
    $array = \array_diff_key($array, [0 =&amp;gt; "xy", "2" =&amp;gt; "xy"]);
                                    //↑           ↑ Array keys which you want to delete
?&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[
    [1] =&amp;gt; b
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Also if you want to use &lt;code&gt;unset()&lt;/code&gt; or &lt;code&gt;\array_splice()&lt;/code&gt; to delete multiple elements with the same value you can use &lt;a href="https://www.php.net/manual/en/function.array-keys.php"&gt;&lt;code&gt;\array_keys()&lt;/code&gt;&lt;/a&gt; to get all the keys for a specific value and then delete all elements.&lt;/p&gt;

&lt;h3&gt;
  
  
  5. Is there any way to use PHP and cURL to get the associated thumbnail from the YouTube API?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Each YouTube video has four generated images. They are predictably formatted as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;https://img.youtube.com/vi/&amp;lt;insert-youtube-video-id-here&amp;gt;/0.jpg
https://img.youtube.com/vi/&amp;lt;insert-youtube-video-id-here&amp;gt;/1.jpg
https://img.youtube.com/vi/&amp;lt;insert-youtube-video-id-here&amp;gt;/2.jpg
https://img.youtube.com/vi/&amp;lt;insert-youtube-video-id-here&amp;gt;/3.jpg
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The first one in the list is a full-size image and others are thumbnail images. The default thumbnail image (i.e., one of &lt;code&gt;1.jpg, 2.jpg, 3.jpg&lt;/code&gt;) is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;https://img.youtube.com/vi/&amp;lt;insert-youtube-video-id-here&amp;gt;/default.jpg
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For the high-quality version of the thumbnail use a URL similar to this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;https://img.youtube.com/vi/&amp;lt;insert-youtube-video-id-here&amp;gt;/hqdefault.jpg
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There is also a medium quality version of the thumbnail, using a URL similar to the HQ:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;https://img.youtube.com/vi/&amp;lt;insert-youtube-video-id-here&amp;gt;/mqdefault.jpg
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For the standard definition version of the thumbnail, use a URL similar to this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;https://img.youtube.com/vi/&amp;lt;insert-youtube-video-id-here&amp;gt;/sddefault.jpg
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For the maximum resolution version of the thumbnail use a URL similar to this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;https://img.youtube.com/vi/&amp;lt;insert-youtube-video-id-here&amp;gt;/maxresdefault.jpg
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;All of the above URLs are available over HTTP too. Additionally, the slightly shorter hostname &lt;code&gt;i3.ytimg.com&lt;/code&gt; works in place of &lt;code&gt;img.youtube.com&lt;/code&gt; in the example URLs above.&lt;/p&gt;

&lt;p&gt;Alternatively, you can use the YouTube Data API (v3) to get thumbnail images.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can use &lt;a href="https://developers.google.com/youtube/v3/"&gt;&lt;strong&gt;YouTube Data API&lt;/strong&gt;&lt;/a&gt; to retrieve video thumbnails, caption, description, rating, statistics, and more. API version 3 requires a key*. Obtain the key and create a &lt;a href="https://developers.google.com/youtube/v3/docs/videos/list"&gt;&lt;strong&gt;videos: list&lt;/strong&gt;&lt;/a&gt; request:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;https://www.googleapis.com/youtube/v3/videos?key=YOUR_API_KEY&amp;amp;part=snippet&amp;amp;id=VIDEO_ID
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Example PHP Code&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$data = file_get_contents("https://www.googleapis.com/youtube/v3/videos?key=YOUR_API_KEY&amp;amp;part=snippet&amp;amp;id=T0Jqdjbed40");
$json = json_decode($data);
var_dump($json-&amp;gt;items[0]-&amp;gt;snippet-&amp;gt;thumbnails);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;object(stdClass)#5 (5) {
  ["default"]=&amp;gt;
  object(stdClass)#6 (3) {
    ["url"]=&amp;gt;
    string(46) "https://i.ytimg.com/vi/T0Jqdjbed40/default.jpg"
    ["width"]=&amp;gt;
    int(120)
    ["height"]=&amp;gt;
    int(90)
  }
  ["medium"]=&amp;gt;
  object(stdClass)#7 (3) {
    ["url"]=&amp;gt;
    string(48) "https://i.ytimg.com/vi/T0Jqdjbed40/mqdefault.jpg"
    ["width"]=&amp;gt;
    int(320)
    ["height"]=&amp;gt;
    int(180)
  }
  ["high"]=&amp;gt;
  object(stdClass)#8 (3) {
    ["url"]=&amp;gt;
    string(48) "https://i.ytimg.com/vi/T0Jqdjbed40/hqdefault.jpg"
    ["width"]=&amp;gt;
    int(480)
    ["height"]=&amp;gt;
    int(360)
  }
  ["standard"]=&amp;gt;
  object(stdClass)#9 (3) {
    ["url"]=&amp;gt;
    string(48) "https://i.ytimg.com/vi/T0Jqdjbed40/sddefault.jpg"
    ["width"]=&amp;gt;
    int(640)
    ["height"]=&amp;gt;
    int(480)
  }
  ["maxres"]=&amp;gt;
  object(stdClass)#10 (3) {
    ["url"]=&amp;gt;
    string(52) "https://i.ytimg.com/vi/T0Jqdjbed40/maxresdefault.jpg"
    ["width"]=&amp;gt;
    int(1280)
    ["height"]=&amp;gt;
    int(720)
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Not only that you need a key, you might be asked for billing information depending on the number of API requests you plan to make. However, a few million requests per day are free.&lt;br&gt;
&lt;a href="https://salman-w.blogspot.com/2010/01/retrieve-youtube-video-title.html"&gt;Source article.&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  6. When to use self over $this?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Use &lt;code&gt;$this&lt;/code&gt; to refer to the current object. Use &lt;code&gt;self&lt;/code&gt; to refer to the current class. In other words, use &lt;code&gt;$this-&amp;gt;member&lt;/code&gt; for non-static members, use &lt;code&gt;self::$member&lt;/code&gt; for static members.&lt;/p&gt;

&lt;p&gt;Here is an example of &lt;strong&gt;correct&lt;/strong&gt; usage of &lt;code&gt;$this&lt;/code&gt; and &lt;code&gt;self&lt;/code&gt; for non-static and static member variables:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php
class X {
    private $non_static_member = 1;
    private static $static_member = 2;

    function __construct() {
        echo $this-&amp;gt;non_static_member . ' '
           . self::$static_member;
    }
}

new X();
?&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here is an example of &lt;strong&gt;incorrect&lt;/strong&gt; usage of &lt;code&gt;$this&lt;/code&gt; and &lt;code&gt;self&lt;/code&gt; for non-static and static member variables:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php
class X {
    private $non_static_member = 1;
    private static $static_member = 2;

    function __construct() {
        echo self::$non_static_member . ' '
           . $this-&amp;gt;static_member;
    }
}

new X();
?&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here is an example of &lt;strong&gt;polymorphism&lt;/strong&gt; with &lt;code&gt;$this&lt;/code&gt; for member functions:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php
class X {
    function foo() {
        echo 'X::foo()';
    }

    function bar() {
        $this-&amp;gt;foo();
    }
}

class Y extends X {
    function foo() {
        echo 'Y::foo()';
    }
}

$x = new Y();
$x-&amp;gt;bar();
?&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here is an example of &lt;strong&gt;suppressing polymorphic behavior&lt;/strong&gt; by using &lt;code&gt;self&lt;/code&gt; for member functions:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php
class X {
    function foo() {
        echo 'X::foo()';
    }

    function bar() {
        self::foo();
    }
}

class Y extends X {
    function foo() {
        echo 'Y::foo()';
    }
}

$x = new Y();
$x-&amp;gt;bar();
?&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The idea is that &lt;code&gt;$this-&amp;gt;foo()&lt;/code&gt; calls the &lt;code&gt;foo()&lt;/code&gt; member function of whatever is the exact type of the current object. If the object is of &lt;code&gt;type X&lt;/code&gt;, it thus calls &lt;code&gt;X::foo()&lt;/code&gt;. If the object is of &lt;code&gt;type Y&lt;/code&gt;, it calls &lt;code&gt;Y::foo()&lt;/code&gt;. But with self::foo(), &lt;code&gt;X::foo()&lt;/code&gt; is always called.&lt;/p&gt;

&lt;p&gt;From &lt;a href="http://www.phpbuilder.com/board/showthread.php?t=10354489:"&gt;http://www.phpbuilder.com/board/showthread.php?t=10354489:&lt;/a&gt;&lt;br&gt;
By &lt;a href="http://board.phpbuilder.com/member.php?145249-laserlight"&gt;http://board.phpbuilder.com/member.php?145249-laserlight&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The keyword self does &lt;strong&gt;NOT&lt;/strong&gt; refer merely to the ‘current class’, at least not in a way that restricts you to static members. Within the context of a non-static member, &lt;code&gt;self&lt;/code&gt; also provides a way of bypassing the vtable (&lt;a href="https://en.wikipedia.org/wiki/Virtual_method_table"&gt;see wiki on vtable&lt;/a&gt;) for the current object. Just as you can use &lt;code&gt;parent::methodName()&lt;/code&gt; to call the parents version of a function, so you can call &lt;code&gt;self::methodName()&lt;/code&gt; to call the current classes implementation of a method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Person {
    private $name;

    public function __construct($name) {
        $this-&amp;gt;name = $name;
    }

    public function getName() {
        return $this-&amp;gt;name;
    }

    public function getTitle() {
        return $this-&amp;gt;getName()." the person";
    }

    public function sayHello() {
        echo "Hello, I'm ".$this-&amp;gt;getTitle()."&amp;lt;br/&amp;gt;";
    }

    public function sayGoodbye() {
        echo "Goodbye from ".self::getTitle()."&amp;lt;br/&amp;gt;";
    }
}

class Geek extends Person {
    public function __construct($name) {
        parent::__construct($name);
    }

    public function getTitle() {
        return $this-&amp;gt;getName()." the geek";
    }
}

$geekObj = new Geek("Ludwig");
$geekObj-&amp;gt;sayHello();
$geekObj-&amp;gt;sayGoodbye();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will output:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Hello, I’m Ludwig the geek Goodbye from Ludwig the person&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;code&gt;sayHello()&lt;/code&gt; uses the &lt;code&gt;$this&lt;/code&gt; pointer, so the vtable is invoked to call &lt;code&gt;Geek::getTitle()&lt;/code&gt;. &lt;code&gt;sayGoodbye()&lt;/code&gt; uses &lt;code&gt;self::getTitle()&lt;/code&gt;, so the vtable is not used and &lt;code&gt;Person::getTitle()&lt;/code&gt; is called. In both cases, we are dealing with the method of an instantiated object, and have access to the &lt;code&gt;$this&lt;/code&gt; pointer within the called functions.&lt;/p&gt;

&lt;h3&gt;
  
  
  7. How to get PHP errors to display?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can do as following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However, this doesn’t make PHP to show parse errors – the only way to show those errors is to modify your php.ini with this line:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;display_errors = on
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;(if you don’t have access to &lt;code&gt;php.ini&lt;/code&gt;, then putting this line in &lt;code&gt;.htaccess&lt;/code&gt; might work too):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php_flag display_errors 1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  8. How to write two functions that would take a string and return if it starts with the specified character/string or ends with it?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can do as given below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function startsWith($haystack, $needle)
{
     $length = strlen($needle);
     return (substr($haystack, 0, $length) === $needle);
}

function endsWith($haystack, $needle)
{
    $length = strlen($needle);
    if ($length == 0) {
        return true;
    }

    return (substr($haystack, -$length) === $needle);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Use this if you don’t want to use a regex.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can use &lt;a href="https://www.php.net/manual/en/function.substr-compare.php"&gt;&lt;code&gt;substr_compare&lt;/code&gt;&lt;/a&gt; function to check start-with and ends-with:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function startsWith($haystack, $needle) {
    return substr_compare($haystack, $needle, 0, strlen($needle)) === 0;
}
function endsWith($haystack, $needle) {
    return substr_compare($haystack, $needle, -strlen($needle)) === 0;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  9. How to make a redirect in PHP?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;i. Basic answer&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can use the &lt;code&gt;header()&lt;/code&gt; function to send a new HTTP header, but this must be sent to the browser before any HTML or text (so before the &lt;code&gt;&amp;lt;!DOCTYPE ...&amp;gt; declaration&lt;/code&gt;, for example).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;header('Location: '.$newURL);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;ii. Important details die() or exit()&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;header("Location: http://example.com/myOtherPage.php");
die();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Why you should use die() or exit(): &lt;a href="http://thedailywtf.com/articles/WellIntentioned-Destruction"&gt;The Daily WTF&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Absolute or relative URL&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Since June 2014 both absolute and relative URLs can be used. See &lt;a href="https://greenbytes.de/tech/webdav/rfc7231.html#header.location"&gt;RFC 7231&lt;/a&gt; which had replaced the old &lt;a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.30"&gt;RFC 2616&lt;/a&gt;, where only absolute URLs were allowed.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Status Codes&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;PHP’s “Location”-header still uses the &lt;a href="https://en.wikipedia.org/wiki/HTTP_302"&gt;HTTP 302&lt;/a&gt;-redirect code, but this is not the one you should use. You should consider either &lt;a href="https://en.wikipedia.org/wiki/HTTP_301"&gt;301&lt;/a&gt; (permanent redirect) or &lt;a href="https://en.wikipedia.org/wiki/HTTP_303"&gt;303&lt;/a&gt; (other).&lt;/p&gt;

&lt;p&gt;Note: &lt;a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4"&gt;W3C mentions&lt;/a&gt; that the 303-header is incompatible with “many pre-HTTP/1.1 user agents. Currently used browsers are all HTTP/1.1 user agents. This is not true for many other user agents like spiders and robots.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;iii. Documentation&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;HTTP Headers and the &lt;code&gt;header()&lt;/code&gt; function in PHP&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.php.net/manual/en/function.header.php"&gt;What the PHP manual says&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Responses"&gt;What Wikipedia says&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.30"&gt;What the W3C says&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;iv. Alternatives&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You may use the alternative method of &lt;code&gt;http_redirect($url)&lt;/code&gt;; which needs the PECL package pecl to be installed.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;v. Helper Functions&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This function doesn’t incorporate the 303 status code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Redirect($url, $permanent = false)
{
    header('Location: ' . $url, true, $permanent ? 301 : 302);

    exit();
}

Redirect('http://example.com/', false);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is more flexible:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function redirect($url, $statusCode = 303)
{
   header('Location: ' . $url, true, $statusCode);
   die();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;vi. Workaround&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;As mentioned, &lt;code&gt;header()&lt;/code&gt; redirects only work before anything is written out. They usually fail if &lt;a href="https://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php"&gt;invoked inmidst HTML&lt;/a&gt; output. Then you might use an HTML header workaround (not very professional!) like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;meta http-equiv="refresh" content="0;url=finalpage.html"&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or a JavaScript redirect even.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;window.location.replace("http://example.com/");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Alternative Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Use the &lt;code&gt;header()&lt;/code&gt; function to send an &lt;a href="https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Responses"&gt;HTTP &lt;code&gt;Location&lt;/code&gt; header&lt;/a&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;header('Location: '.$newURL);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Contrary to what some think, &lt;code&gt;die()&lt;/code&gt; has nothing to do with redirection. Use it &lt;strong&gt;only&lt;/strong&gt; if you want to redirect &lt;strong&gt;instead&lt;/strong&gt; of normal execution. File &lt;em&gt;example.php&lt;/em&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php
    header('Location: static.html');
    $fh = fopen('/tmp/track.txt', 'a');
    fwrite($fh, $_SERVER['REMOTE_ADDR'] . ' ' . date('c') . "\n");
    fclose($fh);
?&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Result of three executions:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;bart@hal9k:~&amp;gt; cat /tmp/track.txt
127.0.0.1 2009-04-21T09:50:02+02:00
127.0.0.1 2009-04-21T09:50:05+02:00
127.0.0.1 2009-04-21T09:50:08+02:00
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Resuming — obligatory &lt;code&gt;die()/exit()&lt;/code&gt; is some urban legend that has nothing to do with actual PHP. It has nothing to do with the client “respecting” the &lt;code&gt;Location:&lt;/code&gt; header. Sending a header does not stop PHP execution, regardless of the client used.&lt;/p&gt;

&lt;h3&gt;
  
  
  10. How do you use bcrypt for hashing passwords in PHP?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;bcrypt&lt;/code&gt; is a hashing algorithm that is scalable with hardware (via a configurable number of rounds). Its slowness and multiple rounds ensure that an attacker must deploy massive funds and hardware to be able to crack your passwords. Add to that per-password &lt;a href="https://en.wikipedia.org/wiki/Salt_%28cryptography%29"&gt;salts&lt;/a&gt; (&lt;code&gt;bcrypt&lt;/code&gt; REQUIRES salts) and you can be sure that an attack is virtually unfeasible without either ludicrous amount of funds or hardware.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;bcrypt&lt;/code&gt; uses the &lt;em&gt;Eksblowfish&lt;/em&gt; algorithm to hash passwords. While the encryption phase of &lt;em&gt;Eksblowfish&lt;/em&gt; and &lt;em&gt;Blowfish&lt;/em&gt; are exactly the same, the key schedule phase of &lt;em&gt;Eksblowfish&lt;/em&gt; ensures that any subsequent state depends on both salt and key (user password), and no state can be precomputed without the knowledge of both. &lt;strong&gt;Because of this key difference&lt;/strong&gt;, &lt;code&gt;bcrypt&lt;/code&gt; &lt;strong&gt;is a one-way hashing algorithm&lt;/strong&gt;. You cannot retrieve the plain text password without already knowing the salt, rounds, &lt;strong&gt;and key&lt;/strong&gt; (password). [&lt;a href="https://www.usenix.org/legacy/events/usenix99/provos/provos_html/node4.html"&gt;Source&lt;/a&gt;]&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How to use bcrypt:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Using PHP &amp;gt;= 5.5-DEV&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Password hashing functions &lt;a href="https://www.php.net/password_hash"&gt;have now been built directly into PHP &amp;gt;= 5.5&lt;/a&gt;. You may now use &lt;a href="https://www.php.net/password_hash"&gt;&lt;code&gt;password_hash()&lt;/code&gt;&lt;/a&gt; to create a &lt;code&gt;bcrypt&lt;/code&gt; hash of any password:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php
// Usage 1:
echo password_hash('rasmuslerdorf', PASSWORD_DEFAULT)."\n";
// $2y$10$xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// For example:
// $2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a

// Usage 2:
$options = [
  'cost' =&amp;gt; 11
];
echo password_hash('rasmuslerdorf', PASSWORD_BCRYPT, $options)."\n";
// $2y$11$6DP.V0nO7YI3iSki4qog6OQI5eiO6Jnjsqg7vdnb.JgGIsxniOn4C
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To verify a user-provided password against an existing hash, you may use the &lt;a href="https://www.php.net/password_verify"&gt;&lt;code&gt;password_verify()&lt;/code&gt;&lt;/a&gt; as such:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php
// See the password_hash() example to see where this came from.
$hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';

if (password_verify('rasmuslerdorf', $hash)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Using PHP &amp;gt;= 5.3.7, &amp;lt; 5.5-DEV (also RedHat PHP &amp;gt;= 5.3.3)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;There is a &lt;a href="https://github.com/ircmaxell/password_compat"&gt;compatibility library&lt;/a&gt; on &lt;a href="https://en.wikipedia.org/wiki/GitHub"&gt;GitHub&lt;/a&gt; created based on the source code of the above functions originally written in C, which provides the same functionality. Once the compatibility library is installed, usage is the same as above (minus the shorthand array notation if you are still on the 5.3.x branch).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Using PHP &amp;lt; 5.3.7 (DEPRECATED)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can use &lt;code&gt;crypt()&lt;/code&gt; function to generate bcrypt hashes of input strings. This class can automatically generate salts and verify existing hashes against an input. &lt;strong&gt;If you are using a version of PHP higher or equal to 5.3.7, it is highly recommended you use the built-in function or the compat library&lt;/strong&gt;. This alternative is provided only for historical purposes.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Bcrypt{
  private $rounds;

  public function __construct($rounds = 12) {
    if (CRYPT_BLOWFISH != 1) {
      throw new Exception("bcrypt not supported in this installation. See http://php.net/crypt");
    }

    $this-&amp;gt;rounds = $rounds;
  }

  public function hash($input){
    $hash = crypt($input, $this-&amp;gt;getSalt());

    if (strlen($hash) &amp;gt; 13)
      return $hash;

    return false;
  }

  public function verify($input, $existingHash){
    $hash = crypt($input, $existingHash);

    return $hash === $existingHash;
  }

  private function getSalt(){
    $salt = sprintf('$2a$%02d$', $this-&amp;gt;rounds);

    $bytes = $this-&amp;gt;getRandomBytes(16);

    $salt .= $this-&amp;gt;encodeBytes($bytes);

    return $salt;
  }

  private $randomState;
  private function getRandomBytes($count){
    $bytes = '';

    if (function_exists('openssl_random_pseudo_bytes') &amp;amp;&amp;amp;
        (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')) { // OpenSSL is slow on Windows
      $bytes = openssl_random_pseudo_bytes($count);
    }

    if ($bytes === '' &amp;amp;&amp;amp; is_readable('/dev/urandom') &amp;amp;&amp;amp;
       ($hRand = @fopen('/dev/urandom', 'rb')) !== FALSE) {
      $bytes = fread($hRand, $count);
      fclose($hRand);
    }

    if (strlen($bytes) &amp;lt; $count) {
      $bytes = '';

      if ($this-&amp;gt;randomState === null) {
        $this-&amp;gt;randomState = microtime();
        if (function_exists('getmypid')) {
          $this-&amp;gt;randomState .= getmypid();
        }
      }

      for ($i = 0; $i &amp;lt; $count; $i += 16) {
        $this-&amp;gt;randomState = md5(microtime() . $this-&amp;gt;randomState);

        if (PHP_VERSION &amp;gt;= '5') {
          $bytes .= md5($this-&amp;gt;randomState, true);
        } else {
          $bytes .= pack('H*', md5($this-&amp;gt;randomState));
        }
      }

      $bytes = substr($bytes, 0, $count);
    }

    return $bytes;
  }

  private function encodeBytes($input){
    // The following is code from the PHP Password Hashing Framework
    $itoa64 = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

    $output = '';
    $i = 0;
    do {
      $c1 = ord($input[$i++]);
      $output .= $itoa64[$c1 &amp;gt;&amp;gt; 2];
      $c1 = ($c1 &amp;amp; 0x03) &amp;lt;&amp;lt; 4;
      if ($i &amp;gt;= 16) {
        $output .= $itoa64[$c1];
        break;
      }

      $c2 = ord($input[$i++]);
      $c1 |= $c2 &amp;gt;&amp;gt; 4;
      $output .= $itoa64[$c1];
      $c1 = ($c2 &amp;amp; 0x0f) &amp;lt;&amp;lt; 2;

      $c2 = ord($input[$i++]);
      $c1 |= $c2 &amp;gt;&amp;gt; 6;
      $output .= $itoa64[$c1];
      $output .= $itoa64[$c2 &amp;amp; 0x3f];
    } while (true);

    return $output;
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can use this code like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$bcrypt = new Bcrypt(15);

$hash = $bcrypt-&amp;gt;hash('password');
$isGood = $bcrypt-&amp;gt;verify('password', $hash);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Alternatively, you may also use the &lt;a href="https://www.openwall.com/phpass/"&gt;Portable PHP Hashing Framework&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  11. How to use PHP to get the current year?
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can use either &lt;a href="https://www.php.net/manual/en/function.date.php"&gt;date&lt;/a&gt; or &lt;a href="https://www.php.net/manual/en/function.strftime.php"&gt;strftime&lt;/a&gt;. In this case, it doesn’t matter as a year is a year, no matter what (unless there’s a locale that formats the year differently?) For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php echo date("Y"); ?&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;On a side note when formatting dates in PHP it matters when you want to format your date in a different locale than your default. If so, you have to use setlocale and strftime. According to the php manual on date:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;To format dates in other languages, you should use the setlocale() and strftime() functions instead of date().&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;From this point of view, it would be best to use strftime as much as possible, if you even have a remote possibility of having to localize your application. If that’s not an issue, pick the one you like best.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;In Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;These are the 11 most commonly asked questions about PHP. If you have any suggestions or any confusion, please comment below. If you need any help, we will be glad to help you.&lt;/p&gt;

&lt;p&gt;We, at &lt;a href="https://www.truemark.dev/"&gt;Truemark&lt;/a&gt;, provide services like web and mobile app development, digital marketing, and website development. So, if you need any help and want to work with us, please feel free to contact us.&lt;/p&gt;

&lt;p&gt;Hope this article helped you.&lt;/p&gt;

&lt;p&gt;Original Source: &lt;a href="https://thedevpost.com/blog/11-most-asked-questions-about-php/"&gt;DevPostbyTruemark&lt;/a&gt;&lt;/p&gt;

</description>
      <category>php</category>
    </item>
  </channel>
</rss>
