| CONTENTS | PREV | NEXT |
add
methods to add the required permissions. And such grouping can be
arbitrarily complicated.
The more difficult issues are the following. First, to understand what actual permissions one is granting when giving out such a super permission, either a fixed and named permission class is created to denote a statically specified group of permissions, or the member permissions need to be spelled out in the policy file. Second, processing the policy (file) can become more complicated because the grouped permissions may need to be expanded. Moreover, nesting of grouped permission increases complexity even more.
One such mechanism is SignedObject. Parallel to this primitive, we will provide SealedObject that uses encryption to hide the content of an object. (Due to current U.S. export control regulations on the use of encryption, the SealedObject class will likely be provided separate from the SDK.)
GuardedObject is a general way to enforce access control at a per class/object per method level. This method, however, should be used only selectively, partly because this type of control can be difficult to administer at a high level.
Often a domain is thought of as supporting inheritance: a subdomain would automatically inherit the parent domain's security attributes, except in certain cases where the parent further restricts the subdomain explicitly. Relaxing a subdomain by right amplification is a possibility with the notion of trusted code.
For convenience, we can think of the system domain as a single, big collection of all system code. For better protection, though, system code should be run in multiple system domains, where each domain protects a particular type of resource and is given a special set of rights. For example, if file system code and network system code run in separate domains, where the former has no rights to the networking resources and the latter has no rights to the file system resources, the risks and consequence of an error or security flaw in one system domain is more likely to be confined within its boundary.
This flexibility brings about the issue of interpretation. The following questions need to be answered, especially when keys are treated differently:
1. Should images and audios be required to be signed with the same key if any class in the archive is signed? 2. If images and audios are signed with different keys, can they be placed in the same appletviewer (or browser page), or should they be sent to different viewers for processing?These questions are not easy to answer, and require consistency across platforms and products to be the most effective. Our intermediate approach is to provide a simple answer -- all images and audio clips are forwarded to be processed within the same applet classloader, whether they are signed or not. This temporary solution will be improved once a consensus is reached.
Moreover, if a digital signature cannot be verified because the bytecode content of a class file does not match the signed hash value in the JAR, a security exception is thrown, as the original intention of the JAR author is clearly altered. Previously, there was a suggestion to run such code as untrusted. This idea is undesirable because the applet classloader allows the loading of code signed by multiple parties. This means that accepting a partially modified JAR file would allow an untrusted piece of code to run together with and access other code through the same classloader.


First I would like to say that I am a somewhat seasoned ďexplorerĒ of the mind. I have use many substances for purposes of recreation or exploration. I'm not boasting or anything I just want to be thorough. I have been known to be able to 'keep my cool' in less than desirable phsychedelic conditions, I have watched many friends cause long term damage to their psyches by misusing psychedelics and I try to remember this and repect the chemicals I use. I just want to imply that I cannot compare the Salvia experience to anything else. I was truly terrified like never before in my life!
The day of my last experience, my girlfriend and I were scheduled to leave for a week vacation the following day, so there was a greatly relaxed atmosphere. I was in a great mood, maybe slightly apprehensive. I had only smoked marijuana and am a regular smoker. I was not stoned at the time. I had experienced mild effects from salvia (10x but I didnít hold it in) before but nothing like the one I was about to. I think this led to over eagerness and lack of respect; I just didn't think it was this strong. My brother brought over a gram of the 10x extract, so I straightened up a little and we immediately got started which I now realize as a mistake. Preparations are a must with this.
Being the 'Salvia pioneer' I fancied myself to be, I voted to go first and met no opposition. I put on some heavy, trippy jazz music and divided the gram into two parts and packed one of them in my large water pipe. Sitting on my large wraparound couch, I blasted my first hit and held it in like a champ and then cleared the bong and I believe I choked on this but it did not matter any longer for my vision was clearly changing. my friend to my left kindly removed the bong from my grip and I relaxed and laid back. I instantly laughed but I think I was just doing it to convince myself I was okay and not to alarm my friends.
I felt a strong current pulling me to my right and rolling under me like a wheel. Looking around, I saw everything, not just the room but my whole reality rolling up into this 'wheel' my friend to the left of me and my brother across from me were being rolled right up too and they seemed to only be props. I later found out that I was looking at my best friend and brother as if I did not know who they were. I noticed I too was being rolled up and assimilated into my hardwood floor. I remember thinking 'You've got to be shitting meí and getting the strong feeling that this was no joke. I was unaware of this but by this time I had rolled off of my couch and nose dived onto the floor and was rolling around. I remember everywhere I looked I saw an image of what I just looked at as if I truly was being wrapped up.
I remember feeling as if my entire life and all my experiences were someone's entertainment or game show and it was being disposed of to start a new one. I'm sure my companion's laughter at my state contributed to this feeling. I vaguely felt as if I had known this all along, but was absolutely terrified. I began resisting this wheel to try to get out but could not. at this point I think my brother came over and to check on me on the floor and was asking me if I was alright but I heard none of this. He was holding my forearm as I was sitting on the floor and I thought my brother was the game show host, pushing me into the wheel because I was trying to resist. The loud heavy jazz (not a good idea) became the theme song to this game show, unrecognizable to me, though I listen to that song all the time!
I remember when it got to the point that my upper body and head were being rolled up I felt an inkling of relief that the struggle we call 'life' or 'reality' was over, but my fear and inability to let go far outweighed this relief. I finally managed to stand and the effects quickly dissipated. Thankfully not hurt, I slowly came to as I put everything back together in my mind and felt amazed at my re-realization of this reality. My amused brother and frightened friend informed me I had just rolled around and spilled the salvia in my fall. By this time I was very amused like a playful cosmic joke had occurred but only after I regained my conciousness. I felt completely normal 15 minutes from ingestion save a slight tired feeling and I went about the rest of my day, pretty flabbergasted at what had happened.
I feel as if I have learned a few things from this harrowing experience. if anything to stop clinging so tightly to my perceptions, and not only on Salvia, for they can drag me into a personal terror. I might feel a heightened creativity but this could just be my excitement at a new experience. this plant does unfold a completely foreign dimension that can be equally pleasant and horrific maybe even simultaneously. I am of the belief that the frightening things we see are really our own fears being projected on things we donít know about. If I am brave and full of love I can handle anything, only when I fear, judge and hate do my nightmares surface. this is easy to remember on other psychedelic trips but Salvia hits too quickly.
I will definitely do Salvia again. When? Iím not sure but soon. I only hope I can have the personal courage to let go and see where it takes me. A true challenge. I am concerned about the safety of losing bodily control. I wish I had access to a padded room!
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.


| timer = any valid timer variable created with the CreateTimer command. |
| This command will destroy a timer variable created with the with the CreateTimer command and free the memory it was using. It is a good practice to destroy elements in your game you are no longer using. |
|
; Create the timer to track speed
frameTimer=CreateTimer(60) ; Your main screen draw loop While Not KeyHit(1) WaitTimer(frameTimer) ; Pause until the timer reaches 60 Cls ; Draw your screen stuff Flip Wend ; Kill the timer FreeTimer(frameTimer) |


