Class MessageResolver<T extends Message>
- java.lang.Object
-
- com.hedera.hashgraph.identity.hcs.MessageResolver<T>
-
- Direct Known Subclasses:
HcsDidResolver
,HcsVcStatusResolver
public abstract class MessageResolver<T extends Message> extends java.lang.Object
-
-
Field Summary
Fields Modifier and Type Field Description static long
DEFAULT_TIMEOUT
Default time to wait before finishing resolution and after the last message was received.protected java.util.Map<java.lang.String,MessageEnvelope<T>>
results
protected com.hedera.hashgraph.sdk.TopicId
topicId
-
Constructor Summary
Constructors Constructor Description MessageResolver(com.hedera.hashgraph.sdk.TopicId topicId)
Instantiates a message resolver.
-
Method Summary
Modifier and Type Method Description void
execute(com.hedera.hashgraph.sdk.Client client)
Resolves queries defined in implementing classes against a mirror node.protected abstract boolean
matchesSearchCriteria(T message)
Checks if the message matches preliminary search criteria.MessageResolver<T>
onDecrypt(java8.util.function.BiFunction<byte[],org.threeten.bp.Instant,byte[]> decrypter)
Defines decryption function that decrypts submitted the message after consensus was reached.MessageResolver<T>
onError(java.util.function.Consumer<java.lang.Throwable> handler)
Defines a handler for errors when they happen during resolution.protected abstract void
processMessage(MessageEnvelope<T> envelope)
Applies custom filters on the message and if successfully verified, adds it to the results map.MessageResolver<T>
setTimeout(long timeout)
Defines a maximum time in milliseconds to wait for new messages from the topic.protected abstract MessageListener<T>
supplyMessageListener()
Supplies message listener for messages of specified type.protected void
validate(Validator validator)
Runs validation logic of the resolver's configuration.MessageResolver<T>
whenFinished(java.util.function.Consumer<java.util.Map<java.lang.String,MessageEnvelope<T>>> handler)
Defines a handler for resolution results.
-
-
-
Field Detail
-
DEFAULT_TIMEOUT
public static final long DEFAULT_TIMEOUT
Default time to wait before finishing resolution and after the last message was received.- See Also:
- Constant Field Values
-
topicId
protected final com.hedera.hashgraph.sdk.TopicId topicId
-
results
protected final java.util.Map<java.lang.String,MessageEnvelope<T extends Message>> results
-
-
Method Detail
-
matchesSearchCriteria
protected abstract boolean matchesSearchCriteria(T message)
Checks if the message matches preliminary search criteria.- Parameters:
message
- The message read from the topic.- Returns:
- True if the message matches search criteria, false otherwise.
-
processMessage
protected abstract void processMessage(MessageEnvelope<T> envelope)
Applies custom filters on the message and if successfully verified, adds it to the results map.- Parameters:
envelope
- Message inside an envelope in PLAIN mode.
-
supplyMessageListener
protected abstract MessageListener<T> supplyMessageListener()
Supplies message listener for messages of specified type.- Returns:
- The
MessageListener
instance.
-
execute
public void execute(com.hedera.hashgraph.sdk.Client client)
Resolves queries defined in implementing classes against a mirror node.- Parameters:
client
- The mirror node client.
-
whenFinished
public MessageResolver<T> whenFinished(java.util.function.Consumer<java.util.Map<java.lang.String,MessageEnvelope<T>>> handler)
Defines a handler for resolution results. This will be called when the resolution process is finished.- Parameters:
handler
- The results handler.- Returns:
- This resolver instance.
-
onError
public MessageResolver<T> onError(java.util.function.Consumer<java.lang.Throwable> handler)
Defines a handler for errors when they happen during resolution.- Parameters:
handler
- The error handler.- Returns:
- This resolver instance.
-
setTimeout
public MessageResolver<T> setTimeout(long timeout)
Defines a maximum time in milliseconds to wait for new messages from the topic. Default is 30 seconds.- Parameters:
timeout
- The timeout in milliseconds to wait for new messages from the topic.- Returns:
- This resolver instance.
-
onDecrypt
public MessageResolver<T> onDecrypt(java8.util.function.BiFunction<byte[],org.threeten.bp.Instant,byte[]> decrypter)
Defines decryption function that decrypts submitted the message after consensus was reached. Decryption function must accept a byte array of encrypted message and an Instant that is its consensus timestamp, If decrypter is not specified, encrypted messages will be ignored.- Parameters:
decrypter
- The decrypter to use.- Returns:
- This resolver instance.
-
validate
protected void validate(Validator validator)
Runs validation logic of the resolver's configuration.- Parameters:
validator
- The errors validator.
-
-


My Order
Lightweight College Backpack
Black, Strapped
- 1 +
₦100,000 X
Business Casual Leather Watch Waterproof
Brown, Leather
- 1 +
₦60,000 X
Have a Voucher? APPLY
Total: ₦ 169,000
Black, Strapped
- 1 +
₦100,000 X
Brown, Leather
- 1 +
₦60,000 X
Have a Voucher? APPLY
Total: ₦ 169,000


|
|||||||||
| PREV PACKAGE NEXT PACKAGE | FRAMES NO FRAMES |
| Interface Summary | |
|---|---|
| BaseFocusListener | |
| ChainedRepaintListener | |
| FeatureSelectionListener | |
| LazyLoadListener | |
| NamedFeatureSelectionListener | |
| OrientationListener | |
| ReverseComplementListener | |
| RubberbandListener | |
| ScrollListener | Introduced to propagate join-scroll events to both panels: the original scroll event can be stored inside, and unwrapped at the point of reaction |
| SetActiveCurStateListener | |
| TierManagerListener | |
| ViewListener | |
| VisibilityListener | |
| ZoomListener |
| Class Summary | |
|---|---|
| BaseFocusEvent | |
| BasicWindowListener | |
| ChainedRepaintEvent | |
| EditWindowListener | Move to annotinfo package. |
| FeatureSelectionEvent | |
| LazyLoadEvent | |
| MethodRunnerActionListener | |
| MouseButtonEvent | Static methods for determining whether certain mouse button events have taken place. |
| NamedFeatureSelectionEvent | I am fired when the system needs to select a feature by name (e.g. |
| OrientationEvent | |
| ReverseComplementEvent | |
| RubberbandEvent | |
| ScrollEvent | Introduced to propagate join-scroll events to both panels: I use the value transmitted as a relative-shift amount in terms of pixels. |
| SetActiveCurStateEvent | |
| TierManagerEvent | |
| ViewEvent | |
| VisibilityEvent | |
| ZoomEvent |
|
|||||||||
| PREV PACKAGE NEXT PACKAGE | FRAMES NO FRAMES |


Instafeed is a dead-simple way to add Instagram photos to your website. No jQuery required, just good ‘ol plain javascript.
 As of now, instafeed.js works for some common uses (eg. embedding a single user’s feed on a web page), but can’t work for more complex uses (eg. retrieving all public images with a particular hashtag, finding posts based on a location, etc).
The platform API will be turned off completely in 2020, which means that instafeed.js in its current form will stop working then.
For more information on the current limitations of the API, please see the following:
Examples:
Buy me a coffee:
If you enjoy using Instafeed.js and want to say thanks, you can leave me a small tip. All payments are securely handled through Stripe.
Setting up Instafeed is pretty straight-forward. Just download the script and include it in your HTML:

Instafeed.js also supports AMD/CommonJS
// AMD
require(["path/to/instafeed"], function(Instafeed) {
});
// CommonJS
var Instafeed = require("instafeed");
Instafeed.js is also available on NPM and Bower:
npm install instafeed.js # npm
bower install instafeed.js # bower
Here’s how easy it is to get all images tagged with #awesome:

Instafeed with automatically look for a

and fill it with linked thumbnails. Of course, you can easily change this behavior using standard options. Also check out the advanced options for some advanced ways of customizing Instafeed.js.
The only thing you’ll need to get going is a valid client id from Instagram’s API. You can easily register for one on Instagram’s website.
If you need help with that step, just try Googling “How to get an Instagram client ID”.
clientId
- Required. Your API client id from Instagram.accessToken
- A valid oAuth token. Can be used in place of clientId
.target
- Either the ID name or the DOM element itself where you want to add the images to.template
- Custom HTML template to use for images. See templating.get
- Customize what Instafeed fetches. Available options are:
popular
(default) - Images from the popular pagetagged
- Images with a specific tag. Use tagName
to specify the tag.location
- Images from a location. Use locationId
to specify the locationuser
- Images from a user. Use userId
to specify the user.tagName
(string) - Name of the tag to get. Use with get: 'tagged'
.locationId
(number) - Unique id of a location to get. Use with get: 'location'
.userId
(number) - Unique id of a user to get. Use with get: 'user'
.sortBy
(string) - Sort the images in a set order. Available options are:
none
(default) - As they come from Instagram.most-recent
- Newest to oldest.least-recent
- Oldest to newest.most-liked
- Highest # of likes to lowest.least-liked
- Lowest # likes to highest.most-commented
- Highest # of comments to lowest.least-commented
- Lowest # of comments to highest.random
- Random order.links
- Wrap the images with a link to the photo on Instagram.limit
- Maximum number of Images to add. Max of 60.useHttp
- By default, image urls are protocol-relative. Set to true
to use the standard http://
.resolution
- Size of the images to get. Available options are:
thumbnail
(default) - 150x150low_resolution
- 306x306standard_resolution
- 612x612before
(function) - A callback function called before fetching images from Instagram.after
(function) - A callback function called when images have been added to the page.success
(function) - A callback function called when Instagram returns valid data. (argument -> json object)error
(function) - A callback function called when there is an error fetching images. (argument -> string message)mock
(bool) - Set to true fetch data without inserting images into DOM. Use with success callback.filter
(function) - A function used to exclude images from your results. The function will be
given the image data as an argument, and expects the function to return a boolean. See the example
below for more information.Example Filter (get username + tagged):
var feed = new Instafeed({
get: 'user',
userId: 'USER_ID',
filter: function(image) {
return image.tags.indexOf('TAG_NAME') >= 0;
}
});
feed.run();
To see a full list of properties that image
has, see issue #21.
The easiest way to control the way Instafeed.js looks on your website is to use the template option. You can write your own HTML markup and it will be used for every image that Instafeed.js fetches.
Here’s a quick example:

Notice the and
? The templating option provides several tags for you to use to control where variables are inserted into your HTML markup. Available keywords are:
image
or video
.square
, portrait
, or landscape
.resolution
option.- Full JSON object of the image. If you want to get a property of the image that isn't listed above you access it using dot-notation. (ex:
would get the filter used.)Until June 1, 2016, Instagram’s API will return square images (with white borders), regardless of how they were originally uploaded.
If you’d like to get images in their original landscape and portrait forms, you can opt-in to the API change by editing your Instagram API client, and clicking on the “Migrations” tab:
Note: If you have the
resolution
option set tothumbnail
(default), all images will be square regardless of your API settings.
As of v1.4.0, Instafeed.js includes several helpers you can use in your template
option to work with the new image sizes. These helpers are meant primarily to help control styling
of the images through CSS.
square
, portrait
, or landscape
.To fetch images specifically from your account, set the get
and userId
options:
var userFeed = new Instafeed({
get: 'user',
userId: YOUR_USER_ID,
accessToken: 'YOUR_ACCESS_TOKEN'
});
userFeed.run();
Note:
YOUR_USER_ID
option corresponds to your Instagram account ID (eg: 4385108), not your username. If you do not know your account ID, do a quick google search for “What is my Instagram account ID?”. There a several free tools available online that will look it up for you.
Troubleshooting: If you are seeing the error
No user specified. Use the 'userId' option
in your browser console, make sure there are no quotation marks around the value foruserId
. Instafeed.js is expecting theuserId
as a number, not as a string.
As of v1.3, Instafeed.js has a .next()
method you can call to load more images from Instagram.
Under the hood, this uses the pagination data from the API. Additionally, there is a helper
.hasNext()
method that you can use to check if pagination data is available.
Together these options can be used to create a “Load More” button:
// grab out load more button
var loadButton = document.getElementById('load-more');
var feed = new Instafeed({
// every time we load more, run this function
after: function() {
// disable button if no more results to load
if (!this.hasNext()) {
loadButton.setAttribute('disabled', 'disabled');
}
},
});
// bind the load more button
loadButton.addEventListener('click', function() {
feed.next();
});
// run our feed!
feed.run();
This isn’t a large project by any means, but I’m definitely welcome to any pull requests and contributions. Everything is written and tested in CoffeeScript.
You can get your copy up and running for development quickly by cloning the repo and running npm:
$ npm install
This will install all the necessary test tools for testing. There is also a Makefile in the repo to make your tests quick and easy:
make test
will run all the tests using Mocha + Chai + CoffeeLintmake min
will create the minified versionmake
will run both the previous steps and compile everything1.4.1
1.4.0
accessToken
is no longer required to fetch images from user accounts!target
can now accept a DOM node directly, instead of just a string ID, thanks @juhamust!file://
). Thanks @spoonben!userId
, locationId
, and limit
options.1.3.2
useHttp
option when no template is set. Thanks @bartekn!1.3.1
sortBy: "most-recent"
did not always correctly sort the images. Thanks
Neil Campbell!sortBy
option to be none
.1.3.0
useHttp
option to disable.filter
option..next()
and .hasNext()
methods.limit
of 15 images. The option is still supported, but by default no limit
is sent to the API.1.2.1
1.2.0
1.1.0
1.0.0


