1. What's a Gem?
2. Example of a Gem (hub)
3. The value of packaging your code
What's a gem?
"A gem is a piece of ruby code that has been formatted into an easy to consume package."
very basic description...
Apt-get for the ruby echo-system
When U install ruby, you get 2 things: ruby & gem
Example of a Gem:
$ gem install hub
Fetching: hub-1.12.4.gem (100%)
- Let's go over an example... very popular...
- Hub is a gem... allows u 2 interact w/ github... CLI
- Hub... EASILY installed... ANY platform... ruby installed
What can Hub do for you?
Create a repo on github automatically
$ mkdir my_project && cd my_project/
$ echo 'hello hub' > h.txt
$ git init && git add . && git commit -m "commit1"
$ hub create
$ git push origin master -u
- Create a repo on your github account
- Here let's walk through the demo
- WTS (walk through slides)
How is it configured?
1 time password request => auth token
Configurations: ~/.config/hub
---
github.com:
- protocol: https
user: TheNotary
oauth_token: this_is_sensative_DEADMEET1337
- So you're probably wondering how it works
- WTS (walk through slides)
Gem is Amazing
gem list
gem uninstall
gem install hub -v 1.12.3
Wait... multiple versions of a single gem? How?
hub _1.12.3_ --version
Packaging your Code is Valuable
> Easily Deploy code on a foreign server
> Easily include code in OTHER ruby projects
> Easily update code (after the fact) without breaking dependent codebases
> Easily share code with others
...it allows you to...[WTS]
So let's get started making our lives better by packaging up some ruby code.
Section 2 - Build Pseudo Complex large_app
The Formation of Our Software
Rails App, Square 1
Add Pseudo complexity, Messy controller
Improve via Basic Method Extraction Refactoring
OO Refactor
The Formation of Our Software
Before we get started... gem... suppose we have some code... large_app... needs to be extracted...
Better than supposing... let's do it!
We'll add logic to the app then iteratively move it into better and better locations
What should that logic be?
Thwart the NSA!
- Ask slide!
- Wait for just a moment... [CLK]
- What if
- What if we needed to enc/dec a string from...
- And we expect to reuse
Typical Workflow
1) Have Rails App
2) App gets huge and takes forever to test
3) App gets extracted into gem(s)
This is a fairly typical workflow for a gem's creation;
CREATION...
Does anyone know how a star is formed?
Typical Workflow
1) Have Rails App
2) App gets huge and takes forever to test
3) App gets extracted into gem(s)
*Work them through it... try to tie it into gems*
I was hoping ... tie in creation stars ... gems.
But I realized last night it's not gems ... rather rails
All this stuff...particles
drifted... gravitated... central monolithic body.
after certain point ... hot!
got outta hand!
Section 3 - Gem Extraction
Bundler Usage and Configs
The Anatomy of a Gem
Gem Extraction, Square 1
Improve Library Interface
Bundler Usage and Configs
...and for my third wish, I wish for more wishes!
(~/.bundle/config)
---
BUNDLE_GEM__COC: 'false'
BUNDLE_GEM__TEST: rspec
BUNDLE_GEM__MIT: false
...under-advertized feature... but bundler, a ruby gem,
has the capability to make more gems.
Usually installed by default
To build a gem, follow these commands:
$ cd /tmp
$ bundle gem kewl_crypto
change into a clean directory, could be tmp, could be somewhere more persistent, either way I want everyone to run this on their local.
Actually do the commands
Anatomy of a Gem
.
├── bin
│ ├── console
│ └── setup
├── Gemfile
├── kewl_crypto.gemspec
├── lib
│ ├── kewl_crypto
│ │ └── version.rb
│ └── kewl_crypto.rb
├── Rakefile
├── README.md
└── spec
├── kewl_crypto_spec.rb
└── spec_helper.rb
Let's briefly go over a gems anatomy.
CLK
Now that's a lot of crap to go over, but a lot of it is no big deal.
Get your favorite text editor ready and open up these files as I go over them.
.
├── bin
│ ├── console
│ └── setup
├── Gemfile
├── kewl_crypto.gemspec
├── lib
│ ├── kewl_crypto
│ │ └── version.rb
│ └── kewl_crypto.rb
├── Rakefile
├── README.md
└── spec
├── kewl_crypto_spec.rb
└── spec_helper.rb
This is the main configuration file for your package. It's basically how you talk to bundler, gemcutter and rubygems.org. You indicate your dependencies here, you add a description and name for your gem, and define package details like the version of the gem.
.
├── bin
│ ├── console
│ └── setup
├── Gemfile
├── kewl_crypto.gemspec
├── lib
│ ├── kewl_crypto
│ │ └── version.rb
│ └── kewl_crypto.rb
├── Rakefile
├── README.md
└── spec
├── kewl_crypto_spec.rb
└── spec_helper.rb
This is the 'entry point' for your ruby app. It's the first file loaded when someone does a `require 'your_gem'`.  An easy rule for breaking up your ruby library is that each class should have it's own file. If a class is massive and has many subclasses that are only used by that one class... then this class can have it's own folder if you want. But with rubygems, you actually get to employ a little bit of creativity
.
├── bin
│ ├── console
│ └── setup
├── Gemfile
├── kewl_crypto.gemspec
├── lib
│ ├── kewl_crypto
│ │ └── version.rb
│ └── kewl_crypto.rb
├── Rakefile
├── README.md
└── spec
├── kewl_crypto_spec.rb
└── spec_helper.rb
The library's subfolder already contains one file, Version
Go ahead and open it up
You enter this file when it's time to do a version bump
gemspec file that sources
.
├── bin
│ ├── console
│ └── setup
├── Gemfile
├── kewl_crypto.gemspec
├── lib
│ ├── kewl_crypto
│ │ └── version.rb
│ └── kewl_crypto.rb
├── Rakefile
├── README.md
└── spec
├── kewl_crypto_spec.rb
└── spec_helper.rb
The bin folder used to be where people put their 'binary' files, but now it's got this setup and console rubish in it.
I'm not fond of either of those files in bin, but... console... setup...
.
├── bin
│ ├── console
│ └── setup
├── Gemfile
├── kewl_crypto.gemspec
├── lib
│ ├── kewl_crypto
│ │ └── version.rb
│ └── kewl_crypto.rb
├── Rakefile
├── README.md
└── spec
├── kewl_crypto_spec.rb
└── spec_helper.rb
Tests!
Notice I'm talking about this after everything else... hmmm...
This is where your tests go. Because I'm awesome... rspec
Gem Extraction, Square 1
So now that you know the anatomy of...
Gem extraction at it's best ... copy and pasting.
--Where do I paste in my code?
*Right! How about `lib/kewl_crypto.rb`*
Let's take a peak at that file now.
(lib/kewl_crypto.rb)
require "kewl_crypto/version"
module KewlCrypto
# Your code goes here...
end
Even tells us!
--My next question is, what code are we going to cut out of the larger_app to be place here?
*Wait for models/kewl_crypto.rb*
Right! Let's start that.
Switch over to Manual and the text editor at this point???
Maybe lib/kewl_crypto.rb will look like...
(lib/kewl_crypto.rb)
require "base64"
require "kewl_crypto/version"
module KewlCrypto
class KewlCrypto
attr_reader :untouched
def initialize(string)
@untouched = string
end
def encrypted
Base64.encode64(@untouched)
end
def decrypted
Base64.decode64(@untouched)
end
end
end
Checkout g1: Basic extraction
git checkout 850e0af
Improve Library Interface
How Cumbersome
$ ruby bin/console
> kc = KewlCrypto::KewlCrypto.new("clear")
Refactor
(lib/kewl_crypto.rb)
module KewlCrypto
def self.new(string)
KewlCrypto.new(string)
end
class KewlCrypto
attr_reader :untouched
def initialize(string)
@untouched = string
end
def encrypted
Base64.encode64(@untouched)
end
def decrypted
Base64.decode64(@untouched)
end
end
end
Checkout g2: easier to use
git checkout a06c602
Are we there yet?
(lib/kewl_crypto.rb)
module KewlCrypto
def self.new(string)
KewlCrypto.new(string)
end
class KewlCrypto
attr_reader :untouched
def initialize(string)
@untouched = string
end
def encrypted
Base64.encode64(@untouched)
end
def decrypted
Base64.decode64(@untouched)
end
end
end
Ok, that's cool and easy to use... but... look closely...
Is it beautiful? What do you think? Would you publish this for your peers to see? How could we clean it up a bit?
*Wait for create extra file*
Right! We can move the KewlCrypto class to its own file now.
https://github.com/TheNotary/kewl_crypto/commit/01e43f96867cb75b6186380de8e8c559d225cd2b
Checkout g3: class gets own file
git checkout 0618958
Weird having two files named the same
Named gem wrong? Named class wrong?
Before we can use it, we need to build it
$ rake build
kewl_crypto 0.1.0 built to pkg/kewl_crypto-0.1.0.gem.
zip file
rake install
rake release
rubygems.org account
Section 4 - Hook it into the Rails App
Source Gem Off File System
Cut Old Logic from Rails App
A Manual Test Indicates it Worked!
Source Gem Off File System
(Gemfile)
$ gem 'kewl_crypto', path: "../kewl_crypto"
Cut Old Logic from Rails App
Final Manual Test
changes to gem = reboot rails
solid? Publish rubygems.org, offline gemserver, or a git server


Simple. Practical. Efficient.
When it comes to automation, there is a huge misconception that a wealth of knowledge about coding is required.
We are here to prove you wrong. We teach simple coding skills in the most practical way that enables you to automate your mundane tasks.
The possibilities are endless.
Start now and let your computer work for you!


This VoiceBase Query Language Guide is designed to get you up to speed and familiar with VoiceBase and walk you through the basic usage of both the data query tool called the Analytics Workbench and the VoiceBase Query Language (VBQL).
VoiceBase is a state-of-the-art Voice Analytics platform that allows you to upload, analyze, categorize and optimize insights around voice and messaging data. VBQL allows you to write powerful, flexible Queries to access and filter your data, and you'll do all your analysis through the Analytics Workbench.
To access the Analytics Workbench, login to your VoiceBase account and go to Analyst Tools > Workbench.


