text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;

namespace iiNotificationService
{
    /// <summary>
    /// iiNotificationContants provide all necessary values.
    /// </summary>
    public class iiNotificationConstants
    {
        #region Constant Values

        public const string iiGcmRegistration = "com.google.android.c2dm.intent.REGISTER";

        /**
        * Intent sent to GCM to unregister the application.
        */
        public const string iiGcmUnRegistration = "com.google.android.c2dm.intent.UNREGISTER";

        /**
        * Intent sent by GCM indicating with the result of a registration request.
        */
        public const string iiGcmRegistrationCallback = "com.google.android.c2dm.intent.REGISTRATION";

        /**
        * Intent used by the GCM library to indicate that the registration call
        * should be retried.
        */
        public const string iiGcmLibraryRetry = "com.google.android.gcm.intent.RETRY";

        /**
        * Intent sent by GCM containing a message.
        */
        public const string iiGcmMessage = "com.google.android.c2dm.intent.RECEIVE";

        /**
        * Extra used on {@link #INTENT_TO_GCM_REGISTRATION} to indicate the sender
        * account (a Google email) that owns the application.
        */
        public const string iiExtraSender = "sender";

        /**
        * Extra used on {@link #INTENT_TO_GCM_REGISTRATION} to get the application
        * id.
        */
        public const string iiExtraAppPendingIntent = "app";

        /**
        * Extra used on {@link #INTENT_FROM_GCM_REGISTRATION_CALLBACK} to indicate
        * that the application has been unregistered.
        */
        public const string iiExtraUnregistered = "unregistered";

        /**
        * Extra used on {@link #INTENT_FROM_GCM_REGISTRATION_CALLBACK} to indicate
        * an error when the registration fails. See constants starting with ERROR_
        * for possible values.
        */
        public const string iiExtraError = "error";

        /**
        * Extra used on {@link #INTENT_FROM_GCM_REGISTRATION_CALLBACK} to indicate
        * the registration id when the registration succeeds.
        */
        public const string iiExtraRegistrationID = "registration_id";

        /**
        * Type of message present in the {@link #INTENT_FROM_GCM_MESSAGE} intent.
        * This extra is only set for special messages sent from GCM, not for
        * messages originated from the application.
        */
        public const string iiExtraSpecialMessage = "message_type";

        /**
        * Special message indicating the server deleted the pending messages.
        */
        public const string iiValueDeletedMessages = "deleted_messages";

        /**
        * Number of messages deleted by the server because the device was idle.
        * Present only on messages of special type
        * {@link #VALUE_DELETED_MESSAGES}
        */
        public const string iiExtraTotalDeleted = "total_deleted";

        /**
        * Permission necessary to receive GCM intents.
        */
        public const string iiPermissionGcmIntents = "com.google.android.c2dm.permission.SEND";

        /**
        * @see GCMBroadcastReceiver
        */
        public const string iiDefaultIntentServiceClassName = ".GCMIntentService";

        /**
        * The device can't read the response, or there was a 500/503 from the
        * server that can be retried later. The application should use exponential
        * back off and retry.
        */
        public const string iiErrorSrviceNotAvailable = "SERVICE_NOT_AVAILABLE";

        /**
        * There is no Google account on the phone. The application should ask the
        * user to open the account manager and add a Google account.
        */
        public const string iiErrorAccountMissing = "ACCOUNT_MISSING";

        /**
        * Bad password. The application should ask the user to enter his/her
        * password, and let user retry manually later. Fix on the device side.
        */
        public const string iiErrorAuthenticationFailed = "AUTHENTICATION_FAILED";

        /**
        * The request sent by the phone does not contain the expected parameters.
        * This phone doesn't currently support GCM.
        */
        public const string iiErrorInvalidParameters = "INVALID_PARAMETERS";
        /**
        * The sender account is not recognized. Fix on the device side.
        */
        public const string iiErrorInvalidSender = "INVALID_SENDER";

        /**
        * Incorrect phone registration with Google. This phone doesn't currently
        * support GCM.
        */
        public const string iiErrorPhoneRegistrationError = "PHONE_REGISTRATION_ERROR";

        #endregion
    }
}


text:
package com.tsy.sdk.social.listener;

import com.tsy.sdk.social.PlatformType;

/**
 * 分享回调监听
 * Created by tsy on 16/8/5.
 */
public interface ShareListener {
    void onComplete(PlatformType platform_type);

    void onError(PlatformType platform_type, String err_msg);

    void onCancel(PlatformType platform_type);
}

redpajama_set_name: RedPajamaGithub


text:
@-webkit-keyframes passing-through {
  0% {
    opacity: 0;
    -webkit-transform: translateY(40px);
    -moz-transform: translateY(40px);
    -ms-transform: translateY(40px);
    -o-transform: translateY(40px);
    transform: translateY(40px); }
  30%, 70% {
    opacity: 1;
    -webkit-transform: translateY(0px);
    -moz-transform: translateY(0px);
    -ms-transform: translateY(0px);
    -o-transform: translateY(0px);
    transform: translateY(0px); }
  100% {
    opacity: 0;
    -webkit-transform: translateY(-40px);
    -moz-transform: translateY(-40px);
    -ms-transform: translateY(-40px);
    -o-transform: translateY(-40px);
    transform: translateY(-40px); } }
@-moz-keyframes passing-through {
  0% {
    opacity: 0;
    -webkit-transform: translateY(40px);
    -moz-transform: translateY(40px);
    -ms-transform: translateY(40px);
    -o-transform: translateY(40px);
    transform: translateY(40px); }
  30%, 70% {
    opacity: 1;
    -webkit-transform: translateY(0px);
    -moz-transform: translateY(0px);
    -ms-transform: translateY(0px);
    -o-transform: translateY(0px);
    transform: translateY(0px); }
  100% {
    opacity: 0;
    -webkit-transform: translateY(-40px);
    -moz-transform: translateY(-40px);
    -ms-transform: translateY(-40px);
    -o-transform: translateY(-40px);
    transform: translateY(-40px); } }
@keyframes passing-through {
  0% {
    opacity: 0;
    -webkit-transform: translateY(40px);
    -moz-transform: translateY(40px);
    -ms-transform: translateY(40px);
    -o-transform: translateY(40px);
    transform: translateY(40px); }
  30%, 70% {
    opacity: 1;
    -webkit-transform: translateY(0px);
    -moz-transform: translateY(0px);
    -ms-transform: translateY(0px);
    -o-transform: translateY(0px);
    transform: translateY(0px); }
  100% {
    opacity: 0;
    -webkit-transform: translateY(-40px);
    -moz-transform: translateY(-40px);
    -ms-transform: translateY(-40px);
    -o-transform: translateY(-40px);
    transform: translateY(-40px); } }
@-webkit-keyframes slide-in {
  0% {
    opacity: 0;
    -webkit-transform: translateY(40px);
    -moz-transform: translateY(40px);
    -ms-transform: translateY(40px);
    -o-transform: translateY(40px);
    transform: translateY(40px); }
  30% {
    opacity: 1;
    -webkit-transform: translateY(0px);
    -moz-transform: translateY(0px);
    -ms-transform: translateY(0px);
    -o-transform: translateY(0px);
    transform: translateY(0px); } }
@-moz-keyframes slide-in {
  0% {
    opacity: 0;
    -webkit-transform: translateY(40px);
    -moz-transform: translateY(40px);
    -ms-transform: translateY(40px);
    -o-transform: translateY(40px);
    transform: translateY(40px); }
  30% {
    opacity: 1;
    -webkit-transform: translateY(0px);
    -moz-transform: translateY(0px);
    -ms-transform: translateY(0px);
    -o-transform: translateY(0px);
    transform: translateY(0px); } }
@keyframes slide-in {
  0% {
    opacity: 0;
    -webkit-transform: translateY(40px);
    -moz-transform: translateY(40px);
    -ms-transform: translateY(40px);
    -o-transform: translateY(40px);
    transform: translateY(40px); }
  30% {
    opacity: 1;
    -webkit-transform: translateY(0px);
    -moz-transform: translateY(0px);
    -ms-transform: translateY(0px);
    -o-transform: translateY(0px);
    transform: translateY(0px); } }
@-webkit-keyframes pulse {
  0% {
    -webkit-transform: scale(1);
    -moz-transform: scale(1);
    -ms-transform: scale(1);
    -o-transform: scale(1);
    transform: scale(1); }
  10% {
    -webkit-transform: scale(1.1);
    -moz-transform: scale(1.1);
    -ms-transform: scale(1.1);
    -o-transform: scale(1.1);
    transform: scale(1.1); }
  20% {
    -webkit-transform: scale(1);
    -moz-transform: scale(1);
    -ms-transform: scale(1);
    -o-transform: scale(1);
    transform: scale(1); } }
@-moz-keyframes pulse {
  0% {
    -webkit-transform: scale(1);
    -moz-transform: scale(1);
    -ms-transform: scale(1);
    -o-transform: scale(1);
    transform: scale(1); }
  10% {
    -webkit-transform: scale(1.1);
    -moz-transform: scale(1.1);
    -ms-transform: scale(1.1);
    -o-transform: scale(1.1);
    transform: scale(1.1); }
  20% {
    -webkit-transform: scale(1);
    -moz-transform: scale(1);
    -ms-transform: scale(1);
    -o-transform: scale(1);
    transform: scale(1); } }
@keyframes pulse {
  0% {
    -webkit-transform: scale(1);
    -moz-transform: scale(1);
    -ms-transform: scale(1);
    -o-transform: scale(1);
    transform: scale(1); }
  10% {
    -webkit-transform: scale(1.1);
    -moz-transform: scale(1.1);
    -ms-transform: scale(1.1);
    -o-transform: scale(1.1);
    transform: scale(1.1); }
  20% {
    -webkit-transform: scale(1);
    -moz-transform: scale(1);
    -ms-transform: scale(1);
    -o-transform: scale(1);
    transform: scale(1); } }
.dropzone, .dropzone * {
  box-sizing: border-box; }