| Interface | Description |
|---|---|
| CustomBottomSheetDialog.BottomSheetListener |
Allows this class to interface with the calling class
|
| fragmentListener |
Passes information from main activity to particular activities to handle results
|
| Class | Description |
|---|---|
| AddBookActivity |
This is a class that creates a new book object through user input
|
| AddBookActivityTest | |
| Book |
A book object represents a book within our system
Books are owned by users, and can be transferred to others
|
| BookTest | |
| BorrowedBorrowingFragment |
A
Fragment subclass that is responsible for displaying all books that a user is borrowing
Firebase manages this adapter and will update in real time based on writes to firestore. |
| BorrowedFragment |
A Fragment that handles all sub-fragments for books that a user is borrowing
|
| BorrowedPageAdapter |
A
FragmentPagerAdapter subclass that allows the user to swipe between tabs in Borrowed. |
| BorrowedPendingFragment |
A
Fragment subclass that is responsible for displaying all books that a user has requested
Firebase manages this adapter and will update in real time based on writes to firestore. |
| BorrowedRequestedFragment |
A
Fragment subclass that is responsible for displaying all books that a user has requested
Firebase manages this adapter and will update in real time based on writes to firestore. |
| BorrowerFragmentTest | |
| CheckBookValidity |
CheckBookValidity is a static class which can be used to check if user input will generate
a valid book
|
| CheckBookValidity.CheckInput |
CheckInput is a static class which can be used to check if user input is valid in various
ways
|
| CheckProfileActivity |
This class is used to check another users profile
This is a class still under development
|
| CheckProfileActivityTest | |
| ChooseLocationActivity |
Activity where the user can select a pick up location.
|
| ChooseLocationActivityTest | |
| CustomBottomSheetDialog |
Dialog that appears at the bottom of the screen when hitting the 3 dots or "more" button on a
book card.
|
| EditProfileActivity |
This is a class used to edit a user's profile information.
|
| EditProfileActivityTest | |
| FirestoreBorrowedAdapter |
Custom RecyclerView Adapter for Book objects in Borrowed books.
|
| FirestoreInitalizeLocation | |
| FirestoreLocationAdapter |
Handles displaying pickup addresses for users
|
| FirestoreMyBooksAdapter |
Custom RecyclerView Adapter for Book objects in My Books.
|
| FirestoreNotificationAdapter |
Notification adapter that listens in real time for changes to the query result
|
| FirestoreRequestAdapter |
Displays all the requests a user has for a book, updates in real time
Using a firestore query
|
| HomeScreen |
Homescreen is the first object a user sees upon signing in, and will contain all the books
borrowed by the user.
|
| ImagePageAdapter |
This is the adapter that manages to enlarge photos from books and navigate
through the different photos
|
| ImageRecyclerViewAdapter |
This is the adapter that sets the option to add and present the image that will be add to books
The adapter is used in the class of MyBooksAddBook
|
| ImageSliderActivity |
This is the main activity for the ImageSlider in which we will enlarge the photos
from a particular book so the user can go through them
|
| InitializeLocationActivity | |
| Login |
Allows the users to sign in / opt to register for the application
|
| LoginActivityTest | |
| MainActivity |
The solve purpose of this activity is to initialize the login screen
|
| MyBooksAvailableFragment |
A
Fragment subclass that is responsible for displaying books a user owns
Firebase manages this adapter and will update in real time based on writes to firestore. |
| MyBooksAvailableFragmentTest | |
| MyBooksFragment |
A
Fragment subclass that is responsible for the page the user sees when in the
"My Books" section. |
| MyBooksLendingFragment |
A
Fragment subclass that is responsible for displaying books a user owns
Firebase manages this adapter and will update in real time based on writes to firestore. |
| MyBooksPageAdapter |
A
FragmentPagerAdapter subclass that allows the user to swipe between tabs in My Books. |
| MyBooksPendingFragment |
A
Fragment subclass that is responsible for displaying books a user owns
Firebase manages this adapter and will update in real time based on writes to firestore. |
| Notification |
Represents a notification for a user
|
| photoAdapter |
A class used to reformat variable representing photos into different types
Referenced https://www.baeldung.com/java-base64-image-string
Referenced https://stackoverflow.com/questions/7620401/how-to-convert-byte-array-to-bitmap
|
| PostScanActivity |
This is a class that creates options for the use of the ISBN
|
| ProfileFragment |
This is a class that displays a user's profile information such as username, email, address, and
phone number.
|
| ProfileFragmentTest | |
| Register |
Register allows a new user to create an account for our app
Register is launched through the log in activity
Each user must be registered with a minimum of a username, password, address, and email
|
| RegisterActivityTest | |
| RobotiumLocationManager | |
| RobotiumLoginManager |
Handles logging in as various robotium controlled users
|
| RobotiumSearchManager | |
| RobotiumTransactionManager | |
| RobotiumUser |
A User controlled by robotium
|
| RobotiumUserBookManager |
Handles adding and deleting books from a robotium controlled user
|
| ScannerActivity |
This activity implements an ISBN scanner and returns the ISBN calling this activity
This activity must be called with startActivityForResult to function properly
https://medium.com/analytics-vidhya/creating-a-barcode-scanner-using-android-studio-71cff11800a2
|
| ScannerTest | |
| SearchFragment |
SearchFragment is a fragment which handles user searching for other users and books
Functionality
|
| SearchFragment.BookQueryHandler |
BookQueryHandler handles search queries by the user for books by making calls to
QueryHandler
|
| SearchFragment.QueryHandler |
QueryHandler handles search queries by the user
|
| SearchFragment.UserQueryHandler |
UserQueryHandler handles search queries by the user for users by making calls to
QueryHandler
|
| SearchFragmentTest | |
| SelectLocationActivity |
SelectLocationActivity is an Activity which allows the user to
select a location on the map (places a marker at the location they clicked)
display the address of said location (so long as the phone has access to a geocoder)
confirm that this is the correct location and click a button to exit
|
| SelectLocationActivity.GoogleGeocoderQueryHandler |
Handles Queries to Google Geocoder API
|
| ShowMapLocationActivity |
Displays the location chosen by the book owner for a borrower
|
| SplashScreen |
This is a splash screen activity
|
| Transaction |
A Transaction object represents various
interactions that two people can have within the app
requesting books, declining requests, transferring of books
between users and returning the book to it's original owner
|
| TransactionTest | |
| User |
A user within our system, contains the methods / variables for any transaction between users
|
| UserLocation |
Represents a location within our system
|
| UserLocationTest | |
| UserNotification |
Represents an in app notification
Not to be confused with a general Notification
|
| ViewRequestsActivity |
Display all the requests for a given book to the user
|
| Exception | Description |
|---|---|
| CheckBookValidity.CheckInput.OutOfRangeException |
A custom exception to throw when user input is outside of set range
|


Package io.github.ma1uta.matrix.server.model.federation
Federation models.
-
Interface Summary Interface Description PersistedDataUnit These events are broadcast from one homeserver to any others that have joined the same room (identified by Room ID). -
Class Summary Class Description DeviceKeysWithUnsigned Device keys with unsigned info.DeviceResponse Device response.DirectoryResponse Directory response.EventContainer Event container.EventTemplate Event Template.Invite Invitation.InviteEvent Invite event.InviteV1Request V1 Invite JSON request.InviteV2Request V2 Invite JSON request.KeyClaimRequest Key claim request.KeyClaimResponse Key claim response.KeyQueryRequest Key query request.KeyQueryResponse Key query response.MakeResponse Response of the make_join/make_leave requests.OnBindRequest Bind request.PduProcessingResult PDU processing result.PduProcessingResults PDU processing results.ProfileResponse Profile.PublicRoomsChunk Public rooms chunk.PublicRoomsResponse Public rooms response.QueryAuth Query auth request.RejectReason Reject reason.RejectReason.Reasons Reasons.RoomStateResponse Room state response.SendRequest JSON request of the send_join/send_leave requests.StateIdResponse Response of the state methods, in the form of event IDs.StateResponse Response of the state methods.ThirdPartyInvite Third party invite event.Transaction The transfer of EDUs and PDUs between homeservers is performed by an exchange of Transaction messages, which are encoded as JSON objects, passed over an HTTP PUT request.UnsignedDeviceInfo Unsigned device info.UserDevice User device.UserInfoResponse User info of the OpenID request.


Select the strategies and the query for identifying potential experts.
| Profile | Platform | Score | Invite |
|---|---|---|---|
| http://www.reddit.com/user/birdsbirdsbirds |
1282
|
Invite | |
| http://www.reddit.com/user/giant_kiwi |
1189
|
Invite | |
| http://www.reddit.com/user/birdingninja |
1180
|
Invite |
No users on the platform Reddit have been found for the
query:
| Profile | Platform | Score | Invite |
|---|---|---|---|
| https://twitter.com/constantsun |
2
|
Invite | |
| https://twitter.com/Gadiouka |
2
|
Invite | |
| https://twitter.com/yocla14 |
2
|
Invite |
| Profile | Platform | Score | Invite |
|---|---|---|---|
| http://www.reddit.com/user/hotspotbirding |
0.95
|
Invite | |
| http://www.reddit.com/user/rkmorten |
0.89
|
Invite | |
| http://www.reddit.com/user/adremeaux |
0.88
|
Invite |
| Select | Property name | Description | Value |
|---|
Evidence not gathered
Evidence not gathered