influenza virus antibodies al, < (Fig AAV antibody vaccine AAV�?HA serum mice titers Cal// WIV vectors cells broadly animals AAV�?cHA induced sera using vector immunization protection viruses determined groups indicated challenge reactive stalk ELISA HAI ferrets protective AAV�?NP induce lung technical FcγR�?activating HA�?stalk head headless heterologous vaccines pre�?challenge viral {border-style However, added immune response used vaccination weight Statistical homologous neutralizing px;} responses #ffffff;} AAV�?vectored FcγR antigen group human inactivated mouse plates significance (Thermo binding hemagglutinin individual performed assay cHA data ferret immunity mean AAV�?HA, AAV�?cHA, IgG Virol: antibodies. clinical expressing incubated pandemic test AAV�?GFP Figure Fischer MDCKII antigenic antigens epitopes indicate induction samples .). Fig compared conformational different infection loss production shown Dunn's HA, IgA KrammerF, Scientific) activation cell chimeric comparison conserved disease min pooled times (:,; (:; (Figs B). HA�?head Immunol: Influenza PBS control described including multiple nasal negative region represent respiratory time virus. (HN)pdm Furthermore, Interestingly, PaleseP, TanGS, analyzed animal associated constructs day detected duplicates. expression gene high indicating protein reduced severe subtypes testing �?GFP, �?cHA, (*P (AAV�?HA, (HN); AAV�?HA�?immunized C). Germany) Mean Nat Sci additional adeno�?associated analysis and/or contained dilution doses epitope expressed groups. humans levels measured non�?neutralizing observed plasmids px; reporter study tested transfected vaccine. {font-family (Appendix A). Cells Data F). Germany). HN, Kruskal–Wallis Med: Table buffer challenged development dilutions domain duplicates). font-size homogenates immunogenicity increased infected intranasal lethal likely peptide peptides protect protected seasonal signal strains titer total viruses. vitro washed wild�?type (pH (red AAV�?GFP�?immunized AAV�?NP, AAV�?vector Acad Agilent Click Clin Ferrets Fisher HaiR, LINK NachbagauerR, Natl Proc Source USA: Vaccine: Yassine able based collab: containing derived did divergent double; ferrets. file. given group). however, humoral immunized increase inhibition intranasally lack murine points) protection. protects purified recognizing reducing replication results screen severity signs strong submucosal universal use vaccinated vaccines. work °C. (black **P Adeno�?associated D). E). HA�?specific Hence, Hum IL�? Lines MargineI, MillerMS, Mol PaleseP Substrate Thus, Vaccine Wilson, WilsonJM activating amino anti�?V�?tag bars border-color border-width broad capsid capsids cellular challenge, challenge. coated detection developed differences dose glands higher i.e., identified incubation indicates induces load low lungs mHL mainly maximum mean. novel obtained period post�?infection pre�?existing pre�?immune produced reactivity receptor regions respective secondary showed significant solid; staining stalk�?specific studies suited survival temperature tissue transfection van virus, virus�?specific von {font-style {font-weight �?week (AAV�?GFP) (OD (Pep), (WHO, (cHA) A/Michigan// A/Puerto AAV�?HL, AAV�?NP�?immunized Broadly B�?cell Cal//�?specific Cell Cell: ELISAs EVA). EVB). EVC). FcγR�?reporter Friedman Garcia�?SastreA, Gene Geneva, HSO. HeW, Health Here, Institute JegaskandaS, LeonPE, Lipofectamine Lung Moreover, MullarkeyCE, One: Optical PR, Pandemic Plates QIV QIV�?immunized RavetchJV Rico// S). SD. Scientific). Solution Switzerland: TMB�?ELISA Ther: Ultra Unexpectedly, V�?tag WilsonPC, World according acid active amounts anesthetized animals, antibodies, applied available avian body bold bronchi cells, cells. chicken clear complete conferred confirmed contain contains contrast, correlated correlation coupled courier; culture currently cycle delivery den density design detectable distinct does effect efficiently elicit elicited em; epithelial evaluated e�? ferrets, finding group) group, group. highly immunization, immunoblot immunogenic included infectious injection intervals. intramuscular limited lines: lower observations parental period, platforms points polyclonal pools prepared presence prime proteins pt;} quadrivalent quantified reacting reaction recently related require requires separated sequential stained stopped strains. suggest suggested taken targeting therapy tract transmembrane turbinates vectored verified viruses, washing, °C— �?Step™ �?day �?mHL �?mHL, �?mer


| Package | Description |
|---|---|
| org.bitcoinj.kits |
High level wrapper APIs around the bitcoinj building blocks.
|
| Modifier and Type | Method and Description |
|---|---|
WalletAppKit |
WalletAppKit.connectToLocalHost()
Will only connect to localhost.
|
WalletAppKit |
WalletAppKit.restoreWalletFromSeed(DeterministicSeed seed)
If a seed is set here then any existing wallet that matches the file name will be renamed to a backup name,
the chain file will be deleted, and the wallet object will be instantiated with the given seed instead of
a fresh one being created.
|
WalletAppKit |
WalletAppKit.setAutoSave(boolean value)
If true, the wallet will save itself to disk automatically whenever it changes.
|
WalletAppKit |
WalletAppKit.setAutoStop(boolean autoStop)
If true, will register a shutdown hook to stop the library.
|
WalletAppKit |
WalletAppKit.setBlockingStartup(boolean blockingStartup)
If true (the default) then the startup of this service won't be considered complete until the network has been
brought up, peer connections established and the block chain synchronised.
|
WalletAppKit |
WalletAppKit.setCheckpoints(InputStream checkpoints)
If set, the file is expected to contain a checkpoints file calculated with BuildCheckpoints.
|
WalletAppKit |
WalletAppKit.setDiscovery(PeerDiscovery discovery)
Sets the peer discovery class to use.
|
WalletAppKit |
WalletAppKit.setDownloadListener(DownloadProgressTracker listener)
If you want to learn about the sync process, you can provide a listener here.
|
WalletAppKit |
WalletAppKit.setPeerNodes(PeerAddress... addresses)
Will only connect to the given addresses.
|
WalletAppKit |
WalletAppKit.setUserAgent(String userAgent,
String version)
Sets the string that will appear in the subver field of the version message.
|
WalletAppKit |
WalletAppKit.useTor()
If called, then an embedded Tor client library will be used to connect to the P2P network.
|
Copyright © 2022. All rights reserved.


Other sources and destinations
Custom written sources & destinations
ETLBox allows you to write your own implementation of sources and destinations. This gives you a great flexibility if you need to integrate systems that are currently now included in the list of default connectors.
CustomSource
A custom source can generate any type of output you need. It will accept tow function: One function that generates the your output, and another one that return true if you reached the end of your data.
Let's look at a simple example. Assuming we have a list of strings, and we want to return these string wrapped into an object data for our source.
First we define an object
public class MyRow {
public int Id { get; set; }
public string Value { get; set; }
}
List<string> Data = new List<string>() { "Test1", "Test2", "Test3" };
int _readIndex = 0;
CustomSource<MySimpleRow> source = new CustomSource<MySimpleRow>(
() => {
return new MyRow()
{
Id = _readIndex++,
Value = Data[_readIndex]
};
},
() => _readIndex >= Data.Count);
CustomSource also works with dynamic ExpandoObject and arrays.
Custom Destination
The use of a custom destination is even simpler - a custom destination just calls an action for every received record.
Here is an example:
CustomDestination<MySimpleRow> dest = new CustomDestination<MySimpleRow>(
row => {
SqlTask.ExecuteNonQuery(Connection, "Insert row",
$"INSERT INTO dbo.CustomDestination VALUES({row.Id},'{row.Value}')");
}
);
Memory Source
A Memory source is a simple source component that accepts a .NET list or enumerable. Use this component within your dataflow if you already have a collection containing your data available in memory. When you execute the flow, the memory destination will iterate through the list and asynchronously post record by record into the flow.
Example code:
MemorySource<MySimpleRow> source = new MemorySource<MySimpleRow>();
source.Data = new List<MySimpleRow>()
{
new MySimpleRow() { Col1 = 1, Col2 = "Test1" },
new MySimpleRow() { Col1 = 2, Col2 = "Test2" },
new MySimpleRow() { Col1 = 3, Col2 = "Test3" }
};
MemoryDestination
A memory destination is a component that store the incoming data within a BlockingCollection.
You can access the received data within the Data
property.
Data can be read from this collection as soon as it arrives.
Example:
MemoryDestination<MySimpleRow> dest = new MemoryDestination<MySimpleRow>();
// data is accessible in dest.Data
When starting the data flow asynchronous, you should wait until the tasks complete. The source task will complete when all data was posted into the data flow, and the destination task completes when all data has arrived in the destination.


About
Bronies
Contact
Home
Cupcakes Wonderbolts Zecora Iron Will cutie mark breezies Owlowiscious. Sapphire Shores Granny Smith apples friends Trenderhoof magic. Adagio Dazzle tail Shining Armor Caramel Peewee. Diamond Tiara hoof Gilda friendship. Hoof Dr. Caballeron Flim Silver Shill moon Pumpkin Cake Lord Tirek Princess Cadance. Wonderbolts hay Ms. Harshwhinny, Apple Bloom Dr. Caballeron Donut Joe Gummy Coco Pommel Everfree Forest apple. Big McIntosh Fluttershy Goldie Delicious Twilight Sparkle, Filthy Rich mane Pipsqueak Dr. Caballeron rainbow power Coco Pommel sun Sonata Dusk Peewee Sweetie Drops Shining Armor. Sunset Shimmer Smarty Pants Princess Celestia Seabreeze kindness friends. Queen Chrysalis pegasus gryphon Babs Seed. Sweetie Belle muffin Pipsqueak Cheese Sandwich, Soarin Goldie Delicious hooves pies Bon Bon laugher harmony Sunset Shimmer Pumpkin Cake. Goldie Delicious Owlowiscious Sunset Shimmer muffin hay Bloomberg Pipsqueak Trenderhoof Flash Sentry Princess Luna Twilight Sparkle Smarty Pants Coco Pommel.


Kenya Camping Safaris
3 Day Maasai Camping Safari
Kenya's most celebrated national reserve. It offers the possibility of seeing "the big five" and many other species of wildlife
From Kshs. 14,500 per person
3 Day Amboseli Camping Safari
Amboseli National park is one of Kenya's most popular parks. Here, elephants, hippos and bird life can be seen against the backdrop of Mt. Kilimanjaro
From Kshs. 6,000 per person
3 Day Samburu Camping adventure
Samburu National reserve is renowned for its rare unique animal species such as the gravy zebra and reticulated giraffe
From Kshs. 6,000 per person
4 Days Maasai Mara & Lake Nakuru Safari Adventure
Camping safari to the world famous bird sanctuary of Lake Nakuru, then to Kenya's greatest national reserve - the Maasai Mara
From Kshs. 6,000 per person
4 Day Maasai Mara Camping Migration Safari
The safari takes you to the Maasai Mara national reserve; famous for its big cat population and annual wildebeest migration from July to October
From Kshs. 12,000 per person
6 Days Amboseli, Tsavo East & Tsavo West & Mombasa Camping Safari
6 Days budget package to Amboseli, both Tsavo East & West and ending in Mombasa
From Kshs. 16,000 per person


4. Dependency Injection: Taming the modules that make up our software.
3. A Tale on Concatenated Indexes: Master Roshi and Goku’s fireside chat
2. Introduction to LSM Trees: May the logs be with you
1. Basics of Database Partitioning and Partition Strategies


Cookies Needed By Location Each Day
New Location
Store Name:
Minimum # of Expected Customers:
Maximum # of Expected Customers:
Average # of Cookies Purchased per Customer:
MAIN


This test demonstrates loading content from an external source by adding a "source" setting defined as a string, which will be translated to a URL. Each tab's "href" will be passed as a parameter to the URL when the tab is activated. No tab panels exist in the base markup, but the markup is generated the first time each tab is activated. On subsequent activations, the existing tab markup is used instead of making a new AJAX call.


--- title: "IDisposable, WCF, and Hole In The Middle" layout: post ---
Steve Smith recently posted about the problem of the Close() (or Dispose()) method throwing an exception in WCF. He proposed a solution that was an extension method to the ICommunicationObject interface and handled safely closing the connection. Now, if you read my blog you likely know I love Extension Methods, and even more so love them on Interfaces, but his code resulted in a usage like this:
var myClient = new ServiceClient();
try
{
int someValue = myClient.GetSomeValue();
}
finally
{
myClient.CloseConnection(); // extension method
}
This is ok, but as he noted doesn’t actually save you much over a using() block except that the error is not thrown from a closing brace, which is confusing. But if you look at this code, it is a classic example of a Hole In The Middle. We want to do some common setup, and common tear down, but do something different in the middle. The easiest way to get around Hole In The Middle problems in C# is to use lambdas. But of course we want to do this in a way that is easy, and preserves our type safety.
So I sat down with Visual Studio, and after about 15 minutes came up with this:
public static TResult SafeExecution<TExtension, TResult>
(this TExtension myServiceClient,
Func<TExtension, TResult> serviceAction)
where TExtension : ICommunicationObject
{
TResult outValue;
try
{
outValue = serviceAction.Invoke(myServiceClient);
}
finally
{
myServiceClient.CloseConnection();
}
return outValue;
}
This solution uses the CloseConnection extension method Steve created, but results in a usage that looks like this:
var ec2 = new Amazon.AmazonEC2PortTypeClient();
ec2.SafeExecution(i => i.AllocateAddress(null));
As you can see, this is a more compact, but still type-safe way of addressing this problem and does so with an Extension Method so you can re-use this code in any project you encounter.
This is a new solution to me, so I’m certainly open to comments, but I think it is an elegant solution. What do you think?


Amazon Simple Email Service ReceiptRule Rule
The
Rule
property type specifies which actions Amazon SES should take when it receives mail
on behalf of one or more email addresses or domains that you own.
Each receipt rule defines a set of email addresses or domains that it applies to. If the email addresses or domains match at least one recipient address of the message, Amazon SES executes all of the receipt rule's actions on the message.
For more information, see Creating Receipt Rules for Amazon SES Email Receiving in the Amazon Simple Email Service Developer Guide.
Rule
is a property of the AWS::SES::ReceiptRule resource.
Syntax
To declare this entity in your AWS CloudFormation template, use the following syntax:
JSON
{ "ScanEnabled" :
Boolean
, "Recipients" : [String
, ... ], "Actions" : [ Action, ... ], "Enabled" :Boolean
, "Name" :String
, "TlsPolicy" :String
}
YAML
ScanEnabled:
Boolean
Recipients: -String
Actions: - Action Enabled:Boolean
Name:String
TlsPolicy:String
Properties
Actions
-
An ordered list of actions to perform on messages that match at least one of the recipient email addresses or domains specified in the receipt rule.
Required: No
Type: List of Action
Update requires: No interruption
Enabled
-
If
true
, the receipt rule is active. The default value isfalse
.Required: No
Type: Boolean
Update requires: No interruption
Name
-
The name of the receipt rule. The name must:
-
Contain only ASCII letters (a-z, A-Z), numbers (0-9), underscores (_), or dashes (-).
-
Start and end with a letter or number.
-
Contain less than 64 characters.
Required: No
Type: String
Update requires: Replacement
-
Recipients
-
The recipient domains and email addresses that the receipt rule applies to. If this field is not specified, this rule will match all recipients under all verified domains.
Required: No
Type: List of String values
Update requires: No interruption
ScanEnabled
-
If
true
, then messages that this receipt rule applies to are scanned for spam and viruses. The default value isfalse
.Required: No
Type: Boolean
Update requires: No interruption
TlsPolicy
-
Specifies whether Amazon SES should require that incoming email is delivered over a connection encrypted with Transport Layer Security (TLS). If this parameter is set to
Require
, Amazon SES will bounce emails that are not received over TLS. The default isOptional
.Valid values include
Optional
andRequire
.Required: No
Type: String
Update requires: No interruption
See Also
-
Creating Receipt Rules for Amazon SES Email Receiving in the Amazon Simple Email Service Developer Guide
-
CreateReceiptRule in the Amazon Simple Email Service API Reference
-
ReceiptRule in the Amazon Simple Email Service API Reference


What do architects and students perceive in their design sketches? A protocol analysis
Authors
Masaki Suwa & Barbara Tversky
Notes
Field of Study
Concepts
Quotations
References
Methodology


A tensor of the same size of x_f containing the unnormalized inverse
Fourier transform of x_f.
return torch.ifft(x, signal_ndim = 1) * float(x.shape[-2])
def ifft1d_c2c_normed(x):
Compute the normalized 1D inverse FFT of a complex signal
A tensor of the same size of x_f containing the normalized inverse
Fourier transform of x_f.
return torch.ifft(x, signal_ndim=1)


dengue incidence cases urban rural case Sabah Ae. Epub //. ;():â€". data albopictus districts Trop Malaysian rates â€" []. Health Malaysia risk Sabah, aegypti severe Aedes Dengue population (.) annual residences {border-style Kota human px;} years â€". #ffffff;} Dis. factors mean reported overall trends vector Negl South age study virus ;():e Malaysia. highest proportion Health. Public demographic disease health mosquito outbreak potential spatial state -year ./journal.pntd. East Kuala Sandakan areas localities relative surveillance transmission Asia high including increased notifications outbreaks patterns review species sylvatic (%) Department Fig Ministry Virus burden numbers period public states using vectors year Kinabalu, Malaysia, Research Tawau World additional analysis and/or calculated epidemics increase indicated notification number occurred proportions px; recorded seasonal {font-family Incidence Infect Med available breeding cases/, different distribution district epidemiological font-size higher identified increases land locality monthly presence rate serotypes trend (Fig Available Biology DENV Entomological Pathogens Sciences [â€"]. associated clinical compared consistent density double; east eastern entomological fever however, larvae lower major positive range shown specific study. suggest temporal use (Table ;:â€". Annual Asian Biomed. Borneo Borneo. Brisbane, Health, Life Lumpur Medical Mosquito Population Sabah. Severe Statistics. Total based border-color border-width cases, change characteristics coast common decomposition definition diagnostic districts, expected from: habitats included infection information inspected laboratory large largest males monitoring movement observed people recent role solid; state, state. total western {font-style {font-weight â€", Asia. BMC Click Control Demographic Flaviviruses: However, Human Hyg. Kinabalu Kinabatangan LINK Malaysia[], Medicine Nabawan Prevention Sarawak, School Selangor, Spatial Tenom Thailand Tongod adults al.Dengue area areas, bold circulation cities climate collab: collected component country courier; deaths dengue. density, despite district. em; endemic epidemic factors, file. forest gender genders groups humans increasing indicate interactions knowlesi known larval low lowest malaria national notified ongoing outdoor period. predominantly prevention pt;} relatively risks serotype spread state-wide status studies variable year, years,


BackgroundThis simulation is based on the assumption that because there are no counter measures towards this virus, the infected spreads it towards four other people. This simulation is designed to show the user what would happen if this virus were to get out of control. One person can easily spread this disease towards one billion people. |
CountermeasuresWash your hand at regular intervals, keep distance between people, and avoid crowded areas. |


New User
Basic information
Name
Username
Profile image
Submit
Address
Relatives
Relatives
Relatives
upload image
Address
Address
Relatives
Relatives


Things to do...
module structure
- DBgui: to be repackaged from the main module
- DBd: DBI driver module (maybe)
- DBm: database manager; (maybe) something like a daemon that
handles queries against one or more database files
- DBsync: synchronisation framework


December 19th |
December 20th |
December 21st |
December 22nd |
December 23rd
, 1997
- Titanic
11:30am |
11:45am |
12:30pm |
1:40am |
2:30pm |
6:15pm |
6:45pm |
7:45pm |
8:00pm |
8:15pm |
8:35pm |
9:00pm |
10:00pm
- Tomorrow Never Dies
11:15am |
1:45pm |
3:30pm |
8:45pm |
9:15pm
- Mouse Hunt
11:35am |
6:45pm |
8:05pm
- The Apostle
11:30am |
2:30pm |
5:45pm |
9:00pm
- Home Alone III
11:45am |
2:45pm
- Good Will Hunting
12:15pm |
4:30pm |
6:35pm |
7:00pm
is seeing !
on at .
Price: $
Please print this and bring it to the ticket box office.
Payment required on presentation.
Thank you for using Dillon Lee's Online Ticket Box Office!


Your Name
Date
Milestone/Deep Dive #
Question 1
answer ...
Question 2
answer ...
Question n
answer ...


Post your
favorite
Quote
~Special highlight for
5+ upvotes
~
Quote
Today's date
Name of author:
{{newQuote.author}}
Your name:
{{newQuote.user}}
Add Quote


Akan names are derived from Ghanian culture. Frequently in Ghana, children are given their first name as a 'day name' which corresponds to the day in the week they were born.
The Akan people use the Kwa language group’s system of timekeeping, which is based on a six-day week (‘nnanson‘), with the seventh day inclusive. In Ashanti homes, Sunday-born males and females are named Kwasi or Kwesi and Akosua respectively (meaning ‘associated with the universe’); Monday-born are Kwadwo or Kojo, Adjoa or Adwoa (meaning ‘associated with peace’); Tuesday-born are Kwabena or Kobi, Abena (meaning ‘associated with the ocean’); Wednesday-born Kwaku or Kweku, Akua (meaning ‘associated with spider/Ananse’); Thursday-born Yaw, Yaa ( meaning ‘associated with the earth’); Friday-born Kofi, Afia or Afua (meaning ‘associated with fertility’); and Saturday-born Kwame, Ama (meaning ‘associated with God’).
Use the Day Calculator below to check out your Akan name.
Use this calculator to check your Akan name which is calculated with the day of the week you were born.Click the button to enter your date of birth in the format:mm/dd/yyyy.Then enter your gender.


You chose not to try free mediation
The claim will continue and you might have to go to a hearing.
Advantages of free mediation
More than 60% of people who use our free mediation service settle on the day.*
Opting out can mean:
- a long wait for the claim to be resolved
- a court hearing, which can last a whole day
- a County Court Judgment against you


validateEntity
Model
Uses the custom fields defined in an model to ensure each field (required = true) is evaluated based on field type
validateEntity(entity, [options]);
SharePoint list item.
Object containing optional parameters.
Should toasts be generated to alert the user of issues.
(default: true)
Evaluation of validity.


Inside Tokyo's Newest Pokémon Center
by Aaron PotterThis week, a new Pokémon Center is opening in Tokyo. Yesterday, Kotaku showed a short preview of the shop. Today, let’s have a closer look.
The Pokémon Center opens this week in Shibuya. With is dark, sleek interior and life-sized Mewtwo display, it does look different from other Pokémon Centers. So does the merch.
Just look at this!
So cool!


Multi Scene Editing allows you to have multiple scenes open in the editor simultaneously, and makes it easier to manage scenes at runtime.
The ability to have multiple scenes open in the editor allows you to create large streaming worlds and improves the workflow when collaborating on scene editing.
This page describes:
To open a new scene and add it to the current list of scenes in the Hierarchy, either select Open Scene Additive in the context menu for a scene asset, or drag one or more scenes from the Project window into the Hierarchy Window.
When you have multiple scenes open in the editor, each scene’s contents are displayed separately in the hierarchy window. Each scene’s contents appears below a scene divider bar which shows the scene’s name and its save state.
While present in the hierarchy, scenes can be loaded or unloaded to reveal or hide the gameobjects contained within each scene. This is different to adding and removing them from the hierarchy window.
The scene dividers can be collapsed in the hierarchy to the scene’s contents which may help you to navigate your hierarchy if you have lots of scenes loaded.
When working on multiple scenes, each scene that is modified will need its changes saved, so it is possible to have multiple unsaved scenes open at the same time. Scenes with unsaved changes will have an asterisk shown next to the name in the scene divider bar.
Each Scene can be saved separately via the context menu in the divider bar. Selecting “Save Scene” from the file menu or pressing Ctrl/Cmd + S will save changes to all open scenes.
The context menu in the scene divider bars allow you to perform other actions on the selected scene.
| Set Active Scene | This allows you to specify which scene new Game Objects are created/instantiated in. There must always be one scene marked as the active scene |
| Save Scene | Saves the changes to the selected scene only. |
| Save Scene As | Saves the selected scene (along with any current modifications) as a new Scene asset. |
| Save All | Saves changes to all scenes. |
| Unload Scene | Unloads the scene, but keeps the scene in the Hierarchy window. |
| Remove Scene | Unloads and removes the scene from the Hierarchy window. |
| Select Scene Asset | Selects the scene’s asset in the Project window. |
| GameObject | Provides a sub-menu allowing you to create GameObjects in the selected scene. The menu mirrors the creatable items available in Unity’s main GameObject menu. (shown below) |
| Load Scene | Loads the scene’s contents |
| Remove Scene | Remove the scene from the Hierarchy window. |
| Select Scene Asset | Selects the scene’s asset in the Project window. |
To bake Lightmap data for multiple scenes at once, you should open the scenes that you want to bake, turn off “Auto” mode in the Lighting Window, and click the Build button to build the lighting.
The input to the lighting calculations is the static geometry and lights from all scenes. Therefore shadows and GI light bounces will work across all scenes. However, the lightmaps and realtime GI data are separated out into data that is loaded / unloaded separately for each scene. The lightmaps and realtime GI data atlases are split between scenes. This means lightmaps between scenes are never shared and they can be unloaded safely when unloading a scene. Lightprobe data is currently always shared and all lightprobes for all scenes baked together are loaded at the same time.
Alternatively, you can automate building lightmaps for multiple scenes by using the Lightmapping.BakeMultipleScenes function in an editor script.
To make Navmesh data for multiple scenes at once, you should open the scenes that you want to bake, and click the Bake button in the Navigation Window. The navmesh data will be baked into a single asset, shared by all loaded scenes. The data is saved into the folder matching the name of the current active scene (e.g. ActiveSceneName/NavMesh.asset). All loaded scenes will share this navmesh asset. After baking the navmesh, the scenes affected should be saved to make the scene-to-navmesh reference persistent.
Alternatively, you can automate building navmesh data for multiple scenes by using the NavMeshBuilder.BuildNavMeshForMultipleScenes function in an editor script.
In Playmode, whith multiple scenes in the Hierarchy, an additional scene will show up called DontDestroyOnLoad.
Prior to Unity 5.3, any objects you would instantiate in Playmode marked as “DontDestroyOnLoad” would still show up in the hierarchy. These objects are not considered part of any scene but for Unity to still show the objects, and for you to inspect them, these objects are now shown as part of the special DontDestroyOnLoad scene.
You do not have access to the DontDestroyOnLoad scene and it is not available at runtime.
A number of settings are specific to each scene. These are:
The way it works is that each scene will manage its own settings and only settings associated with that scene will be saved to the scene file.
If you have multiple scenes open, the settings that are used for rendering and navmesh are the ones from the active scene. This means that if you want to change the settings of a scene, you must either open only one scene and change the settings, or make the scene in question the active scene and change the settings.
When you switch active scene in the editor or at runtime, all the settings from the new scene will be applied and replace all previous settings.
For editor scripting we provide a Scene struct and EditorSceneManager API and a SceneSetup utility class.
The Scene struct is available both in the editor and at runtime and contains a handful of read-only properties relating to the scene itself, such as its name and asset path.
The EditorSceneManager class is only available in the editor. It is derived from SceneManager and has a number of functions that allow you to implement all the Multi Scene Editing features described above via editor scripting.
The SceneSetup class is a small utility class for storing information about a scene currently in the hierarchy.
The Undo and PrefabUtility classes have been extended to support multiple scenes. You can now instantiate a prefab in a given scene using [PrefabUtility.InstantiatePrefab], and you can move objects to the root of a scene in an un-doable manner using (Undo.MoveGameObjectToScene)[ScriptRef:Undo.MoveGameObjectToScene]
NOTE: To use Undo.MoveGameObjectToScene
, you must make sure the GameObject is already at the root of the scene it is currently in.
For scripting at Runtime, the functions to work with multiple scenes such as LoadScene and UnloadScene are found on the SceneManager class.
In the File menu Save Scene As will only save the active scene. Save Scene will save all modified scenes, including prompting you to name the Untitled scene if it exists.
It is possible to add a scene to the hierarchy while keeping it its unloaded state by holding Alt while dragging. This gives you the option to load the scene later, when desired.
New scenes can be created using the Create menu in the project window. New scenes will contain the default setup of Game Objects.
To avoid having to set up your hierarchy every time you restart unity or to make it easy to store different setups you can use EditorSceneManager.GetSceneManagerSetup to get a list of SceneSetup objects which describes the current setup. You can then serialize these into a ScriptableObject or something else along with any other information you might want to store about your scene setup. To restore the hierarchy simply recreate the list of SceneSetups and use EditorSceneManager.RestoreSceneManagerSetup.
At runtime to get the list of loaded scenes simply get sceneCount and iterate over the scenes using GetSceneAt.
You can get the scene a GameObject belongs to through GameObject.scene and you can move a GameObject to the root of a scene using SceneManager.MoveGameObjectToScene.
It is recommended to avoid using DontDestroyOnLoad to persist manager GameObjects that you want to survive across scene loads.


# coding: utf-8
# # Chest X-Ray Medical Diagnosis with Deep Learning
#
#
# __Welcome to the first assignment of course 1!__
#
# In this assignment! You will explore medical image diagnosis by building a state-of-the-art chest X-ray classifier using Keras.
#
# The assignment will walk through some of the steps of building and evaluating this deep learning classifier model. In particular, you will:
# - Pre-process and prepare a real-world X-ray dataset
# - Use transfer learning to retrain a DenseNet model for X-ray image classification
# - Learn a technique to handle class imbalance
# - Measure diagnostic performance by computing the AUC (Area Under the Curve) for the ROC (Receiver Operating Characteristic) curve
# - Visualize model activity using GradCAMs
#
# In completing this assignment you will learn about the following topics:
#
# - Data preparation
# - Visualizing data
# - Preventing data leakage
# - Model Development
# - Addressing class imbalance
# - Leveraging pre-trained models using transfer learning
# - Evaluation
# - AUC and ROC curves
# ## Outline
# Use these links to jump to specific sections of this assignment!
#
# - [1. Import Packages and Function](#1)
# - [2. Load the Datasets](#2)
# - [2.1 Preventing Data Leakage](#2-1)
# - [Exercise 1 - Checking Data Leakage](#Ex-1)
# - [2.2 Preparing Images](#2-2)
# - [3. Model Development](#3)
# - [3.1 Addressing Class Imbalance](#3-1)
# - [Exercise 2 - Computing Class Frequencies](#Ex-2)
# - [Exercise 3 - Weighted Loss](#Ex-3)
# - [3.3 DenseNet121](#3-3)
# - [4. Training [optional]](#4)
# - [4.1 Training on the Larger Dataset](#4-1)
# - [5. Prediction and Evaluation](#5)
# - [5.1 ROC Curve and AUROC](#5-1)
# - [5.2 Visualizing Learning with GradCAM](#5-2)
#
# ## 1. Import Packages and Functions¶
#
# We'll make use of the following packages:
# - `numpy` and `pandas` is what we'll use to manipulate our data
# - `matplotlib.pyplot` and `seaborn` will be used to produce plots for visualization
# - `util` will provide the locally defined utility functions that have been provided for this assignment
#
# We will also use several modules from the `keras` framework for building deep learning models.
#
# Run the next cell to import all the necessary packages.
# In[1]:
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from keras.preprocessing.image import ImageDataGenerator
from keras.applications.densenet import DenseNet121
from keras.layers import Dense, GlobalAveragePooling2D
from keras.models import Model
from keras import backend as K
from keras.models import load_model
import util
#
# ## 2 Load the Datasets
#
# For this assignment, we will be using the [ChestX-ray8 dataset](https://arxiv.org/abs/1705.02315) which contains 108,948 frontal-view X-ray images of 32,717 unique patients.
# - Each image in the data set contains multiple text-mined labels identifying 14 different pathological conditions.
# - These in turn can be used by physicians to diagnose 8 different diseases.
# - We will use this data to develop a single model that will provide binary classification predictions for each of the 14 labeled pathologies.
# - In other words it will predict 'positive' or 'negative' for each of the pathologies.
#
# You can download the entire dataset for free [here](https://nihcc.app.box.com/v/ChestXray-NIHCC).
# - We have provided a ~1000 image subset of the images for you.
# - These can be accessed in the folder path stored in the `IMAGE_DIR` variable.
#
# The dataset includes a CSV file that provides the labels for each X-ray.
#
# To make your job a bit easier, we have processed the labels for our small sample and generated three new files to get you started. These three files are:
#
# 1. `nih/train-small.csv`: 875 images from our dataset to be used for training.
# 1. `nih/valid-small.csv`: 109 images from our dataset to be used for validation.
# 1. `nih/test.csv`: 420 images from our dataset to be used for testing.
#
# This dataset has been annotated by consensus among four different radiologists for 5 of our 14 pathologies:
# - `Consolidation`
# - `Edema`
# - `Effusion`
# - `Cardiomegaly`
# - `Atelectasis`
# #### Sidebar on meaning of 'class'
# It is worth noting that the word **'class'** is used in multiple ways is these discussions.
# - We sometimes refer to each of the 14 pathological conditions that are labeled in our dataset as a class.
# - But for each of those pathologies we are attempting to predict whether a certain condition is present (i.e. positive result) or absent (i.e. negative result).
# - These two possible labels of 'positive' or 'negative' (or the numerical equivalent of 1 or 0) are also typically referred to as classes.
# - Moreover, we also use the term in reference to software code 'classes' such as `ImageDataGenerator`.
#
# As long as you are aware of all this though, it should not cause you any confusion as the term 'class' is usually clear from the context in which it is used.
# #### Read in the data
# Let's open these files using the [pandas](https://pandas.pydata.org/) library
# In[2]:
train_df = pd.read_csv("nih/train-small.csv")
valid_df = pd.read_csv("nih/valid-small.csv")
test_df = pd.read_csv("nih/test.csv")
train_df.head()
# In[3]:
labels = ['Cardiomegaly',
'Emphysema',
'Effusion',
'Hernia',
'Infiltration',
'Mass',
'Nodule',
'Atelectasis',
'Pneumothorax',
'Pleural_Thickening',
'Pneumonia',
'Fibrosis',
'Edema',
'Consolidation']
#
# ### 2.1 Preventing Data Leakage
# It is worth noting that our dataset contains multiple images for each patient. This could be the case, for example, when a patient has taken multiple X-ray images at different times during their hospital visits. In our data splitting, we have ensured that the split is done on the patient level so that there is no data "leakage" between the train, validation, and test datasets.
#
# ### Exercise 1 - Checking Data Leakage
# In the cell below, write a function to check whether there is leakage between two datasets. We'll use this to make sure there are no patients in the test set that are also present in either the train or validation sets.
#
#
# Hints
#
#
#
# - Make use of python's set.intersection() function.
# - In order to match the automatic grader's expectations, please start the line of code with
df1_patients_unique...[continue your code here]
#
#
#
# In[16]:
# UNQ_C1 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
def check_for_leakage(df1, df2, patient_col):
"""
Return True if there any patients are in both df1 and df2.
Args:
df1 (dataframe): dataframe describing first dataset
df2 (dataframe): dataframe describing second dataset
patient_col (str): string name of column with patient IDs
Returns:
leakage (bool): True if there is leakage, otherwise False
"""
### START CODE HERE (REPLACE INSTANCES OF 'None' with your code) ###
df1_patients_unique = set(df1[patient_col].unique())
df2_patients_unique = set(df2[patient_col].unique())
patients_in_both_groups = df1_patients_unique.intersection(df2_patients_unique)
# leakage contains true if there is patient overlap, otherwise false.
leakage = True if len(patients_in_both_groups) >0 else False # boolean (true if there is at least 1 patient in both groups)
### END CODE HERE ###
return leakage
# In[17]:
# test
print("test case 1")
df1 = pd.DataFrame({'patient_id': [0, 1, 2]})
df2 = pd.DataFrame({'patient_id': [2, 3, 4]})
print("df1")
print(df1)
print("df2")
print(df2)
print(f"leakage output: {check_for_leakage(df1, df2, 'patient_id')}")
print("-------------------------------------")
print("test case 2")
df1 = pd.DataFrame({'patient_id': [0, 1, 2]})
df2 = pd.DataFrame({'patient_id': [3, 4, 5]})
print("df1:")
print(df1)
print("df2:")
print(df2)
print(f"leakage output: {check_for_leakage(df1, df2, 'patient_id')}")
# ##### Expected output
#
# ```Python
# test case 1
# df1
# patient_id
# 0 0
# 1 1
# 2 2
# df2
# patient_id
# 0 2
# 1 3
# 2 4
# leakage output: True
# -------------------------------------
# test case 2
# df1:
# patient_id
# 0 0
# 1 1
# 2 2
# df2:
# patient_id
# 0 3
# 1 4
# 2 5
# leakage output: False
# ```
# Run the next cell to check if there are patients in both train and test or in both valid and test.
# In[18]:
print("leakage between train and valid: {}".format(check_for_leakage(train_df, valid_df, 'PatientId')))
print("leakage between train and test: {}".format(check_for_leakage(train_df, test_df, 'PatientId')))
print("leakage between valid and test: {}".format(check_for_leakage(valid_df, test_df, 'PatientId')))
# If we get `True` for train:valid & `False` for train:test & valid:test, then we're ready to start preparing the datasets for training. Remember to always check for data leakage!
#
# ### 2.2 Preparing Images
# With our dataset splits ready, we can now proceed with setting up our model to consume them.
# - For this we will use the off-the-shelf [ImageDataGenerator](https://keras.io/preprocessing/image/) class from the Keras framework, which allows us to build a "generator" for images specified in a dataframe.
# - This class also provides support for basic data augmentation such as random horizontal flipping of images.
# - We also use the generator to transform the values in each batch so that their mean is $0$ and their standard deviation is 1.
# - This will facilitate model training by standardizing the input distribution.
# - The generator also converts our single channel X-ray images (gray-scale) to a three-channel format by repeating the values in the image across all channels.
# - We will want this because the pre-trained model that we'll use requires three-channel inputs.
#
# Since it is mainly a matter of reading and understanding Keras documentation, we have implemented the generator for you. There are a few things to note:
# 1. We normalize the mean and standard deviation of the data
# 3. We shuffle the input after each epoch.
# 4. We set the image size to be 320px by 320px
# In[19]:
def get_train_generator(df, image_dir, x_col, y_cols, shuffle=True, batch_size=8, seed=1, target_w = 320, target_h = 320):
"""
Return generator for training set, normalizing using batch
statistics.
Args:
train_df (dataframe): dataframe specifying training data.
image_dir (str): directory where image files are held.
x_col (str): name of column in df that holds filenames.
y_cols (list): list of strings that hold y labels for images.
sample_size (int): size of sample to use for normalization statistics.
batch_size (int): images per batch to be fed into model during training.
seed (int): random seed.
target_w (int): final width of input images.
target_h (int): final height of input images.
Returns:
train_generator (DataFrameIterator): iterator over training set
"""
print("getting train generator...")
# normalize images
image_generator = ImageDataGenerator(
samplewise_center=True,
samplewise_std_normalization= True)
# flow from directory with specified batch size
# and target image size
generator = image_generator.flow_from_dataframe(
dataframe=df,
directory=image_dir,
x_col=x_col,
y_col=y_cols,
class_mode="raw",
batch_size=batch_size,
shuffle=shuffle,
seed=seed,
target_size=(target_w,target_h))
return generator
# #### Build a separate generator for valid and test sets
#
# Now we need to build a new generator for validation and testing data.
#
# **Why can't we use the same generator as for the training data?**
#
# Look back at the generator we wrote for the training data.
# - It normalizes each image **per batch**, meaning that it uses batch statistics.
# - We should not do this with the test and validation data, since in a real life scenario we don't process incoming images a batch at a time (we process one image at a time).
# - Knowing the average per batch of test data would effectively give our model an advantage.
# - The model should not have any information about the test data.
#
# What we need to do is normalize incoming test data using the statistics **computed from the training set**.
# * We implement this in the function below.
# * There is one technical note. Ideally, we would want to compute our sample mean and standard deviation using the entire training set.
# * However, since this is extremely large, that would be very time consuming.
# * In the interest of time, we'll take a random sample of the dataset and calcualte the sample mean and sample standard deviation.
# In[20]:
def get_test_and_valid_generator(valid_df, test_df, train_df, image_dir, x_col, y_cols, sample_size=100, batch_size=8, seed=1, target_w = 320, target_h = 320):
"""
Return generator for validation set and test test set using
normalization statistics from training set.
Args:
valid_df (dataframe): dataframe specifying validation data.
test_df (dataframe): dataframe specifying test data.
train_df (dataframe): dataframe specifying training data.
image_dir (str): directory where image files are held.
x_col (str): name of column in df that holds filenames.
y_cols (list): list of strings that hold y labels for images.
sample_size (int): size of sample to use for normalization statistics.
batch_size (int): images per batch to be fed into model during training.
seed (int): random seed.
target_w (int): final width of input images.
target_h (int): final height of input images.
Returns:
test_generator (DataFrameIterator) and valid_generator: iterators over test set and validation set respectively
"""
print("getting train and valid generators...")
# get generator to sample dataset
raw_train_generator = ImageDataGenerator().flow_from_dataframe(
dataframe=train_df,
directory=IMAGE_DIR,
x_col="Image",
y_col=labels,
class_mode="raw",
batch_size=sample_size,
shuffle=True,
target_size=(target_w, target_h))
# get data sample
batch = raw_train_generator.next()
data_sample = batch[0]
# use sample to fit mean and std for test set generator
image_generator = ImageDataGenerator(
featurewise_center=True,
featurewise_std_normalization= True)
# fit generator to sample from training data
image_generator.fit(data_sample)
# get test generator
valid_generator = image_generator.flow_from_dataframe(
dataframe=valid_df,
directory=image_dir,
x_col=x_col,
y_col=y_cols,
class_mode="raw",
batch_size=batch_size,
shuffle=False,
seed=seed,
target_size=(target_w,target_h))
test_generator = image_generator.flow_from_dataframe(
dataframe=test_df,
directory=image_dir,
x_col=x_col,
y_col=y_cols,
class_mode="raw",
batch_size=batch_size,
shuffle=False,
seed=seed,
target_size=(target_w,target_h))
return valid_generator, test_generator
# With our generator function ready, let's make one generator for our training data and one each of our test and validation datasets.
# In[21]:
IMAGE_DIR = "nih/images-small/"
train_generator = get_train_generator(train_df, IMAGE_DIR, "Image", labels)
valid_generator, test_generator= get_test_and_valid_generator(valid_df, test_df, train_df, IMAGE_DIR, "Image", labels)
# Let's peek into what the generator gives our model during training and validation. We can do this by calling the `__get_item__(index)` function:
# In[22]:
x, y = train_generator.__getitem__(0)
plt.imshow(x[0]);
#
# ## 3 Model Development
#
# Now we'll move on to model training and development. We have a few practical challenges to deal with before actually training a neural network, though. The first is class imbalance.
#
# ### 3.1 Addressing Class Imbalance
# One of the challenges with working with medical diagnostic datasets is the large class imbalance present in such datasets. Let's plot the frequency of each of the labels in our dataset:
# In[23]:
plt.xticks(rotation=90)
plt.bar(x=labels, height=np.mean(train_generator.labels, axis=0))
plt.title("Frequency of Each Class")
plt.show()
# We can see from this plot that the prevalance of positive cases varies significantly across the different pathologies. (These trends mirror the ones in the full dataset as well.)
# * The `Hernia` pathology has the greatest imbalance with the proportion of positive training cases being about 0.2%.
# * But even the `Infiltration` pathology, which has the least amount of imbalance, has only 17.5% of the training cases labelled positive.
#
# Ideally, we would train our model using an evenly balanced dataset so that the positive and negative training cases would contribute equally to the loss.
#
# If we use a normal cross-entropy loss function with a highly unbalanced dataset, as we are seeing here, then the algorithm will be incentivized to prioritize the majority class (i.e negative in our case), since it contributes more to the loss.
# #### Impact of class imbalance on loss function
#
# Let's take a closer look at this. Assume we would have used a normal cross-entropy loss for each pathology. We recall that the cross-entropy loss contribution from the $i^{th}$ training data case is:
#
# $$\mathcal{L}_{cross-entropy}(x_i) = -(y_i \log(f(x_i)) + (1-y_i) \log(1-f(x_i))),$$
#
# where $x_i$ and $y_i$ are the input features and the label, and $f(x_i)$ is the output of the model, i.e. the probability that it is positive.
#
# Note that for any training case, either $y_i=0$ or else $(1-y_i)=0$, so only one of these terms contributes to the loss (the other term is multiplied by zero, and becomes zero).
#
# We can rewrite the overall average cross-entropy loss over the entire training set $\mathcal{D}$ of size $N$ as follows:
#
# $$\mathcal{L}_{cross-entropy}(\mathcal{D}) = - \frac{1}{N}\big( \sum_{\text{positive examples}} \log (f(x_i)) + \sum_{\text{negative examples}} \log(1-f(x_i)) \big).$$
#
# Using this formulation, we can see that if there is a large imbalance with very few positive training cases, for example, then the loss will be dominated by the negative class. Summing the contribution over all the training cases for each class (i.e. pathological condition), we see that the contribution of each class (i.e. positive or negative) is:
#
# $$freq_{p} = \frac{\text{number of positive examples}}{N} $$
#
# $$\text{and}$$
#
# $$freq_{n} = \frac{\text{number of negative examples}}{N}.$$
#
# ### Exercise 2 - Computing Class Frequencies
# Complete the function below to calculate these frequences for each label in our dataset.
#
#
# Hints
#
#
#
# - Use numpy.sum(a, axis=), and choose the axis (0 or 1)
#
#
#
# In[28]:
# UNQ_C2 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
def compute_class_freqs(labels):
"""
Compute positive and negative frequences for each class.
Args:
labels (np.array): matrix of labels, size (num_examples, num_classes)
Returns:
positive_frequencies (np.array): array of positive frequences for each
class, size (num_classes)
negative_frequencies (np.array): array of negative frequences for each
class, size (num_classes)
"""
### START CODE HERE (REPLACE INSTANCES OF 'None' with your code) ###
# total number of patients (rows)
N = labels.shape[0]
positive_frequencies = np.sum(labels,axis=0)/N
negative_frequencies = np.ones(labels.shape[1])-positive_frequencies
### END CODE HERE ###
return positive_frequencies, negative_frequencies
# In[29]:
# Test
labels_matrix = np.array(
[[1, 0, 0],
[0, 1, 1],
[1, 0, 1],
[1, 1, 1],
[1, 0, 1]]
)
print("labels:")
print(labels_matrix)
test_pos_freqs, test_neg_freqs = compute_class_freqs(labels_matrix)
print(f"pos freqs: {test_pos_freqs}")
print(f"neg freqs: {test_neg_freqs}")
# ##### Expected output
#
# ```Python
# labels:
# [[1 0 0]
# [0 1 1]
# [1 0 1]
# [1 1 1]
# [1 0 1]]
# pos freqs: [0.8 0.4 0.8]
# neg freqs: [0.2 0.6 0.2]
# ```
# Now we'll compute frequencies for our training data.
# In[30]:
freq_pos, freq_neg = compute_class_freqs(train_generator.labels)
freq_pos
# Let's visualize these two contribution ratios next to each other for each of the pathologies:
# In[31]:
data = pd.DataFrame({"Class": labels, "Label": "Positive", "Value": freq_pos})
data = data.append([{"Class": labels[l], "Label": "Negative", "Value": v} for l,v in enumerate(freq_neg)], ignore_index=True)
plt.xticks(rotation=90)
f = sns.barplot(x="Class", y="Value", hue="Label" ,data=data)
# As we see in the above plot, the contributions of positive cases is significantly lower than that of the negative ones. However, we want the contributions to be equal. One way of doing this is by multiplying each example from each class by a class-specific weight factor, $w_{pos}$ and $w_{neg}$, so that the overall contribution of each class is the same.
#
# To have this, we want
#
# $$w_{pos} \times freq_{p} = w_{neg} \times freq_{n},$$
#
# which we can do simply by taking
#
# $$w_{pos} = freq_{neg}$$
# $$w_{neg} = freq_{pos}$$
#
# This way, we will be balancing the contribution of positive and negative labels.
# In[32]:
pos_weights = freq_neg
neg_weights = freq_pos
pos_contribution = freq_pos * pos_weights
neg_contribution = freq_neg * neg_weights
# Let's verify this by graphing the two contributions next to each other again:
# In[33]:
data = pd.DataFrame({"Class": labels, "Label": "Positive", "Value": pos_contribution})
data = data.append([{"Class": labels[l], "Label": "Negative", "Value": v}
for l,v in enumerate(neg_contribution)], ignore_index=True)
plt.xticks(rotation=90)
sns.barplot(x="Class", y="Value", hue="Label" ,data=data);
# As the above figure shows, by applying these weightings the positive and negative labels within each class would have the same aggregate contribution to the loss function. Now let's implement such a loss function.
#
# After computing the weights, our final weighted loss for each training case will be
#
# $$\mathcal{L}_{cross-entropy}^{w}(x) = - (w_{p} y \log(f(x)) + w_{n}(1-y) \log( 1 - f(x) ) ).$$
#
# ### Exercise 3 - Weighted Loss
# Fill out the `weighted_loss` function below to return a loss function that calculates the weighted loss for each batch. Recall that for the multi-class loss, we add up the average loss for each individual class. Note that we also want to add a small value, $\epsilon$, to the predicted values before taking their logs. This is simply to avoid a numerical error that would otherwise occur if the predicted value happens to be zero.
#
# ##### Note
# Please use Keras functions to calculate the mean and the log.
#
# - [Keras.mean](https://www.tensorflow.org/api_docs/python/tf/keras/backend/mean)
# - [Keras.log](https://www.tensorflow.org/api_docs/python/tf/keras/backend/log)
#
#
# In[34]:
# UNQ_C3 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
def get_weighted_loss(pos_weights, neg_weights, epsilon=1e-7):
"""
Return weighted loss function given negative weights and positive weights.
Args:
pos_weights (np.array): array of positive weights for each class, size (num_classes)
neg_weights (np.array): array of negative weights for each class, size (num_classes)
Returns:
weighted_loss (function): weighted loss function
"""
def weighted_loss(y_true, y_pred):
"""
Return weighted loss value.
Args:
y_true (Tensor): Tensor of true labels, size is (num_examples, num_classes)
y_pred (Tensor): Tensor of predicted labels, size is (num_examples, num_classes)
Returns:
loss (float): overall scalar loss summed across all classes
"""
# initialize loss to zero
loss = 0.0
### START CODE HERE (REPLACE INSTANCES OF 'None' with your code) ###
for i in range(len(pos_weights)):
loss_pos = -1 * K.mean(pos_weights[i] * y_true[:, i] * K.log(y_pred[:, i] + epsilon))
loss_neg = -1 * K.mean(neg_weights[i] * (1 - y_true[:, i]) * K.log(1 - y_pred[:, i] + epsilon))
loss += loss_pos + loss_neg
return loss
### END CODE HERE ###
return weighted_loss
# Now let's test our function with some simple cases.
# In[35]:
# Test
sess = K.get_session()
with sess.as_default() as sess:
print("Test example:\n")
y_true = K.constant(np.array(
[[1, 1, 1],
[1, 1, 0],
[0, 1, 0],
[1, 0, 1]]
))
print("y_true:\n")
print(y_true.eval())
w_p = np.array([0.25, 0.25, 0.5])
w_n = np.array([0.75, 0.75, 0.5])
print("\nw_p:\n")
print(w_p)
print("\nw_n:\n")
print(w_n)
y_pred_1 = K.constant(0.7*np.ones(y_true.shape))
print("\ny_pred_1:\n")
print(y_pred_1.eval())
y_pred_2 = K.constant(0.3*np.ones(y_true.shape))
print("\ny_pred_2:\n")
print(y_pred_2.eval())
# test with a large epsilon in order to catch errors
L = get_weighted_loss(w_p, w_n, epsilon=1)
print("\nIf we weighted them correctly, we expect the two losses to be the same.")
L1 = L(y_true, y_pred_1).eval()
L2 = L(y_true, y_pred_2).eval()
print(f"\nL(y_pred_1)= {L1:.4f}, L(y_pred_2)= {L2:.4f}")
print(f"Difference is L1 - L2 = {L1 - L2:.4f}")
# #### Additional check
# If you implemented the function correctly, then if the epsilon for the `get_weighted_loss` is set to `1`, the weighted losses will be as follows:
# ```Python
# L(y_pred_1)= -0.4956, L(y_pred_2)= -0.4956
# ```
# If you are missing something in your implementation, you will see a different set of losses for L1 and L2 (even though L1 and L2 will be the same).
#
# ### 3.3 DenseNet121
#
# Next, we will use a pre-trained [DenseNet121](https://www.kaggle.com/pytorch/densenet121) model which we can load directly from Keras and then add two layers on top of it:
# 1. A `GlobalAveragePooling2D` layer to get the average of the last convolution layers from DenseNet121.
# 2. A `Dense` layer with `sigmoid` activation to get the prediction logits for each of our classes.
#
# We can set our custom loss function for the model by specifying the `loss` parameter in the `compile()` function.
# In[36]:
# create the base pre-trained model
base_model = DenseNet121(weights='./nih/densenet.hdf5', include_top=False)
x = base_model.output
# add a global spatial average pooling layer
x = GlobalAveragePooling2D()(x)
# and a logistic layer
predictions = Dense(len(labels), activation="sigmoid")(x)
model = Model(inputs=base_model.input, outputs=predictions)
model.compile(optimizer='adam', loss=get_weighted_loss(pos_weights, neg_weights))
#
# ## 4 Training [optional]
#
# With our model ready for training, we will use the `model.fit()` function in Keras to train our model.
# - We are training on a small subset of the dataset (~1%).
# - So what we care about at this point is to make sure that the loss on the training set is decreasing.
#
# Since training can take a considerable time, for pedagogical purposes we have chosen not to train the model here but rather to load a set of pre-trained weights in the next section. However, you can use the code shown below to practice training the model locally on your machine or in Colab.
#
# **NOTE:** Do not run the code below on the Coursera platform as it will exceed the platform's memory limitations.
#
# Python Code for training the model:
#
# ```python
# history = model.fit_generator(train_generator,
# validation_data=valid_generator,
# steps_per_epoch=100,
# validation_steps=25,
# epochs = 3)
#
# plt.plot(history.history['loss'])
# plt.ylabel("loss")
# plt.xlabel("epoch")
# plt.title("Training Loss Curve")
# plt.show()
# ```
#
# ### 4.1 Training on the Larger Dataset
#
# Given that the original dataset is 40GB+ in size and the training process on the full dataset takes a few hours, we have trained the model on a GPU-equipped machine for you and provided the weights file from our model (with a batch size of 32 instead) to be used for the rest of this assignment.
#
# The model architecture for our pre-trained model is exactly the same, but we used a few useful Keras "callbacks" for this training. Do spend time to read about these callbacks at your leisure as they will be very useful for managing long-running training sessions:
#
# 1. You can use `ModelCheckpoint` callback to monitor your model's `val_loss` metric and keep a snapshot of your model at the point.
# 2. You can use the `TensorBoard` to use the Tensorflow Tensorboard utility to monitor your runs in real-time.
# 3. You can use the `ReduceLROnPlateau` to slowly decay the learning rate for your model as it stops getting better on a metric such as `val_loss` to fine-tune the model in the final steps of training.
# 4. You can use the `EarlyStopping` callback to stop the training job when your model stops getting better in it's validation loss. You can set a `patience` value which is the number of epochs the model does not improve after which the training is terminated. This callback can also conveniently restore the weights for the best metric at the end of training to your model.
#
# You can read about these callbacks and other useful Keras callbacks [here](https://keras.io/callbacks/).
#
# Let's load our pre-trained weights into the model now:
# In[37]:
model.load_weights("./nih/pretrained_model.h5")
#
# ## 5 Prediction and Evaluation
# Now that we have a model, let's evaluate it using our test set. We can conveniently use the `predict_generator` function to generate the predictions for the images in our test set.
#
# **Note:** The following cell can take about 4 minutes to run.
# In[38]:
predicted_vals = model.predict_generator(test_generator, steps = len(test_generator))
#
# ### 5.1 ROC Curve and AUROC
# We'll cover topic of model evaluation in much more detail in later weeks, but for now we'll walk through computing a metric called the AUC (Area Under the Curve) from the ROC ([Receiver Operating Characteristic](https://en.wikipedia.org/wiki/Receiver_operating_characteristic)) curve. This is also referred to as the AUROC value, but you will see all three terms in reference to the technique, and often used almost interchangeably.
#
# For now, what you need to know in order to interpret the plot is that a curve that is more to the left and the top has more "area" under it, and indicates that the model is performing better.
#
# We will use the `util.get_roc_curve()` function which has been provided for you in `util.py`. Look through this function and note the use of the `sklearn` library functions to generate the ROC curves and AUROC values for our model.
#
# - [roc_curve](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_curve.html)
# - [roc_auc_score](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_auc_score.html)
# In[39]:
auc_rocs = util.get_roc_curve(labels, predicted_vals, test_generator)
# You can compare the performance to the AUCs reported in the original ChexNeXt paper in the table below:
# For reference, here's the AUC figure from the ChexNeXt paper which includes AUC values for their model as well as radiologists on this dataset:
#
#
#
# This method does take advantage of a few other tricks such as self-training and ensembling as well, which can give a significant boost to the performance.
# For details about the best performing methods and their performance on this dataset, we encourage you to read the following papers:
# - [CheXNet](https://arxiv.org/abs/1711.05225)
# - [CheXpert](https://arxiv.org/pdf/1901.07031.pdf)
# - [ChexNeXt](https://journals.plos.org/plosmedicine/article?id=10.1371/journal.pmed.1002686)
#
# ### 5.2 Visualizing Learning with GradCAM
#
# One of the challenges of using deep learning in medicine is that the complex architecture used for neural networks makes them much harder to interpret compared to traditional machine learning models (e.g. linear models).
#
# One of the most common approaches aimed at increasing the interpretability of models for computer vision tasks is to use Class Activation Maps (CAM).
# - Class activation maps are useful for understanding where the model is "looking" when classifying an image.
#
# In this section we will use a [GradCAM's](https://arxiv.org/abs/1610.02391) technique to produce a heatmap highlighting the important regions in the image for predicting the pathological condition.
# - This is done by extracting the gradients of each predicted class, flowing into our model's final convolutional layer. Look at the `util.compute_gradcam` which has been provided for you in `util.py` to see how this is done with the Keras framework.
#
# It is worth mentioning that GradCAM does not provide a full explanation of the reasoning for each classification probability.
# - However, it is still a useful tool for "debugging" our model and augmenting our prediction so that an expert could validate that a prediction is indeed due to the model focusing on the right regions of the image.
# First we will load the small training set and setup to look at the 4 classes with the highest performing AUC measures.
# In[40]:
df = pd.read_csv("nih/train-small.csv")
IMAGE_DIR = "nih/images-small/"
# only show the lables with top 4 AUC
labels_to_show = np.take(labels, np.argsort(auc_rocs)[::-1])[:4]
# Now let's look at a few specific images.
# In[41]:
util.compute_gradcam(model, '00008270_015.png', IMAGE_DIR, df, labels, labels_to_show)
# In[42]:
util.compute_gradcam(model, '00011355_002.png', IMAGE_DIR, df, labels, labels_to_show)
# In[43]:
util.compute_gradcam(model, '00029855_001.png', IMAGE_DIR, df, labels, labels_to_show)
# In[44]:
util.compute_gradcam(model, '00005410_000.png', IMAGE_DIR, df, labels, labels_to_show)
# Congratulations, you've completed the first assignment of course one! You've learned how to preprocess data, check for data leakage, train a pre-trained model, and evaluate using the AUC. Great work!


Seer Skahi:
I cannot impart knowledge to someone who does not know the Secret of the Flame!


MP Quiz
Questions Provided by Sourav Kumar Ghosh(Lecturer, DoIPE, BUTEX)
Enter Your Name: Name Was Entered !
1. The Lathe carriage serves the following purpose of the tool -
2. What is the length of the arc generally?
3. The following is used to support too flexible job very close to the cutting edge -
4. In a shaper_____ movement of the drive is converted into _____ movement.
5. ______ are the spiral grooves which run to the length of the drill.
6. What is the purpose of change gear box?
7. Which type of feed is needed in facing operation?
8. Lead screw is used for -
9. Clapper box is a part of ______ machine.
10. A three jaw chuck is _____.
Take a Screenshot & Share with your Friends !
Made with ❤ by TriptoAfsin


Getting Started
Overview
API Endpoint
https://pdfswitch.io/api/
Welcome to PDFSwitch! PDFSwitch provides a simple and robust REST-ful API to integrate HTML to PDF conversion technology into your existing applications and services.
The PDFSwitch API enables the following operations:
- Conversion of raw HTML/URL to PDF documents
- Get result PDF in binary format OR saved in AWS S3 storage
- Customization of your PDF with css, javascript, headers/footers and much more
Below is a simple picture of how PDFSwitch works.
We use a browser-based PDF render engine, that makes our result PDFs have high fidelity, just like your originial document. This is different from old PDF render engines out there, which use old, outdated parsing engines which may result in a PDF different from your original document.
Also, to provide our service at reasonable price, we use serverless technology on our backend. For this reason, the first request you are making may be slower than the following subsequent requests, as there is a cold start time, to warm our servers.
If you have further questions or feedback you would like to share with us, always feel free to contact us at<EMAIL_ADDRESS>We would love to hear from you :)
Getting an API Key
PDFSwitch uses API keys to allow access to the API. You can find your API keys on your Dashboad, which you can access by logging in or signing up.
Authentication
PDFSwitch expects the API key to be included in all API requests to the server via HTTP Bearer Auth Scheme. Provide your API key in the Authorization
header with the Bearer
authentication scheme, with a single space in between the Bearer
and YOUR_API_KEY
.
Authorization: Bearer YOUR_PDFSWITCH_API_KEY
Conversion API
Convert to PDF
This is the main endpoint of PDFSwitch's API. Simply pass your raw HTML or URL to us and get a PDF in return.
HTTP Request
POST https://pdfswitch.io/api/convert
BODY Parameters
All parameters should be passed as a JSON object. We grouped the parameters into sections by their main usage.
1. Main Options
Default options to manipulate our PDF render engine.
| Parameter | Type | Default | Description |
|---|---|---|---|
| source | string or URL | required | The target document to convert to PDF. Can be an URL or a String of raw HTML. 1. URL Format: The URL of a web page you want to convert. Example: https://example.com 2. HTML Format: Raw HTML string that you want to convert. Example:
Test
 |