.dropzone {
  min-height: 150px;
  border: 2px solid rgba(0, 0, 0, 0.3);
  background: white;
  padding: 20px 20px; }
  .dropzone.dz-clickable {
    cursor: pointer; }
    .dropzone.dz-clickable * {
      cursor: default; }
    .dropzone.dz-clickable .dz-message, .dropzone.dz-clickable .dz-message * {
      cursor: pointer; }
  .dropzone.dz-started .dz-message {
    display: none; }
  .dropzone.dz-drag-hover {
    border-style: solid; }
    .dropzone.dz-drag-hover .dz-message {
      opacity: 0.5; }
  .dropzone .dz-message {
    text-align: center;
    margin: 2em 0; }
  .dropzone .dz-preview {
    position: relative;
    display: inline-block;
    vertical-align: top;
    margin: 16px;
    min-height: 100px; }
    .dropzone .dz-preview:hover {
      z-index: 1000; }
      .dropzone .dz-preview:hover .dz-details {
        opacity: 1; }
    .dropzone .dz-preview.dz-file-preview .dz-image {
      border-radius: 20px;
      background: #999;
      background: linear-gradient(to bottom, #eee, #ddd); }
    .dropzone .dz-preview.dz-file-preview .dz-details {
      opacity: 1; }
    .dropzone .dz-preview.dz-image-preview {
      background: white; }
      .dropzone .dz-preview.dz-image-preview .dz-details {
        -webkit-transition: opacity 0.2s linear;
        -moz-transition: opacity 0.2s linear;
        -ms-transition: opacity 0.2s linear;
        -o-transition: opacity 0.2s linear;
        transition: opacity 0.2s linear; }
    .dropzone .dz-preview .dz-remove {
      font-size: 14px;
      text-align: center;
      display: block;
      cursor: pointer;
      border: none; }
      .dropzone .dz-preview .dz-remove:hover {
        text-decoration: underline; }
    .dropzone .dz-preview:hover .dz-details {
      opacity: 1; }
    .dropzone .dz-preview .dz-details {
      z-index: 20;
      position: absolute;
      top: 0;
      left: 0;
      opacity: 0;
      font-size: 13px;
      min-width: 100%;
      max-width: 100%;
      padding: 2em 1em;
      text-align: center;
      color: rgba(0, 0, 0, 0.9);
      line-height: 150%; }
      .dropzone .dz-preview .dz-details .dz-size {
        margin-bottom: 1em;
        font-size: 16px; }
      .dropzone .dz-preview .dz-details .dz-filename {
        white-space: nowrap; }
        .dropzone .dz-preview .dz-details .dz-filename:hover span {
          border: 1px solid rgba(200, 200, 200, 0.8);
          background-color: rgba(255, 255, 255, 0.8); }
        .dropzone .dz-preview .dz-details .dz-filename:not(:hover) {
          overflow: hidden;
          text-overflow: ellipsis; }
          .dropzone .dz-preview .dz-details .dz-filename:not(:hover) span {
            border: 1px solid transparent; }
      .dropzone .dz-preview .dz-details .dz-filename span, .dropzone .dz-preview .dz-details .dz-size span {
        background-color: rgba(255, 255, 255, 0.4);
        padding: 0 0.4em;
        border-radius: 3px; }
    .dropzone .dz-preview:hover .dz-image img {
      -webkit-transform: scale(1.05, 1.05);
      -moz-transform: scale(1.05, 1.05);
      -ms-transform: scale(1.05, 1.05);
      -o-transform: scale(1.05, 1.05);
      transform: scale(1.05, 1.05);
      -webkit-filter: blur(8px);
      filter: blur(8px); }
    .dropzone .dz-preview .dz-image {
      border-radius: 20px;
      overflow: hidden;
      width: 120px;
      height: 120px;
      position: relative;
      display: block;
      z-index: 10; }
      .dropzone .dz-preview .dz-image img {
        display: block; }
    .dropzone .dz-preview.dz-success .dz-success-mark {
      -webkit-animation: passing-through 3s cubic-bezier(0.77, 0, 0.175, 1);
      -moz-animation: passing-through 3s cubic-bezier(0.77, 0, 0.175, 1);
      -ms-animation: passing-through 3s cubic-bezier(0.77, 0, 0.175, 1);
      -o-animation: passing-through 3s cubic-bezier(0.77, 0, 0.175, 1);
      animation: passing-through 3s cubic-bezier(0.77, 0, 0.175, 1); }
    .dropzone .dz-preview.dz-error .dz-error-mark {
      opacity: 1;
      -webkit-animation: slide-in 3s cubic-bezier(0.77, 0, 0.175, 1);
      -moz-animation: slide-in 3s cubic-bezier(0.77, 0, 0.175, 1);
      -ms-animation: slide-in 3s cubic-bezier(0.77, 0, 0.175, 1);
      -o-animation: slide-in 3s cubic-bezier(0.77, 0, 0.175, 1);
      animation: slide-in 3s cubic-bezier(0.77, 0, 0.175, 1); }
    .dropzone .dz-preview .dz-success-mark, .dropzone .dz-preview .dz-error-mark {
      pointer-events: none;
      opacity: 0;
      z-index: 500;
      position: absolute;
      display: block;
      top: 50%;
      left: 50%;
      margin-left: -27px;
      margin-top: -27px; }
      .dropzone .dz-preview .dz-success-mark svg, .dropzone .dz-preview .dz-error-mark svg {
        display: block;
        width: 54px;
        height: 54px; }
    .dropzone .dz-preview.dz-processing .dz-progress {
      opacity: 1;
      -webkit-transition: all 0.2s linear;
      -moz-transition: all 0.2s linear;
      -ms-transition: all 0.2s linear;
      -o-transition: all 0.2s linear;
      transition: all 0.2s linear; }
    .dropzone .dz-preview.dz-complete .dz-progress {
      opacity: 0;
      -webkit-transition: opacity 0.4s ease-in;
      -moz-transition: opacity 0.4s ease-in;
      -ms-transition: opacity 0.4s ease-in;
      -o-transition: opacity 0.4s ease-in;
      transition: opacity 0.4s ease-in; }
    .dropzone .dz-preview:not(.dz-processing) .dz-progress {
      -webkit-animation: pulse 6s ease infinite;
      -moz-animation: pulse 6s ease infinite;
      -ms-animation: pulse 6s ease infinite;
      -o-animation: pulse 6s ease infinite;
      animation: pulse 6s ease infinite; }
    .dropzone .dz-preview .dz-progress {
      opacity: 1;
      z-index: 1000;
      pointer-events: none;
      position: absolute;
      height: 16px;
      left: 50%;
      top: 50%;
      margin-top: -8px;
      width: 80px;
      margin-left: -40px;
      background: rgba(255, 255, 255, 0.9);
      -webkit-transform: scale(1);
      border-radius: 8px;
      overflow: hidden; }
      .dropzone .dz-preview .dz-progress .dz-upload {
        background: #333;
        background: linear-gradient(to bottom, #666, #444);
        position: absolute;
        top: 0;
        left: 0;
        bottom: 0;
        width: 0;
        -webkit-transition: width 300ms ease-in-out;
        -moz-transition: width 300ms ease-in-out;
        -ms-transition: width 300ms ease-in-out;
        -o-transition: width 300ms ease-in-out;
        transition: width 300ms ease-in-out; }
    .dropzone .dz-preview.dz-error .dz-error-message {
      display: block; }
    .dropzone .dz-preview.dz-error:hover .dz-error-message {
      opacity: 1;
      pointer-events: auto; }
    .dropzone .dz-preview .dz-error-message {
      pointer-events: none;
      z-index: 1000;
      position: absolute;
      display: block;
      display: none;
      opacity: 0;
      -webkit-transition: opacity 0.3s ease;
      -moz-transition: opacity 0.3s ease;
      -ms-transition: opacity 0.3s ease;
      -o-transition: opacity 0.3s ease;
      transition: opacity 0.3s ease;
      border-radius: 8px;
      font-size: 13px;
      top: 130px;
      left: -10px;
      width: 140px;
      background: #be2626;
      background: linear-gradient(to bottom, #be2626, #a92222);
      padding: 0.5em 1.2em;
      color: white; }
      .dropzone .dz-preview .dz-error-message:after {
        content: '';
        position: absolute;
        top: -6px;
        left: 64px;
        width: 0;
        height: 0;
        border-left: 6px solid transparent;
        border-right: 6px solid transparent;
border-bottom: 6px solid #be2626; }


text:
  dispatch_async(dispatch_get_main_queue(), ^{ code })

// This macro is used to execute a block of code in the main event loop while
// waiting for it to complete.
#define synchronize(code) \
  dispatch_sync(dispatch_get_main_queue(), ^{ code })

static int DesktopStyleToNSWindowStyle(int style) {
  int ns = NSTitledWindowMask | NSUnifiedTitleAndToolbarWindowMask;

  if (style & DesktopWindowCloseable) {
    ns |= NSClosableWindowMask;
  }

  if (style & DesktopWindowMinimizable) {
    ns |= NSMiniaturizableWindowMask;
  }

  if (style & DesktopWindowResizable) {
    ns |= NSResizableWindowMask;
  }

  return ns;
}

static DesktopKeyModifier NSModifierFlagsToDesktopKeyModifiers(NSEventModifierFlags flags) {
  DesktopKeyModifier mods = 0;

  if (flags & NSAlphaShiftKeyMask) {
    mods |= DesktopKeyCapsLock;
  }

  if (flags & NSShiftKeyMask) {
    mods |= DesktopKeyShift;
  }

  if (flags & NSControlKeyMask) {
    mods |= DesktopKeyCtrl;
  }

  if (flags & NSAlternateKeyMask) {
    mods |= DesktopKeyAlt;
  }

  if (flags & NSCommandKeyMask) {
    mods |= DesktopKeyCommand;
  }

  if (flags & NSNumericPadKeyMask) {
    mods |= DesktopKeyNumPad;
  }

  if (flags & NSHelpKeyMask) {
    mods |= DesktopKeyHelp;
  }

  if (flags & NSFunctionKeyMask) {
    mods |= DesktopKeyFn;
  }

  return mods;
}

static DesktopScreen NSScreenToDesktopScreen(NSScreen *screen) {
  DesktopScreen res;
  NSRect frame = [screen frame];
  res.number = [[[screen deviceDescription] valueForKey:@"NSScreenNumber"] intValue];
  res.scale = [screen backingScaleFactor];
  res.bounds = frame;
  return res;
}
// Cocoa's hide/unhide methods on the NSCursor class use a counter mechanism but
// this is not the behavior we want for go-vu. We maintain a boolean flag to
// control that at most one call to hide/unhide is made to change the cursor's
// visibility state.
static BOOL NSCursorIsHidden;

static void NSCursorShow() {
  if (NSCursorIsHidden) {
    NSCursorIsHidden = NO;
    [NSCursor unhide];
  }
}

static void NSCursorHide() {
  if (!NSCursorIsHidden) {
    NSCursorIsHidden = YES;
    [NSCursor hide];
  }
}

// One instance of DesktopView is used for each DesktopWindow, the view makes
// it possible to catch a bunch of events and notifications that are otherwise
// not delivered to the window itself.
@interface DesktopView : NSView<NSApplicationDelegate, NSWindowDelegate> {
  CGPoint movingWindowGrabbed;
  CGPoint movingWindowOrigin;
  CGPoint movingWindowPosition;
  NSTimer *movingWindowTimer;
  NSCursor *cursor;
  BOOL hasMouse;
}
@end

// Instances of this class are used to bridge a NSWindow to a driver.Window
// object living in go land.
//
// The address of the Objective-C object is used as a unique id to pass events
// back and forth between Go and C.
@interface DesktopWindow : NSWindow<NSWindowDelegate> { }
- (CGFloat)titleBarHeight;
- (NSSize)windowWillResize:(NSWindow*)w toSize:(NSSize)s;
@end

@implementation DesktopView

- (id)initWithFrame:(NSRect)frame {
  self = [super initWithFrame:frame];

  if (self) {
    const int opt = NSTrackingMouseEnteredAndExited
      | NSTrackingMouseMoved
      | NSTrackingCursorUpdate
      | NSTrackingActiveAlways
      | NSTrackingEnabledDuringMouseDrag
      | NSTrackingInVisibleRect;

    self->movingWindowGrabbed = CGPointMake(0, 0);
    self->movingWindowOrigin = CGPointMake(0, 0);
    self->movingWindowPosition = CGPointMake(0, 0);
    self->movingWindowTimer = nil;
    self->hasMouse = NO;
    self->cursor = [NSCursor currentCursor];

    [self addTrackingArea:[[NSTrackingArea alloc] initWithRect:NSMakeRect(0, 0, 1, 1)
                                                       options:opt
                                                         owner:self
                                                      userInfo:nil]];
  }

  return self;
}

- (BOOL)acceptsFirstResponder {
  return YES;
}

- (BOOL)isFlipped {
  return YES;
}

- (void)windowDidBecomeKey:(NSNotification*)n {
  handleFocusEvent((__bridge void *) [self window], YES);
}

- (void)windowDidResignKey:(NSNotification*)n {
  handleFocusEvent((__bridge void *) [self window], NO);
}

- (void)windowWillClose:(NSNotification*)n {
  handleCloseEvent((__bridge void *) [self window]);
}

- (void)windowDidMiniaturize:(NSNotification*)n {
  handleMinimizeEvent((__bridge void *) [self window]);
}

- (void)windowDidDeminiaturize:(NSNotification*)n {
  handleRestoreEvent((__bridge void *) [self window]);
}

- (void)windowDidChangeScreen:(NSNotification*)n {
  [self windowDidChangeBackingProperties:n];
}

- (void)windowDidChangeScreenProfile:(NSNotification*)n {
  [self windowDidChangeBackingProperties:n];
}

- (void)windowDidChangeBackingProperties:(NSNotification*)n {
  DesktopWindow *window = (DesktopWindow*) [self window];
  DesktopScreen screen = NSScreenToDesktopScreen([window screen]);
  NSRect frame = [window frame];
  NSPoint point = NSMakePoint(
    frame.origin.x,
    (screen.bounds.origin.y + screen.bounds.size.height) - (frame.origin.y + frame.size.height)
  );

  handleChangeScreenEvent((__bridge void *) window, screen);

  if (!window.miniaturized) {
    handleMoveEvent((__bridge void *) self, point);
    [window windowWillResize:window toSize:frame.size];
    [self setNeedsDisplayInRect:[self frame]];
  }
}

- (BOOL)windowShouldZoom:(NSWindow*)w toFrame:(NSRect)r {
  if (w.zoomed) {
    handleRestoreEvent((__bridge void *) w);
  } else {
    handleMaximizeEvent((__bridge void *) w);
  }
  return YES;
}

- (void)windowWillMove:(NSNotification*)n {
  if (self->movingWindowTimer == nil) {
    self->movingWindowOrigin = [[self window] frame].origin;
    self->movingWindowPosition = self->movingWindowOrigin;
    self->movingWindowGrabbed = [NSEvent mouseLocation];
    self->movingWindowTimer = [NSTimer scheduledTimerWithTimeInterval:0.05
                                                             target:self
                                                           selector:@selector(windowMoveProgress)
                                                           userInfo:nil
                                                            repeats:YES];
  }
}

- (void)windowMoveProgress {
  const NSPoint origin = self->movingWindowOrigin;
  const NSPoint start = self->movingWindowGrabbed;
  const NSPoint mouse = [NSEvent mouseLocation];
  const NSPoint delta = NSMakePoint(mouse.x - start.x, mouse.y - start.y);

  if ((delta.x != 0) || (delta.y != 0)) {
    DesktopWindow *window = (DesktopWindow*) [self window];
    CGFloat title = [window titleBarHeight];
    NSScreen *screen = [window screen];
    NSRect frame = [window frame];
    NSRect display = [screen frame];
    NSPoint point = NSMakePoint(origin.x + delta.x, origin.y + delta.y);
    NSPoint last = self->movingWindowPosition;

    point.y = (display.origin.x + display.size.height) - (point.y + frame.size.height);

    if (point.y < 0) {
      point.y = 0;
    }

    point.y += title;

    if ((point.x != last.x) || (point.y != last.y)) {
      self->movingWindowPosition = point;
      handleMoveEvent((__bridge void *) window, point);
    }
  }

  if (!([NSEvent pressedMouseButtons] & 1)) {
    // It happens sometimes that the windowDidMove notification isn't received
    // after windowWillMove was triggered. In that case we check if the left
    // mouse button is still being pressed, if not we deactivate the timer
    // because the window won't be moved anymore.
    [self->movingWindowTimer invalidate];
    self->movingWindowTimer = nil;
  }
}

- (void)drawRect:(NSRect)r {
  CGContextRef gc = [[NSGraphicsContext currentContext] graphicsPort];

  // Sets the default graphic context state, which has to match how the default
  // context state as defined in the `graphic` package.
  CGContextSetRGBFillColor(gc, 0, 0, 0, 1);
  CGContextSetRGBStrokeColor(gc, 0, 0, 0, 1);

  handleRedrawEvent((__bridge void *) [self window], r, gc);
}

- (void)keyDown:(NSEvent*)e {
  handleKeyDownEvent((__bridge void *) [self window], [e keyCode], NSModifierFlagsToDesktopKeyModifiers([e modifierFlags]), (char *) [[e characters] UTF8String]);
}

- (void)keyUp:(NSEvent*)e {
  handleKeyUpEvent((__bridge void *) [self window], [e keyCode], NSModifierFlagsToDesktopKeyModifiers([e modifierFlags]), (char *) [[e characters] UTF8String]);
}

- (void)mouseEntered:(NSEvent*)e {
  self->hasMouse = YES;
  [self setCursor:self->cursor];
  handleMouseEnterEvent((__bridge void *) [self window], [self eventLocation:e], [NSEvent pressedMouseButtons]);
}

- (void)mouseExited:(NSEvent*)e {
  self->hasMouse = NO;
  [self setCursor:self->cursor];
  handleMouseExitEvent((__bridge void *) [self window], [self eventLocation:e], [NSEvent pressedMouseButtons]);
}

- (void)mouseMoved:(NSEvent*)e {
  handleMouseMoveEvent((__bridge void *) [self window], [self eventLocation:e], [NSEvent pressedMouseButtons]);
}

- (void)mouseDown:(NSEvent*)e {
  int button = 0;

  switch ([e type]) {
  case NSLeftMouseDown:
    button = 1;
    break;
  case NSRightMouseDown:
    button = 2;
    break;
  case NSOtherMouseDown:
    button = [e buttonNumber];
    break;
  default:
    break;
  }

  handleMouseDownEvent((__bridge void *) [self window], [self eventLocation:e], [NSEvent pressedMouseButtons], button, [e clickCount]);
}

- (void)mouseUp:(NSEvent*)e {
  int button = 0;

  switch ([e type]) {
  case NSLeftMouseUp:
    button = 1;
    break;
  case NSRightMouseUp:
    button = 2;
    break;
  case NSOtherMouseUp:
    button = [e buttonNumber];
    break;
  default:
    break;
  }

  handleMouseUpEvent((__bridge void *) [self window], [self eventLocation:e], [NSEvent pressedMouseButtons], button, [e clickCount]);
}

- (void)mouseDragged:(NSEvent*)e {
  int button = 0;

  switch ([e type]) {
  case NSLeftMouseDragged:
    button = 1;
    break;
  case NSRightMouseDragged:
    button = 2;
    break;
  default:
    break;
  }

  handleMouseDragEvent((__bridge void *) [self window], [self eventLocation:e], [NSEvent pressedMouseButtons]);
}

- (NSPoint)eventLocation:(NSEvent*)e {
  NSRect r = [[self window] frame];
  NSPoint p = [self convertPoint:[e locationInWindow] fromView:nil];

  if (p.x < 0) {
    p.x = 0;
  } else if (p.x > r.size.width) {
    p.x = r.size.width;
  }

  if (p.y < 0) {
    p.y = 0;
  } else if (p.y > r.size.height) {
    p.y = r.size.height;
  }

  return p;
}

- (void)viewDidEndLiveResize {
  [self setCursor:self->cursor];
}

- (void)setCursor:(NSCursor*)c {
  if (c == nil) {
    self->cursor = nil;

    if (self->hasMouse) {
      NSCursorHide();
    } else {
      NSCursorShow();
    }

    [self discardCursorRects];
  } else {
    NSRect r = [self frame];
    r.origin.x = 0;
    r.origin.y = 0;

    self->cursor = c;
    [self discardCursorRects];
    [self addCursorRect:r cursor:c];

    if (self->hasMouse) {
      NSCursorShow();

      // For some reason the cursor tracking area will only apply the cursor
      // change if the mouse buttons are released.
      // This is not the behavior we want to if the view has the mouse we force
      // the immidiate change.
      [c set];
    }
  }
}

@end

@implementation DesktopWindow

- (id)initWithConfig:(NSString *)title
                size:(NSSize)size
               style:(int)style {
  // Cocoa allows us to create windows with a zero size, which then don't appear
  // on the screen.
  // This is useless and instead we consider null widths or heights as a request
  // to set the default values (800, arbitrary).
  if (size.width == 0) { size.width = 800; }
  if (size.height == 0) { size.height = 800; }

  self = [super initWithContentRect:NSMakeRect(0, 0, size.width, size.height)
                          styleMask:DesktopStyleToNSWindowStyle(style)
                            backing:NSBackingStoreBuffered
                              defer:NO];

  if (self) {
    if (!(style & DesktopWindowTitled)) {
      [self setStyleMask:[self styleMask] | NSFullSizeContentViewWindowMask];
      [self setTitlebarAppearsTransparent:YES];
    }

    [self setTitle:title];

    defer(
      NSRect frame = [self frame];

      // Fire an initial change screen event to communicate to the higher level
      // what screen the window is gonna be running on.
      handleChangeScreenEvent((__bridge void *) self, NSScreenToDesktopScreen([self screen]));

      // No move event is emitted the first time a window is opened, we emulate
      // this behavior by calling handleMoveEvent explicitly.
      NSScreen *screen = [self screen];
      NSRect display = [screen frame];
      NSPoint point = NSMakePoint(
        frame.origin.x,
        (display.origin.y + display.size.height) - (frame.origin.y + frame.size.height)
      );
      handleMoveEvent((__bridge void *) self, point);

      // No resize event is emitted the first time a window is opened, we emulate
      // this behavior by calling windowWillResize explicitly.
      [self windowWillResize:self toSize:[self frame].size];

      // Creating the inner view has to be done asynchronously because the
      // redraw event gets fired when setContentView is called which results in
      // a deadlock on the display's event mutex is Go land.
      //
      // Note that this also triggers the first focus event, which is perfect
      // since it results in the following events being fired for a new window:
      // - screen
      // - move
      // - resize
      // - focus
      // - redraw
      DesktopView *view = [[DesktopView alloc] initWithFrame:NSMakeRect(0, 0, 0, 0)];
      [self setContentView:view];
      [self setDelegate:view];
      [self center];
      [self makeKeyAndOrderFront:nil];
    );
  }

  return self;
}

- (NSSize)windowWillResize:(NSWindow*)w toSize:(NSSize)s {
  NSSize r = s;

  s.height -= [self titleBarHeight];

  if (s.height < 0) {
    s.height = 0;
  }

  handleResizeEvent((__bridge void *) self, s);
  return r;
}

- (CGFloat)titleBarHeight {
  if ([self titlebarAppearsTransparent]) {
    return 0;
  } else {
    return [DesktopWindow windowTitleBarHeight];
  }
}

- (void)setCursor:(NSCursor*)c {
  DesktopView *view = (DesktopView *) [self contentView];
  [view setCursor:c];
}

+ (CGFloat)windowTitleBarHeight {
  NSRect frame = NSMakeRect(0, 0, 100, 100);
  NSRect rect = [NSWindow contentRectForFrameRect:frame
                                        styleMask:NSTitledWindowMask];
  return frame.size.height - rect.size.height;
}

@end

// =============================================================================
// DesktopApp_*
// =============================================================================

void DesktopApp_Init() {
  [NSApplication sharedApplication];
  [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
  [NSApp activateIgnoringOtherApps:YES];
}

void DesktopApp_Run() {
  [NSApp run];
}

void DesktopApp_Stop() {
  defer(
    // TODO:
    //
    // Calling terminate actually exits the program and doesn't give ontrol back
    // to the Go program... this is OK for now but it would be better to allow
    // the app to terminate so deferred functions can execute for example.
    //
    // This can be easily acheived by called [NSapp stop:nil] instead but the
    // problem is that it doesn't wake up the event loop and therefore has to
    // wait for an event to occur before it can break the loop. This causes a
    // noticeable delay when closing the application.
    [NSApp terminate:nil];
  );
}

// =============================================================================
// DesktopWindow_*
// =============================================================================

void *DesktopWindow_Create(const char *title, CGSize size, int style) {
  __block DesktopWindow *self = nil;

  synchronize(
    self = [[DesktopWindow alloc]
               initWithConfig:[NSString stringWithUTF8String:title]
                         size:size
                        style:style];
  );

  return (__bridge_retained void *) self;
}

void DesktopWindow_Destroy(void *ptr) {
  DesktopWindow *self = (__bridge_transfer DesktopWindow *) ptr;

  defer(
    [self close];
  );
}

void DesktopWindow_Redraw(void *ptr, CGRect bounds) {
  DesktopWindow *self = (__bridge DesktopWindow *) ptr;

  defer(
    CGRect r = bounds;

    if (CGRectIsNull(r)) {
      r.size = [self frame].size;
    }

    [[self contentView] setNeedsDisplayInRect:r];
  );
}

void DesktopWindow_Resize(void *ptr, CGSize size) {
  DesktopWindow *self = (__bridge DesktopWindow *) ptr;

  defer(
    CGFloat title = [self titleBarHeight];
    CGRect frame = [self frame];

    frame.size.width = size.width;
    frame.size.height = (size.height + title);

    [self setFrame:frame display:YES animate:YES];
  );
}

void DesktopWindow_Focus(void *ptr, BOOL focused) {
  DesktopWindow *self = (__bridge DesktopWindow *) ptr;

  defer(
    if (focused) {
      [self makeKeyAndOrderFront:nil];
    } else {
      [self orderBack:nil];
    }
  );
}

void DesktopWindow_Close(void *ptr) {
  DesktopWindow *self = (__bridge DesktopWindow *) ptr;

  defer(
    [self performClose:nil];
  );
}

void DesktopWindow_Minimize(void *ptr) {
  DesktopWindow *self = (__bridge DesktopWindow *) ptr;

  defer(
    [self performMiniaturize:nil];
  );
}

void DesktopWindow_Maximize(void *ptr) {
  DesktopWindow *self = (__bridge DesktopWindow *) ptr;

  defer(
    [self performZoom:nil];
  );
}

void DesktopWindow_Restore(void *ptr) {
  DesktopWindow *self = (__bridge DesktopWindow *) ptr;

  defer(
    if (self.miniaturized) {
      [self deminiaturize:nil];
      return;
    }

    if (self.zoomed) {
      [self performZoom:nil];
      return;
    }
  );
}

void DesktopWindow_Move(void *ptr, CGFloat x, CGFloat y) {
  DesktopWindow *self = (__bridge DesktopWindow *) ptr;

  defer(
    CGPoint point = NSMakePoint(x, y);
    CGFloat title = [self titleBarHeight];
    NSScreen *screen = [self screen];
    NSRect frame = [self frame];
    NSRect display = [screen frame];

    if (point.y < title) {
      point.y = title;
    }

    frame.origin.x = point.x;
    frame.origin.y = (display.origin.y + display.size.height) - (point.y + frame.size.height);

    [self setFrame:frame display:YES animate:YES];

    // For some reason the NSWindow doesn't emit windowWillResize when setFrame
    // is called, we emulate the behavior here and force trigger the event.
    handleMoveEvent((__bridge void *) self, point);
  );
}

void DesktopWindow_Cursor(void *ptr, void *cur) {
  DesktopWindow *self = (__bridge DesktopWindow *) ptr;
  [self setCursor:(__bridge NSCursor *) cur];
}

// =============================================================================
// DesktopCursor_*
// =============================================================================

void *DesktopCursor_Arrow() {
  return (__bridge_retained void *) [NSCursor arrowCursor];
}

void *DesktopCursor_CrossHair() {
  return (__bridge_retained void *) [NSCursor crosshairCursor];
}

void *DesktopCursor_HandClosed() {
  return (__bridge_retained void *) [NSCursor closedHandCursor];
}

void *DesktopCursor_HandOpened() {
  return (__bridge_retained void *) [NSCursor openHandCursor];
}

void *DesktopCursor_HandTouch() {
  return (__bridge_retained void *) [NSCursor pointingHandCursor];
}

void *DesktopCursor_ResizeLeft() {
  return (__bridge_retained void *) [NSCursor resizeLeftCursor];
}

void *DesktopCursor_ResizeRight() {
  return (__bridge_retained void *) [NSCursor resizeRightCursor];
}

void *DesktopCursor_ResizeLeftRight() {
  return (__bridge_retained void *) [NSCursor resizeLeftRightCursor];
}

void *DesktopCursor_ResizeUp() {
  return (__bridge_retained void *) [NSCursor resizeUpCursor];
}

void *DesktopCursor_ResizeDown() {
  return (__bridge_retained void *) [NSCursor resizeDownCursor];
}

void *DesktopCursor_ResizeUpDown() {
  return (__bridge_retained void *) [NSCursor resizeUpDownCursor];
}

void *DesktopCursor_Delete() {
  return (__bridge_retained void *) [NSCursor disappearingItemCursor];
}

void *DesktopCursor_Forbid() {
  return (__bridge_retained void *) [NSCursor operationNotAllowedCursor];
}

void *DesktopCursor_Link() {
  return (__bridge_retained void *) [NSCursor dragLinkCursor];
}

void *DesktopCursor_Copy() {
  return (__bridge_retained void *) [NSCursor dragCopyCursor];
}

void *DesktopCursor_Menu() {
  return (__bridge_retained void *) [NSCursor contextualMenuCursor];
}

void *DesktopCursor_IBeam() {
  return (__bridge_retained void *) [NSCursor IBeamCursor];
}

void *DesktopCursor_IBeamVertical() {
  return (__bridge_retained void *) [NSCursor IBeamCursorForVerticalLayout];
}

void *DesktopCursor_Create(CGImageBuffer__ buffer, CGPoint point) {
  NSString *colorSpace = nil;
  NSBitmapFormat format = 0;

  switch (buffer.format) {
  case CGImageAlpha__:
    colorSpace = NSDeviceWhiteColorSpace;
    break;

  case CGImageGray__:
    colorSpace = NSDeviceWhiteColorSpace;
    break;

  case CGImageRGBA__:
    colorSpace = NSDeviceRGBColorSpace;
    format = NS32BitBigEndianBitmapFormat;
    break;

  case CGImageNRGBA__:
    colorSpace = NSDeviceRGBColorSpace;
    format = NS32BitBigEndianBitmapFormat | NSAlphaNonpremultipliedBitmapFormat;
    break;

  case CGImageCMYK__:
    colorSpace = NSDeviceCMYKColorSpace;
    format = NS32BitBigEndianBitmapFormat;
    break;

  default:
    fprintf(stderr, "WARN: invalid image buffer format: %d\n", (int) buffer.format);
    return nil;
  }

  NSBitmapImageRep *rep =
    [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:nil
                                            pixelsWide:buffer.width
                                            pixelsHigh:buffer.height
                                         bitsPerSample:buffer.bpc
                                       samplesPerPixel:(buffer.bpp / buffer.bpc)
                                              hasAlpha:NO
                                              isPlanar:YES
                                        colorSpaceName:colorSpace
                                          bitmapFormat:format
                                              bytesPerRow:buffer.stride
                                             bitsPerPixel:buffer.bpp];
  memmove([rep bitmapData], buffer.data, buffer.size);

  NSImage *image =
    [[NSImage alloc] initWithSize:NSMakeSize(buffer.width, buffer.height)];
  [image addRepresentation:rep];

  return (__bridge_retained void *) [[NSCursor alloc] initWithImage:image
                                                            hotSpot:point];
}

void DesktopCursor_Destroy(void *ptr) {
  // The objective-c runtime is now the owner of that object and will
  // dereference it when the function returns
  (void) (__bridge_transfer NSCursor *) ptr;
}

void DesktopCursor_Draw(void *ptr, CGImageBuffer__ buffer) {
  CGContextRef context = CGContextCreateWithBuffer__(buffer);

  if (context == nil) {
    fprintf(stderr, "WARN: cursors cannot be rendered to images of type %#02x", (int) buffer.format);
    return;
  }

  NSCursor *self = (__bridge NSCursor *) ptr;
  NSGraphicsContext *gc0 = [NSGraphicsContext currentContext];
  NSGraphicsContext *gc1 = [NSGraphicsContext graphicsContextWithCGContext:context flipped:NO];
  [NSGraphicsContext setCurrentContext:gc1];
  [[self image] drawInRect:NSMakeRect(0, 0, buffer.width, buffer.height)];
  [NSGraphicsContext setCurrentContext:gc0];
  CFRelease(context);
}

CGPoint DesktopCursor_Point(void *ptr) {
  NSCursor *self = (__bridge NSCursor *) ptr;
  return [self hotSpot];
}

CGSize DesktopCursor_Size(void *ptr) {
  NSCursor *self = (__bridge NSCursor *) ptr;
  return [[self image] size];
}

// =============================================================================
// CGContext*
// =============================================================================

void CGContextConfigure__(CGContextRef ctx, CGState__ state) {
  if (state.flags & CGStateHasColor__) {
    CGContextSetRGBFillColor(
      ctx,
      state.color[0],
      state.color[1],
      state.color[2],
      state.color[3]
    );

    CGContextSetRGBStrokeColor(
      ctx,
      state.color[0],
      state.color[1],
      state.color[2],
      state.color[3]
    );
  }

  if (state.flags & CGStateHasTransform__) {
    const CGAffineTransform tm = {
      state.transform[0],
      state.transform[1],
      state.transform[2],
      state.transform[3],
      state.transform[4],
      state.transform[5]
    };
    CGContextConcatCTM(ctx, tm);
  }

  if (state.flags & CGStateHasAlpha__) {
    CGContextSetAlpha(ctx, state.alpha);
  }

  if (state.flags & CGStateHasInterpolation__) {
    CGContextSetInterpolationQuality(ctx, state.interpolation);
  }

  if (state.flags & CGStateHasLineCap__) {
    CGContextSetLineCap(ctx, state.lineCap);
  }

  if (state.flags & CGStateHasLineJoin__) {
    CGContextSetLineJoin(ctx, state.lineJoin);
  }

  if (state.flags & CGStateHasLineWidth__) {
    CGContextSetLineWidth(ctx, state.lineWidth);
  }

  if (state.flags & CGStateHasLineDash__) {
    CGContextSetLineDash(ctx, 0, state.lineDashLengths, state.lineDashCount);
  }

  if (state.flags & CGStateHasClip__) {
    CGContextClipPathElements__(ctx, state.clipElements, state.clipLength, state.clipRule);
  }
}

void CGContextAddPathElements__(CGContextRef ctx, const CGPathElement__ *elements, size_t count) {
  for (const CGPathElement__ *ptr = elements, *const end = elements + count; ptr != end; ++ptr) {
    const CGPathElement__ e = *ptr;

    switch (e.type) {
    case kCGPathElementMoveToPoint:
      CGContextMoveToPoint(ctx, e.points[0].x, e.points[0].y);
      break;

    case kCGPathElementAddLineToPoint:
      CGContextAddLineToPoint(ctx, e.points[0].x, e.points[0].y);
      break;

    case kCGPathElementAddQuadCurveToPoint:
      CGContextAddQuadCurveToPoint(ctx, e.points[0].x, e.points[0].y, e.points[1].x, e.points[1].y);
      break;

    case kCGPathElementAddCurveToPoint:
      CGContextAddCurveToPoint(ctx, e.points[0].x, e.points[0].y, e.points[1].x, e.points[1].y, e.points[2].x, e.points[2].y);
      break;

    case kCGPathElementCloseSubpath:
      CGContextClosePath(ctx);
      break;
    }
  }
}

void CGContextClipPathElements__(CGContextRef ctx, const CGPathElement__ *elements, size_t count, CGClipRule__ rule) {
  CGContextBeginPath(ctx);
  CGContextAddPathElements__(ctx, elements, count);

  switch (rule) {
  case CGClipWindingCount__:
    CGContextClip(ctx);
    break;

  case CGClipEvenOdd__:
    CGContextEOClip(ctx);
    break;
  }
}

void CGContextDrawPathElements__(CGContextRef ctx, const CGPathElement__ *elements, size_t count, CGPathDrawingMode mode) {
  CGContextBeginPath(ctx);
  CGContextAddPathElements__(ctx, elements, count);
  CGContextDrawPath(ctx, mode);
}

void CGContextDrawImageBuffer__(CGContextRef ctx, CGImageBuffer__ buffer, CGRect area) {
  CGImageRef image = CGImageCreateWithBuffer__(buffer);

  if (image != nil) {
    CGContextSaveGState(ctx);
    CGContextTranslateCTM(ctx, area.origin.x, area.origin.y + area.size.height);
    CGContextScaleCTM(ctx, 1.0, -1.0);
    CGContextDrawImage(ctx, CGRectMake(0, 0, area.size.width, area.size.height), image);
    CGContextRestoreGState(ctx);
    CFRelease(image);
  }
}

CGContextRef CGContextCreateWithBuffer__(CGImageBuffer__ buffer) {
  CGColorSpaceRef colorSpace = CGColorSpaceCreateWithFormat__(buffer.format);
  CGContextRef context = nil;

  if (colorSpace != nil) {
    context = CGBitmapContextCreateWithData(
      buffer.data,
      buffer.width,
      buffer.height,
      buffer.bpc,
      buffer.stride,
      colorSpace,
      CGBitmapInfoMakeFromFormat__(buffer.format),
      nil,
      nil
    );
    CFRelease(colorSpace);
  }

  return context;
}

CGImageRef CGImageCreateWithBuffer__(CGImageBuffer__ buffer) {
  CGColorSpaceRef colorSpace = nil;
  CGDataProviderRef provider = nil;
  CGImageRef image = nil;

  if ((colorSpace = CGColorSpaceCreateWithFormat__(buffer.format)) == nil) {
    goto err_0;
  }

  if ((provider = CGDataProviderCreateWithData(nil, buffer.data, buffer.size, nil)) == nil) {
    goto err_1;
  }

  image = CGImageCreate(
    buffer.width,
    buffer.height,
    buffer.bpc,
    buffer.bpp,
    buffer.stride,
    colorSpace,
    CGBitmapInfoMakeFromFormat__(buffer.format),
    provider,
    nil,
    NO,
    kCGRenderingIntentDefault
  );

  CFRelease(provider);
 err_1:
  CFRelease(colorSpace);
 err_0:
  return image;
}

CGColorSpaceRef CGColorSpaceCreateWithFormat__(CGImageFormat__ format) {
  switch (format) {
  case CGImageAlpha__:
  case CGImageGray__:
    return CGColorSpaceCreateDeviceGray();

  case CGImageRGBA__:
  case CGImageNRGBA__:
    return CGColorSpaceCreateDeviceRGB();

  case CGImageCMYK__:
    return CGColorSpaceCreateDeviceCMYK();

  default:
    return nil;
  }
}

CGBitmapInfo CGBitmapInfoMakeFromFormat__(CGImageFormat__ format) {
  switch (format) {
  case CGImageAlpha__:
    return (CGBitmapInfo) kCGImageAlphaOnly;

  case CGImageGray__:
    return (CGBitmapInfo) kCGImageAlphaNone;

  case CGImageRGBA__:
    return (CGBitmapInfo) (kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast);

  case CGImageNRGBA__:
    return (CGBitmapInfo) (kCGBitmapByteOrder32Big | kCGImageAlphaLast);

  case CGImageCMYK__:
    return (CGBitmapInfo) (kCGBitmapByteOrder32Big | kCGImageAlphaNone);

  default:
    return 0;
  }
}


text:
About Me

Hi, my name is Brent Stradling. I'm a Frontend Developer and Marketing Professional in Omaha, NE. I help entrepreneurs build their brands and engage their audience to help them grow their businesses.

Experience

Vyral Marketing — Web Developer

									JANUARY 2014 - April 2017

Assurity Life — Frontend Developer

									APRIL 2017 - PRESENT

Skills

								Experience developing websites with HTML, CSS/SASS, Javascript/jQuery, and Python using Flask with a mobile first approach in completely responsive web design.

Education

Metropolitan Community College

								MARCH  2014 - MARCH 2016


text:
package de.fesere.tictactoe;

public interface GameFinishedNotifier {

    void notifyFinished(Board board, Player lastPlayer);
}


text:
Products Index

<router-outlet>


text:
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.Remoting;
using IronPython.Runtime.Types;
using Microsoft.PythonTools.Interpreter;

namespace Microsoft.IronPythonTools.Interpreter {
    class IronPythonType : PythonObject, IAdvancedPythonType {
        private IPythonFunction _ctors;
        private string _name;
        private BuiltinTypeId? _typeId;
        private IList<IPythonType> _propagateOnCall;
        private IReadOnlyList<IPythonType> _mro;
        private PythonMemberType _memberType;
        private bool? _genericTypeDefinition;

        internal static IPythonType[] EmptyTypes = new IPythonType[0];

        public IronPythonType(IronPythonInterpreter interpreter, ObjectIdentityHandle type)
            : base(interpreter, type) {
        }

        #region IPythonType Members

        public IPythonFunction GetConstructors() {
            if (_ctors == null) {
                var ri = RemoteInterpreter;
                if (ri != null && !ri.PythonTypeHasNewOrInitMethods(Value)) {
                    _ctors = GetClrOverloads();
                }

                if (_ctors == null) {
                    _ctors = GetMember(null, "__new__") as IPythonFunction;
                }
            }
            return _ctors;
        }

        /// <summary>
        /// Returns the overloads for a normal .NET type
        /// </summary>
        private IPythonFunction GetClrOverloads() {
            var ri = RemoteInterpreter;
            var ctors = ri != null ? ri.GetPythonTypeConstructors(Value) : null;
            if (ctors != null) {
                return new IronPythonConstructorFunction(Interpreter, ctors, this);
            }
            return null;
        }

        public override PythonMemberType MemberType {
            get {
                if (_memberType == PythonMemberType.Unknown) {
                    var ri = RemoteInterpreter;
                    _memberType = ri != null ? ri.GetPythonTypeMemberType(Value) : PythonMemberType.Unknown;
                }
                return _memberType;
            }
        }

        public string Name {
            get {
                if (_name == null) {
                    var ri = RemoteInterpreter;
                    _name = ri != null ? ri.GetPythonTypeName(Value) : string.Empty;
                }

                return _name;
            }
        }

        public string Documentation {
            get {
                var ri = RemoteInterpreter;
                return ri != null ? ri.GetPythonTypeDocumentation(Value) : string.Empty;
            }
        }

        public BuiltinTypeId TypeId {
            get {
                if (_typeId == null) {
                    var ri = RemoteInterpreter;
                    _typeId = ri?.PythonTypeGetBuiltinTypeId(Value) ?? BuiltinTypeId.Unknown;
                }
                return _typeId.Value;
            }
        }

        public IPythonModule DeclaringModule {
            get {
                var ri = RemoteInterpreter;
                return ri != null ? Interpreter.ImportModule(ri.GetTypeDeclaringModule(Value)) : null;
            }
        }

        public IReadOnlyList<IPythonType> Mro {
            get {
                if (_mro == null) {
                    var ri = RemoteInterpreter;
                    var types = ri != null ? ri.GetPythonTypeMro(Value) : new ObjectIdentityHandle[0];
                    var mro = new IPythonType[types.Length];
                    for (int i = 0; i < types.Length; ++i) {
                        mro[i] = Interpreter.GetTypeFromType(types[i]);
                    }
                    _mro = mro;
                }
                return _mro;
            }
        }

        public bool IsBuiltin {
            get {
                return true;
            }
        }

        public IEnumerable<IPythonType> IndexTypes {
            get {
                return null;
            }
        }

        public bool IsArray {
            get {
                var ri = RemoteInterpreter;
                return ri != null ? ri.IsPythonTypeArray(Value) : false;
            }
        }

        public IPythonType GetElementType() {
            var ri = RemoteInterpreter;
            return ri != null ? Interpreter.GetTypeFromType(ri.GetPythonTypeElementType(Value)) : null;
        }

        public IList<IPythonType> GetTypesPropagatedOnCall() {
            if (_propagateOnCall == null) {
                var ri = RemoteInterpreter;
                if (ri != null && ri.IsDelegateType(Value)) {
                    _propagateOnCall = GetEventInvokeArgs();
                } else {
                    _propagateOnCall = EmptyTypes;
                }
            }

            return _propagateOnCall == EmptyTypes ? null : _propagateOnCall;
        }

        #endregion

        private IPythonType[] GetEventInvokeArgs() {
            var ri = RemoteInterpreter;
            var types = ri != null ? ri.GetEventInvokeArgs(Value) : new ObjectIdentityHandle[0];

            var args = new IPythonType[types.Length];
            for (int i = 0; i < types.Length; i++) {
                args[i] = Interpreter.GetTypeFromType(types[i]);
            }
            return args;
        }

        #region IPythonType Members

        public bool IsGenericTypeDefinition {
            get {
                if (_genericTypeDefinition == null) {
                    var ri = RemoteInterpreter;
                    _genericTypeDefinition = ri != null ? ri.IsPythonTypeGenericTypeDefinition(Value) : false;
                }
                return _genericTypeDefinition.Value;
            }
        }

        public IPythonType MakeGenericType(IPythonType[] indexTypes) {
            // Should we hash on the types here?
            ObjectIdentityHandle[] types = new ObjectIdentityHandle[indexTypes.Length];
            for (int i = 0; i < types.Length; i++) {
                types[i] = ((IronPythonType)indexTypes[i]).Value;
            }
            var ri = RemoteInterpreter;
            return ri != null ? Interpreter.GetTypeFromType(ri.PythonTypeMakeGenericType(Value, types)) : null;
        }

        #endregion
    }
}


text:
@extends('layouts.app')

@section('content')

@lang('view.Taskcomments')

           @lang('view.Add New')

        @include('flash::message')

                    @include('taskcomments.table')

@endsection


text:
title: "Gerrit ESC Meeting Minutes"
tags: esc
keywords: esc minutes
permalink: 2020-06-02-esc-minutes.html
summary: "Minutes from the ESC meeting held on June 2nd"
hide_sidebar: true
hide_navtoggle: true
toc: true
---

## Engineering Steering Committee Meeting, June 2, 2020

### Attendees

David Pursehouse, Ben Rohlfs, Alice Kober-Sotzek, Patrick Hiesel, Luca Milanesio

### Place/Date/Duration

Online, June 2, 09:30 - 10:30 CEST

### Next meeting

The next meeting will be held on July 7, 12:30 CEST.

## Minutes

### Project News

The latest news post was due to be published at the end of May. David forgot about
it and only published it this week. It hasn't been announced yet; we can still add
items to it if there are any.

Ben will follow up internally at Google to add information about recent frontend
changes.

### Gerrit v3.2 release

We had a brief retrospective about the recent 3.2 release. Everyone agreed that
it went well.

David mentioned that there were not as many blocking issues found. There were
a couple of issues found in the replication plugin, thanks to the e2e tests that
were run by the GerritForge Team.

Alice asked if the E2E tests could be run automatically for validation.
Even though it is posssible and not very expensive, it would add too much delay
to the CI validation as it takes around 15 mins to create a brand-new production
stack. However, it could be done on a regular basis on the stable branches
when a commit is merged. The feedback could be then posted back post-merge
with a new checker or label.

### EOL for 2.16

With the release of 3.2, our EOL policy means that 2.16 is now EOL. However in the
[release plan for 3.2](https://www.gerritcodereview.com/2020-04-22-gerrit-3.2-release-plan.html)
we mentioned that there will be exceptions for fixes related to the notedb migration.

We agreed that we need to specify a time limit on this.

### Follow-up on pending Library-Compliance votes

David asked the Google team to have another look at the pending library upgrades
that require the Library-Compliance vote.

* [Junit 4.13](https://gerrit-review.googlesource.com/c/gerrit/+/250096)

  Alice confirmed that this is being worked on internally at Google, but is not
  likely to be done within this quarter.

* [Caffeine](https://gerrit-review.googlesource.com/c/gerrit/+/251113)

  Youssef is working on this. Alice will follow up on the progress.

* [gson](https://gerrit-review.googlesource.com/c/gerrit/+/239953)

  Gal has looked into it, but it has turned out to be more difficult
  than expected.

David pointed out that none of the upgrades are critical. The Caffeine
upgrade will align with what is used in the latest version of ErrorProne,
and the JUnit upgrade is nice to have because it will allow us to remove
our custom implementation of `assertThrows`. There's nothing specific that
we need in gson; the upgrade is just to keep up-to-date with the latest
release.

### Review of open design documents

* [Auth backend](https://gerrit-review.googlesource.com/c/homepage/+/246449)

  No progress here. David will follow up with Jacek about when this can
  be resumed.

* [Deletion of groups](https://gerrit-review.googlesource.com/c/homepage/+/246928)

  David has updated the document to address feedback from Matthias and this
  is now ready for review again. Alice will have another look at it.

* [Subchecks](https://gerrit-review.googlesource.com/q/topic:subchecks+project:homepage)

  Alice hasn't had time to follow up yet.

### Review of issues on the ESC component

We reviewed the open issue. There were no issues that require immediate attention.


text:
A class or method decorator which binds methods to the instance
so `this` is always correct, even when the method is detached.

This is particularly useful for situations like React components, where
you often pass methods as event handlers and would otherwise need to
`.bind(this)`.

```js
Before:
<button onClick={ this.handleClick.bind(this) }></button>

After:
<button onClick={ this.handleClick }></button>
```

As decorators are a part of future ES2016 standard they can only be used with
transpilers such as [Babel](http://babeljs.io).

**Note Babel 6 users:**
The implementation of the decorator transform is currently on hold as the syntax
is not final. If you would like to use this project with Babel 6.0, you may use
[babel-plugin-transform-decorators-legacy](https://github.com/loganfsmyth/babel-plugin-transform-decorators-legacy)
which implement Babel 5 decorator transform for Babel 6.

Installation:

    % npm install autobind-decorator

Example:

```js
import autobind from 'autobind-decorator'

class Component {

  constructor(value) {
    this.value = value
  }

  @autobind
  method() {
    return this.value
  }
}

let component = new Component(42)
let method = component.method // .bind(component) isn't needed!
method() // returns 42

// Also usable on the class to bind all methods

@autobind
class Component { }
```


text:
package net.bmjames.opts

package object types {

  type Args = List[String]

}


text:
/**
 */
var grails = grails || {};
grails.mobile = grails.mobile || {};
grails.mobile.push = grails.mobile.push || {};

grails.mobile.push.pushmanager = function (grailsEvents, domainName, store, model, options) {
    var that = {};
    var store = store;
    var domainName = domainName;
    var model = model;
    that.grailsEvents = grailsEvents;

    if (options && options.eventPush) {
        that.grailsEvents.on('save-' + domainName , function (data) {
            if (data !== Object(data)) {
                data = JSON.parse(data);
            }
            if (!model.getItems()[data.id]) {
                data.NOTIFIED = true;
                if (options.offline) {
                    store.store(data);
                }
                model.createItem(data);
            }
        });

        that.grailsEvents.on('update-' + domainName , function (data) {
            if (data !== Object(data)) {
                data = JSON.parse(data);
            }
            var retrievedData = model.getItems()[data.id];
            if (retrievedData && retrievedData.version < data.version) {
                data.NOTIFIED = true;
                if (options.offline) {
                    store.store(data);
                }
                model.updateItem(data);
            }
        });

        that.grailsEvents.on('delete-' + domainName , function (data) {
            if (data !== Object(data)) {
                data = JSON.parse(data);
            }
            if (model.getItems()[data.id]) {
                data.NOTIFIED = true;
                if (options.offline) {
                    store.remove(data);
                }
                model.deleteItem(data);
            }
        });
    }
    return that;
};


text:
from __future__ import absolute_import, division, print_function, unicode_literals

import base64, json, sys

from thrift.protocol.TProtocol import TProtocolBase, TProtocolException
from thrift.Thrift import TType

__all__ = ["TJSONProtocol", "TJSONProtocolFactory"]

VERSION = 1

COMMA = ","
COLON = ":"
LBRACE = "{"
RBRACE = "}"
LBRACKET = "["
RBRACKET = "]"
QUOTE = '"'
BACKSLASH = "\\"
ZERO = "0"

ESCSEQ = "\\u00"
ESCAPE_CHAR = '"\\bfnrt'
ESCAPE_CHAR_VALS = ['"', "\\", "\b", "\f", "\n", "\r", "\t"]
NUMERIC_CHAR = "+-.0123456789Ee"

CTYPES = {
    TType.BOOL: "tf",
    TType.BYTE: "i8",
    TType.I16: "i16",
    TType.I32: "i32",
    TType.I64: "i64",
    TType.DOUBLE: "dbl",
    TType.STRING: "str",
    TType.STRUCT: "rec",
    TType.LIST: "lst",
    TType.SET: "set",
    TType.MAP: "map",
}

JTYPES = {}
for key in CTYPES.keys():
    JTYPES[CTYPES[key]] = key

class JSONBaseContext(object):
    def __init__(self, protocol):
        self.protocol = protocol
        self.first = True

    def doIO(self, function):
        pass

    def write(self):
        pass

    def read(self):
        pass

    def escapeNum(self):
        return False

class JSONListContext(JSONBaseContext):
    def doIO(self, function):
        if self.first is True:
            self.first = False
        else:
            function(COMMA)

    def write(self):
        self.doIO(self.protocol.trans.write)

    def read(self):
        self.doIO(self.protocol.readJSONSyntaxChar)

class JSONPairContext(JSONBaseContext):
    colon = True

    def doIO(self, function):
        if self.first is True:
            # Ignore extra commas at field start. Once context stack handling
            # fix is fully rolled out this can be removed.
            if self.protocol.reader.peek() == COMMA:
                self.protocol.readJSONSyntaxChar(COMMA)
            self.first = False
            self.colon = True
        else:
            function(COLON if self.colon is True else COMMA)
            self.colon = not self.colon

    def write(self):
        self.doIO(self.protocol.trans.write)

    def read(self):
        self.doIO(self.protocol.readJSONSyntaxChar)

    def escapeNum(self):
        return self.colon

class LookaheadReader:
    hasData = False
    data = ""

    def __init__(self, protocol):
        self.protocol = protocol

    def read(self):
        if self.hasData is True:
            self.hasData = False
        else:
            self.data = self.protocol.trans.read(1)
        if sys.version_info[0] >= 3 and isinstance(self.data, bytes):
            self.data = str(self.data, "utf-8")
        return self.data

    def peek(self):
        if self.hasData is False:
            self.data = self.protocol.trans.read(1)
        self.hasData = True
        if sys.version_info[0] >= 3 and isinstance(self.data, bytes):
            self.data = str(self.data, "utf-8")
        return self.data

class TJSONProtocolBase(TProtocolBase):
    def __init__(self, trans, validJSON=True):
        TProtocolBase.__init__(self, trans)
        self.validJSON = validJSON
        self.resetWriteContext()
        self.resetReadContext()

    def resetWriteContext(self):
        self.context = JSONBaseContext(self)
        self.contextStack = [self.context]

    def resetReadContext(self):
        self.resetWriteContext()
        self.reader = LookaheadReader(self)

    def pushContext(self, ctx):
        self.contextStack.append(ctx)
        self.context = ctx

    def popContext(self):
        self.contextStack.pop()
        if self.validJSON:
            self.context = self.contextStack[-1]

    def writeJSONString(self, string):
        # Python 3 JSON will not serialize bytes
        if isinstance(string, bytes) and sys.version_info.major >= 3:
            string = string.decode()
        self.context.write()
        self.trans.write(json.dumps(string))

    def writeJSONNumber(self, number):
        self.context.write()
        jsNumber = str(number)
        if self.context.escapeNum():
            jsNumber = "%s%s%s" % (QUOTE, jsNumber, QUOTE)
        self.trans.write(jsNumber)

    def writeJSONBase64(self, binary):
        self.context.write()
        self.trans.write(QUOTE)
        self.trans.write(base64.b64encode(binary))
        self.trans.write(QUOTE)

    def writeJSONObjectStart(self):
        self.context.write()
        self.trans.write(LBRACE)
        self.pushContext(JSONPairContext(self))

    def writeJSONObjectEnd(self):
        self.popContext()
        self.trans.write(RBRACE)

    def writeJSONArrayStart(self):
        self.context.write()
        self.trans.write(LBRACKET)
        self.pushContext(JSONListContext(self))

    def writeJSONArrayEnd(self):
        self.popContext()
        self.trans.write(RBRACKET)

    def readJSONSyntaxChar(self, character):
        current = self.reader.read()
        if character != current:
            raise TProtocolException(
                TProtocolException.INVALID_DATA, "Unexpected character: %s" % current
            )

    def readJSONString(self, skipContext):
        string = []
        if skipContext is False:
            self.context.read()
        self.readJSONSyntaxChar(QUOTE)
        while True:
            character = self.reader.read()
            if character == QUOTE:
                break
            if character == ESCSEQ[0]:
                character = self.reader.read()
                if character == ESCSEQ[1]:
                    self.readJSONSyntaxChar(ZERO)
                    self.readJSONSyntaxChar(ZERO)
                    data = self.trans.read(2)
                    if sys.version_info[0] >= 3 and isinstance(data, bytes):
                        character = json.JSONDecoder().decode(
                            '"\\u00%s"' % str(data, "utf-8")
                        )
                    else:
                        character = json.JSONDecoder().decode('"\\u00%s"' % data)
                else:
                    off = ESCAPE_CHAR.find(character)
                    if off == -1:
                        raise TProtocolException(
                            TProtocolException.INVALID_DATA, "Expected control char"
                        )
                    character = ESCAPE_CHAR_VALS[off]
            string.append(character)
        return "".join(string)

    def isJSONNumeric(self, character):
        return True if NUMERIC_CHAR.find(character) != -1 else False

    def readJSONQuotes(self):
        if self.context.escapeNum():
            self.readJSONSyntaxChar(QUOTE)

    def readJSONNumericChars(self):
        numeric = []
        while True:
            character = self.reader.peek()
            if self.isJSONNumeric(character) is False:
                break
            numeric.append(self.reader.read())
        return "".join(numeric)

    def readJSONInteger(self):
        self.context.read()
        self.readJSONQuotes()
        numeric = self.readJSONNumericChars()
        self.readJSONQuotes()
        try:
            return int(numeric)
        except ValueError:
            raise TProtocolException(
                TProtocolException.INVALID_DATA, "Bad data encounted in numeric data"
            )

    def readJSONDouble(self):
        self.context.read()
        if self.reader.peek() == QUOTE:
            string = self.readJSONString(True)
            try:
                double = float(string)
                if (
                    self.context.escapeNum is False
                    and double != float("inf")
                    and double != float("-inf")
                    and double != float("nan")
                ):
                    raise TProtocolException(
                        TProtocolException.INVALID_DATA,
                        "Numeric data unexpectedly quoted",
                    )
                return double
            except ValueError:
                raise TProtocolException(
                    TProtocolException.INVALID_DATA,
                    "Bad data encounted in numeric data",
                )
        else:
            if self.context.escapeNum() is True:
                self.readJSONSyntaxChar(QUOTE)
            try:
                return float(self.readJSONNumericChars())
            except ValueError:
                raise TProtocolException(
                    TProtocolException.INVALID_DATA,
                    "Bad data encounted in numeric data",
                )

    def readJSONBase64(self):
        string = self.readJSONString(False)
        return base64.b64decode(string)

    def readJSONObjectStart(self):
        self.context.read()
        self.readJSONSyntaxChar(LBRACE)
        self.pushContext(JSONPairContext(self))

    def readJSONObjectEnd(self):
        self.readJSONSyntaxChar(RBRACE)
        self.popContext()

    def readJSONArrayStart(self):
        self.context.read()
        self.readJSONSyntaxChar(LBRACKET)
        self.pushContext(JSONListContext(self))

    def readJSONArrayEnd(self):
        self.readJSONSyntaxChar(RBRACKET)
        self.popContext()

class TJSONProtocol(TJSONProtocolBase):
    def readMessageBegin(self):
        self.resetReadContext()
        self.readJSONArrayStart()
        if self.readJSONInteger() != VERSION:
            raise TProtocolException(
                TProtocolException.BAD_VERSION, "Message contained bad version."
            )
        name = self.readJSONString(False)
        typen = self.readJSONInteger()
        seqid = self.readJSONInteger()
        return (name, typen, seqid)

    def readMessageEnd(self):
        self.readJSONArrayEnd()

    def readStructBegin(self):
        self.readJSONObjectStart()

    def readStructEnd(self):
        self.readJSONObjectEnd()

    def readFieldBegin(self):
        character = self.reader.peek()
        ttype = 0
        id = 0
        if character == RBRACE:
            ttype = TType.STOP
        else:
            id = self.readJSONInteger()
            self.readJSONObjectStart()
            ttype = JTYPES[self.readJSONString(False)]
        return (None, ttype, id)

    def readFieldEnd(self):
        self.readJSONObjectEnd()

    def readMapBegin(self):
        self.readJSONArrayStart()
        keyType = JTYPES[self.readJSONString(False)]
        valueType = JTYPES[self.readJSONString(False)]
        size = self.readJSONInteger()
        self.readJSONObjectStart()
        return (keyType, valueType, size)

    def readMapEnd(self):
        self.readJSONObjectEnd()
        self.readJSONArrayEnd()

    def readCollectionBegin(self):
        self.readJSONArrayStart()
        elemType = JTYPES[self.readJSONString(False)]
        size = self.readJSONInteger()
        return (elemType, size)

    readListBegin = readCollectionBegin
    readSetBegin = readCollectionBegin

    def readCollectionEnd(self):
        self.readJSONArrayEnd()

    readSetEnd = readCollectionEnd
    readListEnd = readCollectionEnd

    def readBool(self):
        return False if self.readJSONInteger() == 0 else True

    def readNumber(self):
        return self.readJSONInteger()

    readByte = readNumber
    readI16 = readNumber
    readI32 = readNumber
    readI64 = readNumber

    def readDouble(self):
        return self.readJSONDouble()

    def readFloat(self):
        return self.readJSONDouble()

    def readString(self):
        string = self.readJSONString(False)
        if sys.version_info.major >= 3:
            # Generated code expects that protocols deal in bytes in Py3
            return string.encode("utf-8")
        return string

    def readBinary(self):
        return self.readJSONBase64()

    def writeMessageBegin(self, name, request_type, seqid):
        self.resetWriteContext()
        self.writeJSONArrayStart()
        self.writeJSONNumber(VERSION)
        self.writeJSONString(name)
        self.writeJSONNumber(request_type)
        self.writeJSONNumber(seqid)

    def writeMessageEnd(self):
        self.writeJSONArrayEnd()

    def writeStructBegin(self, name):
        self.writeJSONObjectStart()

    def writeStructEnd(self):
        self.writeJSONObjectEnd()

    def writeFieldBegin(self, name, ttype, id):
        self.writeJSONNumber(id)
        self.writeJSONObjectStart()
        self.writeJSONString(CTYPES[ttype])

    def writeFieldEnd(self):
        self.writeJSONObjectEnd()

    def writeFieldStop(self):
        pass

    def writeMapBegin(self, ktype, vtype, size):
        self.writeJSONArrayStart()
        self.writeJSONString(CTYPES[ktype])
        self.writeJSONString(CTYPES[vtype])
        self.writeJSONNumber(size)
        self.writeJSONObjectStart()

    def writeMapEnd(self):
        self.writeJSONObjectEnd()
        self.writeJSONArrayEnd()

    def writeListBegin(self, etype, size):
        self.writeJSONArrayStart()
        self.writeJSONString(CTYPES[etype])
        self.writeJSONNumber(size)

    def writeListEnd(self):
        self.writeJSONArrayEnd()

    def writeSetBegin(self, etype, size):
        self.writeJSONArrayStart()
        self.writeJSONString(CTYPES[etype])
        self.writeJSONNumber(size)

    def writeSetEnd(self):
        self.writeJSONArrayEnd()

    def writeBool(self, boolean):
        self.writeJSONNumber(1 if boolean is True else 0)

    def writeInteger(self, integer):
        self.writeJSONNumber(int(integer))

    writeByte = writeInteger
    writeI16 = writeInteger
    writeI32 = writeInteger
    writeI64 = writeInteger

    def writeDouble(self, dbl):
        self.writeJSONNumber(dbl)

    def writeFloat(self, flt):
        self.writeJSONNumber(flt)

    def writeString(self, string):
        self.writeJSONString(string)

    def writeBinary(self, binary):
        self.writeJSONBase64(binary)

class TJSONProtocolFactory:
    # validJSON specifies whether to emit valid JSON or possibly invalid but
    # backward-compatible one.
    def __init__(self, validJSON: bool = True) -> None:
        self.validJSON = validJSON

    def getProtocol(self, trans):
        return TJSONProtocol(trans, self.validJSON)


text:
declare class Knex$Transaction<R> mixins Knex$QueryBuilder<R>, events$EventEmitter, Promise<R> {
  commit(connection?: any, value?: any): Promise<R>,
  rollback(): Promise<R>,
  savepoint(connection?: any): Promise<R>
}

declare type Knex$QueryBuilderFn<R> = (
  qb: Knex$QueryBuilder<R>
) => Knex$QueryBuilder<R> | void;

declare class Knex$QueryBuilder<R> mixins Promise<R> {
  clearSelect(): this,
  clearWhere(): this,
  select(key?: string[]): this,
  select(...key: string[]): this,
  timeout(ms: number, options?: { cancel: boolean }): this,
  column(key: string[]): this,
  column(...key: string[]): this,
  with(alias: string, w: string | Knex$QueryBuilderFn<R>): this,
  withSchema(schema: string): this,
  returning(column: string): this,
  returning(...columns: string[]): this,
  returning(columns: string[]): this,
  as(name: string): this,
  transacting(trx: ?Knex$Transaction<R>): this,
  transaction((trx: Knex$Transaction<R>) => void): this,
  where(object: { [string]: any }): this,
  where(builder: Knex$QueryBuilderFn<R>): this,
  where(column: string, value: any): this,
  where(column: string, operator: string, value: any): this,
  whereNot(object: { [string]: any }): this,
  whereNot(builder: Knex$QueryBuilderFn<R>): this,
  whereNot(column: string, value: any): this,
  whereNot(column: string, operator: string, value: any): this,
  whereIn(column: string, values: any[]): this,
  whereNotIn(column: string, values: any[]): this,
  whereNull(column: string): this,
  whereNotNull(column: string): this,
  whereExists(column: string): this,
  whereNotExists(column: string): this,
  whereBetween(column: string, range: number[]): this,
  whereNotBetween(column: string, range: number[]): this,
  whereRaw(sql: string, bindings?: Knex$RawBindings): this,
  orWhere(object: { [string]: any }): this,
  orWhere(builder: Knex$QueryBuilderFn<R>): this,
  orWhere(column: string, value: any): this,
  orWhere(column: string, operator: string, value: any): this,
  orWhereNot(object: { [string]: any }): this,
  orWhereNot(builder: Knex$QueryBuilderFn<R>): this,
  orWhereNot(column: string, value: any): this,
  orWhereNot(column: string, operator: string, value: any): this,
  orWhereIn(column: string, values: any[]): this,
  orWhereNotIn(column: string, values: any[]): this,
  orWhereNull(column: string): this,
  orWhereNotNull(column: string): this,
  orWhereExists(column: string): this,
  orWhereNotExists(column: string): this,
  orWhereBetween(column: string, range: number[]): this,
  orWhereNotBetween(column: string, range: number[]): this,
  orWhereRaw(sql: string, bindings?: Knex$RawBindings): this,
  innerJoin(table: string, c1: string, operator: string, c2: string): this,
  innerJoin(table: string, c1: string, c2: string): this,
  innerJoin(
    builder: Knex$QueryBuilder<R> | Knex$QueryBuilderFn<R>,
    c1?: string,
    c2?: string
  ): this,
  innerJoin(table: string, builder: Knex$QueryBuilderFn<R>): this,
  leftJoin(table: string, c1: string, operator: string, c2: string): this,
  leftJoin(table: string, c1: string, c2: string): this,
  leftJoin(builder: Knex$QueryBuilder<R>): this,
  leftJoin(table: string, builder: Knex$QueryBuilderFn<R>): this,
  leftOuterJoin(table: string, c1: string, operator: string, c2: string): this,
  leftOuterJoin(table: string, c1: string, c2: string): this,
  leftOuterJoin(table: string, builder: Knex$QueryBuilderFn<R>): this,
  rightJoin(table: string, c1: string, operator: string, c2: string): this,
  rightJoin(table: string, c1: string, c2: string): this,
  rightJoin(table: string, builder: Knex$QueryBuilderFn<R>): this,
  rightOuterJoin(table: string, c1: string, operator: string, c2: string): this,
  rightOuterJoin(table: string, c1: string, c2: string): this,
  rightOuterJoin(table: string, builder: Knex$QueryBuilderFn<R>): this,
  outerJoin(table: string, c1: string, operator: string, c2: string): this,
  outerJoin(table: string, c1: string, c2: string): this,
  outerJoin(table: string, builder: Knex$QueryBuilderFn<R>): this,
  fullOuterJoin(table: string, c1: string, operator: string, c2: string): this,
  fullOuterJoin(table: string, c1: string, c2: string): this,
  fullOuterJoin(table: string, builder: Knex$QueryBuilderFn<R>): this,
  crossJoin(column: string, c1: string, c2: string): this,
  crossJoin(column: string, c1: string, operator: string, c2: string): this,
  crossJoin(table: string, builder: Knex$QueryBuilderFn<R>): this,
  joinRaw(sql: string, bindings?: Knex$RawBindings): this,
  distinct(): this,
  groupBy(column: string): this,
  groupByRaw(sql: string, bindings?: Knex$RawBindings): this,
  orderBy(column: string, direction?: "desc" | "asc"): this,
  orderByRaw(sql: string, bindings?: Knex$RawBindings): this,
  offset(offset: number): this,
  limit(limit: number): this,
  having(column: string, operator: string, value: mixed): this,
  havingIn(column: string, values: Array<mixed>): this,
  havingNotIn(column: string, values: Array<mixed>): this,
  havingNull(column: string): this,
  havingNotNull(column: string): this,
  havingExists(builder: Knex$QueryBuilderFn<R> | Knex$QueryBuilder<R>): this,
  havingNotExists(builder: Knex$QueryBuilderFn<R> | Knex$QueryBuilder<R>): this,
  havingBetween<T>(column: string, range: [T, T]): this,
  havingNotBetween<T>(column: string, range: [T, T]): this,
  havingRaw(column: string, operator: string, value: mixed): this,
  havingRaw(column: string, value: mixed): this,
  havingRaw(raw: string, bindings?: Knex$RawBindings): this,
  union(): this,
  unionAll(): this,
  count(column?: string): this,
  countDistinct(column?: string): this,
  min(column?: string): this,
  max(column?: string): this,
  sum(column?: string): this,
  sumDistinct(column?: string): this,
  avg(column?: string): this,
  avgDistinct(column?: string): this,
  pluck(column: string): this,
  first(): this,
  from(table: string): this,
  from(
    builder: Knex$QueryBuilderFn<R> | Knex$Knex<R> | Knex$QueryBuilder<R>
  ): this,
  into(table: string, options?: Object): this,

  insert(val: Object | Object[]): this,
  del(): this,
  delete(): this,
  update(column: string, value: any): this,
  update(val: Object): this,
  returning(columns: string[]): this
}

declare class Knex$Knex<R> mixins Knex$QueryBuilder<R>, Promise<R>, events$EventEmitter {
  static (config: Knex$Config): Knex$Knex<R>,
  static QueryBuilder: typeof Knex$QueryBuilder,
  $call: (tableName: string) => Knex$QueryBuilder<R>,
  raw(sqlString: string, bindings?: Knex$RawBindings): any,
  client: any,
  destroy(): Promise<void>
}

declare type Knex$PostgresConfig = {
  client?: "pg",
  connection?:
    | string
    | {
        host?: string,
        user?: string,
        password?: string,
        database?: string,
        charset?: string
      },
  searchPath?: string
};

declare type Knex$RawBindings = Array<mixed> | { [key: string]: mixed };

declare type Knex$MysqlConfig = {
  client?: "mysql",
  connection?: {
    host?: string,
    user?: string,
    password?: string,
    database?: string
  }
};
declare type Knex$SqliteConfig = {
  client?: "sqlite3",
  connection?: {
    filename?: string
  }
};
declare type Knex$Config =
  | Knex$PostgresConfig
  | Knex$MysqlConfig
  | Knex$SqliteConfig;

declare module "knex" {
  declare type Error = {
    name: string,
    length: number,
    severity: string,
    code: string,
    detail: string,
    hint?: string,
    position?: any,
    intenralPosition?: any,
    internalQuery?: any,
    where?: any,
    schema: string,
    table: string,
    column?: any,
    dataType?: any,
    constraint?: string,
    file: string,
    line: string,
    routine: string
  };
  declare type $QueryBuilder<R> = Knex$QueryBuilder<R>;
  declare var exports: typeof Knex$Knex;
}


text:
"""Define metric factory."""

import tensorflow as tf
from tensorflow_addons import optimizers as tfa_optimizers

from vatt.configs import experiment

def get_optimizer(learning_rate, config):
  """Returns the optimizer of choice given the configurations."""

  if isinstance(config, experiment.MomentumOptimizer):
    optimizer = tf.keras.optimizers.SGD(
        learning_rate=learning_rate,
        momentum=config.momentum,
        nesterov=config.nesterov
        )
  elif isinstance(config, experiment.MomentumWOptimizer):
    optimizer = tfa_optimizers.SGDW(
        weight_decay=config.weight_decay,
        learning_rate=learning_rate,
        momentum=config.momentum,
        nesterov=config.nesterov
        )
  elif isinstance(config, experiment.AdamOptimizer):
    optimizer = tf.keras.optimizers.Adam(
        learning_rate=learning_rate,
        beta_1=config.beta_1,
        beta_2=config.beta_2,
        epsilon=config.epsilon,
        )
  elif isinstance(config, experiment.AdamWOptimizer):
    optimizer = tfa_optimizers.AdamW(
        weight_decay=config.weight_decay,
        learning_rate=learning_rate,
        beta_1=config.beta_1,
        beta_2=config.beta_2,
        epsilon=config.epsilon,
        )
  else:
    optimizer = tf.keras.optimizers.SGD(learning_rate=learning_rate)
  return optimizer


text:
//
// Created by Andrea Giove on 17/04/16.
//

#ifndef TGBOT_CALLBACKQUERY_H
#define TGBOT_CALLBACKQUERY_H

#include <memory>
#include <string>

#include "tgbot/types/User.h"
#include "tgbot/types/Message.h"

namespace TgBot {

/**
 * This object represents an incoming callback query from a callback button in an inline keyboard.
 * @ingroup types
 */
class CallbackQuery {
public:
	typedef std::shared_ptr<CallbackQuery> Ptr;

	/**
	 * Unique identifier for this query.
	 */
	std::string id;

	/**
	 * Sender.
	 */
	User::Ptr from;

	/**
	 * Optional. Message with the callback button that originated the query. Note that message content and message date will not be available if the message is too old.
	 */
	Message::Ptr message;

	/**
	 * Optional. Identifier of the message sent via the bot in inline mode, that originated the query.
	 */
	std::string inlineMessageId;

	/**
	 * Global identifier, uniquely corresponding to the chat to which the message with the callback button was sent. Useful for high scores in games.
	 */
	std::string chatInstance;

	/**
	 * Data associated with the callback button. Be aware that a bad client can send arbitrary data in this field.
	 */
	std::string data;

	/*
	 * Optional. Short name of a Game to be returned, serves as the unique identifier for the game
	 */
	std::string gameShortName;
};
}

#endif //TGBOT_CALLBACKQUERY_H


text:
package com.fangxuele.tool.push.domain;

import java.io.Serializable;

public class TMsgDing implements Serializable {
    private Integer id;

    private Integer msgType;

    private String msgName;

    private String radioType;

    private String dingMsgType;

    private String agentId;

    private String webHook;

    private String content;

    private String createTime;

    private String modifiedTime;

    private String previewUser;

    private static final long serialVersionUID = 1L;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getMsgType() {
        return msgType;
    }

    public void setMsgType(Integer msgType) {
        this.msgType = msgType;
    }

    public String getMsgName() {
        return msgName;
    }

    public void setMsgName(String msgName) {
        this.msgName = msgName == null ? null : msgName.trim();
    }

    public String getRadioType() {
        return radioType;
    }

    public void setRadioType(String radioType) {
        this.radioType = radioType == null ? null : radioType.trim();
    }

    public String getDingMsgType() {
        return dingMsgType;
    }

    public void setDingMsgType(String dingMsgType) {
        this.dingMsgType = dingMsgType == null ? null : dingMsgType.trim();
    }

    public String getAgentId() {
        return agentId;
    }

    public void setAgentId(String agentId) {
        this.agentId = agentId == null ? null : agentId.trim();
    }

    public String getWebHook() {
        return webHook;
    }

    public void setWebHook(String webHook) {
        this.webHook = webHook == null ? null : webHook.trim();
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content == null ? null : content.trim();
    }

    public String getCreateTime() {
        return createTime;
    }

    public void setCreateTime(String createTime) {
        this.createTime = createTime == null ? null : createTime.trim();
    }

    public String getModifiedTime() {
        return modifiedTime;
    }

    public void setModifiedTime(String modifiedTime) {
        this.modifiedTime = modifiedTime == null ? null : modifiedTime.trim();
    }

    public String getPreviewUser() {
        return previewUser;
    }

    public void setPreviewUser(String previewUser) {
        this.previewUser = previewUser == null ? null : previewUser.trim();
    }
}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2016.04.05 at 03:08:21 PM BRT
//

package jaxbClasses.basictypes;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for MatchingService complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="MatchingService">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="MatchingValueID" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element name="ServiceInfo" type="{http://semanticsco/interactions/BasicTypes}ServiceInfo"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "MatchingService", propOrder = {
    "matchingValueID",
    "serviceInfo"
})
public class MatchingService {

    @XmlElement(name = "MatchingValueID", required = true)
    protected String matchingValueID;
    @XmlElement(name = "ServiceInfo", required = true)
    protected ServiceInfo serviceInfo;

    /**
     * Gets the value of the matchingValueID property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getMatchingValueID() {
        return matchingValueID;
    }

    /**
     * Sets the value of the matchingValueID property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setMatchingValueID(String value) {
        this.matchingValueID = value;
    }

    /**
     * Gets the value of the serviceInfo property.
     *
     * @return
     *     possible object is
     *     {@link ServiceInfo }
     *
     */
    public ServiceInfo getServiceInfo() {
        return serviceInfo;
    }

    /**
     * Sets the value of the serviceInfo property.
     *
     * @param value
     *     allowed object is
     *     {@link ServiceInfo }
     *
     */
    public void setServiceInfo(ServiceInfo value) {
        this.serviceInfo = value;
    }

}


text:
using System;
using System.Collections.Generic;
using SharpKit.Html;
using SharpKit.JavaScript;

namespace qx.ui.decoration
{
    /// <summary>
	/// <para>A simple decorator featuring background images and colors and a simple
	/// uniform border based on CSS styles.</para>
	/// </summary>
	[JsType(JsMode.Prototype, Name = "qx.ui.decoration.Uniform", OmitOptionalParameters = true, Export = false)]
    public partial class Uniform : qx.ui.decoration.Single
    {
		#region Methods

		public Uniform() { throw new NotImplementedException(); }

		/// <param name="width">Width of the border</param>
		/// <param name="style">Any supported border style</param>
		/// <param name="color">The border color</param>
		public Uniform(double width, string style, string color) { throw new NotImplementedException(); }

		#endregion Methods
    }
}


text:
using System;
using System.IO;
using System.Reflection;
using NUnit.Framework;
using Zirpl.Reflection;

namespace Zirpl.Common.Tests.Reflection
{
    [TestFixture]
    public class AssemblyExtensionsTests
    {
        private String assemblyDirectory;
        private String exampleResourceInputFilePath;
        private String exampleResourceOutputFilePath;

        [SetUp]
        public void SetUp()
        {
            var path = Assembly.GetExecutingAssembly().CodeBase;
            assemblyDirectory = Path.GetDirectoryName(path.Replace(@"file:///", null));
            exampleResourceOutputFilePath = Path.Combine(assemblyDirectory, @"IO\example_resource.txt.output");
        }

        [TearDown]
        public void TearDown()
        {
            if (File.Exists(exampleResourceOutputFilePath))
            {
                File.Delete(exampleResourceOutputFilePath);
            }
        }

        [Test]
        public void TestWriteEmbeddedResourceToFile()
        {
            Assembly.GetExecutingAssembly().WriteEmbeddedResourceToFile("Zirpl.Common.Tests.IO.example_embedded.txt", exampleResourceOutputFilePath);

            Assert.IsTrue(File.Exists(exampleResourceOutputFilePath));
            Assert.AreEqual("example_embedded Testing123", File.ReadAllText(exampleResourceOutputFilePath));
        }
    }
}