So, you admaire the tool. Make it then even better! Don't like the project? Make it the way you will like it! 8) Post your response on the project's home forum at http://rubyforge.org/projects/testcase post any found in the project bugs, post your feature requests. Just post your 'hello there!'. We are all easy going people, so welcome!
First you'll need to have the freshest source code from svn. If you don't have Subversion on your machine you'll have to install it first.
Then checkout it froum the projects svn source.
svn co svn://rubyforge.org/var/svn/testcase/trunk testcase
Then once you've got the changes you wanted, go to the project main directory and create the diff file with the same svn util like that.
svn diff > your.diff
Once you've got the diff, post it on the project's forum, or simple send it to me at nemshilov-g mail,com
Simple and plain. And don't forget to test your changes before public them. There are lots of various tests and runners inside the test/ directory.
There are nothing special. I just follow the Ruby/Rails coding conventions. Classes/Mixings should be named in the camelized and capitalized style. All the methods and attributes, should be downcased and underscored. The indentation is the same, 2 spaces.
The files naming principles are more or less the same.
The only thing I would ask from you is make the things having a predictable interface. So the people would as possible less time spend searching your super-interface in the api-documenation.
That's all, have fun! 8)


{% extends "skeleton.html" %} {% block navbar %}
{% endblock %} {% block header %}Ready to make a positive impact? Eager to network and work with like-minded undergraduates like yourself?
If you are interested in joining us on our mission, please apply to be a part of your respective University Chapter.
Application Deadline: {{ app.due_date }}
For more information contact:
{{ app.contact }}