Panels
animate
default: true
- Sets whether the panel will animate when opening and closing. If set to false, the panel will just appear and disappear without animation. This is recommended for fastest performance. Also available via the
data-animate
attribute on the panel container.
dismissible
default: true
- Sets whether the panel can be closed by clicking outside onto the page. Also available via the
data-dismissible
attribute on the link that opens the panel.
display
default: "reveal"
- The relationship of the panel to the page contents. Can either push the page over ("reveal"), re-flow the content to fit the panel content as a column ("push"), or sit over the content ("overlay"). Also available via the
data-display
attribute on the link that opens the panel.
initSelector
default: ":jqmData(role='panel')"
- The role (or and valid jQuery selector) used to trigger auto-initialization of the panel widget.
position
default: "left"
- The side of the screen the panel appears on. Values can be "left" or "right". Also available via the
data-position
attribute on the link that opens the panel.
positionFixed
default: false
- Sets whether the panel has fixed positioning so the contents are in view even if the page is scrolled down. This also allows the page to scroll while the panel stays fixed. We recommend not to enable this feature when panels are used withing Android apps because of poor performance and display issues. Also available via the
data-position-fixed
attribute on the panel.
swipeClose
default: true
- Sets whether the panel can be closed by swiping over the panel or, if
dismissible=true
, the page content and toolbars. Also available via the data-swipe-close
attribute on the panel.
theme
default: "c"
- Theme swatch for the panel. Can be any valid swatch letter in your theme (a-z). Also available via the
data-theme
attribute on the panel container.
Classes Option
The classes
option define the structural classnames that the plugin uses. This is only configurable via JavaScript because it expects an object literal value.
classes.panel
default: "ui-panel"
- Class added to the panel.
classes.panelOpen
default: "ui-panel-open"
- Class added to the panel when opening. Used for targeting hardware acceleration only during transitions.
classes.panelClosed
default: "ui-panel-closed"
- Class added to the panel when closed.
classes.panelFixed
default: "ui-panel-fixed"
- Class added to the panel when fixed positioning is applied.
classes.panelInner
default: "ui-panel-inner"
- Class added to the panel contents wrapper div.
classes.modal
default: "ui-panel-dismiss"
- Class added to the overlay on the page to dismiss the panel when hidden.
classes.modalOpen
default: "ui-panel-dismiss-open"
- Class added to the invisible overlay over the page when the panel is open. Used to dismiss the panel.
classes.pagePanel
default: "ui-page-panel"
- Class added to the page container when a panel widget is present.
classes.pagePanelOpen
default: "ui-page-panel-open"
- Class added to the page when a panel is open.
classes.contentWrap
default: "ui-panel-content-wrap"
- Class added to the wrapper injected around the page contents (header, content, footer), needed for transitioning the page contents. Fixed toolbars are not wrapped.
classes.contentWrapOpen
default: "ui-panel-content-wrap-open"
- Class added to the page contents wrapper when the panel is opening.
classes.contentWrapClosed
default: "ui-panel-content-wrap-closed"
- Class added to the page contents wrapper after the close animation is complete.
classes.contentFixedToolbar
default: "ui-panel-fixed-toolbar-wrap"
- Class added to fixed header and footer, needed for transitioning fixed toolbars.
classes.contentFixedToolbarOpen
default: "ui-panel-content-fixed-toolbar-open"
- Class added to fixed toolbars when the panel is opening.
classes.contentFixedToolbarClosed
default: "ui-panel-content-fixed-toolbar-closed"
- Class added to fixed toolbars after the close animation is complete.
classes.animate
default: "ui-panel-animate"
- Class added to the panel, page contents wrapper and fixed toolbars when option
animate
is true
and the 3D transform feature test returns true
.


Daily Views
Customers
Blogs
Rate
| Diet ID | Author | BMI fit | Basic taste |
|---|---|---|---|
| 1 | Dr. Alison | 18 to 20 | Sweet, Sour |
| 2 | Dr. Toan Nguyen | Up to 25 | Cool, Salty |
| 3 | Dr. Smith | 20 to 25 | Hot, Salty |
| 4 | Jacob | Less than 18 | Meaty |
| 5 | Edison | 18 to 20 | Bitter |
| 6 | Dr. Jenny | Less than 18 | Bitter, Hot |
| 7 | Dr. John | Up to 20 | Bitter, Hot |
| 8 | Dr. Lisa | Less than 18 | Meaty, Hot |
| 9 | Dr. Alice | 25 to 30 | Meaty, Bitter, Hot |
| 10 | John Pham | Less than 20 | Bitter,Cool, Salty |
| 11 | Dr. Alison | Up to 30 | Sweet, Salty, Meaty |
| 12 | Dr. Jenny | Up to 25 | Bitter, Hot, Sweet |
| 13 | Dr. Toan Nguyen | Up to 18 | Bitter, Hot, Meaty |
| 14 | Dr. Alice | 20 to 25 | Sweet, Bitter, Hot |
| 15 | Dr. Cristia | 18 to 25 | Cool, Sweet |
| ID | Name | Ex | NoPost |
|---|---|---|---|
| 1 | Dr. Alison | 30 years | 2 |
| 2 | Dr. Toan N | 10 years | 2 |
| 3 | Dr. Smith | 12 years | 1 |
| 4 | Jacob | None - User | 2 |
| 5 | Edison | None - User | 1 |
| 6 | Dr. Jenny | 8 years | 2 |
| 7 | Dr. John | 6 years | 1 |
| 8 | Dr. Lisa | 2 years | 1 |
| 9 | Dr. Alice | 8 years | 2 |
| 10 | John Pham | None - User | 1 |
| 11 | Dr. Cristia | 14 years | 1 |


Human Calculator
Do As Many Calculation As You Can In 60 seconds.
Start
+
=
Time
60
Player
Score
0
color1
color2
color3
color4
All Data
Back


| DOSE: |
2 hits |
sublingual |
DOC |
11:00 Suspend 2 hits DOC in water under my tongue for a couple minutes then swallow with more water. I turn on some Enya and go to my bed to lay down until it starts. I have been doing 2-4 hits every other day for over a week at this point.
11:45 I decide to go for a walk around my neighborhood. I make my way out the door and just cruise around a couple streets. My thoughts are mostly vacant except for the disgust of the neighborhood idea. Absolutely no privacy.
12:00 I am back inside, I turn on some Bob Marley, and again lay on my bed. Couple mins later I change the music to something less politically charged. IDM artist Wisp. During these trips I try not to have too many words enter my brain.
12:10 I am now seeing the usual fractals and unclear symbols and characters in their pink, turquoise, purple, colors. This computer destroys those, as does TV, or any other focus oriented activity. The carpet has become puzzle pieces, with the dark/light areas forming the lines. At around this time I also dissect every relationship I am in. Friendships, etc. DOC has had this effect on my almost every time. I am constantly thinking, almost paranoid, about my friendships, but these thoughts, like most, are fleeting.
12:20 In my room, feeling extremely isolated. Read experiences about people being connected with the universe, but it just the opposite. We are in a fishbowl, swimming around in our daily lives, almost blindly. Yes, the universe is there, and yes we are in it, but how small! I can vision life, and rebirth, and am fixated by it, but now, here, we are fish.
12:25 My body feels like it needs an endless stretch, and my mind feels like I am waiting for something. I also have yawns fairly often.
12:30 Start questioning if this is actually reality. Feels very dreamy, and unrealistic. Light changes provide new insights into any situation.
1:00 For last 30 minutes I have been thinking about the conflicts I have within myself. I find the beauty in the uncertainty of this and next lives. I realize that love plays a major part in the human experience and wants desperately for someone. But I still know that I am not sure if its what I want, or if its just human instinct taking over. Then i masturbate and have a decent time with that.
1:05 DOC always aches my jaw. Most recently feels like a pin is being driven up through the bottom of my mouth. A few weeks ago, my jaw also locked up while tripping for 10-15 seconds. Really hurt. Gum and something to drink usually helps with this issue.
1:10 I love to focus in on one source of light. And when it separates into the rainbow it is the most beautiful thing I have ever seen. Like small butterflies of light and color. Very vibrant color. No music now.  Immediately I tell myself never to open them again. Nothing about death or anything, just never open them again.  As I do, I realize I have been making circles with my index finger in the air the whole time. It gave me some sense of hope knowing that things could actually be happening without seeing them happen.
1:20 Decide to go lay back down on my bed with some calming music playing. Undoubtedly I will be in a closed eye world for a while.
Yes this is left open ended but that is just how life is. beauty in the uncertainty. :)
Experience Reports are the writings and opinions of the individual authors who submit them.
Some of the activities described are dangerous and/or illegal and none are recommended by Erowid.


|
|
| PointerType (Type *to, std::int32_t indlev) |
| |
|
string | print () |
| |
|
| PointerType (Type *to, std::int32_t indlev) |
| |
|
| Type (BasicTypeKinds typeCode) |
| |
|
BasicTypeKinds | getTypeCode () |
| |
|
bool | isInteger () |
| |
|
bool | isUnsigned () |
| |
|
bool | isFloat () |
| |
|
bool | isNumeric () |
| |
|
bool | isPointer () |
| |
|
bool | isFunc () |
| |
|
bool | isStruct () |
| |
|
bool | isVoid () |
| |
|
| Type (BasicTypeKinds typeCode) |
| |
|
BasicTypeKinds | getTypeCode () |
| |
|
bool | isInteger () |
| |
|
bool | isUnsigned () |
| |
|
bool | isFloat () |
| |
|
bool | isNumeric () |
| |
|
bool | isPointer () |
| |
|
bool | isFunc () |
| |
|
bool | isStruct () |
| |
|
bool | isVoid () |
| |
The documentation for this class was generated from the following files:


Paul M. Leonardi, Carlos Rodriguez-Lluesma
Considers the metaphysics of analysing sociomaterial entanglements, and whether the metaphor of tiling or imbrication is better - stuck together like a puzzle, looking like one thing from far off, but rather revealed to be separate things - social and material, when the analysis is close up, and benefits from this distinction.
"re-focusing attention on the materiality of the tools with which people work—is especially important if one wishes to take a design orientation to organizational analysis. By design orientation we mean conducting research that not only allows us to describe organizational processes, but to generate insights about how to improve them"
"the metaphor of imbrication becomes a useful alternative to the metaphor of entanglement (Leonardi 2011). The verb “to imber” derives from a kind of Greek and Roman tile, known as imbrex (from imber, “rain”), used in combination with other kind of tile called “tegula”. Imbrices were laid out so that one slightly overlapped the next one, in the same way as the scales of a fish, thereby channeling the rain over the tegulae, and off the roof. In the same way as imbrices and tegulae differ in their constituent make-up, so too do social and material agencies. “Though both [are] capabilities for action, [they] differ phenomenologically with respect to intention. Thus, like the tegula and the imbrex, they have distinct contours and through their imbrication they come to form an integrated organizational structure” (Leonardi 2011, p. 37)."
imbrication
Orlikowski 2007 (affordances in work tasks as central to organizational processes)