| page_ranges | string | null | Returns only specified pages of the PDF document. If not provided, it will return all pages by default. Pattern: 1|5-6 |
| page_orientation | string | portrait | Page orientation Enum: portrait|landscape cf) Portrait vs Landscape |
| page_format | string | A4 | Page size for converted pdf Enum: Letter|Legal|Tabloid|Ledger|A0|A1|A2|A3|A4|A5|A6 cf) A0~A6 Sizes, Letter~Ledger Sizes |
| page_width | string | null | Custom pdf page width. Use it together with custom page_height . Unit can be one of px|in|mm|cm .Pattern: NUM[px|in|mm|cm] Example: 600px |
| page_height | string | null | Custom pdf page height. Use it together with custom page_width . Unit can be one of px|in|mm|cm .Pattern: NUM[px|in|mm|cm] Example: 600px |
| emulate_media | string | screen | Force CSS media emulation for print or screen. The print option controls how your page looks when printed. Enum: screen|print |
| margins | object | null | CSS style margin sizes. Use it to give space between the limits of the document and captured content.
{"top": "100px", "right": "0px", "bottom": "0px", "left": "300px" } cf) If a certain key [top, right, bottom, left] is not defined, the value for the key is 0px by default. |
| zoom | number | 1 | Allows you to increase the zoom in the document. It should be a float value between 0.1 and 2. Value larger than 1 means zooming in(larger), smaller than 1 means zooming out(smaller). For example, the default 1 means 100% zoom(original state) on the document, 2 means 200% zoom(zoom in), 0.1 means 10% zoom(zoom out) and so on. Example: 1.5 |
2. Injection Options
Options to inject on PDF render.
| Parameter | Type | Default | Description |
|---|---|---|---|
| css | string or URL | null | Additional CSS to be injected into the page before render. Can be an URL or String of CSS Rules. 1. URL: The URL to a file of CSS Rules Example: https://path-to-css-rules 2. String: String of CSS Rules. Example: body{background-color: red;} h1{background-color: blue;} |
| javascript | string or URL | null | Additional Javascript to be injected into the page before render. Can be an URL or a String of Javascript code. 1. URL: The URL to a file of Javascript code Example: https://path-to-javascript-code 2. String: String of Javascript code. Example: document.getElementById("some-id").style.display = "none" |
| custom_header | string | null | HTML template for custom page header. See Custom Header/Footer section for more details. Example: Page  of  |
| custom_footer | string | null | HTML template for custom page footer. See Custom Header/Footer section for more details. Example: Date:  |
3. Disable Options
Options to disable on PDF render.
| Parameter | Type | Default | Description |
|---|---|---|---|
| disable_images | boolean | false | Images will be excluded in the rendered PDF. |
| disable_javascript | boolean | false | Will not execute any javascript in the document on render. |
| disable_links | boolean | false | The links( tags) in the rendered PDF will not link to anywhere. |
| disable_backgrounds | boolean | false | The rendered PDF will not have any background images. |
4. Delay Options
Options to delay on PDF render.
| Parameter | Type | Default | Description |
|---|---|---|---|
| delay | integer | 0 | Time in milliseconds to delay render after page load. Max: 10000 |
| wait_for_selector | string | null | CSS selector. Waits until a DOM element matching the provided CSS selector becomes present on the page. Times out after 10 seconds. Example: span.someClassName |
| wait_for_function | string | null | Name of a globally available function(assigned in the window scope). Waits until the function returns a truthy value(boolean true, 1, etc). Times out after 10 seconds.Example: someFunctionName |
5. Request Options
Options on manipulating requests before render.
| Parameter | Type | Default | Description |
|---|---|---|---|
| http_headers | object | null | An object containing additional HTTP headers to be sent on a request before render. All header values must be strings. Example: {"Accept-Language": "en-US,en;q=0.5"} |
6. Storage Options
Options for using 3rd Party Storage(AWS S3) for rendered PDFs.
| Parameter | Type | Default | Description |
|---|---|---|---|
| filename | string | null | If a filename is specified, PDFSwitch will not return a binary PDF but store the PDF in a AWS S3 storage and return the storage URL. See Saving the document to Amazon S3 section for more details. Example: result.pdf |
Custom Header/Footer
Rendered PDFs do not contain any header/footer by default. If you want to add a custom header/footer to your documents, provide an HTML template and PDFSwitch injects it into your document at time of render.
We refer to the html strings you pass as HTML Templates because you can use the below predefined template variables in your html strings. For example, if you want to display the current page number in your PDF pages, you can simply use a placeholder element like
, and our PDF render engine automatically injects the current page number in the pageNumber
class element.
Header/Footer Template Classnames
Custom Header/Footer
import requests
response = requests.post(
'https://pdfswitch.io/api/convert',
headers={'Authorization': Bearer YOUR_API_KEY },
json={'source': 'https://www.wikipedia.org/',
# use margins with custom header/footer
'margins': {'top': '50px', 'bottom': '50px'},
'custom_header': 'Page  of ',
'custom_footer': 'Date: '},
stream=True
)
response.raise_for_status()
with open('result.pdf', 'wb') as output:
for chunck in response.iter_content(chunk_size=1024):
output.write(chunk)
// example in a Node.js env
const request = require('request');
const fs = require('fs');
const options = {
url: 'https://pdfswitch.io/api/convert/',
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY' // Replace it with your API Key
},
body: {
source: 'https://www.wikipedia.org/',
page_orientation: 'portrait'
},
json: true,
encoding: null // this makes the below body a Buffer
};
request.post(options, function (err, response, body) {
if (!err && response.statusCode == 200) {
//do something with PDF Buffer
fs.writeFile('result.pdf', body, function (err) {
if(err) return console.error('writeFile error:', err);
})
} else return console.error('request error:', err);
})
The above command returns a PDF in binary format.
These are the predefined classnames that you can use for dynamic data.
| Classname | Description |
|---|---|
| date | formatted date of render in UTF |
| title | document title |
| url | document location |
| pageNumber | current page number |
| totalPages | total number of pages in the document |
Note that custom header/footer are automatically added to all pages. Also, you must use margins
together with custom_header|custom_footer
, to provide top and bottom margins to your page so there is space for the custom header/footer to show up.
Examples
We have provided examples of how to perform PDF conversions using our API in various use cases.
Please report problems or request new examples via<EMAIL_ADDRESS>Saving the document to Amazon S3
import requests
response = requests.post(
'https://pdfswitch.io/api/convert',
headers={'Authorization': Bearer YOUR_API_KEY },
json={
'source': 'https://www.wikipedia.org/',
'filename': 'wiki.pdf'
}
)
response.raise_for_status()
json_response = response.json()
# the filesize unit is MB.
// example in a Node.js env
const request = require('request');
const fs = require('fs');
const options = {
url: 'https://pdfswitch.io/api/convert/',
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY' // Replace it with your API Key
},
body: {
source: 'https://www.wikipedia.org/',
filename: 'wiki.pdf'
},
json: true
};
request.post(options, function (err, response, body) {
if (!err && response.statusCode == 200) {
// do something with S3 URL in json
// the filesize unit is MB.
let json = JSON.parse(body);
console.log(json.url);
} else return console.error('request error:', err);
})
The above command returns JSON structured like this:
{
"url": "https://pdfswitch.s3.us-west-1.amazonaws.com/pdfswitch/d/2/2019-11/46301658ad7e4ace8f97903ac53d88e6/wiki.pdf",
"filesize": 0.797048
}
Amazon Simple Storage Service(Amazon S3) is an object storage service to store data. By passing the filename
parameter, PDFSwitch won't return a binary PDF, but upload the PDF to AWS S3 and return an URL to the storage location.
When is this useful?
This feature is useful when you don't want to hold a large binary PDF in memory in your server but to just serve the storage URL to users for download.
Errors
The PDFSwitch API uses the following error codes:
| Error Code | Meaning |
|---|---|
| 400 | Bad Request -- Your request is invalid. |
| 401 | Unauthorized -- Your API key is wrong. |
| 403 | Forbidden -- The resource requested is hidden for administrators only. |
| 404 | Not Found -- The page you tried to reach could not be found. |
| 405 | Method Not Allowed -- You tried to perform an action with an invalid method. |
| 500 | Internal Server Error -- We had a problem with our server. Try again later. |


Specific mobile widget platforms (WAC in this case) offer an reference to external native phone applications, and along with it the ability to launch those applications individually.
Select the application you want to launch and click launch to see what happens...
The code for registering this event can be found in
js/Routes.js


{% extends 'base.html' %} {% block content %}
This project is aimed to help Pytorch machine learning developers to quickly build a Flask
web app
in a Docker container ready to be deployed.
View on GitHub
By default, this app uses MobileNetV2 image classifier that was pre-trained on the ImageNet dataset. This can be easily changed with any custom deep learning model. If you wish to contribute to the project, please feel free to add more example models.