Introduction to sDraw
Version 1.1: July 16, 2006.
Version 1.2: January 13, 2007.
What is sDraw?
A GDI replacement in some aspects, an upgrade in others, and a
convenient library in all cases. All drawing/blending is done in
software on one back-buffer DIB or on a custom surface (bitmap in
memory). All drawing/blending is internally clipped (by one rectangle,
any more would slow-down drawing). The final result is BitBlt-ed from
the back-buffer DIB onto the window DC.
Features
• Loading and management of bitmaps is easy and straightforward.
• No need for brushes, pens, DCs, hBitmaps
• supports images with alpha-channel
• alpha-blending, additive-blending, custom blending, transparency-Blt
• 12 ROPs (raster operations) for drawing
• clipping - useful for complex GUI
• preprocessing of bitmaps: Color-to-Alpha, Premultiply-Alpha
• speed - completely written and optimized in x86 assembler
• interoperability with GDI, DirectDraw and Direct3D.
Lacks:
• On nVidia videocards, the final BitBlt fucks up and decreases
performance (but not enough to throw sDraw into the Void of the Recycle
Bin). Maybe the beta-testers had driver problems? ATi R9200, ATi R9250
and GeForce2 work perfectly (meaning 0.5% cpu usage at 30-50 fps forced
update-rate, instead of FX5900's 45% cpu load).
• not opensource.
sDraw can be linked statically (sDraw.lib) in C/C++/asm apps,
or dynamically (sDraw.dll) in VisualBasic apps.
Copyright:
Ilian Dinev,
Ultrano Software http://www.ultranos.com
License:
Public domain. Meaning "completely free", no need for credits. Use and
modify as you wish in commercial/free/opensource projects. An email
with title "sDraw feedback" would be appreciated. I'd love to see my
code useful, even if the coding itself was fun (~3000 lines for 1 day,
but all this hateful documentation for two days ^^")
Where to start?
InitSDraw(),


Username
{{ render_form(form.username, class_="input is-primary") }}
Name
{{ render_form(form.name, class_="input is-primary") }}
E-mail
{{ render_form(form.email, class_="input is-primary") }}
change password? just logout and do forget password it will change your password


Here is a footnote reference,1 and another.2
This paragraph won’t be part of the note, because it isn’t indented.
Here is the footnote.↩
Here’s one with multiple blocks.
Subsequent paragraphs are indented to show that they belong to the previous footnote.
{ some.code }
The whole paragraph can be indented, or just the first line. In this way, multi-paragraph footnotes work like multi-paragraph list items.↩


This is a page that tells you all about me!
So here is some general information about me.
- I am transgender and proud of it!!!
- I tell bad jokes that usually fail or make people mad at me
- I tend to think I am smarter than I am
- I try to make funny comebacks and jokes on these kinds of things
- 9/10 dogs recommend my belly rubs
- I am fresh out of high school and found something I love, which is coding
- You should usually not take what I say to heart or take it seriously


Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. It is written on top of busboy for maximum efficiency.
NOTE: Multer will not process any form which is not multipart (multipart/form-data).
action 处理表单提交的 URL。
enctype 当 method 属性值为 post 时，enctype 就是将表单的内容提交给服务器的 MIME 类型 。可能的取值有：


About initial and boundary conditions
Q: How many vertical levels are there in experiment 1?
Q: Should there be a file which defines lat/lon for the half
degree grid?
More information can be found at
PIRCS domain on the Boundary Conditions Development Web page.
Q: I would like to know where I could get information on what the number
means in the landuse file (i.e. LNDF60k.88051500)
A: First of all, the actual number in the file should be the max (14)
minus this number. For example, 5 stands for 9 (=14-5).
(Note: this list is adopted from MM5 documentation.)
Q: Is PIRCS dataset available at other sites aside from Iowa
State University?
A: Yes. As a backup in case of network failure or slowness, we have
loaded PIRCS dataset at NCAR. They are in MSS (mass storage
system). The directories are:
In order to download them, one has to have a "shavano"
account at NCAR.
A: Forty two levels from 25 mb (1st level) down to 1050 mb
(42nd) at 25 mb interval.
A: The domain configuration of the 0.5x0.5 degree lat/lon is
as following:
NW corner (1,YMAX).......................(XMAX,YMAX) NE Corner
The lat/lon is at SW corner (130.0 W, 20.0 N),
NE ( 70.0 W, 55.0 N),
center (100.0 W, 37.5 N).
...........(I,J)...............
...............................
(1,2) .........................(XMAX,2)
SW Corner (1,1) .........................(XMAX,1) SE Corner
/ZPAN/PIRCS_EPRI/PSTDOM60k/PRCF60k.880515-31.tar
/PRCF60k.880601-15.tar
/PRCF60k.880616-30.tar
/PRCF60k.880701-15.tar
/ZPAN/PIRCS_EPRI/REGDOM0p5/PRCF0p5.880515-31.tar
/PRCF0p5.880601-15.tar
/PRCF0p5.880616-30.tar
/PRCF0p5.880701-15.tar
These are large data files excluding smaller ones which can
be easily downloaded by other means.
Q: What is deep-soil heat flux in list of
PIRCS-collecting variables?
A:The deep-soil flux is the net flux from the atmosphere into the model domain
below the atmosphere. It is thus the flux across the interface from the
atmosphere to the model's soil-vegetation domain.
Q: I would like to know how to define the mixed-layer
depth, especially in cloudy conditions and night time.
A: Mixed-Layer Depth in PIRCS is defined based on the potential
temperature profile. The top of the mixed layer should be the
midpoint of the model layer closest to the surface for which
the potential temperature change with height, d(theta)/dz,
exceeds +1 K/km. In case of multiple such layers under cloudy
conditions, only the FIRST one from the ground is considered.
Please note that when the surface layer is stably stratified,
the mixed layer depth is zero.
Copyright/Trademark
Legal Notice


Gallery
The internet’s source of freely-usable images. Powered by creators everywhere.
Trending:flower, wallpapers, backgrounds, happy, love


Understanding the Youtube War
Since international news media was banned in Syria, the social media platform YouTube has become a primary source for transmitting footage of the Syrian Civil War. YouTube has become a war zone of all its own as competing groups use the platform to further their political interests on the battlefield. The importance of YouTube to the conflict is directly related to the prevalence of recording devices among citizens living in war-ravaged areas, as well as the politically murky nature of the Civil War.
This project is an investigation of the YouTube war, investigating the platform as a means to better understand the physical destruction and humanitarian crisis in the city. While the maps we have access to, as well as the data collected by UNOSAT and Human Rights watch, is viewable by us on high resolution satellite imagery, YouTube allows us to look closely at th ewar from another perspective of distance. What follows, of course, are many questions about the spatial relevance and political meaning of the ‘YouTube War.’
The Dynamics of War in Social Media
The videos uploaded to YouTube - and the political actors which these videos represent - are mediated by YouTube’s online platform. The platform’s structure for sharing and consuming videos has set a context through which the narrative of the conflict has evolved.
Beyond a curated front page, Youtube’s familiar interface is fairly standard across digital media platforms; a search term delivers a list of twenty results on a white background. The order of this list is determined by youtube’s search algorithm and can be modified by the viewer using several filter options, including content type, upload date, and a sorting category, prioritizing videos by relevance, upload date, view count, or rating. Each video or group of videos shown in the resulting list includes an image, title, author, the amount of time since the video was uploaded, the number of views, and a two line description of the contents. The limited display of information for any one video in the interface prioritizes the list of videos from a search over the content within a single result.
Within the context of YouTube’s existing platform, users uploading videos have developed a common method for categorizing content so that it is more easily accessible given the YouTube’s search-based interface. Videos uploaded of events on the ground in Syria are titled with a formula of location and date, in addition to a specific description of the event. This common language of describing videos transforms YouTube’s general search algorithm into an archive of war footage with great depth. A YouTube search of ‘حلب الشيخ خضر برميل’ [Aleppo Sheikh Kheder (a neighborhood in eastern Aleppo) barrel], on July 6th, 2016, for example, returns 2,510 results.
The question of place as it corresponds to the locations referenced in videos is an open question in our research. In the videos we have seen over the course of our research, place is often referenced as the neighborhood of the event. However this is not always the case. Some neighborhoods in the center of the city are referred to as the “Citadel” (القلعة). Other events are tied to particular known spaces, such as intersections or open spaces. One building, the tower of Aleppo’s city hall, functions as a major point of conflict between rebel groups and the Syrian regime and is used as a placement to locate videos.
Mapping the YouTube War
While YouTube is an important resource for accessing and distributing footage of the Syrian Civil War, it’s platform does not give access to the spatial dynamic of the conflict. The below map plots youtube search results across a map of Aleppo, taking advantage of the naming conventions which have become the standard of accessing first person content.* Videos are located on the map corresponding to the searches for the place names used in the video titles. Filters corresponding to other common keywords can be turned on and off to further specify the videos shown. *An appearance of videos on these maps does not indicate that they are confirmed or collaborated.


MS Patch Tuesday
► Page Contents:
MS Patch Tuesday⌗
This is a simple tool (written python) to perfrom quick analysis on security updates for MS Patch Tuesday. It highlights:
- Products Families
- Vulnerability Types
- High severity vulnerabities (>= CVSS 8.5)
- High likelihood vulnerabilities (contains ‘Exploitation More Likely’)
- Vulnerabilties that exploited in wild (Exploited:Yes)
Microsoft Security Response Center (MSRC) investigates all reports of security vulnerabilities affecting Microsoft products and services, and provides these updates as part of the ongoing effort to help you manage security risks and help keep your systems protected. All the details from Microsoft security update are formatted according to the Common Vulnerability Reporting Framework (CVRF). For more details, please visit msrc.microsoft.com/update-guide.
Usage⌗
$ patch_tuesday -h
usage: patch_tuesday [-h] [-c] [-k <YYYY-mmm>] [-v]
Zzzzz |\ _,,,---,,_
/,`.-'`' -. ;-;;,_ __author__ : [ zd ]
|,4- ) )-,_..;\ ( `'-' __year__ : [ 2022.03 ]
'---''(_/--' `-'\_) __file__ : [ /home/xx/admin/patch_tuesday ]
[ To get vulnerability stats and updates for Patch Tuesday from MSRC. ]
options:
-h, --help show this help message and exit
-c show chart output
-k <YYYY-mmm> Date string for the report query in format YYYY-mmm
-v verbose output
Get detailed Microsoft security update, formatted according to the Common Vulnerability Reporting Framework. MSRC investigates all reports of security vulnerabilities affecting Microsoft products and services, and provides these updates as part of the ongoing effort to help you manage security risks and help keep your systems protected. For more details, please visit msrc.microsoft.com/update-guide.
A similar wbesite can be found at https://patchtuesdaydashboard.com (by Morphus Labs).
Get quick summary of MS vulnerability stats for current month.
$ ./patch_tuesday.py
Tips⌗
Show quick summary with simple ASCII chart.
$ ./patch_tuesday.py -vc -k 2022-apr
$ ./patch_tuesday -k 2022-may -v
$ ./patch_tuesday -k 2022-jun -v
References⌗
Read other posts


Hi.. I need to generate a 5 digit random number on unix env., i have tried with rand() but it is giving same value for each time i run my binary. i tried with srand() as well but it is giving same value for same second.. Can u please suggest any alternative way to get 5 digit random number...?


University of California, Los Angeles
B.S. Computer Science
- Expected Graduation: 2019
- Activities: UPE, VP of DevX, Creative Labs, ACM Hack
- GPA: 3.85
PayPal
Software Engineer Intern
- Developed global, consumer facing, full stack, production features
- Helped create next generation isomorphic node.js / react / redux application
- Created solution that improved unit testing experience
- Integrated better development and build processes
LA Hacks
Director of Technology/Developer
- Worked to design clean and maintainable software
- Developed REST APIs in Go for user applications and QR code generation
- Created in house application using react and redux to streamline grading
DevX @ UCLA
Vice President/Developer
- Helping lead the premier software development organization at UCLA
BruinSpeak
Giving Student's a Voice
- Backend developer for Ruby on Rails application
- Integrated Google OAuth login and created trending algorithm
- Developed several interactive ajax components
- Added file upload and modification with carrier wave
FixMoto
Platform to store vehicle maintenance records
- Developed a JSON REST API using Go and PostgreSQL
- Implemented authentication with jwt and bcrypt
- Creating react native application to consume API
Visualizing LA
Connecting LA with Data
- Created a way to visualize parking tickets on a map of LA
- Used leaflet and D3 to show ticket density over map
- Utilized hexbining to create visually appealing heat map


Mağaza heyəti
Azərbaycanda milli dəyərlərə bağlı, qürurla yaradılmış, etibarlı qida markası olmaq. Biz, mağazalarda müştərilərə qida/qeyri-qida sahəsindəki beynəlxalq standartlarla işlədiyimizi göstəririk. Buna nail olmaq üçün biz Azərbaycanın daxilində fərqli və yeni düşüncə tərzinə sahib, təşəbbüskar və məsuliyyəti üzərinə götürən və pərakəndə satışı sahəsində karyera qurmaq arzusu olan mütəxəssisləri cəlb etməkdir.
Mağaza heyətimizə indi qoşulun. Bravo-da işiniz olsun!
Müraciət
İşəqəbul bir neçə mərhələlərdən ibarətdir.
- İLKİN MÜRACİƏTLƏRİN DƏYƏRLƏNDİRMƏSİ
- İLKİN MÜSAHİBƏ
- İKİNCİ MÜSAHİBƏ
- UYGUN NAMİZƏDƏ İŞ TƏKLİFİNİN EDİLMƏSİ
- GİRİS TƏLİMİ
Müsbət qərar verilmiş namizədlər Azərbaycan Respublikasının Əmək qanunvericiliyinə və Şirkətin daxili qaydalarına uyğun olaraq 3 (üç) ay sınaq müddəti müəyyən edilməklə işə qəbul edilir.
Azerbaijan Supermarket MMC-yə işə qəbul üçün CV formaların qəbulu bir neçə mənbədən olunur:
CV formalar qeyd olunan marketlərin müştəri xidmətlərində yerləşən CV qutularında saxlanılır. CV qutuların yerləşdiyi ünvanlar: Azure, Khirdalan, Khatai, Winter park, Globus Center, 28 mall, Sharifzada Center, Baki Tennis Akademiya.
Namizədlər saytda mövcud olan vakansiyalarla tanış olduqdan sonra, İŞƏ QƏBUL ANKETİ tam şəkildə doldurulub<EMAIL_ADDRESS>e-mail ünvanına göndərirlər.
Vakansiyalar
- Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Read More Read Less
- Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Read More Read Less
- Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Read More Read Less
- Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Read More Read Less
- Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Read More Read Less
- Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Read More Read Less
- Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Read More Read Less
- Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Read More Read Less
- Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Read More Read Less
- Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Read More Read Less
- Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Read More Read Less
- Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Read More Read Less
- Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Very long description of the vacancy which occupies several lines, due to which there is a need to transfer details to a new page Read More Read Less


Justin Moorhouse's panel show appearances
Justin Moorhouse (born 1970-05-15[ref]) has appeared in 14 episodes between 2009-2016. Justin Moorhouse on IMDB. Justin Moorhouse on Wikipedia. Justin Moorhouse on Chortle.
- 2016-02-12 / The News Quiz
- 2015-11-17 / Alan Davies: As Yet Untitled
- 2015-06-05 / The News Quiz
- 2015-05-29 / The News Quiz
- 2014-06-27 / The News Quiz
- 2014-03-07 / The News Quiz
- 2013-08-02 / The News Quiz
- 2013-07-23 / It's Not What You Know
- 2012-05-11 / 8 Out of 10 Cats
- 2012-04-27 / The News Quiz
- 2010-03-01 / Just A Minute
- 2010-01-18 / Just A Minute
- 2009-03-16 / Just A Minute
- 2009-02-16 / Just A Minute


{% extends "base.html" %} {% block title %}{{ unit.name }} - {{ assignment.name }} - {{ submission.user.username }}{% endblock %} {% block breadcrumbs %}
| Name of Person | {{ submission.user.username }} |
|---|---|
| Submitted on | {{ submission.date }} |
| Submitted solution | {{ submission.solution }} |
| Maximum Mark | {{ assignment.total }} |
| AutoMark | {{ submission.automark}} / {{ assignment.total }} |
| AutoFeedback | {{ submission.autofeedback }} |
| Marks | {{ submission.mark}} / {{ assignment.total }} |
| Feedback | {{ submission.feedback }} |
No feedback has been given.
{% endif %} {% else %}


The trading strategy uses VIX futures as a trading vehicle and S&P E-mini for hedging purposes. The spot VIX price data and the continuous front contract price of VIX and E-mini S&P500 futures in the daily resolution are from Quandl.
def Initialize(self): self.SetStartDate(2011, 1, 1) # Set Start Date self.SetEndDate(2018, 9, 1) # Set End Date self.SetCash(10000000) # Set Strategy Cash self.vix = self.AddData(QuandlVix, "CBOE/VIX", Resolution.Daily).Symbol # Add Quandl VIX price (daily) self.vx1 = self.AddData(QuandlFutures, "CHRIS/CBOE_VX1", Resolution.Daily).Symbol # Add Quandl VIX front month futures data (daily) self.es1 = self.AddData(QuandlFutures, "CHRIS/CME_ES1", Resolution.Daily).Symbol # Add Quandl E-mini S&P500 front month futures data (daily) # Add VIX futures contract data self.AddFuture(Futures.Indices.VIX).SetFilter(timedelta(0), timedelta(days=180)) # Add E-mini S&P500 futures contract data self.AddFuture(Futures.Indices.SP500EMini).SetFilter(timedelta(0), timedelta(days=180))
Futures basis is defined as the difference between the underlying product cash price and futures contract price at a given time.
\[Basis_t=S_t-F_t\]Where \(S_t\) is the spot VIX price, \(F_t\) is the VIX futures price. The basis is in contango means the futures price is higher than the spot price. The opposite of Contango is Backwardation. It refers to the market condition in which the futures price is less than the spot price.
\[Contango=S_tWe select the nearest VIX and E-mini futures with at least ten trading days to maturity in the futures chains.
def OnData(self, data): # select the nearest VIX and E-mini S&P500 futures with at least 10 trading days to maturity # if the front contract expires, roll forward to the next nearest contract for chain in data.FutureChains: if chain.Key.Value == Futures.Indices.VIX: if self.front_VX is None or ((self.front_VX.Expiry-self.Time).days <= 1): contracts = list(filter(lambda x: x.Expiry >= self.Time + timedelta(days = 10), chain.Value)) self.front_VX = sorted(contracts, key = lambda x: x.Expiry)[0] if chain.Key.Value == Futures.Indices.SP500EMini: if self.front_ES is None or ((self.front_ES.Expiry-self.Time).days <= 1): contracts = list(filter(lambda x: x.Expiry >= self.Time + timedelta(days = 10), chain.Value)) self.front_ES = sorted(contracts, key = lambda x: x.Expiry)[0]
While this trading strategy takes advantage of the roll by selling VIX futures at a premium to the VIX and by buying VIX futures at a discount to the VIX, it is exposed to the potentially substantial risks associated with adverse moves in the VIX futures curve. However, as the tendency of VIX futures prices to move inversely to equity returns, much of this risk can be hedged by open the E-mini S&P 500 futures position in the same direction.
The number of mini-S&P futures contracts to buy or sell per VIX futures contract is based on the hedge ratio estimates. The hedge ratios are constructed from regressions of VIX futures price changes on a constant and on contemporaneous percentage changes of the front mini-S&P 500 futures contract both alone and multiplied by the number of business days that the VIX futures contract is from the settlement, as shown below.
\[\Delta P^{VX}_t=\beta_0+\beta_1* Return^{ES}_t+\beta_2*(Return^{ES}_t*TimeToSettlement^{VX}_t)+\mu_t\]After we get the parameters \(beta_0\), \(beta_1\) and \(beta_2\), the formula for the hedge ratio is
\[HR_t=\frac{\beta_1*1000+\beta_2*TimeToSettlement_{t-1}*1000}{0.01*P^{ES}_{t-1}*50}\]def CalculateHedgeRatio(self): price_VX = np.array(self.price_VX) price_ES = np.array(self.price_ES) delta_VX = np.diff(price_VX) res_ES = np.diff(price_ES)/price_ES[:-1]*100 tts = np.array(self.days_to_maturity)[1:] df = pd.DataFrame({"delta_VX":delta_VX, "SPRET":res_ES, "product":res_ES*tts}).dropna() # remove rows with zero value df = df[(df != 0).all(1)] y = df['delta_VX'].astype(float) X = df[['SPRET', "product"]].astype(float) X = sm.add_constant(X) model = sm.OLS(y, X).fit() beta_1 = model.params[1] beta_2 = model.params[2] hedge_ratio = abs((1000*beta_1 + beta_2*((self.front_VX.Expiry-self.Time).days)*1000)/(0.01*50*float(self.Securities[self.es1].Price))) self.Plot("Trade", "Hedge Ratio", hedge_ratio) return hedge_ratio
Our daily futures price data is from the continuous front contract. To measure the time to settlement, we import the custom data of the VIX futures expiration dates from 2011 to 2018. We populate the date index with the backward fill method to make it easy to calculate the time to settlement.
# import the futures expiry calendar url = "https://www.dropbox.com/s/5k4rbuzfsfn3w0h/expiry.csv?dl=1" data = self.Download(url).split('\r\n') expiry = [x.split(',')[1] for x in data][1:] date = [x.split(',')[0] for x in data][1:] df_date = pd.DataFrame(expiry, index = date, columns = ['expiry']) df_date.index = pd.to_datetime(df_date.index) df_date['expiry'] = pd.to_datetime(df_date['expiry']) idx = pd.date_range('01-01-2011', '04-19-2019') # populate the date index and backward fill the dataframe return df_date.reindex(idx, method='bfill')
To perform the regression, we save the history price in deque list and update the list every day.
# the rolling window to save the front month VX future price self.price_VX = deque(maxlen=252) # the rolling window to save the front month ES future price self.price_ES = deque(maxlen=252) # the rolling window to save the time-to-maturity of the contract self.days_to_maturity = deque(maxlen=252) # initialize the deque list for index, row in df.iterrows(): self.price_VX.append(row[self.vx1]) self.price_ES.append(row[self.es1]) self.days_to_maturity.append((row['expiry']-index).days)
The daily roll is defined as the difference between the front VIX futures price and the VIX, divided by the number of business days until the VIX futures contract settles. Short VIX futures positions are entered when the VIX futures basis is in contango and the daily roll exceeds 0.10 and long VIX futures positions are entered when the VIX futures basis is in backwardation and the daily roll is less than -0.10.
# calculate the daily roll daily_roll = (self.Securities[self.vx1].Price - self.Securities[self.vix].Price)/(self.front_VX.Expiry-self.Time).days self.Plot("Trade", "VIX", self.Securities[self.vix].Price) self.Plot("Trade", "VIX Futures", self.Securities[self.vx1].Price) self.Plot("Trade", "Daily Roll", daily_roll) if not self.Portfolio[self.front_VX.Symbol].Invested: # Short if the contract is in contango with adaily roll greater than 0.10 if daily_roll > 0.1: hedge_ratio = self.CalculateHedgeRatio() self.Plot("Trade", "Sell", self.Securities[self.vx1].Price) self.SetHoldings(self.front_VX.Symbol, -0.5) self.SetHoldings(self.front_ES.Symbol, -0.5*hedge_ratio) # Long if the contract is in backwardation with adaily roll less than -0.10 elif daily_roll < -0.1: hedge_ratio = self.CalculateHedgeRatio() self.Plot("Trade", "Buy", self.Securities[self.vx1].Price) self.SetHoldings(self.front_VX.Symbol, 0.5) self.SetHoldings(self.front_ES.Symbol, 0.5*hedge_ratio)
Trades are exited when the motivating conditions no longer exist. The exit condition is defined as the daily roll being less than 0.05 for short trades and higher than -0.05 VIX futures points for long trades. If these exit conditions are not triggered, trades are exited two days before the contract expires.
# exit if the daily roll being less than 0.05 if holding short positions if self.Portfolio[self.front_VX.Symbol].IsShort and daily_roll < 0.05: self.Liquidate() self.front_VX = None self.front_ES = None return # exit if the daily roll being greater than -0.05 if holding long positions if self.Portfolio[self.front_VX.Symbol].IsLong and daily_roll > -0.05: self.Liquidate() self.front_VX = None self.front_ES = None return if self.front_VX and self.front_ES: # if these exit conditions are not triggered, trades are exited two days before it expires if self.Portfolio[self.front_VX.Symbol].Invested and self.Portfolio[self.front_ES.Symbol].Invested: if (self.front_VX.Expiry-self.Time).days <=2 or (self.front_ES.Expiry-self.Time).days <=2: self.Liquidate() self.front_VX = None self.front_ES = None return


DB2 Contingency Planning Guidelines
When developing your DB2 disaster recovery plan be sure to consider the following tips and techniques.
Plan Before a Disaster Strikes
Ensure that an adequate disaster recovery plan is in place for the DB2 subsystem. This involves backing up system data sets and system table spaces and integrating the timing of the backups with the needs of each DB2 application.
Remember, the absolute worst time to devise a disaster recovery plan is during a disaster!
Create a Schedule to Ship Vital Image Copies Offsite Regularly
Remember that the RECOVER utility can recover only with the backup tapes sent to the remote site. Updates on the active log at the time of the disaster are lost, as are all archive logs and image copy backup tapes not sent offsite.
Ensure that every table space has a valid offsite image copy backup.
Do Not Forget to Back Up Other Vital DB2 Data
Copying DB2 table space data is not sufficient to ensure a complete disaster recovery plan. Be sure to back up and send offsite all related DB2 libraries, such as
Any DB2 DDL libraries that might be required JCL and proc libraries DBRM libraries Application program load libraries Libraries and passwords for critical third party DB2 products Stored procedure program load libraries Application program, stored procedure source code, and copy book libraries
Use SHRLEVEL REFERENCE for Offsite Copies
SHRLEVEL CHANGE means that other processes can read and modify the table space as the COPY is running. SHRLEVEL REFERENCE means that other processes are permitted only to read the table space data during the COPY utility execution.
When running the COPY utility for offsite backup needs:
If you run COPY with SHRLEVEL CHANGE for an offsite image copy be sure to send the archive logs, or a copy of the archive logs offsite, too. Additionally, ensure that related table spaces are assigned the same quiesce point for recoverability.
Beware of Compression
If your site uses tape-compression software, be sure that the offsite location to be used for disaster recovery uses the same tape-compression software. If it does not, specify the following JCL parm for any offsite image copy data set:
DCB=TRTCH=NOCOMP
Document Your Strategy
Document the backup strategy for each table space (sledgehammer, scalpel, DSN1COPY, or some other internally developed strategy). Document the state of each DB2 application and the DB2 subsystem by producing DB2 Catalog, DB2 Directory, and BSDS reports after producing your offsite backups. Send this information daily to your remote site.
Use an Appropriate Active Log Size
Keep the active log relatively small, but not so small that it affects system performance. Active logging poses a logistical problem. If a disaster strikes, the active log will be lost. Therefore, you will not be able to restore all DB2 data to its state just prior to the disaster. Remember, a disaster implies total loss of your machine or site. At best, data can be restored only back to the last archive log sent offsite. This is one reason to have small active logs, thereby forcing more frequent log archival. If DB2 provided the capability to remote log and remote copy, it would be technically possible to recover data back to its most recent state using remote logs and remote copies.
When the active log is small, consider increasing the maximum number of archive logs for the DB2 subsystem. This maximum is controlled using the MAXARCH DSNZPARM parameter.
| As of DB2 V8, the maximum value acceptable for MAXARCH is 10000. The previous maximum was 1000. |
Automate Use of the ARCHIVE LOG Command
The ARCHIVE LOG command can be used within a job that is submitted periodically, forcing an archive log and creating a copy of the archive log for offsite recovery. This is an important component of the DB2 disaster recovery plan because the BSDS and the SYSIBM.SYSCOPY table, which play a substantial role in the recovery process, are backed up at log archival time. Be sure to put the appropriate procedures in place to move the archive log copies offsite as soon as feasible after the job completes. A tape that is still sitting in the shop when a disaster strikes will be useless for disaster recovery purposes.
The general recommendation for logging is to enable dual logging—both active and archive. If this is the case, be sure to do one of the following:
Keep both archive log sets on site, but make a copy of one of the archive log sets and send that copy offsite. Keep one archive log set on site and send the second set offsite. This alternative creates a greater exposure to the primary site because only one backup of the logs is available on site.
Copy Each Table Space After an Offsite Recovery
Back up each application's table spaces at the remote site immediately after each application has been recovered.
Validate Your Offsite Recovery
Run a battery of SELECT statements against the recovered application tables to validate the state of the data.
Test Your Offsite Recovery Plan
Test your disaster recovery plan before a disaster occurs. This gives you time to correct problems before it is too late. It is wise to schedule at least yearly disaster recovery tests in which disaster conditions are mimicked. The DB2 environment should be recovered at the offsite location minimally once a year to ensure that the plan is up-to-date and able to be implemented in case of a disaster.
CAUTION
If you fail to test your disaster recovery plan, you are basically planning to fail. Without regularly scheduled disaster recovery testing there is no way to be sure that your plan is up-to-date and workable in the event of a disaster.
Appropriate Copying Is Dependent Upon Each Application
DB2 disaster recovery is a complex topic that deserves substantial attention. Each application must be analyzed to uncover its optimal disaster recovery strategy. The frequency of copying will be dependent upon the volatility of the data, the size of the batch window, the length of time allowable for an eventual recovery, and the frequency of log archival.
Include Resumption of Normal Business in Your DR Plan
Be sure to include a section in your disaster recovery plan for returning to "normal" business at a new, real data center. Conducting business from a disaster recovery site can be very costly. A disaster recovery plan with a well-thought-out strategy for resuming normal business practices after the disaster can save time and money.
|


{# (c) Crown Owned Copyright, 2016. Dstl. #}
{% if top_organisations.count > 10 %} Here are the 10 organisations with the most teams. {% else %} {% if top_organisations.count == 1 %} Here is the organisation with the most teams. {% else %} Here are the {{top_organisations.count}} organisations with the most teams. {% endif %} {% endif %}
There aren't enough organisations in the system to display at this moment in time.
{% endif %}


Profile
- Name
- {{auth.userProfile.name}}
- Email
- {{auth.userProfile.email}}
- Nickname
- {{auth.userProfile.nickname}}
- Created At
- {{auth.userProfile.created_at}}
- Updated At
- {{auth.userProfile.updated_at}}
- Address
- {{auth.userProfile.user_metadata.address}}
Edit address
You are not logged in, please click 'Log in' button to login


Email History
| Subject | Message | Status | Sent Date |
|---|---|---|---|
| Subject | Message | Status | Sent Date |
| Tiger Nixon | System Architect | Edinburgh | 61 |
| Garrett Winters | Accountant | Tokyo | 63 |
| Ashton Cox | Junior Technical Author | San Francisco | 66 |
| Cedric Kelly | Senior Javascript Developer | Edinburgh | 22 |
| Airi Satou | Accountant | Tokyo | 33 |
| Brielle Williamson | Integration Specialist | New York | 61 |
| Herrod Chandler | Sales Assistant | San Francisco | 59 |
| Rhona Davidson | Integration Specialist | Tokyo | 55 |
| Colleen Hurst | Javascript Developer | San Francisco | 39 |
| Sonya Frost | Software Engineer | Edinburgh | 23 |
| Jena Gaines | Office Manager | London | 30 |
| Quinn Flynn | Support Lead | Edinburgh | 22 |
| Charde Marshall | Regional Director | San Francisco | 36 |
| Haley Kennedy | Senior Marketing Designer | London | 43 |
| Tatyana Fitzpatrick | Regional Director | London | 19 |
| Michael Silva | Marketing Designer | London | 66 |
| Paul Byrd | Chief Financial Officer (CFO) | New York | 64 |
| Gloria Little | Systems Administrator | New York | 59 |
| Bradley Greer | Software Engineer | London | 41 |
| Dai Rios | Personnel Lead | Edinburgh | 35 |


|
| | Array1D () |
| | Default constructor, which does not allocate any memory. More...
|
| |
| | Array1D (const int &nx) |
| | Constructor that allocates the memory. More...
|
| |
| | Array1D (const int &nx, const double &t) |
| | Constructor that allocates and initializes the data to a value t. More...
|
| |
| Array1D & | operator= (const Array1D &obj) |
| | Assignment operator copies the data structure by value. More...
|
| |
| | Array1D (const Array1D &obj) |
| | Copy constructor. More...
|
| |
| | ~Array1D () |
| | Destructor that frees up the memory. More...
|
| |
| void | Clear () |
| | Function to clear the memory. More...
|
| |
| int | XSize () const |
| | Returns size in the x-direction. More...
|
| |
| int | Length () const |
| | Returns length (i.e. size in the x-direction) More...
|
| |
| void | Resize (const int &nx) |
| | Resizes the array. More...
|
| |
| void | Resize (const int &nx, const double &t) |
| | Resizes the array and sets ALL entries to the specified value. More...
|
| |
| void | SetValue (const double &t) |
| | Set all values in the array to the given value. More...
|
| |
| void | PushBack (const double &t) |
| | Add element to the end of the vector. More...
|
| |
| double * | GetArrayPointer () |
| | Return a pointer to the first element of the data in the vector so we can use it access the data in array format (e.g. for passing it to a Fortran program). More...
|
| |
| const double * | GetConstArrayPointer () const |
| | Return a const point to the first element of the data in the vector so we can use it access the data in array format (e.g. for passing it to a Fortran program). More...
|
| |
| double & | operator() (int ix) |
| |
| const double & | operator() (int ix) const |
| |
| void | insert (Array1D< double > &insarr, int ix) |
| | Insert a given array to the position ix. More...
|
| |
| void | insert (const double &insval, int ix) |
| | Insert a given value to the position ix. More...
|
| |
| void | erase (int ix) |
| | Erase the value from the position ix. More...
|
| |
| void | DumpBinary (FILE *f_out) const |
| | Dump contents of the array to a file in binary format. More...
|
| |
| void | ReadBinary (FILE *f_in) |
| | Read contents of the array from a file in binary format. More...
|
| |
| double & | operator[] (int i) |
| |
| vector< int > | shape () |
| |
| void | assign (const int x, const double val) |
| |
| void | DumpBinary (char *filename) |
| | Dump contents of the array to a file in binary format. More...
|
| |
| void | ReadBinary (char *filename) |
| |
| void | DumpBinary4py (char *filename) |
| |
| void | ReadBinary4py (char *filename, int n) |
| |
| void | setArray (vector< double > inarray) |
| |
| void | setnpdblArray (vector< double > inarray, int n) |
| |
| void | getnpdblArray (double *outarray) |
| |
| vector< double > | flatten () |
| |
| string | type () |
| |


I was broken from a young age Taking my sulking to the masses Seeing the beauty through the.
I was broken from a young age Taking my sulking to the masses Seeing the beauty through the.
I was broken from a young age Taking my sulking to the masses Seeing the beauty through the.
A small river named Duden flows by their place and supplies it with the necessary regelialia.
A small river named Duden flows by their place and supplies it with the necessary regelialia.
A small river named Duden flows by their place and supplies it with the necessary regelialia.


Evolution charts support ZOOM IN
Just click, hold and drag on the chart to select the are to zoom in. You can go as deep as you want. Click on the chart to go back to initial overview


Gaussian Processes¶
Introduction¶
Gaussian Processes have been used in supervised, unsupervised, and even reinforcement learning problems and are described by an elegant mathematical theory (for an overview of the subject see [1, 4]). They are also very attractive conceptually, since they offer an intuitive way to define priors over functions. And finally, since Gaussian Processes are formulated in a Bayesian setting, they come equipped with a powerful notion of uncertainty.
Happily, Pyro offers some support for Gaussian Processes in the pyro.contrib.gp
module. The goal of this tutorial is to give a brief introduction to Gaussian Processes (GPs) in the context of this module. We will mostly be focusing on how to use the GP interface in Pyro and refer the reader to the references for more details about GPs in general.
The model we’re interested in is defined by
and
Here \(x, x' \in\mathbf{X}\) are points in the input space and \(y\in\mathbf{Y}\) is a point in the output space. \(f\) is a draw from the GP prior specified by the kernel \(\mathbf{K}_f\) and represents a function from \(\mathbf{X}\) to \(\mathbf{Y}\). Finally, \(\epsilon\) represents Gaussian observation noise.
We will use the radial basis function kernel (RBF kernel) as the kernel of our GP:
Here \(\sigma^2\) and \(l\) are parameters that specify the kernel; specifically, \(\sigma^2\) is a variance or amplitude squared and \(l\) is a lengthscale. We’ll get some intuition for these parameters below.
Imports¶
First, we import necessary modules.
[1]:
import os
import matplotlib.pyplot as plt
import torch
import numpy as np
import pyro
import pyro.contrib.gp as gp
import pyro.distributions as dist
from matplotlib.animation import FuncAnimation
from mpl_toolkits.axes_grid1 import make_axes_locatable
import seaborn as sns
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
smoke_test = "CI" in os.environ # ignore; used to check code integrity in the Pyro repo
assert pyro.__version__.startswith('1.8.6')
pyro.set_rng_seed(0)
torch.set_default_tensor_type(torch.DoubleTensor)
Throughout the tutorial we’ll want to visualize GPs. So we define a helper function for plotting:
[2]:
# note that this helper function does three different things:
# (i) plots the observed data;
# (ii) plots the predictions from the learned GP after conditioning on data;
# (iii) plots samples from the GP prior (with no conditioning on observed data)
def plot(
plot_observed_data=False,
plot_predictions=False,
n_prior_samples=0,
model=None,
kernel=None,
n_test=500,
ax=None,
):
if ax is None:
fig, ax = plt.subplots(figsize=(12, 6))
if plot_observed_data:
ax.plot(X.numpy(), y.numpy(), "kx")
if plot_predictions:
Xtest = torch.linspace(-0.5, 5.5, n_test) # test inputs
# compute predictive mean and variance
with torch.no_grad():
if type(model) == gp.models.VariationalSparseGP:
mean, cov = model(Xtest, full_cov=True)
else:
mean, cov = model(Xtest, full_cov=True, noiseless=False)
sd = cov.diag().sqrt() # standard deviation at each input point x
ax.plot(Xtest.numpy(), mean.numpy(), "r", lw=2) # plot the mean
ax.fill_between(
Xtest.numpy(), # plot the two-sigma uncertainty about the mean
(mean - 2.0 * sd).numpy(),
(mean + 2.0 * sd).numpy(),
color="C0",
alpha=0.3,
)
if n_prior_samples > 0: # plot samples from the GP prior
Xtest = torch.linspace(-0.5, 5.5, n_test) # test inputs
noise = (
model.noise
if type(model) != gp.models.VariationalSparseGP
else model.likelihood.variance
)
cov = kernel.forward(Xtest) + noise.expand(n_test).diag()
samples = dist.MultivariateNormal(
torch.zeros(n_test), covariance_matrix=cov
).sample(sample_shape=(n_prior_samples,))
ax.plot(Xtest.numpy(), samples.numpy().T, lw=2, alpha=0.4)
ax.set_xlim(-0.5, 5.5)
Data¶
The data consist of \(20\) points sampled from
with \(x\) sampled uniformly from the interval \([0, 5]\).
[3]:
N = 20
X = dist.Uniform(0.0, 5.0).sample(sample_shape=(N,))
y = 0.5 * torch.sin(3 * X) + dist.Normal(0.0, 0.2).sample(sample_shape=(N,))
plot(plot_observed_data=True) # let's plot the observed data
Define model¶
First we define a RBF kernel, specifying the values of the two hyperparameters variance
and lengthscale
. Then we construct a GPRegression
object. Here we feed in another hyperparameter, noise
, that corresponds to \(\epsilon\) above.
[4]:
kernel = gp.kernels.RBF(
input_dim=1, variance=torch.tensor(6.0), lengthscale=torch.tensor(0.05)
)
gpr = gp.models.GPRegression(X, y, kernel, noise=torch.tensor(0.2))
Let’s see what samples from this GP function prior look like. Note that this is before we’ve conditioned on the data. The shape these functions take—their smoothness, their vertical scale, etc.—is controlled by the GP kernel.
[5]:
plot(model=gpr, kernel=kernel, n_prior_samples=2)
_ = plt.ylim((-8, 8))
For example, if we keep the same variance
and noise
and increase the lengthscale
, we will see smoother function samples.
[6]:
kernel2 = gp.kernels.RBF(
input_dim=1, variance=torch.tensor(6.0), lengthscale=torch.tensor(1)
)
gpr2 = gp.models.GPRegression(X, y, kernel2, noise=torch.tensor(0.2))
plot(model=gpr2, kernel=kernel2, n_prior_samples=2)
_ = plt.ylim((-8, 8))
Now, if we make variance
and noise
smaller we will see function samples with smaller vertical amplitude.
[7]:
kernel3 = gp.kernels.RBF(
input_dim=1, variance=torch.tensor(1.0), lengthscale=torch.tensor(1)
)
gpr3 = gp.models.GPRegression(X, y, kernel3, noise=torch.tensor(0.01))
plot(model=gpr3, kernel=kernel3, n_prior_samples=2)
_ = plt.ylim((-8, 8))
Inference¶
In the above we set the kernel hyperparameters by hand. If we want to learn the hyperparameters from the data, we need to do inference. In the simplest (conjugate) case we do gradient ascent on the log marginal likelihood. In pyro.contrib.gp
, we can use any PyTorch optimizer to optimize parameters of a model. In addition, we need a loss function which takes inputs are the pair model and guide and returns an ELBO loss (see SVI Part
I tutorial).
[8]:
optimizer = torch.optim.Adam(gpr.parameters(), lr=0.005)
loss_fn = pyro.infer.Trace_ELBO().differentiable_loss
losses = []
variances = []
lengthscales = []
noises = []
num_steps = 2000 if not smoke_test else 2
for i in range(num_steps):
variances.append(gpr.kernel.variance.item())
noises.append(gpr.noise.item())
lengthscales.append(gpr.kernel.lengthscale.item())
optimizer.zero_grad()
loss = loss_fn(gpr.model, gpr.guide)
loss.backward()
optimizer.step()
losses.append(loss.item())
[9]:
# let's plot the loss curve after 2000 steps of training
def plot_loss(loss):
plt.plot(loss)
plt.xlabel("Iterations")
_ = plt.ylabel("Loss") # supress output text
plot_loss(losses)
Let’s see if we’re learned anything reasonable:
[10]:
plot(model=gpr, plot_observed_data=True, plot_predictions=True)
Here the thick red curve is the mean prediction and the blue band represents the 2-sigma uncertainty around the mean. It seems we learned reasonable kernel hyperparameters, as both the mean and uncertainty give a reasonable fit to the data. (Note that learning could have easily gone wrong if we e.g. chose too large of a learning rate or chose bad initital hyperparameters.)
Note that the kernel is only well-defined if variance
and lengthscale
are positive. Under the hood Pyro is using PyTorch constraints (see docs) to ensure that hyperparameters are constrained to the appropriate domains. Let’s see the constrained values we’ve learned.
[11]:
gpr.kernel.variance.item()
[11]:
0.21701954305171967
[12]:
gpr.kernel.lengthscale.item()
[12]:
0.513454258441925
[13]:
gpr.noise.item()
[13]:
0.04248063638806343
The period of the sinusoid that generated the data is \(T = 2\pi/3 \approx 2.09\) so learning a lengthscale that’s approximiately equal to a quarter period makes sense. Let us now try to animate and see how our model improves over the training iterations.
[14]:
fig, ax = plt.subplots(figsize=(12, 6))
def update(iteration):
pyro.clear_param_store()
ax.cla()
kernel_iter = gp.kernels.RBF(
input_dim=1,
variance=torch.tensor(variances[iteration]),
lengthscale=torch.tensor(lengthscales[iteration]),
)
gpr_iter = gp.models.GPRegression(
X, y, kernel_iter, noise=torch.tensor(noises[iteration])
)
plot(model=gpr_iter, plot_observed_data=True, plot_predictions=True, ax=ax)
ax.set_title(f"Iteration: {iteration}, Loss: {losses[iteration]:0.2f}")
anim = FuncAnimation(fig, update, frames=np.arange(0, num_steps, 30), interval=100)
plt.close()
anim.save("../source/_static/img/gpr-fit.gif", fps=60)
Fit the model using MAP¶
We need to define priors for the hyperparameters.
[15]:
# Define the same model as before.
pyro.clear_param_store()
kernel = gp.kernels.RBF(
input_dim=1, variance=torch.tensor(5.0), lengthscale=torch.tensor(10.0)
)
gpr = gp.models.GPRegression(X, y, kernel, noise=torch.tensor(1.0))
# note that our priors have support on the positive reals
gpr.kernel.lengthscale = pyro.nn.PyroSample(dist.LogNormal(0.0, 1.0))
gpr.kernel.variance = pyro.nn.PyroSample(dist.LogNormal(0.0, 1.0))
optimizer = torch.optim.Adam(gpr.parameters(), lr=0.005)
loss_fn = pyro.infer.Trace_ELBO().differentiable_loss
losses = []
num_steps = 2000 if not smoke_test else 2
for i in range(num_steps):
optimizer.zero_grad()
loss = loss_fn(gpr.model, gpr.guide)
loss.backward()
optimizer.step()
losses.append(loss.item())
plot_loss(losses)
[16]:
plot(model=gpr, plot_observed_data=True, plot_predictions=True)
Let’s inspect the hyperparameters we’ve learned:
[17]:
# tell gpr that we want to get samples from guides
gpr.set_mode("guide")
print("variance = {}".format(gpr.kernel.variance))
print("lengthscale = {}".format(gpr.kernel.lengthscale))
print("noise = {}".format(gpr.noise))
variance = 0.24472779035568237
lengthscale = 0.5217776894569397
noise = 0.042222216725349426
Note that the MAP values are different from the MLE values due to the prior.
Sparse GPs¶
For large datasets computing the log marginal likelihood is costly due to the expensive matrix operations involved (e.g. see Section 2.2 of [1]). A variety of so-called ‘sparse’ variational methods have been developed to make GPs viable for larger datasets. This is a big area of research and we won’t be going into all the details. Instead we quickly show how we can use SparseGPRegression
in pyro.contrib.gp
to make use of these methods.
First, we generate more data.
[18]:
N = 1000
X = dist.Uniform(0.0, 5.0).sample(sample_shape=(N,))
y = 0.5 * torch.sin(3 * X) + dist.Normal(0.0, 0.2).sample(sample_shape=(N,))
plot(plot_observed_data=True)
Using the sparse GP is very similar to using the basic GP used above. We just need to add an extra parameter \(X_u\) (the inducing points). Let us initialize the inducing points uniformly. During the course of learning, we will also optimize the locations of these inducing points.
[19]:
N = 1000
X = dist.Uniform(0.0, 5.0).sample(sample_shape=(N,))
y = 0.5 * torch.sin(3 * X) + dist.Normal(0.0, 0.2).sample(sample_shape=(N,))
plot(plot_observed_data=True)
# initialize the inducing inputs
Xu = torch.arange(20.0) / 4.0
def plot_inducing_points(Xu, ax=None):
for xu in Xu:
g = ax.axvline(xu, color="red", linestyle="-.", alpha=0.5)
ax.legend(
handles=[g],
labels=["Inducing Point Locations"],
bbox_to_anchor=(0.5, 1.15),
loc="upper center",
)
plot_inducing_points(Xu, plt.gca())
[20]:
# initialize the kernel and model
pyro.clear_param_store()
kernel = gp.kernels.RBF(input_dim=1)
# we increase the jitter for better numerical stability
sgpr = gp.models.SparseGPRegression(X, y, kernel, Xu=Xu, jitter=1.0e-5)
# the way we setup inference is similar to above
optimizer = torch.optim.Adam(sgpr.parameters(), lr=0.005)
loss_fn = pyro.infer.Trace_ELBO().differentiable_loss
losses = []
locations = []
variances = []
lengthscales = []
noises = []
num_steps = 2000 if not smoke_test else 2
for i in range(num_steps):
optimizer.zero_grad()
loss = loss_fn(sgpr.model, sgpr.guide)
locations.append(sgpr.Xu.data.numpy().copy())
variances.append(sgpr.kernel.variance.item())
noises.append(sgpr.noise.item())
lengthscales.append(sgpr.kernel.lengthscale.item())
loss.backward()
optimizer.step()
losses.append(loss.item())
[21]:
plot_loss(losses)
Now, we can plot the predictions from the learnt model along with the optimized inducing points locations.
[22]:
plot(model=sgpr, plot_observed_data=True, plot_predictions=True)
plot_inducing_points(sgpr.Xu.data.numpy(), plt.gca())
We can see that the model learns a reasonable fit to the data. We can also see how that the inducing point locations are fairly different from our initialization. We can also view the model learning process via an animation below.
[23]:
fig, ax = plt.subplots(figsize=(12, 6))
def update(iteration):
pyro.clear_param_store()
ax.cla()
kernel_iter = gp.kernels.RBF(
input_dim=1,
variance=torch.tensor(variances[iteration]),
lengthscale=torch.tensor(lengthscales[iteration]),
)
sgpr_iter = gp.models.SparseGPRegression(
X,
y,
kernel_iter,
Xu=torch.tensor(locations[iteration]),
noise=torch.tensor(noises[iteration]),
jitter=1.0e-5,
)
plot(model=sgpr_iter, plot_observed_data=True, plot_predictions=True, ax=ax)
plot_inducing_points(sgpr_iter.Xu.data.numpy(), ax=ax)
ax.set_title(f"Iteration: {iteration}, Loss: {losses[iteration]:0.2f}")
fig.tight_layout()
anim = FuncAnimation(fig, update, frames=np.arange(0, num_steps, 30), interval=100)
plt.close()
anim.save("../source/_static/img/svgpr-fit.gif", fps=60)
There are three different sparse approximations that are currently implemented in Pyro:
“DTC” (Deterministic Training Conditional)
“FITC” (Fully Independent Training Conditional)
“VFE” (Variational Free Energy)
By default, SparseGPRegression
will use “VFE” as the inference method. We can use other methods by passing a different approx
flag to SparseGPRegression
.
More Sparse GPs¶
Both GPRegression
and SparseGPRegression
above are limited to Gaussian likelihoods. We can use other likelihoods with GPs—for example, we can use the Bernoulli likelihood for classification problems—but the inference problem becomes more difficult. In this section, we show how to use the VariationalSparseGP
module, which can handle non-Gaussian likelihoods. So we can compare to what we’ve done above, we’re still going to use a Gaussian likelihood. The point is that the inference
that’s being done under the hood can support other likelihoods.
Gaussian Likelihood¶
[24]:
# initialize the inducing inputs
Xu = torch.arange(10.0) / 2.0
# initialize the kernel, likelihood, and model
pyro.clear_param_store()
kernel = gp.kernels.RBF(input_dim=1)
likelihood = gp.likelihoods.Gaussian()
# turn on "whiten" flag for more stable optimization
vsgp = gp.models.VariationalSparseGP(
X, y, kernel, Xu=Xu, likelihood=likelihood, whiten=True
)
# instead of defining our own training loop, we will
# use the built-in support provided by the GP module
num_steps = 1500 if not smoke_test else 2
losses = gp.util.train(vsgp, num_steps=num_steps)
plot_loss(losses)
[25]:
plot(model=vsgp, plot_observed_data=True, plot_predictions=True)
GP Classification¶
We will now briefly discuss GP classification for multi-class classification. The two main changes needed to the model specification (in comparison to GP regression) are:
or
We will be using the Iris dataset in our example. We will encode the three classes as numbers 0 for setosa, 1 for versicolor, and 2 for virginica. Also, to keep the example simple, we will be considering only two input features (petal length and petal width).
[26]:
df = sns.load_dataset("iris")
df.head()
[26]:
| sepal_length | sepal_width | petal_length | petal_width | species | |
|---|---|---|---|---|---|
| 0 | 5.1 | 3.5 | 1.4 | 0.2 | setosa |
| 1 | 4.9 | 3.0 | 1.4 | 0.2 | setosa |
| 2 | 4.7 | 3.2 | 1.3 | 0.2 | setosa |
| 3 | 4.6 | 3.1 | 1.5 | 0.2 | setosa |
| 4 | 5.0 | 3.6 | 1.4 | 0.2 | setosa |
[27]:
# only take petal length and petal width
X = torch.from_numpy(
df[df.columns[2:4]].values.astype("float64"),
)
df["species"] = df["species"].astype("category")
# encode the species as 0, 1, 2
y = torch.from_numpy(df["species"].cat.codes.values.copy())
[28]:
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Paired, edgecolors=(0, 0, 0))
plt.xlabel("Feature 1 (Petal length)")
_ = plt.ylabel("Feature 2 (Petal width)")
[29]:
kernel = gp.kernels.RBF(input_dim=2)
pyro.clear_param_store()
likelihood = gp.likelihoods.MultiClass(num_classes=3)
# Important -- we need to add latent_shape argument here to the number of classes we have in the data
model = gp.models.VariationalGP(
X,
y,
kernel,
likelihood=likelihood,
whiten=True,
jitter=1e-03,
latent_shape=torch.Size([3]),
)
num_steps = 1000
loss = gp.util.train(model, num_steps=num_steps)
[30]:
plot_loss(loss)
[31]:
mean, var = model(X)
y_hat = model.likelihood(mean, var)
print(f"Accuracy: {(y_hat==y).sum()*100/(len(y)) :0.2f}%")
Accuracy: 96.00%
We can also calculate the confusion matrix.
[32]:
cm = confusion_matrix(y, y_hat, labels=[0, 1, 2])
ConfusionMatrixDisplay(cm).plot()
[32]:
<sklearn.metrics._plot.confusion_matrix.ConfusionMatrixDisplay at 0x133782b80>
As before, let us plot our predictions over a 2d grid.
[33]:
xs = torch.linspace(X[:, 0].min() - 0.5, X[:, 0].max() + 0.5, steps=100)
ys = torch.linspace(X[:, 1].min() - 0.5, X[:, 1].max() + 0.5, steps=100)
xx, yy = torch.meshgrid(xs, ys, indexing="xy")
with torch.no_grad():
mean, var = model(torch.vstack((xx.ravel(), yy.ravel())).t())
Z = model.likelihood(mean, var)
[34]:
def plot_pred_2d(arr, xx, yy, contour=False, ax=None, title=None):
if ax is None:
fig, ax = plt.subplots()
image = ax.imshow(
arr,
interpolation="nearest",
extent=(xx.min(), xx.max(), yy.min(), yy.max()),
aspect="equal",
origin="lower",
cmap=plt.cm.PuOr_r,
)
if contour:
contours = ax.contour(
xx,
yy,
torch.sigmoid(mean).reshape(xx.shape),
levels=[0.5],
linewidths=2,
colors=["k"],
)
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.1)
ax.get_figure().colorbar(image, cax=cax)
if title:
ax.set_title(title)
[35]:
fig, ax = plt.subplots(ncols=3, figsize=(16, 4))
for cl in [0, 1, 2]:
plot_pred_2d(
mean[cl, :].reshape(xx.shape), xx, yy, ax=ax[cl], title=f"f (class {cl})"
)
[36]:
p_class = torch.nn.functional.softmax(mean, dim=0)
[37]:
fig, ax = plt.subplots(ncols=3, figsize=(16, 4))
for cl in [0, 1, 2]:
plot_pred_2d(
p_class[cl, :].reshape(xx.shape), xx, yy, ax=ax[cl], title=f" p(class {cl})"
)
[38]:
plot_pred_2d(Z.reshape(xx.shape), xx, yy, title="Prediction")
We can see our model doing a good job in classifying the IRIS data based on the two features.
Combining Kernels¶
We now look into combining different kernels. We will create a simple data set containing a linear trend and some periodicity.
[39]:
X = torch.linspace(-5, 5, 100)
y = torch.sin(X * 8) + 2 * X + 4 + 0.2 * torch.rand_like(X)
plt.scatter(X, y)
plt.show()
We can clearly see a trend in the data. Let us use a combined kernel as follows:
Linear + RBF * Periodic
[40]:
pyro.clear_param_store()
linear = gp.kernels.Linear(
input_dim=1,
)
periodic = gp.kernels.Periodic(
input_dim=1, period=torch.tensor(0.5), lengthscale=torch.tensor(4.0)
)
rbf = gp.kernels.RBF(
input_dim=1, lengthscale=torch.tensor(0.5), variance=torch.tensor(0.5)
)
k1 = gp.kernels.Product(kern0=rbf, kern1=periodic)
k = gp.kernels.Sum(linear, k1)
model = gp.models.GPRegression(
X=X,
y=y,
kernel=k,
jitter=2e-3,
)
loss = gp.util.train(model)
plot_loss(loss)
[41]:
plt.scatter(X, y, s=50, alpha=0.5)
with torch.no_grad():
mean, var = model(X)
_ = plt.plot(X, mean, color="C3", lw=2)
We can see that our combination of kernel does a fairly good job in learning the inherent trend and periodicity in the data.
That’s all there is to it. For more details on the pyro.contrib.gp
module see the docs. For an example on binary classification see here, for an example on deep kernel learning see here, and for an advanced example for GP classification using deep kernel learning see
here.
Reference¶
[1] Deep Gaussian processes and variational propagation of uncertainty
, Andreas Damianou
[2] A unifying framework for sparse Gaussian process approximation using power expectation propagation
, Thang D. Bui, Josiah Yan, and Richard E. Turner
[3] Scalable variational Gaussian process classification
, James Hensman, Alexander G. de G. Matthews, and Zoubin Ghahramani
[4] Gaussian Processes for Machine Learning
, Carl E. Rasmussen, and Christopher K. I. Williams
[5] A Unifying View of Sparse Approximate Gaussian Process Regression
, Joaquin Quinonero-Candela, and Carl E. Rasmussen


If global onError function set up, favor using it even for require callback errors. More info.
Check console for messages


This html doc is the notes for Steve Huffman's The Basics of the Web and HTML. It is also the first project Stage 0 for Udacity's Nanodegree:Introduction to Programming. An example of what the project is supposed to resemble can be found at Andy Brown's Codepen samples.
WWW (World Wide Web)-Collection of HTML docs
HTML (HyperText Markup Language)-glues everything together
Hyper Links-make the web web-like
Major Pieces of the Web:
you -> Computer & Browser = Program that runs on your PC to display files found on web -> Internet = world's largest computer network -> HTTP (HyperText Transfer Protocol) = Main Protocol of Web(to communicate with) -> Servers = computers hosting files that make up web
Computers are stupid and need exact programming instructions to run properly.
HTML is made up of:
plain text = text that is unformated
text content = what you see
markup = what it looks like
references to other documents, e.g. imges & videos
links to other pages
HTML markup is made of tags. Tags usually have an opening tag, <tag name>, content, and a closing tag, </tag name>. Some tags like the break tag,
, does not have a closing tag and are called void tags. Complete tags can also be referred to as elements. Tags may also have attributes such as src for the image tag. An example of a tag: This is a bold tag.
There are two basic types of tags: inline elements and block elements.
HTML treats all continuous white space as a single white space.
Internet, servers, browsers, http
1) Web Page=text doc written in HTML.  Little mistakes can be big trouble
4) Programmers can't remember all. Google. Stackoverflow
5) Intro to HTML
tags: inline elements, block elements, void tags, attribute (property of an element)