Trauma
Executive summary
Introduction
Traumatic injuries can range from minor isolated wounds to complex injuries involving multiple organ systems. All trauma patients require a systematic approach to management to maximize outcomes and reduce the risk of undiscovered injuries and death.
Relatively few patients die after the first 24 hours following injury. Rather, the majority of deaths occur either at the scene or within the first four hours after the patient reaches a trauma centre.
The "golden hour" concept, which emphasises the increased risk of death and the need for rapid intervention during the first hour of care following major trauma should guide our practice locally.
Most trauma cases should be referred on to the EFSTH, where a multi-disciplinary team is on call 24 hrs. However in some cases a minor trauma case like RTA without fracture or bleeding may be managed conservatively and discharged.
Target users
· Nurses
· Doctors
Target area of use
· Outpatient department
· Ward
Key areas of focus / New additions / Changes
This guideline outlines the initial stabilization of trauma cases within CSD. Most patients will then need to be transferred elsewhere for definitive care.
When more than 1 major trauma case is received out-of-hours or 2 or more are received at any time, then a major incident must be declared and SOP-CLS-015 should be followed to guide management of the department.
Limitations
There are no surgeons or anaesthetists at the unit, so our involvement is limited to the initial resuscitation and stabilization of patients.
Presenting symptoms and signs
Mechanism — Particular mechanisms predispose patients to specific injuries. Common blunt trauma mechanisms and their most frequently associated injuries are described in the accompanying table (Table 1 below). In addition, certain high-risk blunt mechanisms, including pedestrians struck by automobiles, motorcycle accidents, severe motor vehicle accidents (e.g., extensive damage leading to prolonged extrication time), and falls greater than 20 feet, have been associated with greater morbidity and mortality.
Table 1: Blunt trauma mechanisms and associated injuries
|
Mechanism of injury |
Potential associated injuries |
|
Motor vehicle collision: Head-on collision, Windshield damage, Steering wheel damage |
Facial injuries, Lower extremity injuries, Aortic injuries, Thoracic injuries, Abdominal injuries: spleen, liver etc. |
|
Pedestrian versus automobile: Low or high speed (braking automobile, |
Tibia and fibula fractures, knee injuries |
|
Falls: |
Calcaneal and lower extremity fractures, Pelvic fractures Closed head injuries, Cervical spine fractures, Hand and wrist fractures |
Preparation
Whenever possible, the ward should be notified that a trauma patient is en route. This provides the receiving Nurses and Doctors with information and time that can be crucial to the management of the severely injured patient.
When trauma cases, do however present to the ward. Efforts should be made to assess, stabilise and refer to the appropriate centre where necessary.
Primary evaluation and management
A clear, simple, and organized approach is needed when managing a severely injured patient prior to referral for a definitive treatment.
The primary survey consists of the following steps:
· Airway assessment and protection (maintain cervical spine stabilization when appropriate)
· Breathing and ventilation assessment (maintain adequate oxygenation, usually oxygen saturation above 96%)
· Circulation assessment (control haemorrhage and maintain adequate end-organ perfusion)
· Disability assessment (perform basic neurologic evaluation)
· Exposure, with environmental control (undress patient and search everywhere for possible injury, while preventing hypothermia)
While performing the primary survey, keep the following points in mind :
· Airway obstruction is a major cause of death immediately following trauma. The airway may be obstructed by the tongue, a foreign body, aspirated material, tissue oedema, or expanding haematoma.
· Haemorrhage is the most common preventable cause of mortality in trauma. Be alert for subtle signs of haemorrhagic shock, particularly in the elderly, who may be on cardiovascular medications that blunt such signs, and young, healthy adults who may not present with obvious manifestations. Hypotension generally does not manifest until at least 30 percent of the patient's blood volume has been lost. Such patients are at high risk of death. Elderly patients may be hypotensive relative to their baseline blood pressure but still have blood pressure measurements in the "normal" range.
· Brain injuries are common in patients who have sustained severe blunt trauma and even a single episode of hypotension increases their risk of death
Management
Patients should be managed on the ward – the endoscopy room or the emergency bed are best as there is plenty of room to access the patient. The aim is to stabilise and refer, especially in a major case.
Airway Assessment
In a conscious patient, initial airway assessment can be performed as follows
· Begin by asking the patient a simple question (e.g., "What is your name?" especially in adults). A clear accurate response verifies the patient's ability to mentate, phonate, and to protect their airway, at least temporarily.
· Observe the face, neck, chest, and abdomen for signs of respiratory difficulty, including tachypnea, accessory or asymmetric muscle use, abnormal patterns of respiration, and stridor.
· Inspect the oropharyngeal cavity for disruption; injuries to the teeth or tongue; blood, vomitus, or pooling secretions.
· Inspect and palpate the anterior neck for lacerations, hemorrhage, crepitus, swelling, or other signs of injury.
Breathing and ventilation
Once airway patency is ensured, assess the adequacy of oxygenation and ventilation. Inspect the chest wall looking for signs of injury, including asymmetric or paradoxical movement (e.g., flail chest), auscultate breath sounds at the apices and axillae, and palpate for crepitus and deformity. Where necessary provide supplemental oxygen to keep saturation >96%.
Presumptively treat patients with signs of tension pneumothorax, including hypotension, dyspnoea, and ipsilateral decreased breath sounds, with needle decompression before obtaining imaging or referring to the EFSTH. Needle decompression is performed with a large bore (14 gauge or larger), either in the second intercostal space in the midclavicular line or in the fifth intercostal space in the midaxillary line.
Circulation: Recognition and management of haemorrhage
Once the airway and breathing are stabilized, perform an initial evaluation of the patient's circulatory status by palpating central pulses. If a carotid or femoral pulse is verified and no obvious exsanguinating external injury is noted, circulation may be assumed to be intact. While circulation is assessed, one or two large-bore (16 gauge or larger) intravenous (IV) catheters are placed, most often in the antecubital fossa of each arm.
Life-threatening haemorrhage must be controlled. A combination of manual pressure, proximal compression with either a tourniquet or a manual blood pressure cuff, and elevation is typically sufficient to control external arterial haemorrhage. Venous bleeding is controlled with direct pressure. Bleeding from severe pelvic injuries may require the application of a pelvic binder. Most trauma patients with hypotension or signs of shock (eg, pale, cool, moist skin) could be bleeding internally, initial fluid resuscitation for these patients may consist of a bolus of intravenous crystalloid (eg, 20 mL/kg isotonic saline) while arrangement is being made to transfer to the EFSTH for definitive treatment
Disability and neurologic evaluation
Once problems related to the airway, breathing, and circulation are addressed, perform a focused neurologic examination. This should include a description of the patient's level of consciousness using the Glasgow Coma Scale (GCS) score or the paediatric GCS, a validated scale for children ≤2 year old and assessments of pupillary size and reactivity, gross motor function, and sensation. Trauma patients with a GCS ≤8 or who are unresponsive or only respond to pain have severe altered mental status and require rapid resuscitative efforts.
Exposure and environmental control
Be certain that the trauma patient is completely undressed and that his or her entire body is examined for signs of injury during the primary survey. Missed injuries pose a grave threat. Regions often neglected include the scalp, axillary folds, perineum, and in obese patients, abdominal folds.
Patients should be stabilized as well as possible without delaying transfer; delays are associated with increased mortality. Criteria for transfer are based upon the patient's demographics, mechanism of injury, and clinical findings.
Secondary Survey
· AMPLE History: Allergies, medications, past medical history/pregnancy, last meal, events and environment surrounding injury.
· Physical examination from head to toe including a rectal examination (major trauma)
· Decide on definitive management (is emergency referral needed?)
· Use MIST template when writing a referral to have a patient transferred to EFSTH for further care. This includes: mechanism of injury plus sex and age of patient, injuries, signs and and symptoms and treatment so far
Laboratory investigations.
It cannot be overemphasized that a complete workup is not a requirement for transfer or referral to the EFSTH, Banjul; postponing transfer to obtain laboratory results or imaging studies only delays definitive treatment. Often such studies must be repeated at the receiving facility.
However some laboratory and radiological studies that may be done are
1. Portable radiographs
2. Ultrasound scan (FAST – Focused Assessment with Sonography for Trauma)
3. Blood sugar
4. HCG - especially in women of child-bearing age .
5. Haemoglobin.
Key Issues for Nursing care
Always call the attention of the Doctor when you are presented with a case of a major trauma.
Check vital sign on arrival and attempt to start resuscitation management as outlined above if required until the doctor arrives.
The decision to refer should be made by the doctor or the senior nurse on duty upon initial assessment.
References
1. Feliciano, DV, Mattox, et al. Trauma, 6th, McGraw-Hill, New York 2008.
2. CDC. National estimates of the ten leading causes of nonfatal injuries, Centers for Disease Control and Prevention 2004. www.cdc.gov/injury/wisqars.html.
3. Mackenzie EJ, Rivara FP, Jurkovich GJ, et al. The National Study on Costs and Outcomes of Trauma. J Trauma 2007; 63:S54.
4. Global Status on Road Safety 2015, World Health Organization, http://www.who.int/violence_injury_prevention/road_safety_status/2015/.
5. Søreide K. Epidemiology of major trauma. Br J Surg 2009; 96:697.
6. Demetriades D, Murray J, Sinz B, et al. Epidemiology of major trauma and trauma deaths in Los Angeles County. J Am Coll Surg 1998; 187:373.
7. Evans JA, van Wessem KJ, McDougall D, et al. Epidemiology of traumatic deaths: comprehensive population-based assessment. World J Surg 2010; 34:158.
8. MacKenzie EJ, Rivara FP, Jurkovich GJ, et al. A national evaluation of the effect of trauma-center care on mortality. N Engl J Med 2006; 354:366.
|
Written by: |
Name: Okpara Chibuike |
Date: 26 November 2018 |
|
Reviewed by: |
Name: Orighomisan Agboghoroma |
Date: 31 December 2018 |
|
Version: |
Change history: |
Review due date: |
|
1.0 |
New document |
31 January 2021 |
|
1.1 |
Executive summary added |
31 January 2021 |
|
Review Comments (if applicable) |
|
|


Neuroplasticity and Growth Mindset
1. Reasearch Neuroplasticity
- Understanding the principles of neuroplasticity is the first and most important step as it may be the one that starts to move your thought train. The principles of this topic should be enough to raise interest in individuals to try understand more about themselves. And ultimately improve.
- 1st step after finishing this task I'll do a refresher on previous sprints and spend a minute reflecting on them. Repeat that in future. Keep the challenge alive on a daily basis. When I'm learning I should try to incorporate my knowledge from other/similar topics.
- Find a new hobby or strengthen your current one. Try a different approach at problem solving. Consciously decide that you will learn a new [insert skill or whatever here] and work towards it. Everyday even if for 5 minutes.
- Good examples on how to learn anything
2. Research Growth Mindset
- Growth mindset is a setting of your mind that thinks in terms of improvement and the vast potential of available improvement around us, for us, for people around us. This mindset is what is going to make neuroplasticity work and prove to us individually that our potential is way greater than we ever imagined.
- Forgotten thoughts resurfaced and made even more sense now. Looking back I'm already practicing it and succeeding as well.
- I'll tell that little voice that tries to bring me down to shut up. And practice mindfulness with some positive reinforcement. You CAN do this. You KNOW how to solve this.
- A book which translates into: Nothing is not impossible
3. Mix it in with learning plan and strategies
- These understanding may influence my learning if I act on this information. They definitely are shaping my understanding of topic and significance of it. It's all important and revolutionary even but only if I do these things. So my plan is to try and involve them.


Minio gRPC Administrative API Server
Welcome to the gRPC Administrative API Server
Some relevant links:
Swagger UI
minioadmin/v1 Swagger File
minioadmin/v1 Protobuf File


To ensure delivery accuracy, we suggest the change selected below. Please choose which address you would like to use:


Anam1634.github.io
Ohaus Corporation, USA, was examined and evaluated in 1994 by the Bureau Veritas Quality International, BVQI, and was awarded ISO 9001 registration. This certifies that Ohaus Corporation, USA, has a quality system that conforms Explorer Pro Bedienungsanleitung - dmx.ohaus.com. Ohaus® - EP612C - $1,828.80 - Affordablescales.com.
Ohaus® Explorer® Pro balance EP612C, AC/DC input 120 V AC; find Sigma-Z707287 MSDS, related peer-reviewed papers, technical documents, similar products more at Sigma-Aldrich.
Ohaus® - EP612C - Precision Balance. The Explorer Pro Series of standard level balances was designed for simplicity and includes the industry’s easiest user interface for easy setup and operation; no training is required. Ohaus EP612C Description: The Explorer Pro Series of standard level balances was designed for simplicity and includes the industry’s easiest user interface for easy setup and operation; no training is required. Ohaus® Explorer® Pro balance EP612C, AC/DC input
Ohaus EP612C 610g Capacity/0.01g Readabilit - Instrument.
Find instrument drivers that are available for this instrument for use in LabVIEW, LabWindows/CVI, or Measurement Studio. Example programs are included with most instrument driver downloads. Ohaus® - EP6102C - $2,364.80 - Affordablescales.com. Balances Ohaus® Explorer® Pro Precision and High Capacity Balances STANDARD FEATURES t -BSHF IJHI SFTPMVUJPO EPU NBUSJY -JRVJE $SZTUBM %JTQMBZ -$% dot matrix. OHAUS is a worldwide leader that manufactures and markets analytical balances, precision balances, portable balances and industrial electronic and mechanical weighing scales. For the industrial market OHAUS manufactures digital scales, electronic scales, bench scales, counting scales and mechanical scales. OHAUS also offers, precision weights.
EP612C Ohaus Explorer® Pro Balance Ohaus EP612C. Ohaus Pro Precision and High Capacity Balances Ohaus® - EP6102C - Precision Balance. The Explorer Pro Series of standard level balances was designed for simplicity and includes the industry’s easiest user interface for easy setup and operation; no training is required.
Explorer Pro Manual de Instrucciones - dmx.ohaus.com.


ADD NEW FOOD
SCHEDULE DELIVERIES
| FOOD NAME | QUANTITY | PRICE | CUSTOMER NAME | DELIVERY PERSON | MORE INFO | DISPATCH | |
|---|---|---|---|---|---|---|---|
| = $order['food_name']?> | = $order['food_quantity']?> | = $order['food_price']?> | = $order['customer_first_name']?> = $order['customer_second_name']?> | = $order['delivery_person_first_name']?> = $order['delivery_person_second_name']?> |
No Schedule Deliveries
CURRENT DELIVERIES
| FOOD NAME | QUANTITY | PRICE | CUSTOMER NAME | DELIVERY PERSON | TRACK FOOD | MORE INFO | |
|---|---|---|---|---|---|---|---|
| = $c_order['food_name']?> | = $c_order['food_quantity']?> | = $c_order['food_price']?> | = $c_order['customer_first_name']?> = $c_order['customer_second_name']?> | = $c_order['delivery_person_first_name']?> = $c_order['delivery_person_second_name']?> |
No Current Deliveries
MY MENU
PREVIOUS ORDERS AND DELIVERIES
| FOOD NAME | QUANTITY | PRICE | FOOD CATEGORY | INFO | |
|---|---|---|---|---|---|
| = $order['food_name']?> | = $order['food_quantity']?> | = $order['food_price']?> | = $order['restaurant_name']?> |
- VIEW:
- TRACK MY LOCATION
CURRENT DELIVERIES
| FOOD | FROM | DESTNATION | DELIVERY PRICE | DELIVERY TIME | DISTANCE | view | |
|---|---|---|---|---|---|---|---|
| = $current_data['food_name']?> | = $current_data['r_pos_name']?> | = $current_data['c_pos_name']?> | kSH = $current_data['delivery_price']?> | = $current_data['delivery_date']?> = $current_data['deliver_time']?> | = $current_data['delivery_distance']?> KMs |
No Current Deliveries


Summary
Natural Language Processing in Action is your guide to creating machines that understand human language using the power of Python with its ecosystem of packages dedicated to NLP and AI.
Purchase of the print book includes a free eBook in PDF, Kindle, and ePub formats from Manning Publications. All examples are included in the open source `nlpia` package on python.org and github.com, complete with a conda environment and Dockerfile to help you get going quickly on any platform.
About the Technology
Recent advances in deep learning empower applications to understand text and speech with extreme accuracy. The result? Chatbots that can imitate real people, meaningful resume-to-job matches, superb predictive search, and automatically generated document summaries--all at a low cost. New techniques, along with accessible tools like Keras and TensorFlow, make professional-quality NLP easier than ever before.
About the Book
Natural Language Processing in Action is your guide to building machines that can read and interpret human language. In it, you'll use readily available Python packages to capture the meaning in text and react accordingly. The book expands traditional NLP approaches to include neural networks, modern deep learning algorithms, and generative techniques as you tackle real-world problems like extracting dates and names, composing text, and answering free-form questions.
What's inside
- Some sentences in this book were written by NLP! Can you guess which ones?
- Working with Keras, TensorFlow, gensim, and scikit-learn
- Rule-based and data-based NLP
- Scalable pipelines
About the Reader
This book requires a basic understanding of deep learning and intermediate Python skills.
About the Authors
Hobson Lane, Cole Howard, and Hannes Max Hapke are experienced NLP engineers who use these techniques in production for profit and fun: contributing to social-benefit projects like smart guides for people with blindness and cognitive assistance for those with developmental challenges or suffering from information overload (don't we all?).
Table of Contents
PART 1 - WORDY MACHINES
- Packets of thought (NLP overview)
- Build your vocabulary (word tokenization)
- Math with words (TF-IDF vectors)
- Finding meaning in word counts (semantic analysis)
PART 2 - DEEPER LEARNING (NEURAL NETWORKS)
- Baby steps with neural networks (perceptrons and backpropagation)
- Reasoning with word vectors (Word2vec)
- Getting words in order with convolutional neural networks (CNNs)
- Loopy (recurrent) neural networks (RNNs)
- Improving retention with long short-term memory networks
- Sequence-to-sequence models and attention
PART 3 - GETTING REAL (REAL-WORLD NLP CHALLENGES)
- Information extraction (named entity extraction and question answering)
- Getting chatty (dialog engines)
- Scaling up (optimization, parallelization, and batch processing)


A bit about me
You?
Please ask!
In Atom menu, select View > Toggle Soft Wrap
This helps us view long sentences easily.Currently, the browser doesn’t know how to read our content.
But soon, we will use HTML to apply meaning to our content.
After we’ve written our HTML, we will use CSS to describe the presentation of our content.
Is not crucial, but the half & half view is a good way to get started.
The most basic building block of the web.
It defines the meaning and structure of web content.
filename.html
file-name.html
Links that connect web pages to one another
Within a single website, or between websitesContact us
We use markup to annotate text, images, and other content for display in a web browser.
This markup determines how the computer (and other users!) interpret your content.
Semantic: relating to meaning in language or logic.
You need to use the following sentence on a webpage:
This is a very dangerous liquid.
We have to tell it — we mark it up.
This is a [start strong importance]very dangerous[end here please] liquid.
This is a very dangerous liquid.
gives us:
This is a very dangerous liquid.
<!DOCTYPE html>

<meta charset="utf-8">
<title>Browser tab</title>

A web page by [your name]

Copy this code into index.html (remove old text)
*Note: This may change, depending on your project
Any others?
Exercise:
Learn a bit, then build a bit.
Create an online recipe book
HTML elements:
Contains machine-readable information (metadata) about the document.
Not to be confused with  or <heading>.
After this, we will mostly be working within the  tags.
HTML elements:
HTML:
My online recipe book
A collection of recipes I've collected over the years.
Recipes:
Berry yoghurt ice blocks recipe
A web page by [your name]
By default, the browser gives us some sensibile styling
HTML elements:

Self-closing tag!

HTML elements:

…

…

…

Modern browsers give us great tools for checking how our code is being interpreted.
Right click on any element, choose 'inspect element' option, or press F12 to bring up the developer tools.
Chrome, Firefox, IE (Edge)
HTML elements:
This is a link
Our team
Members
Will look within team.html for an element with an id of "members"
HTML elements:
In a sentence:

Learn more about our team

Learn more about our team
What does href mean? It comes from Hyperlink REFerence
Make the logo a link to the page we are on (index.html)
Try in your browser: hover over the image.
The cursor should change, and the href (url) shows at the bottom of your browser.
Make the text 'Berry yoghurt ice blocks' a link to iceblocks.html
Note: Keep saving your work, and reloading your browser.
HTML elements: Links continued
<a<EMAIL_ADDRESS>Toni
Wikipedia website
Wikipedia website
Note: target="_blank" opens the link in a new tab.
Adding rel="noopener noreferrer" protects your users against having the site you’ve linked to potentially hijacking the browser (via rogue JavaScript).
HTML elements:
- First place
- Second place
- Third place
HTML elements:
- Oranges
- Lemons
- Plums
Exercise:
Copy the text below, paste it after your Berry yoghurt ice blocks heading
These easy-to-make ice blocks are the perfect way to cool down without the sugar and nasties found in store-bought ice blocks.
Recipe
Ingredients
125 g fresh or frozen boysenberries
300 ml natural unsweetened yoghurt
2 tbsp honey
Method
Mash the berries and honey in a measuring jug using a fork
Add the yoghurt and combine
Pour mixture into ice block moulds
Freeze overnight
Notes
You can use other berries such as strawberries, blackberries or even a mixture. Try adding granola to your recipe for some additional texture.
Use the mark up we’ve looked at today to assign meaning to our additional content.
A language used for describing the presentation of a document written in a markup language.
filename.css
file-name.css
We’re using it to Style the page
It’s separate from the HTML (is its own Sheet)
It’s Cascading*
*We’ll get to this part soon
Content
Presentation

Try with blueberries

Try with blueberries

p { ... }
footer { ... }
p {
color: green;
font-weight: bold;
}
p { /* selector */
color: green; /* rule */
font-weight: bold; /* rule */
}
body {
background-color: yellow;
}
It’s not working!
In the  (metadata) section of your HTML document:
Note: not in the !
Make sure to add it to both of your html files
All sorts! Here are a few things we can adjust:
*color!
When declaring sizes, we can:
margin-top: 10px;
margin-right: 20px;
margin-bottom: 10px;
margin-left: 20px;
margin: 10px 20px 5px 15px; /* [top] [right] [bottom] [left] */
margin: 10px 20px 5px; /* [top] [right + left] [bottom] */
margin: 10px 20px; /* [top + bottom] [right + left] */
margin: 20px; /* [all values are the same] */
Add the following additional code to your stylesheet:
header {
background-color: #ffcd03;
padding: 20px 30px;
/* test start */
width: 300px;
height: 150px;
border: 5px solid blue;
margin: 30px;
box-sizing: border-box; /* see note*/
/* test end */
}
* Tells browser to account for any border and padding in the values you specify for an element's width and height. This typically makes it much easier to size elements.
There are a couple of elements we can use to assist with styling.
Note: examples use the same HTML
Text with link 1 link 2 inside
Text without
a {
display: inline; /* note: default */
padding-bottom: 20px;
}
Text with link 1 link 2 inside
Text without a link
a {
display: block; /* change */
padding-bottom: 20px;
}
Text with link 1 link 2 inside
Text without a link
a {
display: inline-block; /* change */
padding-bottom: 20px;
}
Text with link 1 link 2 inside
Text without a link
We want to 'float' this image so the text reflows around it. We can float things either to the left or the right. We need to be careful though, floated elements don't sit in the page properly any more. Read about 'clearfix' to learn about this.
img { float: left; margin: 0 20px 10px 0; }
a:hover /* link is interacted with, but not clicked */
a:active /* link is being activated */
a:visited /* link has been visited */
p:first-child /* select the first paragraph (child) */
p:last-child /* select the last paragraph (child) */
static /* default */
relative
absolute
fixed
There are different ways of referring to a specific element or elements on the page.
In the HTML use an element’s id,
or ideally, give it a class.
Paragraph which needs different styling
Paragraph which is standard
Paragraph which needs different styling
Paragraph which is standard
For a class, we use a period:
.intro {
font-size: 20px;
}
A class can be used more than once
Paragraph which needs different styling
To refer to a class, we use a period:
.intro {
font-size: 20px;
}
A class can be used more than once
Elephant history
To refer to an ID, we use a hash:
#elephant-info {
color: green;
}
An ID is unique — it can only be used once.

Text

<input id="vote">

Text

Text

p { ... }
#vote { ... } /* unique */
.time { ... } /* resuable */
.time.new { ... }
The great thing about CSS is that we can stack the selectors.
Let’s say we have this HTML:
This sentence has the first link in it.
This one has the second link in it.
And we want to make only the second link green
.fact a { color: green; }
This will only affect 'a' tags that are contained within elements that have the 'fact' class.
What happens if we also have a rule to make all the links blue?
a { color: blue; }
The most specific rule will always be applied where possible
But the ordering of CSS rules is important
If two (or more) rules are equally specific, the lowest (bottommost) rule wins
Online learning
(note: you’ll need to create a user account)


x
Edit
Short Url
Destination
Tags
Views
At
IP
User-Agent
SHRLS Admin
Submit
Views
Url
Tags
Actions
x
Settings
Restore from backup
Activity Feed


It seems too early in the year to be wondering where it’s all going. I am suffocated by the surrounding air, the same stale air of desperation as a man with a noose around his neck and his hands tied behind his back…
And yet.
Waiting and restraint are my dogma these days; my mantra. “Let the debris fall to the bottom and then pick up the pieces like an emotional vacuum cleaner” is what the voices seems to advise.
Nonsense.  These voices would have me chowing on mediocrity and complacency like it was a well-crafted trail mix.
So, what to do in these harsh times? I try the city. The city does not welcome you out into its streets with open arms, especially when the temperature drops and the clouds darken like the inside of a caged heart; on the contrary, with a maddening indifference that shuns indiscriminately, it grimaces malicious intent. I head for friendly territory, the pads of friends, the bars they frequent and occasionally, I just plain old work late. Often I write, but sometimes…
I don’t know. I think that sometimes I don’t write because I’m afraid that I’ll start and not be able to finish; that I’m afraid of losing my thread; silly, of course, but I suspect it nonetheless. More likely, though, that I’m sometimes hampered by how terrified I might be if I start seeing what really wants to come out of my fingers when I put them to the keyboard.  You know?
–
Maybe I should try to remember when it was in my life that I was happiest, and see what it was that I was doing, who I was with, what was going on, what was I anticipating? And then see if I took a wrong turn and if so, head back in that direction, back to that road…
But I know that life is a one way street, and that although you can correct some of your mistakes, you can’t undo them.  I guess I can change, but I can’t change the way I once was or the things I did then.
So be it.
I’ve been satisfied with things before, this much I remember. I was content, not only with the way things were going but with my prospects, my outlooks. I guess that’s what most saddens me these days is that I’m on a different path; one that is leading me away from what I really want. A path wherein I look ahead of me and see days still in front of me that are marked only by the fading tan line of a band that weighs me down and that never fit me too well to begin with. A path that makes me feel limited, isolated from the path of my friends and family.
hmmm — yeah. I can’ t say anything else strikes me as important or significant except that I don’t want this anymore – any of it. Other symptoms are just that: symptoms. Travel, profession, education, social life… all these things are more limited than they were, and more desired than ever, but they are just symptoms. What matters is the choice I’ve already made, and that that’s what this has always been about.
I guess I’m terrified of being one of those guys that in the near future, someone will ask if I still write or what I ended up doing with this or that skill and that I had; if I had turned that into a tool for success, if I had milked my opportunities like I always promised myself that I would…had I become a writer? A traveler? A real leader? A man in any sense?
…and instead have to question all that I once thought I was because all I see is a shell floating on the sea, making no waves, leaving no wake, going absolutely nowhere. Working in a reasonably fun but pointless job, with less than no prospect of growth: no ambition to do so. Not writing anything more than a diary, and not an impressive word or phrase in it. Consuming every ounce of his will to exercise enough to simply slow-down the middle-age weight-gaining that is sure to follow. Satisfied but unquenched. Life will be an ejaculation with no orgasm.
Terrified because the one doing the asking is me, and knowing that I would, in fact, answer in this way.
Terrified that there’s no way back and that if the way out is forward that I may tire before I find my way.
Terrified of it all, really.
–
Harsh times, dudes. Harsh times indeed. But they say that this too, will pass.
Goddamn it — I hope it does.


Before Change
self.assertEqual(len(executor.execution_logs), 2)
def test_execution_stats(self):
task = ExampleTask()
workflow = EOWorkflow(dependencies=[
Dependency(task=task, inputs=[]),
])
execution_args = [
{"arg1": 1},
{"arg1": 2}
After Change
self.assertEqual(len(executor.execution_stats), 4)
for stats in executor.execution_stats:
for time_stat in ["start_time", "end_time"]:
self.assertTrue(time_stat in stats and isinstance(stats[time_stat], datetime.datetime))
def test_execution_errors(self):
with tempfile.TemporaryDirectory() as tmp_dir_name:
executor = EOExecutor(self.workflow, self.execution_args, file_path=tmp_dir_name)
executor.run(workers=5)


The action you attempted requires the proper credentials to perform. Please re-enter your username and password to try again.


Ezekiel 14:5
That I may take the house of Israel in their own heart, because they are all estranged from me through their idols.


SiaNet.Model.Layers Namespace
Classes
| Class | Description | |
|---|---|---|
| Activation |
Applies an activation function to an output.
|
|
| AvgPool1D |
Average pooling for temporal data.
|
|
| AvgPool2D |
Average pooling operation for spatial data.
|
|
| AvgPool3D |
Average pooling operation for 3D data (spatial or spatio-temporal).
|
|
| BatchNorm |
Batch normalization layer (Ioffe and Szegedy, 2014). Normalize the activations of the previous layer at each batch, i.e.applies a transformation that maintains the mean activation close to 0 and the activation standard deviation close to 1.
|
|
| Conv1D |
1D convolution layer (e.g. temporal convolution). This layer creates a convolution kernel that is convolved with the layer input over a single spatial (or temporal) dimension to produce a tensor of outputs. If use_bias is True, a bias vector is created and added to the outputs. Finally, if activation is not None, it is applied to the outputs as well.
|
|
| Conv2D |
2D convolution layer (e.g. spatial convolution over images). This layer creates a convolution kernel that is convolved with the layer input to produce a tensor of outputs. If use_bias is True, a bias vector is created and added to the outputs. Finally, if activation is not None, it is applied to the outputs as well.
|
|
| Conv3D |
3D convolution layer (e.g. spatial convolution over volumes). This layer creates a convolution kernel that is convolved with the layer input to produce a tensor of outputs. If use_bias is True, a bias vector is created and added to the outputs. Finally, if activation is not None, it is applied to the outputs as well.
|
|
| Dense |
Dense implements the operation: output = activation(dot(input, kernel) + bias) where activation is the element-wise activation function passed as the activation argument, kernel is a weights matrix created by the layer, and bias is a bias vector created by the layer (only applicable if use_bias is True).
|
|
| Dropout |
Dropout consists in randomly setting a fraction rate of input units to 0 at each update during training time, which helps prevent overfitting.
|
|
| Embedding |
Turns positive integers (indexes) into dense vectors of fixed size. eg. [[4], [20]] -> [[0.25, 0.1], [0.6, -0.2]]. This layer can only be used as the first layer in a model.
|
|
| GlobalAvgPool1D |
Global average pooling operation for temporal data.
|
|
| GlobalAvgPool2D |
Global average pooling operation for spatial data.
|
|
| GlobalAvgPool3D |
Global average pooling operation for 3D data (spatial or spatio-temporal).
|
|
| GlobalMaxPool1D |
Global max pooling operation for temporal data.
|
|
| GlobalMaxPool2D |
Global max pooling operation for spatial data.
|
|
| GlobalMaxPool3D |
Global max pooling 3D data (spatial or spatio-temporal).
|
|
| LSTM |
Long short-term memory (LSTM) is a recurrent neural network (RNN) architecture that remembers values over arbitrary intervals
|
|
| MaxPool1D |
Max pooling operation for temporal data.
|
|
| MaxPool2D |
Max pooling operation for spatial data.
|
|
| MaxPool3D |
Max pooling operation for 3D data (spatial or spatio-temporal).
|
|
| Reshape |
Reshapes an output to a certain shape.
|


|
| Contents | |
| Background |
On some Windows systems, limitations in the installed sound hardware, the software drivers for the sound hardware, or the operating system's audio architecture may result in a situation where the Beatnik Player cannot play audio at the same time as other media players that wish to play audio. Typically, with these systems only one application can use the system's audio services at a time. This limitation may often result in a situation where two (or more) applications are contending for this single audio device that cannot be shared by multiple applications simultaneously. This problematic situation is referred to as an "audio device contention".
On systems that are not able to share the audio device from multiple applications simultaneously, content sonified using the Beatnik Player could be affected primarily in two ways...
If some other media player (such as Microsoft's Windows Media Player, Real Networks' RealPlayer, nullsoft's Winamp, Liquid Audio's Liquid Player, etc.) is using the system's audio device at the time that a Web page loads that is using the Beatnik Player, the Beatnik Player will not be able to play audio and the Beatnik-sonified content will not be heard.
Starting from version 2.1, the Beatnik Player offers a way for sonified content to determine whether or not the player's underlying audio engine is engaged. If the audio engine is disengaged (possibly as a result of another media player holding on to the system's audio device), this information can be reflected in the content's user interface or the user can be alerted. This helps content developers to avoid situations where the user has the expectation of hearing audio from Beatnik-sonified content when, in actual fact, the Beatnik Player is not able to play audio because some other media player is using the system's audio device.
If the user has a Web page open that is playing audio through the Beatnik Player and they then launch another media player (such as Microsoft's Windows Media Player, Real Networks' RealPlayer, nullsoft's Winamp, Liquid Audio's Liquid Player, etc.), or they open another Web page that uses another media player, or they click on a link to a media file that will be played through another media player, then that other media player will not be able to play audio and may report an error message to the user.
Some users may blame this problem on the Beatnik Player, some may blame the other media player that failed to play audio, some may blame the Web content that has links to media that appears unable to play correctly, and some may blame the system for being incapable of mixing audio from multiple applications. However the user interprets the situation, they are likely to blame someone for this kind of failure condition. This ultimately translates to a technical support burden for someone.
Beatnik has found itself in the troubled situation of being unfairly blamed for the inability of some systems to mix audio from multiple applications. One of the cool ways of sonifying a Web site using the Beatnik Player is to create a persistent "soundtrack" for the site. This is typically done through the technique of frameset-based sonification. However, some developers using this technique found that introducing persistent Beatnik-sonification into their sites also introduced more technical support incidences.
Sites that have links to media files that would be played through different media players may have had these kinds of problems before, but the user's expectations may have been slightly different. A user may not find it unreasonable to have to close one media player application in order to allow another media player application to play audio - especially if they've experienced this kind of limitation in their system before. However, this same user may have little patience with a Web site where none of the links to media files can play audio correctly because the persistent sonification throughout the Web site is causing the Beatnik Player to hold on to the system's audio device.
The audio device contention issue is not a widespread problem. A small percentage of Windows systems are affected - mostly systems with older versions of the Windows operating system (such as Windows 95 and earlier versions of Windows NT) and older audio hardware. By far the majority of new Windows systems have the appropriate combination of audio hardware, software drivers, and operating system in order to allow multiple applications to mix audio simultaneously. There may be a very small number of new systems that still have this limitation, but the chances are quite low.
Even though the number of users experiencing this problem may be low, it is - nevertheless - not an insignificant problem. And if it results in a developer choosing not to use the Beatnik technology in their Web content because they have no way of managing this problem, this could potentially be very damaging to the adoption of the Beatnik technology in general.
With the Beatnik Player version 2.1, a system was put in place to manage this problem and help to avoid situations where the use of the Beatnik Player in sonifying a Web site could interfere with some users' ability to experience audio or audiovisual content through other media players - situations which could otherwise lead to technical support queries for the manager or developer of the Web site and which could potentially damage the reputation of the site.
This system is aptly named the "Audio Device Contention Manager" and is referred to throughout the remainder of this document simply as the ADCM.
| The System Explained |
The primary goal behind the design of the ADCM system is to provide as easy a way as possible for content authors to avoid exposing users to the audio device contention issue, with minimal modification of content needed in most cases in order to gain the benefits of the system.
Secondary goals include...
Because it is beyond Beatnik's power to rewrite inadequate older operating systems or magically manifest new audio hardware for those systems that are mixing-challenged, the ADCM focuses on measures designed to alleviate the problem and to drastically reduce the incidence of situations where the user is trying to use a media player but cannot hear audio as expected.
Feedback received from developers of high traffic Web sites indicates that while broad sonification of a Web site is an enhancement that these developers are willing to invest their effort in, such sonification is not compelling enough to take priority over the many other media offerings that these Web sites make available that are targeted for playback through other media players (such as RealNetworks' RealPlayer, Microsoft's Media Player, Apple's QuickTime Player, etc.).
When faced with a choice between having broad Web site sonification, that may cause audio device contention problems for a small yet not insignificant percentage of their users, and having no Web site sonification with the guarantee that no additional tech support problems will be introduced as a result of using the Beatnik technology, such Web developers would choose to forgo the Beatnik sonification. The risk of incurring tech support problems is just too great of a concern.
These same developers, however, have no problem with having other dedicated Beatnik audio applications, such as eMixes, launched from certain pages of their Web site. Because an eMix is a dedicated audio application that has a "face" and is associated, in the user's mind, with a specific "player" window, the user's expectations are different. For example, a user who has a system with the potential for audio device contention situations may have already experienced the inability to hear Real Audio content while playing streaming audio in another window through the QuickTime player. A dedicated Beatnik audio application is much the same, in this regard, and such a user will probably understand that an eMix needs to be closed first before opening a link to Real Audio content, and vice versa.
Developers who have sonified high traffic Web sites do see the value to adding a tasteful "soundtrack" to a Web site, and they would like to be able to offer this added richness in their content. They just don't want to incur the wrath of a small percentage of their users in doing so. In fact, being able to easily disable sonification for just those users who's systems are not capable of mixing audio from multiple applications is quite an attractive solution to these developers, since the majority of users who do not have such problems with their systems can still get the full experience intended by the developer.
The ADCM system, that is incorporated into Beatnik Player versions 2.1 and higher, combines the concept of audio device priority with an improved behavior for the Music.engageAudio static method to make it possible to use Beatnik in sonifying a high traffic Web site, and have the sonification automatically yield on those systems that cannot mix audio from multiple applications.
The concept of "audio device priority" was introduced as a means for sonified content to indicate how "hungry" it is to use the system's audio device when the system is incapable of sharing the audio device with other applications simultaneously (ie. mixing audio from multiple applications). In simple terms, the lowest audio device priority level indicates that the content thoroughly desires to not be using the audio device on problematic systems, whereas the highest audio device priority level indicates that the content is completely unwilling to let go of the audio device on such systems.
A sonified document may be set to one of four possible audio device priority levels...
This audio device priority level is used to indicate content that is sonified using the Beatnik Player, and that may also contain inline media using a non-Beatnik media player that may want to also use the audio device. This class of content would like the Beatnik sonification to yield on those systems that are incapable of mixing audio from multiple applications, so that the Beatnik sonification takes a lower priority to the other inline media. Because of the behavior of audio device priority level 1, it is not necessary to use audio device priority level 0 for content that merely has links that may launch other media players in different windows.
When a sonified document is set to audio device priority level 0, the system's audio device will be released by the audio engine only if all of the following conditions are met...
This audio device priority level is used to indicate the most typical kind of content that is sonified using the Beatnik Player. This class of content would only like to use the audio device on systems that are incapable of mixing audio from multiple applications, on the condition that the window containing the sonified content is focused and that the content has not requested that the audio engine be disengaged (using the Music.engageAudio static method). This is the default level for any sonified content that does not explicitly set the audio device priority level using the Music.setAudioDevicePriority static method. By only desiring to use the audio device when the content's parent window is focused, this audio device priority level affords the user the greatest protection against audio device contention issues.
Switching to another unrelated browser window that may contain media using other media players will cause the window containing the sonified content to lose focus and the sonified content will, therefore, no longer desire to use the audio device. Similarly, launching an application by clicking on the Windows system's "Start" menu will also cause the window containing the sonified content to lose focus. Audio device priority level 1 is also appropriate for sonified content that has links that may launch other media players in different windows, since the act of launching this other media in other windows will cause the window containing the sonified content to lose focus and the sonified content will, therefore, no longer desire to use the audio device.
When a sonified document is set to audio device priority level 1, there is a fairly tricky set of logic that determines ultimately whether or not the audio engine will be engaged (ie. using the system's audio device). For a better understanding of this logic, consult the section Rules Used to Determine Audio Engaged State.
Audio device priority level 1 may not be appropriate for certain styles of sonified content, such as music remixing applications or jukebox applications, where the user may desire that the content continue playing audio while in the background, and while the user continues to browse other Web sites (or use another application) in a foreground window. For such content, audio device priority level 2 is more appropriate.
This audio device priority level is used to indicate the kind of content that is sonified using the Beatnik Player, where the user may desire that the content continue playing audio while in the background, and while the user continues to browse other Web sites (or use another application) in a foreground window. This class of content includes dedicated music applications that may pop open in separate "player-like" windows, such as music remixing applications or jukebox applications.
This class of content would like to use the audio device on systems that are incapable of mixing audio from multiple applications, even when the window containing the sonified content is not focused, but provided that the content has not requested that the audio engine be disengaged (using the Music.engageAudio static method). Audio device priority level 2 does not afford the user the same level of protection against audio device contention issues as audio device priority level 1, but does allow content developers to still offer dedicated music applications that can play audio in the background and are not significantly crippled on problematic systems.
When a sonified document is set to audio device priority level 2, there is a fairly tricky set of logic that determines ultimately whether or not the audio engine will be engaged (ie. using the system's audio device). For a better understanding of this logic, consult the section Rules Used to Determine Audio Engaged State.
This audio device priority level is used to indicate the kind of content that is sonified using the Beatnik Player, where the user or the content provider may desire that the content continue playing audio while in the background, regardless of whether or not there is another window that is focused and that contains sonified content that is set to audio device priority level 0.
There are few - if any - types of content that would fall into this class, but this class may include what are considered to be ultra-important music applications. Because this audio device priority level essentially undermines audio device priority level 0, it is not recommended to use this level unless there is an exceptionally compelling reason.
When a sonified document is set to audio device priority level 3 and the system is incapable of mixing audio from multiple applications, the system's audio device will be in use by the audio engine provided that the content has not requested that the audio engine be disengaged (using the Music.engageAudio static method), and provided also that another media player application is not holding on to the audio device.
Because of the sensible default of audio device priority level 1, no action will be required for most sonified content in order to gain the benefits of the ADCM system. There are really just a few types of content where explicitly setting an audio device priority level is desirable. And, even in such cases where audio device priority level needs to be set explicitly, the ADCM makes it a snap.
The ADCM has been designed in such a way that the burden is not placed on you, as a content developer, to determine if the user's system has the potential for audio device contention. In fact, all that you need to do is to choose an audio device priority level appropriate for your sonified content, to achieve the desired ADCM behavior for that content on problematic systems. For systems that are fully capable of mixing audio from multiple applications, the audio device priority setting simply has no effect. So, nothing needs to be specially conditionalized for these different systems.
The following rather straightforward sample code example illustrates the code that would need to be added in a typical application of the ADCM...
<HTML><HEAD><TITLE>High Traffic Site - Navbar</TITLE></HEAD>
<BODY>
<SCRIPT SRC="music-object.js"></SCRIPT>
<SCRIPT LANGUAGE=JavaScript><!-- //
Music.setAudioDevicePriority (0);
uiPlayer = new Music ();
jinglePlayer = new Music ();
backgroundPlayer = new Music ();
uiPlayer.stubEmbed ('music/stub.rmf');
jinglePlayer.preloadEmbed ('music/corporate-jingle.rmf');
backgroundPlayer.magicEmbed (
'SRC="music/bg-theme.rmf" ' +
'HIDDEN WIDTH=0 HEIGHT=0 ' +
'AUTOSTART=TRUE LOOP=TRUE'
);
// --></SCRIPT>
<!--......................rest of document follows......................-->
|
In the above sample code listing, the highlighted code indicates the code that has been added in order to customize the ADCM's behavior. Notice how it is only one line of code.
In this example, the sonified document represents a navigation bar that will be loaded into one frame of the Web site's frameset and will persist throughout the site. Because the site may contain documents that use other media players (such as Macromedia's Flash Player, Apple's QuickTime Player, etc.), we need to ensure that the Beatnik Player is not using the system's audio device when the window containing this site is focused (ie. the user is browsing it) and the user's system is not capable of mixing audio from multiple applications. In order to ensure this, all that is needed is to set the audio device priority level for the sonified document to 0. This is done quite simply by calling the Music.setAudioDevicePriority static method immediately after sourcing in the "music-object.js" file.
While this example addresses only one type of situation, most other situations can be addressed just as easily by selecting appropriate audio device priority levels for sonified documents. More sophisticated management of the audio device contention issue can be achieved, if desired, using the various other API features of the ADCM (see the section API Features for Customizing the Behavior of the ADCM).
The audio engaged state for the audio engine is typically re-assessed each time one of the following events occurs...
Each time that the engaged state for the audio engine is re-assessed (see the section When the Engine's Audio Engaged State is Re-assessed), the following rules are used to determine the audio engine's new engaged state...
Upon first inspection, this may seem like some fairly tricky logic, but it is this set of rules that achieves the desired and intuitive behaviors for the various audio device priority levels 0, 1, 2, and 3, as well as the improved behavior for the Music.engageAudio static method (see the section New Behavior for the Music.engageAudio Method).
Each time there is a change in the engaged state of the audio engine, the onAudioEngagedChange static callback will be triggered. At this time, any handlers that have been registered for this callback (using the dedicated Music.onAudioEngagedChange static method or the more general Music.addCallbackHandler static method) will be executed.
By registering handlers for the onAudioEngagedChange static callback, the engaged state of the audio engine can be reflected in a sonified document's user interface or the user can be alerted. This can help to avoid situations where the user has the expectation of hearing audio from Beatnik-sonified content when, in actual fact, the Beatnik Player is not able to play audio at that moment because some condition has caused the audio engine to become disengaged.
While the onAudioEngagedChange callback is used to monitor changes that occur in the player's global audio engine that is shared by all sonified documents, multiple sonified documents can independently register handlers for this callback. All handlers registered for this callback by all sonified documents will be executed each time there is a change in the audio engine's engaged state, so all sonified documents have the option of indicating this state in some manner in their user interface, or otherwise acting on updates of the audio engine's engaged state.
Several new static methods were introduced in Music Object 3.3 to allow the behavior of the ADCM system to be customized to suit the needs of specific sonified content. These new static methods are as follows...
With player versions earlier than 2.1, it is still possible to alleviate the audio device contention problem in a limited manner by using the Auto Disengage extension. And, without any extra work, this extension can also provide improved behavior under the ADCM system that is incorporated into Beatnik Player versions 2.1 and higher.
| Examples |
| Backwards Compatibility Issues |
The API for the ADCM has been designed deliberately in such a way as to fail gracefully when the player installed in the user's browser is earlier than version 2.1.
In most cases, content authors who have concerns about the audio device contention issue will merely update their content to include a call to the Music.setAudioDevicePriority static method before any player instances have been embedded. This method, as it is implemented in the Music Object API, is designed to fail gracefully with Beatnik Player versions earlier than 2.1.
While the value returned by the Music.getAudioDevicePriority static method will correctly return the last value that was set using the Music.setAudioDevicePriority static method, Beatnik Player versions earlier than 2.1 will simply not exhibit any of the behaviors of the ADCM system because these versions of the player do not incorporate this system.
In some more sophisticated cases, content authors may make use of the other API features of the ADCM, such as the Music.isAudioEngaged, Music.isAudioDeviceShared, and Music.onAudioEngagedChange static methods. These methods have all been designed so as to fail gracefully when the installed version of the Beatnik Player is earlier than 2.1.
| New Behavior for the Music.engageAudio Method |
The Music Object API's Music.engageAudio static method and the obsoleted engageAudio instance method have been used historically to try to manage the audio device contention issue. However, because of security restrictions that are placed upon the JavaScript language, different sonified windows are not able to cooperate with one another in setting the engaged state of the player's underlying audio engine. Consequently, with the behavior of the Music.engageAudio method in Beatnik Player versions earlier than 2.1, different sonified windows could potentially "step all over" one another in trying to engage or disengage the audio engine.
The new behavior for the Music.engageAudio static method, introduced at Beatnik Player version 2.1, prevents this kind of tug of war situation. With the new behavior, a sonified document uses the Music.engageAudio method to register whether or not it wishes the audio engine to be engaged, based upon its understanding of whether or not there is any audio activity in the document. Using the Music.engageAudio method no longer has the effect of explicitly setting the engaged state of the audio engine. Instead, the audio device priority settings for all sonified documents, along with all calls that have been made to the Music.engageAudio method by the sonified documents, and the focused states of the various windows containing the sonified documents are used to cooperatively determine the audio engine's engaged state.
For a better understanding of the rules that are used to determine the audio engine's engaged state, consult the section The System Explained: Rules Used to Determine Audio Engaged State.
| Emulating Audio Device Contention |
While there are a good number of Windows systems that may be prone to the audio device contention issue, there is no guarantee that a Windows system that you are doing development or testing on will actually exhibit this problem. If your Windows system does not exhibit the problem, then the Beatnik Player will not, by default, engage the ADCM in order to mitigate the problem. Any customizations that you make to the ADCM's behaviors will not affect the behavior of your content on such a system, and so you will not be able to gauge how these settings would affect the user experience for a user who's system does exhibit the audio device contention issue. So, you would essentially be working in the dark.
In order to help you in customizing your sonified content to best make use of the ADCM, Beatnik Player versions 2.2 and higher (Windows only) allow you to coerce the player into thinking that the system either does or does not exhibit the audio device contention issue (regardless of whether it truly does or not). This effectively overrides the player's auto-detection for audio device contention.
Coercing the different behaviors is achieved quite easily through the use of the convenient registry scripts that are provided along with this documentation. These scripts are listed and described in the table below...
|
In order to run one of these registry scripts, save the desired script to your desktop. To do this, simply right-click on the script's filename in the above table. Then, from the menu that pops up, select the 'Save Link As...' or 'Save Target As...' option and save the file to your desktop. Once the file is saved, locate the file on your desktop and double-click on it in order to run it. Once the script has been run, the appropriate registry entry for the Beatnik Player will have been updated. In order for the change to take effect in the Beatnik Player, you should quit and relaunch your browser.
| Further Scenarios |
The following diagrams illustrate different combinations of ADCM settings for different windows, and how the states of these windows ultimately determines whether or not the audio engine is engaged (as indicated by the return value of the Music.isAudioEngaged static method shown underneath each diagram). It should be stressed that these illustrations indicate the expected results for problematic systems and that, for systems that are fully capable of mixing audio from multiple applications simultaneously, it should be expected that the Music.isAudioEngaged method would always return the value true.


In this project, you'll use generative adversarial networks to generate new images of faces.
You'll be using two datasets in this project:
Since the celebA dataset is complex and you're doing GANs in a project for the first time, we want you to test your neural network on MNIST before CelebA. Running the GANs on MNIST will allow you to see how well your model trains sooner.
If you're using FloydHub, set data_dir
to "/input" and use the FloydHub data ID "R5KrjnANiKVhLWAkpXhNBe".
data_dir = './data'
# FloydHub - Use with data ID "R5KrjnANiKVhLWAkpXhNBe"
#data_dir = '/input'
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import helper
helper.download_extract('mnist', data_dir)
helper.download_extract('celeba', data_dir)
show_n_images = 25
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
%matplotlib inline
import os
from glob import glob
from matplotlib import pyplot
mnist_images = helper.get_batch(glob(os.path.join(data_dir, 'mnist/*.jpg'))[:show_n_images], 28, 28, 'L')
pyplot.imshow(helper.images_square_grid(mnist_images, 'L'), cmap='gray')
The CelebFaces Attributes Dataset (CelebA) dataset contains over 200,000 celebrity images with annotations. Since you're going to be generating faces, you won't need the annotations. You can view the first number of examples by changing show_n_images
.
show_n_images = 25
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
mnist_images = helper.get_batch(glob(os.path.join(data_dir, 'img_align_celeba/*.jpg'))[:show_n_images], 28, 28, 'RGB')
pyplot.imshow(helper.images_square_grid(mnist_images, 'RGB'))
Since the project's main focus is on building the GANs, we'll preprocess the data for you. The values of the MNIST and CelebA dataset will be in the range of -0.5 to 0.5 of 28x28 dimensional images. The CelebA images will be cropped to remove parts of the image that don't include a face, then resized down to 28x28.

You'll build the components necessary to build a GANs by implementing the following functions below:
model_inputs
discriminator
generator
model_loss
model_opt
train
This will check to make sure you have the correct version of TensorFlow and access to a GPU
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
from distutils.version import LooseVersion
import warnings
import tensorflow as tf
# Check TensorFlow Version
assert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or newer. You are using {}'.format(tf.__version__)
print('TensorFlow Version: {}'.format(tf.__version__))
# Check for a GPU
if not tf.test.gpu_device_name():
warnings.warn('No GPU found. Please use a GPU to train your neural network.')
else:
print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))
Implement the model_inputs
function to create TF Placeholders for the Neural Network. It should create the following placeholders:
image_width
, image_height
, and image_channels
.z_dim
.Return the placeholders in the following the tuple (tensor of real input images, tensor of z data)
import problem_unittests as tests
def model_inputs(image_width, image_height, image_channels, z_dim):
"""
Create the model inputs
:param image_width: The input image width
:param image_height: The input image height
:param image_channels: The number of image channels
:param z_dim: The dimension of Z
:return: Tuple of (tensor of real input images, tensor of z data, learning rate)
"""
# TODO: Implement Function
inputs = tf.placeholder(tf.float32, shape=[None, image_width, image_height, image_channels], name="input")
z = tf.placeholder(tf.float32, shape=[None, z_dim], name="z")
lr = tf.placeholder(tf.float32, name="learning_rate")
return inputs, z, lr
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_model_inputs(model_inputs)
Implement discriminator
to create a discriminator neural network that discriminates on images
. This function should be able to reuse the variabes in the neural network. Use tf.variable_scope
with a scope name of "discriminator" to allow the variables to be reused. The function should return a tuple of (tensor output of the discriminator, tensor logits of the discriminator).
def discriminator(images, reuse=False):
"""
Create the discriminator network
:param image: Tensor of input image(s)
:param reuse: Boolean if the weights should be reused
:return: Tuple of (tensor output of the discriminator, tensor logits of the discriminator)
"""
# TODO: Implement Function
with tf.variable_scope('discriminator', reuse=reuse):
alpha = tf.constant(0.2, dtype=tf.float32, name="alpha")
# Input layer is 28x28x3
x1 = tf.layers.conv2d(images, 64, 5, strides=2, padding='same')
relu1 = tf.maximum(alpha * x1, x1)
# 14x14x64
x2 = tf.layers.conv2d(relu1, 128, 5, strides=2, padding='same')
bn2 = tf.layers.batch_normalization(x2, training=True)
relu2 = tf.maximum(alpha * bn2, bn2)
# 7x7x128
x3 = tf.layers.conv2d(relu2, 256, 5, strides=2, padding='valid')
bn3 = tf.layers.batch_normalization(x3, training=True)
relu3 = tf.maximum(alpha * bn3, bn3)
# 4x4x256
# Flatten it
flat = tf.reshape(relu3, (-1, 4*4*256))
logits = tf.layers.dense(flat, 1)
out = tf.sigmoid(logits)
return out, logits
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_discriminator(discriminator, tf)
Implement generator
to generate an image using z
. This function should be able to reuse the variabes in the neural network. Use tf.variable_scope
with a scope name of "generator" to allow the variables to be reused. The function should return the generated 28 x 28 x out_channel_dim
images.
def generator(z, out_channel_dim, is_train=True, alpha=0.2):
"""
Create the generator network
:param z: Input z
:param out_channel_dim: The number of channels in the output image
:param is_train: Boolean if generator is being used for training
:return: The tensor output of the generator
"""
# TODO: Implement Function
with tf.variable_scope('generator', reuse=(not is_train)):
# First fully connected layer
x1 = tf.layers.dense(z, 2*2*512)
# Reshape it to start the convolutional stack
x1 = tf.reshape(x1, (-1, 2, 2, 512))
x1 = tf.layers.batch_normalization(x1, training=is_train)
x1 = tf.maximum(alpha * x1, x1)
# 2x2x512
x2 = tf.layers.conv2d_transpose(x1, 256, 5, strides=2, padding='valid')
x2 = tf.layers.batch_normalization(x2, training=is_train)
x2 = tf.maximum(alpha * x2, x2)
# 7x7x256
x3 = tf.layers.conv2d_transpose(x2, 128, 5, strides=2, padding='same')
x3 = tf.layers.batch_normalization(x3, training=is_train)
x3 = tf.maximum(alpha * x3, x3)
# 14x14x128
# Output layer
logits = tf.layers.conv2d_transpose(x3, out_channel_dim, 5, strides=2, padding='same')
# 28x28x3 or 28x28x1 now
out = tf.tanh(logits)
return out
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_generator(generator, tf)
Implement model_loss
to build the GANs for training and calculate the loss. The function should return a tuple of (discriminator loss, generator loss). Use the following functions you implemented:
discriminator(images, reuse=False)
generator(z, out_channel_dim, is_train=True)
def model_loss(input_real, input_z, out_channel_dim):
"""
Get the loss for the discriminator and generator
:param input_real: Images from the real dataset
:param input_z: Z input
:param out_channel_dim: The number of channels in the output image
:return: A tuple of (discriminator loss, generator loss)
"""
# TODO: Implement Function
g_model = generator(input_z, out_channel_dim)
d_model_real, d_logits_real = discriminator(input_real)
d_model_fake, d_logits_fake = discriminator(g_model, reuse=True)
soft = 0.98
d_loss_real = tf.reduce_mean(
tf.nn.sigmoid_cross_entropy_with_logits(
logits=d_logits_real, labels=tf.ones_like(d_model_real) * soft
),
name='d_loss_real',
)
d_loss_fake = tf.reduce_mean(
tf.nn.sigmoid_cross_entropy_with_logits(
logits=d_logits_fake, labels=tf.zeros_like(d_model_fake)
),
name='d_loss_fake',
)
g_loss = tf.reduce_mean(
tf.nn.sigmoid_cross_entropy_with_logits(
logits=d_logits_fake, labels=tf.ones_like(d_model_fake) * soft
),
name='g_loss',
)
d_loss = d_loss_real + d_loss_fake
return d_loss, g_loss
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_model_loss(model_loss)
Implement model_opt
to create the optimization operations for the GANs. Use tf.trainable_variables
to get all the trainable variables. Filter the variables with names that are in the discriminator and generator scope names. The function should return a tuple of (discriminator training operation, generator training operation).
def model_opt(d_loss, g_loss, learning_rate, beta1):
"""
Get optimization operations
:param d_loss: Discriminator loss Tensor
:param g_loss: Generator loss Tensor
:param learning_rate: Learning Rate Placeholder
:param beta1: The exponential decay rate for the 1st moment in the optimizer
:return: A tuple of (discriminator training operation, generator training operation)
"""
# Get weights and bias to update
t_vars = tf.trainable_variables()
d_vars = [var for var in t_vars if var.name.startswith('discriminator')]
g_vars = [var for var in t_vars if var.name.startswith('generator')]
# Optimize
with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)):
d_train_opt = tf.train.AdamOptimizer(learning_rate, beta1=beta1).minimize(d_loss, var_list=d_vars)
g_train_opt = tf.train.AdamOptimizer(learning_rate, beta1=beta1).minimize(g_loss, var_list=g_vars)
return d_train_opt, g_train_opt
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_model_opt(model_opt, tf)
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import numpy as np
def show_generator_output(sess, n_images, input_z, out_channel_dim, image_mode):
"""
Show example output for the generator
:param sess: TensorFlow session
:param n_images: Number of Images to display
:param input_z: Input Z Tensor
:param out_channel_dim: The number of channels in the output image
:param image_mode: The mode to use for images ("RGB" or "L")
"""
cmap = None if image_mode == 'RGB' else 'gray'
z_dim = input_z.get_shape().as_list()[-1]
example_z = np.random.uniform(-1, 1, size=[n_images, z_dim])
samples = sess.run(
generator(input_z, out_channel_dim, False),
feed_dict={input_z: example_z})
images_grid = helper.images_square_grid(samples, image_mode)
pyplot.imshow(images_grid, cmap=cmap)
pyplot.show()
Implement train
to build and train the GANs. Use the following functions you implemented:
model_inputs(image_width, image_height, image_channels, z_dim)
model_loss(input_real, input_z, out_channel_dim)
model_opt(d_loss, g_loss, learning_rate, beta1)
Use the show_generator_output
to show generator
output while you train. Running show_generator_output
for every batch will drastically increase training time and increase the size of the notebook. It's recommended to print the generator
output every 100 batches.
def train(epoch_count, batch_size, z_dim, learning_rate, beta1, get_batches, data_shape, data_image_mode):
"""
Train the GAN
:param epoch_count: Number of epochs
:param batch_size: Batch Size
:param z_dim: Z dimension
:param learning_rate: Learning Rate
:param beta1: The exponential decay rate for the 1st moment in the optimizer
:param get_batches: Function to get batches
:param data_shape: Shape of the data
:param data_image_mode: The image mode to use for images ("RGB" or "L")
"""
# TODO: Build Model
image_width, image_height, num_channels = data_shape[1:4]
input_real, input_z, input_lr = model_inputs(image_width, image_height, num_channels, z_dim)
d_loss, g_loss = model_loss(input_real, input_z, num_channels)
d_opt, g_opt = model_opt(d_loss, g_loss, input_lr, beta1)
losses = []
steps = 0
show_every = 200
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for epoch_i in range(epoch_count):
for batch_images in get_batches(batch_size):
steps += 1
batch_images *= 2
# Sample random noise for G
batch_z = np.random.uniform(-1, 1, size=(batch_size, z_dim))
# Run optimizers
_ = sess.run(d_opt, feed_dict={input_real: batch_images, input_z: batch_z, input_lr: learning_rate})
_ = sess.run(g_opt, feed_dict={input_real: batch_images, input_z: batch_z, input_lr: learning_rate})
if steps % show_every == 0:
# At the end of each epoch, get the losses and print them out
train_loss_d = d_loss.eval({input_real: batch_images, input_z: batch_z, input_lr: learning_rate})
train_loss_g = g_loss.eval({input_real: batch_images, input_z: batch_z, input_lr: learning_rate})
print("Epoch {}/{}...".format(epoch_i + 1, epoch_count),
"Discriminator Loss: {:.4f}...".format(train_loss_d),
"Generator Loss: {:.4f}".format(train_loss_g))
# Save losses to view after training
losses.append((train_loss_d, train_loss_g))
if steps % show_every == 0:
show_generator_output(sess, 25, input_z, num_channels, data_image_mode)
print("Final: ")
show_generator_output(sess, 25, input_z, num_channels, data_image_mode)
Test your GANs architecture on MNIST. After 2 epochs, the GANs should be able to generate images that look like handwritten digits. Make sure the loss of the generator is lower than the loss of the discriminator or close to 0.
batch_size = 32
z_dim = 100
learning_rate = 0.00015
beta1 = 0.2
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
epochs = 2
mnist_dataset = helper.Dataset('mnist', glob(os.path.join(data_dir, 'mnist/*.jpg')))
with tf.Graph().as_default():
train(epochs, batch_size, z_dim, learning_rate, beta1, mnist_dataset.get_batches,
mnist_dataset.shape, mnist_dataset.image_mode)
Run your GANs on CelebA. It will take around 20 minutes on the average GPU to run one epoch. You can run the whole epoch or stop when it starts to generate realistic faces.
batch_size = 64
z_dim = 100
learning_rate = 0.0002
beta1 = 0.1
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
epochs = 1
celeba_dataset = helper.Dataset('celeba', glob(os.path.join(data_dir, 'img_align_celeba/*.jpg')))
with tf.Graph().as_default():
train(epochs, batch_size, z_dim, learning_rate, beta1, celeba_dataset.get_batches,
celeba_dataset.shape, celeba_dataset.image_mode)
When submitting this project, make sure to run all the cells before saving the notebook. Save the notebook file as "dlnd_face_generation.ipynb" and save it as a HTML file under "File" -> "Download as". Include the "helper.py" and "problem_unittests.py" files in your submission.