Category Archives: Uncategorized

Create sync method around async operation

async method

sync version

Borrowing Methods (js)

http://javascriptissexy.com/javascript-apply-call-and-bind-methods-are-essential-for-javascript-professionals/

The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

XML

https://www.w3schools.com/xml/

XML stands for eXtensible Markup Language.

XML was designed to store and transport data.

XML was designed to be both human- and machine-readable.

XML stands for eXtensible Markup Language
XML is a markup language much like HTML
XML was designed to store and transport data
XML was designed to be self-descriptive
XML is a W3C Recommendation

XML Does Not DO Anything

like this:

Its just data. And the data looks like markup similar to HTML.

XML is just information wrapped in tags.

Someone must write a piece of software to send, receive, store, or display it

XML and HTML were designed with different goals:

XML was designed to carry data – with focus on what data is
HTML was designed to display data – with focus on how data looks
XML tags are not predefined like HTML tags are – in HTML b tag means to bold whatever text is in between. But XML tags are not predefined.

The XML language has no predefined tags.

The tags in the example above (like ‘to’ and ‘from’) are not defined in any XML standard. These tags are “invented” by the author of the XML document.

HTML works with predefined tags like ‘p’, ‘h1’, ‘table’, etc.

With XML, the author must define both the tags and the document structure.

XML is Extensible
Most XML applications will work as expected even if new data is added (or removed).

Imagine an application designed to display the original version of note.xml (‘to’ ‘from’ ‘heading’ ‘data’).

Then imagine a newer version of note.xml with added ‘date’ and ‘hour’ elements, and a removed ‘heading’.

The way XML is constructed, older version of the application can still work:

It will simply the extra data.

XML Simplifies Things

It simplifies data sharing
It simplifies data transport
It simplifies platform changes
It simplifies data availability
Many computer systems contain data in incompatible formats. Exchanging data between incompatible systems (or upgraded systems) is a time-consuming task for web developers. Large amounts of data must be converted, and incompatible data is often lost.

XML stores data in plain text format. This provides a software- and hardware-independent way of storing, transporting, and sharing data.

XML also makes it easier to expand or upgrade to new operating systems, new applications, or new browsers, without losing data.

With XML, data can be available to all kinds of “reading machines” like people, computers, voice machines, news feeds, etc.

XML Separates Data from Presentation

XML does not carry any information about how to be displayed.

The same XML data can be used in many different presentation scenarios.

Because of this, with XML, there is a full separation between data and presentation.

XML is Often a Complement to HTML

In many HTML applications, XML is used to store or transport data, while HTML is used to format and display the same data.

XML Separates Data from HTML

When displaying data in HTML, you should not have to edit the HTML file when the data changes.

With XML, the data can be stored in separate XML files.

With a few lines of JavaScript code, you can read an XML file and update the data content of any HTML page.

Self-Describing Syntax

XML uses a much self-describing syntax.

A prolog defines the XML version and the character encoding:

The next line is the root element of the document:

The next line starts a ‘book’ element:

The ‘book’ elements have 4 child elements: ‘title’, ‘author’, ‘year’, ‘price’.

The next line ends the book element:

XML Documents Must Have a Root Element

XML documents must contain one root element that is the parent of all other elements:

The XML Prolog

This line is called the XML prolog:

The XML prolog is optional. If it exists, it must come first in the document.

XML Tags are Case Sensitive

XML tags are case sensitive. The tag is different from the tag .

Opening and closing tags must be written with the same case:

XML Attribute Values Must be Quoted

XML elements can have attributes in name/value pairs just like in HTML.

In XML, the attribute values must always be quoted.

INCORRECT:

Entity References

Some characters have a special meaning in XML.

If you place a character like “<" inside an XML element, it will generate an error because the parser interprets it as the start of a new element. This will generate an XML error:

What is an XML Element?

An XML element is everything from (including) the element’s start tag to (including) the element’s end tag.

An element can contain:

text
attributes
other elements
or a mix of the above

In the example above:

XML Elements vs. Attributes

Take a look at these examples:

In the first example gender is an attribute. In the last, gender is an element. Both examples provide the same information.

There are no rules about when to use attributes or when to use elements in XML.

BUT, Avoid XML Attributes?

Some things to consider when using attributes are:

attributes cannot contain multiple values (elements can)
attributes cannot contain tree structures (elements can)
attributes are not easily expandable (for future changes)

Don’t end up like this:

Namespace Declaration

A Namespace is declared using reserved attributes. Such an attribute name must either be xmlns or begin with xmlns: shown as below −

Syntax
The Namespace starts with the keyword xmlns.
The word name is the Namespace prefix.
The URL is the Namespace identifier.

Example
Namespace affects only a limited area in the document. An element containing the declaration and all of its descendants are in the scope of the Namespace. Following is a simple example of XML Namespace −