My Second Post
Wed Aug 22 2012 19:00:00 GMT-0500 (Central Daylight Time)
A super-interesting piece of prose I had already written weeks ago.


SOLUTION
提供了一个开放的应用上传，发布，交流，分享的网络平台，打造更加便利的电视应用生态圈。
SERVICE
SYSTEM INTEGRATION SERVICES
NETWORK DEPLOYMENT SERVICES
OTT OPERATION PROMOTION SERVICES
TECHNICAL SUPPORT SERVICES
PRODUCT
DVB-S2+CA+LAN+USB+WIFI


Because I'm just ... um .... I don't know. Why give an interview when you can leave a warning, you know?  Be one of us.' News flash! I am special, and I'll never be one of you! ... There it is.
You know, he might be Nails, but I'm frickin' bayonets, you know? I am battle-tested bayonets, bro. But ... whatever. I agreed to do it. There's just one deal point that Jim Robinson - a wonderful man at Morgan Creek, a great company - need to work out is they want me in it. If they do, it's a smash. If they don't, it's a turd that opens on a tugboat.
You know, he might be Nails, but I'm frickin' bayonets, you know? I am battle-tested bayonets, bro. Yeah, but I can't use the word 'sober' because that's a term from 'those people', and I have cleansed myself.


load table from server url
+
ok
{{ selectedLayout.name }}
Rotation
-
{{ rotation }}
+
Top/Y
-
{{ top }}
+
Left/X
-
{{ left }}
+
Width
-
{{ width }}
+
Height
-
{{ height }}
+
Shape
Rect
Circle
Status
Enable
Disable
Action
Rename
Delete
+ add table
return
ok
share
saved in localStorage
{{ layout.name }}
rename
rename
delete layout
cancel
{{ layout.name }}
rename
rename
delete table
cancel


What is Rails?
"Rails is a web application development framework written in the Ruby language. It is designed to make programming web applications easier by making assumptions about what every developer needs to get started. It allows you to write less code while accomplishing more than many other languages and frameworks." To fully understand what this means, let us go back to the beginning...
What is Ruby?
In its most basic form, Ruby is an object oriented programming language known for its readablility. It is similar in structure to the english written language and doesn't adhere to the strict constructs of most other programming languages. It aims to be user-friendy as opposed to other languages which are more concerned with being computer friendly.
Rails is a software library that can be added to the Ruby programming language. It is a Ruby gem that is added via the computers command line and is a framework for building websites. What this means is that Rails can combine the Ruby programming language with the front-end design of HTML and CSS as well as Javascript to create web applications.
A more in-depth explanation of Ruby on Rails would be that it is a Model-View-Controller framework fro creating database-driven websites in Ruby. But what is a Model-View-Controller framework?
Model-View-Controller or (MVC) is a way to divide the web application into different sections. The model is responsible for database interactions, the controller handles all the web server interaction and the view generates the HTML code that is displayed to the user. In lamens terms, it can be described as a tri-level system. The user interface is the first layer in which the user can interact with the application via the browser much like they would any website. The application layer is the middle section which utilizes Ruby to communicate between the user layer and the database layer. The database layer is the third and final layer which stores all the user data. An example could be a user purchasing items online, the users info. would be stored in the database, including the items in their cart and personal info, etc.
The Rails Philosophy
- Don't Repeat Yourself: "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system." The idea behind DRY code is that developers shoudl ensure to write reusable code which will make their programs more maintainable.
- Convention Over Configuration: The Rials framework has "opinions" on how to do certain things to maintain best practices. This ensures that the developer doesn't have to waste time with tedious work and can focus on the bigger picture