Here, the Namespace prefix is cont, and the Namespace identifier (URI) as www.tutorialspoint.com/profile. This means, the element names and attribute names with the cont prefix (including the contact element), all belong to the www.tutorialspoint.com/profile namespace.

calling function on optional, optional initializer

Having optionals is very helpful in that if you decide to call a function on it, it will not crash and simply return nil.

In our case, we created a class where if its dictionary has valid entries, others can use that class and query it.
However, if that dictionary does not have anything, then execution would continue without a crash.

Quick note about dictionaries

Chapter 11: Dictionaries

A dictionary is an unordered collection that stores multiple values of the same type.

Each value from the dictionary is associated with a unique key. All the keys have the same type.

The type of a dictionary is determined by the type of the keys and the type of the values. A dictionary of type[String:Int] has keys of type String and values of type Int.

Declare Dictionaries
To declare a dictionary you can use the square brackets syntax([KeyType:ValueType]).

You can access specific elements from a dictionary using the subscript syntax. To do this pass the key of the value you want to retrieve within square brackets immediately after the name of the dictionary.

Because it’s possible not to have a value associated with the provided key (i.e, nil) the subscript will return an optional value of the value type

Thus this means that

Hence, to unwrap the value returned by the subscript you can do one of two things: use optional binding or force the value if you know for sure it exists.

Example 1

If we have a valid property in order to initialize the dictionary, we return a valid self object. This let’s others create and query our OutOfBoundsDictionary.

If our property name does not exist, then we do not want others to be able to query. Thus in the initialization function, it put a ? to denote that what we return is optional self. If the name does not exist, then we return nil. When we return nil, any function calls on a nil, will simply be ignored.

Thus, if name is initialized, then execution will run through normally and print a valid last name.
If property name was not initialized, then a is returned as nil and calling any functions on it will be ignored.

Another way to do it

…is to have a standard initializer. Return a valid self object. However due to not having any entries in the dictionary, when other objects try to use findPerson with a firstName, it will return nil. And thus, will not print anything

What is the equivalent of an Objective-C id in Swift?

https://stackoverflow.com/questions/24005678/what-is-the-equivalent-of-an-objective-c-id-in-swift

Swift 3

Any, if you know the sender is never nil.

@IBAction func buttonClicked(sender : Any) {
println(“Button was clicked”, sender)
}
Any?, if the sender could be nil.

@IBAction func buttonClicked(sender : Any?) {
println(“Button was clicked”, sender)
}

Reader Writer #2 using Semaphore

semaphore_Reader_Writer_2

https://en.wikipedia.org/wiki/Readers%E2%80%93writers_problem

Readers won’t starve Writers anymore

Due to readTry, if additional future reads come in, these future reads wait FCFS with future writes via readTry. Thus, this line gives
fair chance for future writes to grab readTry and do its writing.

Another very important thing is that once a future write grabs readyTry, no future reads will be able to grab readTry. This causes existing reads to eventually finish reading, decreasing readCount back to 0. Once this future write finishes, then the next waiting Read can start again.

Writers may starve Readers

The very first writer has a hold on readyTry so that no other “additional” readers can come in.
When we’re done writing, we decrement. IF WE’RE THE LAST WRITER, make sure to let go of readyTry, so other readers can come in.

However, this starves readers because reader’s first execution is to try to grab readTry. Since its already been held by the first
writer, the reader will fail.

Furthermore, future writers come in and do not need to grab readTry again. It was already held by the first
writer and thus, future writers will simply wait for the resource to do its writing, then decrement writeCount.

ONLY the last writer can let go of readTry. And this is where it starves readers.

Let’s see what happens when a reader X and writer C get executed.

output

Reader Writer #1 using Semaphore

Semaphore Reader Writer #1 demo

https://en.wikipedia.org/wiki/Readers%E2%80%93writers_problem

Starting off

We have a semaphore that holds 1 process. We the reference to this object semaphoreResource
The whole point of this semaphore is for Readers and Writers to fight over it. If a Reader is holding it, a Writer cannot write.
If a Writer is holding it, Readers cannot read.

Writers fight with Readers for semaphoreResource but will never ever touch semaphoreReaderMutex.

That’s because semaphoreReaderMutex is used between Readers in order to update/change a variable called readCount.

readCount determines whether the first reader will hold the semaphoreResource and also whether the last reader will let go of semaphoreResource.
That’s the whole purpose of semaphoreReaderMutex.

We define two callbacks to simulate reading and writing. Reading takes 3 seconds and writing takes 5 seconds.

Writer

In the case of Writers, its very straightforward. It grabs the resource semaphoreResource. If its succeeds, it will then do the writing by simply calling the runWriteCodeBlock callback. After the writing, it will let go of the semaphore:

Readers

The idea is that we grab the reader semaphore (semaphoreReaderMutex) in order to make changes to the resource semaphore (semaphoreResource).
The reader semaphore allows the 1st reader to lock the resource semaphore, and naturally, the last reader to unlock the semaphore.