{{ define "title" }}{{ .Site.Title }}: Accessible CS exploration programs for all{{ end}} {{ define "body_classes" }}page-home{{ end }} {{ define "meta_tags" }} {{ end }} {{ define "main" }}
We're hard at work planning something new. Interested in getting a preview and sharing some thoughts? Contact us, and we'd love to chat with you!
{{ .Description | default .Content | plainify | htmlUnescape | truncate 240 "…" }}


Site Header
Section 1
Some article text
Section 2
Some article text
Section 3
Some article text
Section 4
Some article text


Removes the given events from the calendar. ## Syntax
removeEvents(events: <#Variable#>, includeFuture: <#Boolean#>)
removeEvents(events: myEvents, includeFuture: true)


| DOSE: |
14 mg |
transdermal |
Nicotine |
(patch) |
Summary:
A deliberately sleep-deprived non-smoker puts on a strong nicotine patch to investigate the effect of nicotine on dreaming.
Conclusion:
Interesting dreams in which I 'felt'¯ someone else was present, but the physical reactions to the nicotine were awful. I don't recommend it.
---
I'd been informed by a friend that when she started using nicotine patches she experienced strange dreams, apparently her brain wasn't used to the nicotine while asleep.
I'd been a smoker once but hadn't smoked for over 2 years.
I was taking no other medication of any sort, and was generally healthy of mind and body. I deliberately hadn't slept for about the preceding 40 hours.
I applied one 14mg nicotine patch to my back. About 45 minutes later I began to experience the light headiness I associate with smoking and my leg began quivering, though I could control it if I chose.
By 75 minutes in, I had begun to feel quite nauseous, dizzy and uncomfortable. At about the 90 minute, my head was swimming and I was rolling around on the couch feeling very bad. The part of my brain that warms me 'something's wrong, something's not right' was screaming just that.
At about this point I felt certain I was going to vomit so I ran outside. I felt so bad after only an hour and a half that I ripped off the patch and threw it away. I didn't vomit.
After 10 minutes outside the queasiness began to subside. I went back in and, head still swimming, lay down.
I don't recall falling asleep. The next thing I recall is having a conversation with someone, it was a very interesting conversation about something concrete, but I no longer remember the topic. We were talking talk in two different languages, one was very fast and easy, the other 'normal speech' took considerably more effort and we used it rarely to say only one or two significant words. After some considerable conversation, I got carried away talking for a while excitedly in the fast, easy form. I realised I had begun to loose awareness of my partner because suddenly she said, in normal speech, in a slightly amused, but friendly and warm tone, 'go to sleep'. This made me realise that I was lying on the couch about to fall asleep.  This I actually did say out loud in the real world and doing so woke me up completely.
I felt very strange after waking. This may sound like a normal dream but there's two key things which were very different.
Firstly my conversation partner wasn't present in the normal way people are present in dreams, which is more akin to 'imagesā' or 'ideas'. She 'felt'¯ present in the very real way people feel right next to you when you are talking to them, so much so that I felt very strongly impelled to look for her under the cushions after I awoke. I suspect that the part of my brain which tracks the presence of other humans was active, while usually during sleeping it's not.
Secondly, usually in dreams things somehow follow a logical flow based on me at the centre of them. My partner's statement of 'go to sleep'¯ was very unexpected and felt like something external someone had butted in and said, not something that had been generated internally by my mind. I'm not sure if I've explained this well. I wasn't myself aware that one could feel something external was intruding into one's dream state until this happened, but that's how it felt.
All in all: the dreams were interesting but the nicotine patch was awful.
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.