Any readers after the 1st one, does not need to lock the resource semaphore anymore. They just go on ahead and do their reading.
However, they DO NEED to grab the reader mutex because they are changing the readCount variable. This is to update the number of readers.
Only when the last reader finishes reading (updates the readCount to 0) then it unlocks the resource semaphore so that the writers can write.

However, it may be that other readers will read also. In this solution, every writer must claim the resource individually. This means that a stream of readers can subsequently lock all potential writers out and starve them. As long as future readers keep coming in, the next waiting writer will NEVER be able to write.

This is so, because after the first reader locks the resource, no writer can lock it, before it gets released. All future writers MUST WAIT FOR ALL READERS TO FINISH (readCount back to 0) in order to grab hold of the resource semaphore in order to do its writing.

In other words, a few readers come along, increases the readCount. Then leaves. Then more readers come. And more, and further even into the future such that readCount is always > 0. Hence this is what will starve the writer.

Therefore, this solution does not satisfy fairness.

full source

DispatchSemaphore

https://priteshrnandgaonkar.github.io/concurrency-with-swift-3/

Dispatch Groups

Dispatch group demo xCode 8.3.3

DispatchQueue uses enter() and leave() to group chunks of code into one work item and process them in the group. This can be done async or sync.

Note that DispatchQueues do not use sync, because the purpose would not make sense. The whole purpose of a DispatchGroup is to have multiple tasks run, and notify when they are done. Since sync is done one by one, and in order, there is no purpose to notify anything due to the nature of sync: Each task must begin and end in order.

Source Code

First, take note that we are looping through placing code chunks onto a global queue via async operation. Thus,

Then these 4 code chunks gets processed by the global queue asynchronously. Their initial lines gets printed:

—– code execution entered dispatchGroup for index 0 ——
—– code execution entered dispatchGroup for index 2 ——
—– code execution entered dispatchGroup for index 3 ——
—– code execution entered dispatchGroup for index 1 ——
code execution 0 start
code execution 2 start
code execution 3 start
code execution 1 start

This means that for each code chunk, that code chunk has placed a section of code into the dispatchGroup. In our case, the section of code prints 0 to 100.
The dispatchGroup now has 4 section of code to process.

The dispatchGroup will now execute the 4 section of code asynchronously.

Due to code chunk 0’s NO SLEEP, it simply does its printing first and it does it fast. Code chunk 1 can’t start because it requires every loop to sleep for 0.01 seconds before it starts. Thus, since code chunk 0’s loop does 0 sleep, it prints all first.

Then code chunk 1 starts, and sleeps for 0.01 between each print. Code chunk 2 will also start, and it sleeps for 0.02 between each print….

Due to

index 1’s loop having to sleep 0.01ms,
index 2’s loop having to sleep 0.02ms,
index 3’s loop having to sleep 0.03ms,

for every iteration, you can see that index 1’s printing of its loop is just a tad bit faster than index 2 and index 3’s loops.

index 1’s code chunk finishes and thus, it leaves the group.

eventually index 2’s code also finishes and leaves the group. Then index 3 will finally group after printing its loop.

Then when the group is finally empty, it will notify us and process the code block to print “Block 4”. Since this command is within the for loop, it will print 4 times.

Of course you can also remove the sleep line, if that’s the case, all of code chunks on the global queue will be processed asynchronously and they will all finish in similar time to no sleep for any of them. It still holds that once ALL of them are finished, they will notify, and thus, the notify code blocks will run.

output

—– code execution entered dispatchGroup for index 0 ——
—– code execution entered dispatchGroup for index 2 ——
—– code execution entered dispatchGroup for index 3 ——
—– code execution entered dispatchGroup for index 1 ——
code execution 0 start
code execution 2 start
code execution 3 start
code execution 1 start
loop index 0—- code chunk 0—
loop index 1—- code chunk 0—
….
loop index 100—- code chunk 0—
code execution 0 finish

—— code execution left dispatchGroup for index 0 ——–
loop index 0—- code chunk 1—
loop index 0—- code chunk 2—
loop index 1—- code chunk 1—
loop index 0—- code chunk 3—
….
loop index 100—- code chunk 1—
code execution 1 finish

—— code execution left dispatchGroup for index 1 ——–
loop index 51—- code chunk 2—
loop index 35—- code chunk 3—
loop index 52—- code chunk 2—

loop index 68—- code chunk 3—
loop index 100—- code chunk 2—
code execution 2 finish

—— code execution left dispatchGroup for index 2 ——–
loop index 69—- code chunk 3—
loop index 70—- code chunk 3—
loop index 71—- code chunk 3—

loop index 98—- code chunk 3—
loop index 99—- code chunk 3—
loop index 100—- code chunk 3—
code execution 3 finish

—— code execution left dispatchGroup for index 3 ——–

Block 4
Block 4
Block 4
Block 4