text:
<?php

namespace Alex\BehatLauncher;

use Alex\BehatLauncher\Behat\Project;
use Alex\BehatLauncher\Behat\ProjectList;
use Alex\BehatLauncher\Behat\MysqlStorage;
use Alex\BehatLauncher\Form\BehatLauncherExtension;
use Doctrine\DBAL\DriverManager;
use Silex\Application as BaseApplication;
use Silex\Provider\FormServiceProvider;
use Silex\Provider\ServiceControllerServiceProvider;
use Silex\Provider\TranslationServiceProvider;
use Silex\Provider\TwigServiceProvider;
use Silex\Provider\UrlGeneratorServiceProvider;
use Silex\Provider\WebProfilerServiceProvider;

class Application extends BaseApplication
{
    const VERSION = 'dev-master';

    public function __construct(array $values = array())
    {
        parent::__construct($values);

        $this['db'] = $this->share(function ($app) {
            return DriverManager::getConnection(array(
                'driver'   => 'pdo_mysql',
                'host'     => $app['db_host'],
                'dbname'   => $app['db_name'],
                'user'     => $app['db_user'],
                'password' => $app['db_password'],
            ));
        });

        $this['project_list'] = $this->share(function ($app) {
            return new ProjectList();
        });

        $this['run_storage'] = $this->share(function ($app) {
            return new MysqlStorage($app['db'], __DIR__.'/../../../data/output_files');
        });

        $this->register(new UrlGeneratorServiceProvider());
        $this->register(new TranslationServiceProvider(), array('locale_fallback' => 'en'));
        $this->register(new FormServiceProvider());
        $this->register(new ServiceControllerServiceProvider());
        $this->register(new TwigServiceProvider(), array(
            'twig.path'    => __DIR__.'/Resources/views',
            'debug'        => $this['debug'],
            'twig.options' => array('cache' => __DIR__.'/../../../cache/twig'),
        ));

        if ($this['debug']) {
            $this->register($profiler = new WebProfilerServiceProvider(), array(
                'profiler.cache_dir' => __DIR__.'/../../../cache/profiler',
            ));
            $this->mount('/_profiler', $profiler);
        }

        $controllers = array(
            'outputFile' => 'Alex\BehatLauncher\Controller\OutputFileController',
            'project'    => 'Alex\BehatLauncher\Controller\ProjectController',
            'run'        => 'Alex\BehatLauncher\Controller\RunController',
        );

        // Controllers as service
        foreach ($controllers as $id => $class) {
            $this['controller.'.$id] = $this->share(function($app) use ($class) {
                return new $class($app);
            });
        }

        // Routes
        $this->get('/', 'controller.project:listAction')->bind('project_list');
        $this->get('/project/{project}', 'controller.project:showAction')->bind('project_show');
        $this->get('/project/{project}/create-run', 'controller.run:createAction')->bind('run_create')->method('GET|POST');
        $this->get('/runs', 'controller.run:listAction')->bind('run_list');
        $this->get('/runs/{id}', 'controller.run:showAction')->bind('run_show');
        $this->get('/output/{id}', 'controller.outputFile:showAction')->bind('outputFile_show');

        $this->extend('form.extensions', function ($extensions, $app) {
            $extensions[] = new BehatLauncherExtension();

            return $extensions;
        });
    }

    public function configureMysql($host, $database, $user, $password)
    {
        $this['db_host']     = $host;
        $this['db_name']     = $database;
        $this['db_user']     = $user;
        $this['db_password'] = $password;

        return $this;
    }

    public function createProject($name, $path)
    {
        $project = new Project();
        $project
            ->setName($name)
            ->setPath($path)
        ;

        $this['project_list']->add($project);

        return $project;
    }
}


text:
static struct {
  FSEventStreamEventId            sinceWhen;
  CFTimeInterval                  latency;
  FSEventStreamCreateFlags        flags;
  CFMutableArrayRef               paths;
  enum FSEventWatchOutputFormat   format;
} config = {
  (UInt64) kFSEventStreamEventIdSinceNow,
  (double) 0.3,
  (CFOptionFlags) kFSEventStreamCreateFlagNone,
  NULL,
  kFSEventWatchOutputFormatClassic
};

// Prototypes
static void         append_path(const char* path);
static inline void  parse_cli_settings(int argc, const char* argv[]);
static void         callback(FSEventStreamRef streamRef,
                             void* clientCallBackInfo,
                             size_t numEvents,
                             void* eventPaths,
                             const FSEventStreamEventFlags eventFlags[],
                             const FSEventStreamEventId eventIds[]);
static bool needs_fsevents_fix = false;

// Resolve a path and append it to the CLI settings structure
// The FSEvents API will, internally, resolve paths using a similar scheme.
// Performing this ahead of time makes things less confusing, IMHO.
static void append_path(const char* path)
{
#ifdef DEBUG
  fprintf(stderr, "\n");
  fprintf(stderr, "append_path called for: %s\n", path);
#endif

#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060

#ifdef DEBUG
  fprintf(stderr, "compiled against 10.6+, using CFURLCreateFileReferenceURL\n");
#endif

  CFURLRef url = CFURLCreateFromFileSystemRepresentation(NULL, (const UInt8*)path, (CFIndex)strlen(path), false);
  CFURLRef placeholder = CFURLCopyAbsoluteURL(url);
  CFRelease(url);

  CFMutableArrayRef imaginary = NULL;

  // if we don't have an existing url, spin until we get to a parent that
  // does exist, saving any imaginary components for appending back later
  while(!CFURLResourceIsReachable(placeholder, NULL)) {
#ifdef DEBUG
    fprintf(stderr, "path does not exist\n");
#endif

    CFStringRef child;

    if (imaginary == NULL) {
      imaginary = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
    }

    child = CFURLCopyLastPathComponent(placeholder);
    CFArrayInsertValueAtIndex(imaginary, 0, child);
    CFRelease(child);

    url = CFURLCreateCopyDeletingLastPathComponent(NULL, placeholder);
    CFRelease(placeholder);
    placeholder = url;

#ifdef DEBUG
    fprintf(stderr, "parent: ");
    CFShow(placeholder);
#endif
  }

#ifdef DEBUG
  fprintf(stderr, "path exists\n");
#endif

  // realpath() doesn't always return the correct case for a path, so this
  // is a funky workaround that converts a path into a (volId/inodeId) pair
  // and asks what the path should be for that. since it looks at the actual
  // inode instead of returning the same case passed in like realpath()
  // appears to do for HFS+, it should always be correct.
  url = CFURLCreateFileReferenceURL(NULL, placeholder, NULL);
  CFRelease(placeholder);
  placeholder = CFURLCreateFilePathURL(NULL, url, NULL);
  CFRelease(url);

#ifdef DEBUG
  fprintf(stderr, "path resolved to: ");
  CFShow(placeholder);
#endif

  // if we stripped off any imaginary path components, append them back on
  if (imaginary != NULL) {
    CFIndex count = CFArrayGetCount(imaginary);
    for (CFIndex i = 0; i<count; i++) {
      CFStringRef component = CFArrayGetValueAtIndex(imaginary, i);
#ifdef DEBUG
      fprintf(stderr, "appending component: ");
      CFShow(component);
#endif
      url = CFURLCreateCopyAppendingPathComponent(NULL, placeholder, component, false);
      CFRelease(placeholder);
      placeholder = url;
    }
    CFRelease(imaginary);
  }

#ifdef DEBUG
  fprintf(stderr, "result: ");
  CFShow(placeholder);
#endif

  CFStringRef cfPath = CFURLCopyFileSystemPath(placeholder, kCFURLPOSIXPathStyle);
  CFRelease(placeholder);

  char cPath[PATH_MAX];
  if (CFStringGetCString(cfPath, cPath, PATH_MAX, kCFStringEncodingUTF8)) {
    FSEventsFixRepairStatus status = FSEventsFixRepairIfNeeded(cPath);
    if (status == FSEventsFixRepairStatusFailed) {
      needs_fsevents_fix = true;
    }
  }

  CFArrayAppendValue(config.paths, cfPath);
  CFRelease(cfPath);

#else

#ifdef DEBUG
  fprintf(stderr, "compiled against 10.5, using realpath()\n");
#endif

  char fullPath[PATH_MAX + 1];

  if (realpath(path, fullPath) == NULL) {
#ifdef DEBUG
    fprintf(stderr, "  realpath not directly resolvable from path\n");
#endif

    if (path[0] != '/') {
#ifdef DEBUG
      fprintf(stderr, "  passed path is not absolute\n");
#endif
      size_t len;
      getcwd(fullPath, sizeof(fullPath));
#ifdef DEBUG
      fprintf(stderr, "  result of getcwd: %s\n", fullPath);
#endif
      len = strlen(fullPath);
      fullPath[len] = '/';
      strlcpy(&fullPath[len + 1], path, sizeof(fullPath) - (len + 1));
    } else {
#ifdef DEBUG
      fprintf(stderr, "  assuming path does not YET exist\n");
#endif
      strlcpy(fullPath, path, sizeof(fullPath));
    }
  }

#ifdef DEBUG
  fprintf(stderr, "  resolved path to: %s\n", fullPath);
  fprintf(stderr, "\n");
#endif

  CFStringRef pathRef = CFStringCreateWithCString(kCFAllocatorDefault,
                                                  fullPath,
                                                  kCFStringEncodingUTF8);
  CFArrayAppendValue(config.paths, pathRef);
  CFRelease(pathRef);

#endif
}

// Parse commandline settings
static inline void parse_cli_settings(int argc, const char* argv[])
{
  // runtime os version detection
  SInt32 osMajorVersion, osMinorVersion;
  if (!(Gestalt(gestaltSystemVersionMajor, &osMajorVersion) == noErr)) {
    osMajorVersion = 0;
  }
  if (!(Gestalt(gestaltSystemVersionMinor, &osMinorVersion) == noErr)) {
    osMinorVersion = 0;
  }

  if ((osMajorVersion == 10) & (osMinorVersion < 5)) {
    fprintf(stderr, "The FSEvents API is unavailable on this version of macos!\n");
    exit(EXIT_FAILURE);
  }

  struct cli_info args_info;
  cli_parser_init(&args_info);

  if (cli_parser(argc, argv, &args_info) != 0) {
    exit(EXIT_FAILURE);
  }

  config.paths = CFArrayCreateMutable(NULL,
                                      (CFIndex)0,
                                      &kCFTypeArrayCallBacks);

  config.sinceWhen = args_info.since_when_arg;
  config.latency = args_info.latency_arg;
  config.format = args_info.format_arg;

  if (args_info.no_defer_flag) {
    config.flags |= kFSEventStreamCreateFlagNoDefer;
  }
  if (args_info.watch_root_flag) {
    config.flags |= kFSEventStreamCreateFlagWatchRoot;
  }

  if (args_info.ignore_self_flag) {
    if ((osMajorVersion == 10) & (osMinorVersion >= 6)) {
      config.flags |= kFSEventStreamCreateFlagIgnoreSelf;
    } else {
      fprintf(stderr, "MacOSX 10.6 or later is required for --ignore-self\n");
      exit(EXIT_FAILURE);
    }
  }

  if (args_info.file_events_flag) {
    if ((osMajorVersion == 10) & (osMinorVersion >= 7)) {
      config.flags |= kFSEventStreamCreateFlagFileEvents;
    } else {
      fprintf(stderr, "MacOSX 10.7 or later required for --file-events\n");
      exit(EXIT_FAILURE);
    }
  }

  if (args_info.mark_self_flag) {
    if ((osMajorVersion == 10) & (osMinorVersion >= 9)) {
      config.flags |= kFSEventStreamCreateFlagMarkSelf;
    } else {
      fprintf(stderr, "MacOSX 10.9 or later required for --mark-self\n");
      exit(EXIT_FAILURE);
    }
  }

  if (args_info.inputs_num == 0) {
    append_path(".");
  } else {
    for (unsigned int i=0; i < args_info.inputs_num; ++i) {
      append_path(args_info.inputs[i]);
    }
  }

  cli_parser_free(&args_info);

#ifdef DEBUG
  fprintf(stderr, "config.sinceWhen    %llu\n", config.sinceWhen);
  fprintf(stderr, "config.latency      %f\n", config.latency);

// STFU clang
#if defined(__LP64__)
  fprintf(stderr, "config.flags        %#.8x\n", config.flags);
#else
  fprintf(stderr, "config.flags        %#.8lx\n", config.flags);
#endif

  FLAG_CHECK_STDERR(config.flags, kFSEventStreamCreateFlagUseCFTypes,
                    "  Using CF instead of C types");
  FLAG_CHECK_STDERR(config.flags, kFSEventStreamCreateFlagNoDefer,
                    "  NoDefer latency modifier enabled");
  FLAG_CHECK_STDERR(config.flags, kFSEventStreamCreateFlagWatchRoot,
                    "  WatchRoot notifications enabled");
  FLAG_CHECK_STDERR(config.flags, kFSEventStreamCreateFlagIgnoreSelf,
                    "  IgnoreSelf enabled");
  FLAG_CHECK_STDERR(config.flags, kFSEventStreamCreateFlagFileEvents,
                    "  FileEvents enabled");

  fprintf(stderr, "config.paths\n");

  long numpaths = CFArrayGetCount(config.paths);

  for (long i = 0; i < numpaths; i++) {
    char path[PATH_MAX];
    CFStringGetCString(CFArrayGetValueAtIndex(config.paths, i),
                       path,
                       PATH_MAX,
                       kCFStringEncodingUTF8);
    fprintf(stderr, "  %s\n", path);
  }

  fprintf(stderr, "\n");
#endif
}

// original output format for rb-fsevent
static void classic_output_format(size_t numEvents,
                                  char** paths)
{
  for (size_t i = 0; i < numEvents; i++) {
    fprintf(stdout, "%s:", paths[i]);
  }
  fprintf(stdout, "\n");
}

// output format used in the Yoshimasa Niwa branch of rb-fsevent
static void niw_output_format(size_t numEvents,
                              char** paths,
                              const FSEventStreamEventFlags eventFlags[],
                              const FSEventStreamEventId eventIds[])
{
  for (size_t i = 0; i < numEvents; i++) {
    fprintf(stdout, "%lu:%llu:%s\n",
            (unsigned long)eventFlags[i],
            (unsigned long long)eventIds[i],
            paths[i]);
  }
  fprintf(stdout, "\n");
}

static void tstring_output_format(size_t numEvents,
                                  char** paths,
                                  const FSEventStreamEventFlags eventFlags[],
                                  const FSEventStreamEventId eventIds[],
                                  TSITStringFormat format)
{
  CFMutableArrayRef events = CFArrayCreateMutable(kCFAllocatorDefault,
                             0, &kCFTypeArrayCallBacks);

  for (size_t i = 0; i < numEvents; i++) {
    CFMutableDictionaryRef event = CFDictionaryCreateMutable(kCFAllocatorDefault,
                                   0,
                                   &kCFTypeDictionaryKeyCallBacks,
                                   &kCFTypeDictionaryValueCallBacks);

    CFStringRef path = CFStringCreateWithBytes(kCFAllocatorDefault,
                       (const UInt8*)paths[i],
                       (CFIndex)strlen(paths[i]),
                       kCFStringEncodingUTF8,
                       false);
    CFDictionarySetValue(event, CFSTR("path"), path);

    CFNumberRef flags = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &eventFlags[i]);
    CFDictionarySetValue(event, CFSTR("flags"), flags);

    CFNumberRef ident = CFNumberCreate(kCFAllocatorDefault, kCFNumberLongLongType, &eventIds[i]);
    CFDictionarySetValue(event, CFSTR("id"), ident);

    CFArrayAppendValue(events, event);

    CFRelease(event);
    CFRelease(path);
    CFRelease(flags);
    CFRelease(ident);
  }

  CFMutableDictionaryRef meta = CFDictionaryCreateMutable(kCFAllocatorDefault,
                                0,
                                &kCFTypeDictionaryKeyCallBacks,
                                &kCFTypeDictionaryValueCallBacks);
  CFDictionarySetValue(meta, CFSTR("events"), events);

  CFNumberRef num = CFNumberCreate(kCFAllocatorDefault, kCFNumberCFIndexType, &numEvents);
  CFDictionarySetValue(meta, CFSTR("numEvents"), num);

  CFDataRef data = TSICTStringCreateRenderedDataFromObjectWithFormat(meta, format);
  fprintf(stdout, "%s", CFDataGetBytePtr(data));

  CFRelease(events);
  CFRelease(num);
  CFRelease(meta);
  CFRelease(data);
}

static void callback(__attribute__((unused)) FSEventStreamRef streamRef,
                     __attribute__((unused)) void* clientCallBackInfo,
                     size_t numEvents,
                     void* eventPaths,
                     const FSEventStreamEventFlags eventFlags[],
                     const FSEventStreamEventId eventIds[])
{
  char** paths = eventPaths;

#ifdef DEBUG
  fprintf(stderr, "\n");
  fprintf(stderr, "FSEventStreamCallback fired!\n");
  fprintf(stderr, "  numEvents: %lu\n", numEvents);

  for (size_t i = 0; i < numEvents; i++) {
    fprintf(stderr, "\n");
    fprintf(stderr, "  event ID: %llu\n", eventIds[i]);

// STFU clang
#if defined(__LP64__)
    fprintf(stderr, "  event flags: %#.8x\n", eventFlags[i]);
#else
    fprintf(stderr, "  event flags: %#.8lx\n", eventFlags[i]);
#endif

    FLAG_CHECK_STDERR(eventFlags[i], kFSEventStreamEventFlagMustScanSubDirs,
                      "    Recursive scanning of directory required");
    FLAG_CHECK_STDERR(eventFlags[i], kFSEventStreamEventFlagUserDropped,
                      "    Buffering problem: events dropped user-side");
    FLAG_CHECK_STDERR(eventFlags[i], kFSEventStreamEventFlagKernelDropped,
                      "    Buffering problem: events dropped kernel-side");
    FLAG_CHECK_STDERR(eventFlags[i], kFSEventStreamEventFlagEventIdsWrapped,
                      "    Event IDs have wrapped");
    FLAG_CHECK_STDERR(eventFlags[i], kFSEventStreamEventFlagHistoryDone,
                      "    All historical events have been processed");
    FLAG_CHECK_STDERR(eventFlags[i], kFSEventStreamEventFlagRootChanged,
                      "    Root path has changed");
    FLAG_CHECK_STDERR(eventFlags[i], kFSEventStreamEventFlagMount,
                      "    A new volume was mounted at this path");
    FLAG_CHECK_STDERR(eventFlags[i], kFSEventStreamEventFlagUnmount,
                      "    A volume was unmounted from this path");
    FLAG_CHECK_STDERR(eventFlags[i], kFSEventStreamEventFlagItemCreated,
                      "    Item created");
    FLAG_CHECK_STDERR(eventFlags[i], kFSEventStreamEventFlagItemRemoved,
                      "    Item removed");
    FLAG_CHECK_STDERR(eventFlags[i], kFSEventStreamEventFlagItemInodeMetaMod,
                      "    Item metadata modified");
    FLAG_CHECK_STDERR(eventFlags[i], kFSEventStreamEventFlagItemRenamed,
                      "    Item renamed");
    FLAG_CHECK_STDERR(eventFlags[i], kFSEventStreamEventFlagItemModified,
                      "    Item modified");
    FLAG_CHECK_STDERR(eventFlags[i], kFSEventStreamEventFlagItemFinderInfoMod,
                      "    Item Finder Info modified");
    FLAG_CHECK_STDERR(eventFlags[i], kFSEventStreamEventFlagItemChangeOwner,
                      "    Item changed ownership");
    FLAG_CHECK_STDERR(eventFlags[i], kFSEventStreamEventFlagItemXattrMod,
                      "    Item extended attributes modified");
    FLAG_CHECK_STDERR(eventFlags[i], kFSEventStreamEventFlagItemIsFile,
                      "    Item is a file");
    FLAG_CHECK_STDERR(eventFlags[i], kFSEventStreamEventFlagItemIsDir,
                      "    Item is a directory");
    FLAG_CHECK_STDERR(eventFlags[i], kFSEventStreamEventFlagItemIsSymlink,
                      "    Item is a symbolic link");

    fprintf(stderr, "  event path: %s\n", paths[i]);
    fprintf(stderr, "\n");
  }

  fprintf(stderr, "\n");
#endif

  if (config.format == kFSEventWatchOutputFormatClassic) {
    classic_output_format(numEvents, paths);
  } else if (config.format == kFSEventWatchOutputFormatNIW) {
    niw_output_format(numEvents, paths, eventFlags, eventIds);
  } else if (config.format == kFSEventWatchOutputFormatTNetstring) {
    tstring_output_format(numEvents, paths, eventFlags, eventIds,
                          kTSITStringFormatTNetstring);
  } else if (config.format == kFSEventWatchOutputFormatOTNetstring) {
    tstring_output_format(numEvents, paths, eventFlags, eventIds,
                          kTSITStringFormatOTNetstring);
  }

  fflush(stdout);
}

int main(int argc, const char* argv[])
{
  parse_cli_settings(argc, argv);

  if (needs_fsevents_fix) {
    FSEventsFixEnable();
  }

  FSEventStreamContext context = {0, NULL, NULL, NULL, NULL};
  FSEventStreamRef stream;
  stream = FSEventStreamCreate(kCFAllocatorDefault,
                               (FSEventStreamCallback)&callback,
                               &context,
                               config.paths,
                               config.sinceWhen,
                               config.latency,
                               config.flags);

#ifdef DEBUG
  FSEventStreamShow(stream);
  fprintf(stderr, "\n");
#endif

  if (needs_fsevents_fix) {
    FSEventsFixDisable();
  }

  FSEventStreamScheduleWithRunLoop(stream,
                                   CFRunLoopGetCurrent(),
                                   kCFRunLoopDefaultMode);
  FSEventStreamStart(stream);
  CFRunLoopRun();
  FSEventStreamFlushSync(stream);
  FSEventStreamStop(stream);

  return 0;
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Data;
using System.Configuration;
using LTAF;

[WebTestClass]
public class GridViewInUpdatePanelTests
{
    [WebTestMethod]
    public void GridViewSortTest()
    {
        HtmlPage page = new HtmlPage();
        LoginAndGoToHome(page);

        // Get the gridview table
        HtmlTableElement gridView = (HtmlTableElement) page.Elements.Find("CoursesGridView");

        // Sort by name
        gridView.Rows[0].Cells[4].ChildElements[0].Click(WaitFor.AsyncPostback);

        // Verify sort operation
        Assert.AreEqual("Course Name #17", gridView.Rows[10].Cells[4].GetInnerText());
    }

    private void LoginAndGoToHome(HtmlPage page)
    {
        // Navigate to Home page
        page.Navigate("Home.aspx");

        if (page.Elements.Exists(new HtmlElementFindParams("tab-login"), 0))
        {
            // If the login tab exists, then we were unauthenticated and we need to login
            page.Elements.Find("UserName").SetText("ValidUser");
            page.Elements.Find("Password").SetText("foo");
            page.Elements.Find("LoginButton").Click(WaitFor.Postback);
        }
    }

    [WebTestMethod]
    public void GridViewPagingTest()
    {
        HtmlPage page = new HtmlPage();
        LoginAndGoToHome(page);

        // Get the gridview table
        HtmlTableElement gridView = (HtmlTableElement)page.Elements.Find("CoursesGridView");

        // Verify current last entry
        Assert.AreEqual("Course Name #9", gridView.Rows[10].Cells[4].GetInnerText());

        // Go to page two
        gridView.Rows[11].ChildElements.Find("a", 0).Click(WaitFor.AsyncPostback);

        // Verify current last entry
        Assert.AreEqual("Course Name #19", gridView.Rows[10].Cells[4].GetInnerText());
    }

    [WebTestMethod]
    public void GridViewEditTest()
    {
        HtmlPage page = new HtmlPage();
        LoginAndGoToHome(page);

        // Build the expected grades that are going to be set
        Random rand = new Random(DateTime.Now.Second);
        string grade1 = rand.Next(100).ToString();
        string grade2 = rand.Next(100).ToString();
        string grade3 = rand.Next(100).ToString();

        // Get the gridview table
        HtmlTableElement gridView = (HtmlTableElement)page.Elements.Find("CoursesGridView");

        // Go to edit mode
        gridView.Rows[1].Cells[1].ChildElements[0].Click(WaitFor.AsyncPostback);

        // Fill the textboxes
        gridView.ChildElements.Refresh();
        gridView.Rows[1].Cells[6].ChildElements[0].SetText(grade1);
        gridView.Rows[1].Cells[7].ChildElements[0].SetText(grade2);
        gridView.Rows[1].Cells[8].ChildElements[0].SetText(grade3);

        // Click update button
        gridView.Rows[1].Cells[1].ChildElements[0].Click(WaitFor.AsyncPostback);

        // Verify new values
        gridView.ChildElements.Refresh();
        Assert.AreEqual(grade1, gridView.Rows[1].Cells[6].CachedInnerText);
        Assert.AreEqual(grade2, gridView.Rows[1].Cells[7].CachedInnerText);
        Assert.AreEqual(grade3, gridView.Rows[1].Cells[8].CachedInnerText);
    }
}


text:
import gulp from 'gulp';
import clean from 'gulp-clean';
import babel from 'gulp-babel';
import minify from 'gulp-minifier';
import jsonModify from 'gulp-json-modify';
import fs from 'fs';

const src = './src';
const dist_folder = './dist';
const logs_folder = './logs';
const dist_folder_server = `${dist_folder}/server`;

gulp.task('clean', () => {
  fs.access(logs_folder, err => {
    if (err) {
      fs.mkdir(logs_folder, () => {});
    }
  });
  return gulp
    .src([`${dist_folder}/*`, `${logs_folder}/*`], { read: false })
    .pipe(clean({ force: true }));
});

gulp.task('build-babel', () => {
  return gulp
    .src(`${src}/**/*.js`)
    .pipe(babel())
    .pipe(gulp.dest(dist_folder_server));
});

gulp.task('static', () => {
  gulp.src(['src/**/*.yaml']).pipe(gulp.dest(dist_folder_server));
  gulp
    .src('package.json')
    .pipe(jsonModify({ key: 'devDependencies', value: {} }))
    .pipe(gulp.dest(dist_folder));
  gulp
    .src(['src/views/**/*.{html,css}'])
    .pipe(
      minify({
        minify: true,
        collapseWhitespace: true,
        conservativeCollapse: true,
        minifyJS: true,
        minifyCSS: true
      })
    )
    .pipe(gulp.dest(`${dist_folder_server}/views`));
  return gulp
    .src(['src/views/**/*.*', '!src/views/**/*.{html,css}'])
    .pipe(gulp.dest(`${dist_folder_server}/views`));
});

gulp.task('build', gulp.series('clean', 'build-babel', 'static'));


text:
using namespace std;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    screen = new GameScreen;
    screen->setSceneRect(QRectF(0, 0, WORLD_SIZE, WORLD_SIZE));
    veiw = new QGraphicsView(screen);

    veiw->setTransform(QTransform().scale(5,5));

    QHBoxLayout * lay = new QHBoxLayout(this);
    lay->addWidget(make_layout());
    lay->addWidget(veiw,Qt::AlignLeft);
    QWidget * W = new QWidget;
    W->setLayout(lay);
    setCentralWidget(W);

    setWindowTitle(tr("Economy Simulator"));

    frame_timer.setInterval(250);
    frame_timer.start();
    connect(&frame_timer,&QTimer::timeout,this,&MainWindow::draw);
}
QWidget * MainWindow::make_layout(){
    QWidget * W = new QWidget(this);

    chks[0] = check_obj("residents",false,[&](){screen->draw_thing(screen->screen_data.num_residents,Qt::black, 0.5);},W);
    chks[1] = check_obj("workers",false,[&](){screen->draw_thing(screen->screen_data.num_workers,Qt::blue, 0.5);},W);
    chks[2] = check_obj("transportation investment",true,[&](){screen->draw_thing(screen->screen_data.trans_invest_view,Qt::yellow, 0.5);},W);
    chks[3] = check_obj("upgrade benefit",true,[&](){screen->draw_thing(screen->screen_data.upgrade_vs_view,Qt::green, 0.5);},W);

    QLabel * sclab = new QLabel(QString("Speed Control"));
    QSlider * scslide = new QSlider(this);
    connect(scslide,&QSlider::sliderMoved,[&](int slide_val){
        frame_timer.setInterval(slide_time(slide_val));
    });

    QLabel * zclab = new QLabel(QString("Zoom Control"));
    QSlider * zcslide = new QSlider(this);
    connect(zcslide,&QSlider::sliderMoved,[&](int slide_val){
        veiw->setTransform(QTransform().scale(slide_val,slide_val));
    });

    QVBoxLayout * lay = new QVBoxLayout(this);
    for(check_obj & ck : chks){
        lay->addWidget(ck.box,0,Qt::AlignTop);
    }
    lay->addWidget(zclab);
    lay->addWidget(zcslide,0,Qt::AlignTop);
    lay->addWidget(sclab);
    lay->addWidget(scslide,10,Qt::AlignTop);
    W->setLayout(lay);
    return W;
}
void MainWindow::draw(){
    int64_t st = uclock();
    screen->clear();
    int64_t algost = uclock();
    screen->screen_data.update();
    int64_t algotot = uclock() - algost;
    for(check_obj & ck : chks){
        ck.call_if_checked();
    }
    int64_t tot = uclock() - st;
    cout << "Algorithm time update: " << time_to_sec(algotot) << endl;
    cout << "Total time update: " << time_to_sec(tot) << endl;
}
MainWindow::~MainWindow()
{
    delete ui;
}


text:
import {
  attribute,
  clickable,
  create,
  collection,
  hasClass,
  fillable,
  isPresent,
  text,
  value,
} from 'ember-cli-page-object';

const definition = {
  scope: '[data-test-pending-updates-summary]',
  title: text('[data-test-title]'),
  summary: text('[data-test-summary]'),
  hasAlert: hasClass('alert'),
  schoolFilter: {
    scope: '[data-test-schools]',
    set: fillable('select'),
    hasMultiple: isPresent(' select'),
    selected: value('select'),
    options: collection('option'),
  },
  manage: {
    scope: '[data-test-manage]',
    link: attribute('href'),
    click: clickable('button'),
  },
};

export default definition;
export const component = create(definition);


text:
export default Ember.View.extend({
  tagName: 'section',
  classNames: ['router'],
  classNameBindings: ['flipped'],

  flipped: Ember.computed.alias('controller.flipped')
});


text:
<?xml version="1.0" encoding="utf-8"?>

<interface id="CSS-Counter" name="Counter" since="DOM Level 2">
  <descr>

      The Counter interface is used to represent any <xspecref href="&css2;/syndata.html#value-def-counter">counter or
      counters function</xspecref> value. This interface reflects the values in
      the underlying style property.

  </descr>

  <attribute id="CSS-Counter-identifier" name="identifier" type="DOMString" readonly="yes">
    <descr>

        This attribute is used for the identifier of the counter.

    </descr>
  </attribute>

  <attribute id="CSS-Counter-listStyle" name="listStyle" type="DOMString" readonly="yes">
    <descr>

        This attribute is used for the style of the list.

    </descr>
  </attribute>

  <attribute id="CSS-Counter-separator" name="separator" type="DOMString" readonly="yes">
    <descr>

        This attribute is used for the separator of the nested counters.

    </descr>
  </attribute>

</interface>


text:
package io.github.azaiats.androidmvvm.sample.fragments;

import android.support.annotation.NonNull;

import io.github.azaiats.androidmvvm.R;
import io.github.azaiats.androidmvvm.core.MvvmFragment;
import io.github.azaiats.androidmvvm.core.common.BindingConfig;
import io.github.azaiats.androidmvvm.databinding.FragmentFirstBinding;
import io.github.azaiats.androidmvvm.sample.viewmodels.SecondFragmentViewModel;

/**
 * @author Andrei Zaiats
 * @since 05/26/2016
 */
public class SecondFragment extends MvvmFragment<FragmentFirstBinding, SecondFragmentViewModel> {

    @NonNull
    @Override
    public BindingConfig getBindingConfig() {
        return new BindingConfig(R.layout.fragment_second);
    }

    @NonNull
    @Override
    public SecondFragmentViewModel createViewModel() {
        return new SecondFragmentViewModel();
    }
}


text:
/*
 * MapComposerFrame.java
 *
 * Created on July 31, 2007, 9:39 AM
 */
package edu.oregonstate.carto.mapcomposer.gui;

import edu.oregonstate.carto.mapcomposer.Map;
import edu.oregonstate.carto.utils.FileUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.xml.bind.JAXBException;

/**
 * Main window for composing a map consisting of multiple layers. The UI
 * elements mostly handled by a MapComposerPanel.
 *
 * @author Bernhard Jenny, Institute of Cartography, ETH Zurich.
 * @author Charlotte Hoarau, COGIT Laboratory, IGN France
 */
public class MapComposerFrame extends javax.swing.JFrame {

    /**
     * Creates new form MapComposerFrame
     */
    public MapComposerFrame() {
        initComponents();
        mapComposerPanel.registerUndoMenuItems(undoMenuItem, redoMenuItem);
        /*
        // FIXME temp hack for developing. Remove for final release.
        String filePath = "/Users/jennyb/Desktop/local.xml";
        if (filePath != null) {
            try {
                mapComposerPanel.setMap(Map.unmarshal(filePath));
            } catch (JAXBException | FileNotFoundException ex) {
                Logger.getLogger(MapComposerFrame.class.getName()).log(Level.SEVERE, null, ex);
                String msg = "Could not load style file";
                String title = "Error";
                ErrorDialog.showErrorDialog(msg, title, ex, rootPane);
            }
        }*/
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        zoomAndPanPanel = new javax.swing.JPanel();
        javax.swing.JLabel zoomMapLabel = new javax.swing.JLabel();
        zoomFormattedTextField = new javax.swing.JFormattedTextField();
        javax.swing.JLabel longitudeLabel = new javax.swing.JLabel();
        longitudeFormattedTextField = new javax.swing.JFormattedTextField();
        javax.swing.JLabel latitudeLabel = new javax.swing.JLabel();
        latitudeFormattedTextField = new javax.swing.JFormattedTextField();
        mapComposerPanel = new edu.oregonstate.carto.mapcomposer.gui.MapComposerPanel();
        menuBar = new javax.swing.JMenuBar();
        fileMenu = new javax.swing.JMenu();
        openStyleMenuItem = new javax.swing.JMenuItem();
        saveStyleMenuItem = new javax.swing.JMenuItem();
        javax.swing.JPopupMenu.Separator jSeparator2 = new javax.swing.JPopupMenu.Separator();
        saveMapMenuItem = new javax.swing.JMenuItem();
        editMenu = new javax.swing.JMenu();
        undoMenuItem = new javax.swing.JMenuItem();
        redoMenuItem = new javax.swing.JMenuItem();
        mapMenu = new javax.swing.JMenu();
        addLayerMenuItem = new javax.swing.JMenuItem();
        removeLayerMenuItem = new javax.swing.JMenuItem();
        javax.swing.JPopupMenu.Separator jSeparator4 = new javax.swing.JPopupMenu.Separator();
        removeAllLayersMenuItem = new javax.swing.JMenuItem();
        javax.swing.JPopupMenu.Separator jSeparator1 = new javax.swing.JPopupMenu.Separator();
        mapExtentMenuItem = new javax.swing.JMenuItem();
        jSeparator3 = new javax.swing.JPopupMenu.Separator();
        reloadMapPreviewMenuItem = new javax.swing.JMenuItem();
        javax.swing.JPopupMenu.Separator jSeparator5 = new javax.swing.JPopupMenu.Separator();
        zoomAndPanMenuItem = new javax.swing.JMenuItem();
        debugMenu = new javax.swing.JMenu();
        printXMLMenuItem = new javax.swing.JMenuItem();

        zoomAndPanPanel.setLayout(new java.awt.GridBagLayout());

        zoomMapLabel.setText("Zoom");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
        zoomAndPanPanel.add(zoomMapLabel, gridBagConstraints);

        zoomFormattedTextField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(java.text.NumberFormat.getIntegerInstance())));
        zoomFormattedTextField.setPreferredSize(new java.awt.Dimension(140, 28));
        zoomAndPanPanel.add(zoomFormattedTextField, new java.awt.GridBagConstraints());

        longitudeLabel.setText("Longitude");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
        zoomAndPanPanel.add(longitudeLabel, gridBagConstraints);

        longitudeFormattedTextField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#,##0.#####"))));
        longitudeFormattedTextField.setPreferredSize(new java.awt.Dimension(140, 28));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        zoomAndPanPanel.add(longitudeFormattedTextField, gridBagConstraints);

        latitudeLabel.setText("Latitude");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
        zoomAndPanPanel.add(latitudeLabel, gridBagConstraints);

        latitudeFormattedTextField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#,##0.#####"))));
        latitudeFormattedTextField.setPreferredSize(new java.awt.Dimension(140, 28));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        zoomAndPanPanel.add(latitudeFormattedTextField, gridBagConstraints);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        mapComposerPanel.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 5, 0, 0));
        getContentPane().add(mapComposerPanel, java.awt.BorderLayout.CENTER);

        fileMenu.setText("File");

        openStyleMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        openStyleMenuItem.setText("Open Map Settings");
        openStyleMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openStyleMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(openStyleMenuItem);

        saveStyleMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        saveStyleMenuItem.setText("Save Map Settings");
        saveStyleMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveStyleMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(saveStyleMenuItem);
        fileMenu.add(jSeparator2);

        saveMapMenuItem.setText("Export Tiles");
        saveMapMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveMapMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(saveMapMenuItem);

        menuBar.add(fileMenu);

        editMenu.setText("Edit");

        undoMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Z, java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        undoMenuItem.setText("Undo");
        undoMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                undoMenuItemActionPerformed(evt);
            }
        });
        editMenu.add(undoMenuItem);

        redoMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Y, java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        redoMenuItem.setText("Redo");
        redoMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                redoMenuItemActionPerformed(evt);
            }
        });
        editMenu.add(redoMenuItem);

        menuBar.add(editMenu);

        mapMenu.setText("Map");

        addLayerMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_PLUS, java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        addLayerMenuItem.setText("Add Layer");
        addLayerMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addLayerMenuItemActionPerformed(evt);
            }
        });
        mapMenu.add(addLayerMenuItem);

        removeLayerMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_MINUS,    java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        removeLayerMenuItem.setText("Remove Layer");
        removeLayerMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeLayerMenuItemActionPerformed(evt);
            }
        });
        mapMenu.add(removeLayerMenuItem);
        mapMenu.add(jSeparator4);

        removeAllLayersMenuItem.setText("Remove All Layers");
        removeAllLayersMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeAllLayersMenuItemActionPerformed(evt);
            }
        });
        mapMenu.add(removeAllLayersMenuItem);
        mapMenu.add(jSeparator1);

        mapExtentMenuItem.setText("Set Map Extent");
        mapExtentMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mapExtentMenuItemActionPerformed(evt);
            }
        });
        mapMenu.add(mapExtentMenuItem);
        mapMenu.add(jSeparator3);

        reloadMapPreviewMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_R, java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        reloadMapPreviewMenuItem.setText("Reload Map Preview");
        reloadMapPreviewMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                reloadMapPreviewMenuItemActionPerformed(evt);
            }
        });
        mapMenu.add(reloadMapPreviewMenuItem);
        mapMenu.add(jSeparator5);

        zoomAndPanMenuItem.setText("Zoom and Pan Map");
        zoomAndPanMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                zoomAndPanMenuItemActionPerformed(evt);
            }
        });
        mapMenu.add(zoomAndPanMenuItem);

        menuBar.add(mapMenu);

        debugMenu.setText("Debug");

        printXMLMenuItem.setText("Print XML");
        printXMLMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                printXMLMenuItemActionPerformed(evt);
            }
        });
        debugMenu.add(printXMLMenuItem);

        menuBar.add(debugMenu);

        setJMenuBar(menuBar);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void openStyleMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openStyleMenuItemActionPerformed
        String filePath = FileUtils.askFile(null, "Load Style.xml file", null, true, "xml");
        if (filePath != null) {
            try {
                mapComposerPanel.setMap(Map.unmarshal(filePath));
            } catch (JAXBException | FileNotFoundException ex) {
                Logger.getLogger(MapComposerFrame.class.getName()).log(Level.SEVERE, null, ex);
                String msg = "Could not load style file";
                String title = "Error";
                ErrorDialog.showErrorDialog(msg, title, ex, rootPane);
            }
        }
    }//GEN-LAST:event_openStyleMenuItemActionPerformed

    private void saveMapMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveMapMenuItemActionPerformed
        try {
            String directoryPath = FileUtils.askDirectory(null, "Save Tiled Images", false, null);
            if (directoryPath == null) {
                // user canceled
                return;
            }
            mapComposerPanel.readGUIAndRenderMap();
            mapComposerPanel.renderTilesWithProgressDialog(new File(directoryPath));
        } catch (IOException ex) {
            Logger.getLogger(MapComposerFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_saveMapMenuItemActionPerformed

    private void saveStyleMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveStyleMenuItemActionPerformed
        String filePath = FileUtils.askFile(null, "Save XML Style", null, false, "xml");
        if (filePath == null) {
            return;
        }
        File file = new File(filePath);
        try {
            mapComposerPanel.getMap().marshal(file.getAbsolutePath());
        } catch (JAXBException | FileNotFoundException ex) {
            Logger.getLogger(MapComposerFrame.class.getName()).log(Level.SEVERE, null, ex);
            String msg = "Could not save style file";
            String title = "Error";
            ErrorDialog.showErrorDialog(msg, title, ex, rootPane);
        }
    }//GEN-LAST:event_saveStyleMenuItemActionPerformed

    private void addLayerMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addLayerMenuItemActionPerformed
        boolean focusList = true;
        mapComposerPanel.addLayer(focusList);
    }//GEN-LAST:event_addLayerMenuItemActionPerformed

    private void removeLayerMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeLayerMenuItemActionPerformed
        mapComposerPanel.removeLayer();
    }//GEN-LAST:event_removeLayerMenuItemActionPerformed

    private void reloadMapPreviewMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_reloadMapPreviewMenuItemActionPerformed
        mapComposerPanel.loadHTMLMap();
    }//GEN-LAST:event_reloadMapPreviewMenuItemActionPerformed

    private void mapExtentMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mapExtentMenuItemActionPerformed
        mapComposerPanel.askMapExtent();
    }//GEN-LAST:event_mapExtentMenuItemActionPerformed

    private void undoMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_undoMenuItemActionPerformed
        mapComposerPanel.undo();
    }//GEN-LAST:event_undoMenuItemActionPerformed

    private void redoMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_redoMenuItemActionPerformed
        mapComposerPanel.redo();
    }//GEN-LAST:event_redoMenuItemActionPerformed

    private void removeAllLayersMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeAllLayersMenuItemActionPerformed
        mapComposerPanel.removeAllLayers();
    }//GEN-LAST:event_removeAllLayersMenuItemActionPerformed

    private void zoomAndPanMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_zoomAndPanMenuItemActionPerformed
        String title = "Zoom and Pan";
        int res = JOptionPane.showOptionDialog(mapComposerPanel, zoomAndPanPanel, title,
                JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, null, null);
        if (res == JOptionPane.OK_OPTION) {
            int zoom = ((Number) zoomFormattedTextField.getValue()).intValue();
            double lon = ((Number) longitudeFormattedTextField.getValue()).doubleValue();
            double lat = ((Number) latitudeFormattedTextField.getValue()).doubleValue();
            mapComposerPanel.panAndZoom(zoom, lon, lat);
        }
    }//GEN-LAST:event_zoomAndPanMenuItemActionPerformed

    private void printXMLMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_printXMLMenuItemActionPerformed
        System.out.println(mapComposerPanel.getMap().toString());
    }//GEN-LAST:event_printXMLMenuItemActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem addLayerMenuItem;
    private javax.swing.JMenu debugMenu;
    private javax.swing.JMenu editMenu;
    private javax.swing.JMenu fileMenu;
    private javax.swing.JPopupMenu.Separator jSeparator3;
    private javax.swing.JFormattedTextField latitudeFormattedTextField;
    private javax.swing.JFormattedTextField longitudeFormattedTextField;
    private edu.oregonstate.carto.mapcomposer.gui.MapComposerPanel mapComposerPanel;
    private javax.swing.JMenuItem mapExtentMenuItem;
    private javax.swing.JMenu mapMenu;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JMenuItem openStyleMenuItem;
    private javax.swing.JMenuItem printXMLMenuItem;
    private javax.swing.JMenuItem redoMenuItem;
    private javax.swing.JMenuItem reloadMapPreviewMenuItem;
    private javax.swing.JMenuItem removeAllLayersMenuItem;
    private javax.swing.JMenuItem removeLayerMenuItem;
    private javax.swing.JMenuItem saveMapMenuItem;
    private javax.swing.JMenuItem saveStyleMenuItem;
    private javax.swing.JMenuItem undoMenuItem;
    private javax.swing.JMenuItem zoomAndPanMenuItem;
    private javax.swing.JPanel zoomAndPanPanel;
    private javax.swing.JFormattedTextField zoomFormattedTextField;
    // End of variables declaration//GEN-END:variables
}


text:
import { Typeahead as InnerTypeahead } from "@dcos/ui-kit";
import PropTypes from "prop-types";

import * as React from "react";

import FilterInputText from "./FilterInputText";

class Typeahead extends FilterInputText {
  static defaultProps = {
    emptyLabel: "Nothing to show.",
    onDropdownItemSelection() {},
    items: [],
    selected: [],
    placeholder: "Filter",
  };
  static propTypes = {
    emptyLabel: PropTypes.string,
    labelKey: PropTypes.string.isRequired,
    onDropdownItemSelection: PropTypes.func,
    handleFilterChange: PropTypes.func.isRequired,
    items: PropTypes.arrayOf(
      PropTypes.shape({
        id: PropTypes.string,
        name: PropTypes.node,
      })
    ),
    selected: PropTypes.array,
    placeholder: PropTypes.string,
    searchString: PropTypes.string.isRequired,
  };

  getInputField() {
    let {
      emptyLabel,
      labelKey,
      handleFilterChange,
      items,
      onDropdownItemSelection,
      placeholder,
      searchString,
      selected,
    } = this.props;

    if (selected === "") {
      selected = [];
    }

    const toUiKit = (i) => ({ value: i.id, label: i[labelKey] });
    const fromUiKit = (i) => ({ id: i });
    const options = items
      .filter((i) => i[labelKey].match(new RegExp(searchString)))
      .map(toUiKit);

    const onChange = (e) => handleFilterChange(e?.currentTarget?.value);
    const onSelect = (os) => onDropdownItemSelection(os.map(fromUiKit));

    return (

        <InnerTypeahead
          items={options}
          menuEmptyState={
{emptyLabel}
}
          onSelect={onSelect}
          resetInputOnSelect={true}
          textField={
            <input
              className="form-control filter-input-text"
              onChange={onChange}
              placeholder={placeholder}
              ref={(ref) => (this.inputField = ref)}
              value={searchString}
            />
          }
        />

    );
  }
}
export default Typeahead;


text:
using System;

namespace ThirdParty.iOS4Unity
{
    public class NSBundle : NSObject
    {
        private static readonly IntPtr _classHandle;

        static NSBundle()
        {
            _classHandle = ObjC.GetClass("NSBundle");
        }

        public override IntPtr ClassHandle
        {
            get { return _classHandle; }
        }

        internal NSBundle(IntPtr handle)
            : base(handle)
        {
        }

        public string BundleIdentifier
        {
            get { return ObjC.MessageSendString(Handle, Selector.GetHandle("bundleIdentifier")); }
        }

        public string BundlePath
        {
            get { return ObjC.MessageSendString(Handle, Selector.GetHandle("bundlePath")); }
        }

        public static NSBundle FromIdentifier(string str)
        {
            return Runtime.GetNSObject<NSBundle>(ObjC.MessageSendIntPtr(_classHandle, Selector.GetHandle("bundleWithIdentifier:"), str));
        }

        public static NSBundle FromPath(string path)
        {
            return Runtime.GetNSObject<NSBundle>(ObjC.MessageSendIntPtr(_classHandle, Selector.GetHandle("bundleWithPath:"), path));
        }

        public static NSBundle MainBundle
        {
            get { return Runtime.GetNSObject<NSBundle>(ObjC.MessageSendIntPtr(_classHandle, Selector.GetHandle("mainBundle"))); }
        }

        public string LocalizedString(string key, string value = "", string table = "")
        {
            return ObjC.MessageSendString(Handle, Selector.GetHandle("localizedStringForKey:value:table:"), key, value, table);
        }

        public string ResourcePath
        {
            get { return ObjC.MessageSendString(Handle, Selector.GetHandle("resourcePath")); }
        }

        public NSDictionary InfoDictionary
        {
            get
            {
                return Runtime.GetNSObject<NSDictionary>(ObjC.MessageSendIntPtr(Handle, Selector.GetHandle("infoDictionary")));
            }
        }
    }
}


text:
"""
Abstraction for handling KNXnet/IP routing.

Routing uses UDP Multicast to send and receive KNXnet/IP messages.
"""
from __future__ import annotations

import asyncio
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
import logging
import random
from typing import TYPE_CHECKING, Final

from xknx.core import XknxConnectionState
from xknx.exceptions import CommunicationError
from xknx.knxip import (
    HPAI,
    CEMIFrame,
    CEMIMessageCode,
    KNXIPFrame,
    KNXIPServiceType,
    RoutingBusy,
    RoutingIndication,
    RoutingLostMessage,
)
from xknx.telegram import IndividualAddress, Telegram, TelegramDirection

from .const import DEFAULT_INDIVIDUAL_ADDRESS, DEFAULT_MCAST_GRP, DEFAULT_MCAST_PORT
from .interface import Interface, TelegramCallbackType
from .ip_secure import SecureGroup
from .transport import KNXIPTransport, UDPTransport

if TYPE_CHECKING:
    from xknx.xknx import XKNX

logger = logging.getLogger("xknx.log")

BUSY_DECREMENT_TIME: Final = 0.005  # 5 ms
BUSY_INCREMENT_COOLDOWN: Final = 0.01  # 10 ms
BUSY_RANDOM_TIME_FACTOR: Final = 0.05  # 50 ms
BUSY_SLOWDURATION_TIME_FACTOR: Final = 0.1  # 100 ms
ROUTING_INDICATION_WAIT_TIME: Final = 0.02  # 20 ms

DEFAULT_LATENCY_TOLERANCE_MS: Final = 1000

class _RoutingFlowControl:
    """
    Class for hanling KNXnet/IP routing flow control.

    See KNX Specifications 3.8.5 Routing §2.3.5 Flow control handling
    """

    def __init__(self) -> None:
        self._last_busy_frame_time: float = 0.0
        self._last_sent_routing_indication_time: float = 0.0
        self._loop = asyncio.get_running_loop()
        self._ready = asyncio.Event()
        self._ready.set()
        self._received_busy_frames: int = 0
        self._timer_task: asyncio.Task[None] | None = None
        self._wait_start_time: float | None = None
        self._wait_time_ms: int = 0

    def cancel(self) -> None:
        """Cancel internal tasks."""
        if self._timer_task:
            self._timer_task.cancel()

    @asynccontextmanager
    async def throttle(self) -> AsyncIterator[None]:
        """Context manager to wait for ready state and throttle outgoing frames."""
        # limit RoutingIndication transmission rate according to
        # KNX Specifications 3.2.6 Communication Medium KNX IP §2.1
        # simplified version - pause 20 ms after transmit a RoutingIndication
        elapsed = self._loop.time() - self._last_sent_routing_indication_time
        if elapsed < ROUTING_INDICATION_WAIT_TIME:
            await asyncio.sleep(ROUTING_INDICATION_WAIT_TIME - elapsed)

        await self._ready.wait()
        yield
        self._last_sent_routing_indication_time = self._loop.time()

    def handle_routing_busy(self, routing_busy: RoutingBusy) -> None:
        """Handle incoming RoutingBusy."""
        self._ready.clear()
        now = self._loop.time()
        previous_busy_frame_time = self._last_busy_frame_time
        self._last_busy_frame_time = now
        if self._wait_start_time is None:
            logger.info(
                "RoutingBusy received: %s",
                routing_busy,
            )
        else:
            # only apply if we have already received a RoutingBusy frame and are still pausing
            if (now - previous_busy_frame_time) > BUSY_INCREMENT_COOLDOWN:
                self._received_busy_frames += 1
            logger.debug(
                "RoutingBusy received: %s - %s ms since previous - number %s in moving time window",
                routing_busy,
                round((now - previous_busy_frame_time) * 1000),
                self._received_busy_frames,
            )
            # discard frame if wait time is lower than remaining time
            remaining_ms = (now - self._wait_start_time) * 1000
            if remaining_ms >= routing_busy.wait_time:
                return
        self._wait_time_ms = routing_busy.wait_time
        self._wait_start_time = now

        if self._timer_task:
            self._timer_task.cancel()
        self._timer_task = asyncio.create_task(self._resume_sending())

    async def _resume_sending(self) -> None:
        """Reset ready flag after wait_time_ms and fade out slowduration."""
        random_wait_extension = (
            random.random() * self._received_busy_frames * BUSY_RANDOM_TIME_FACTOR
        )
        slowduration = self._received_busy_frames * BUSY_SLOWDURATION_TIME_FACTOR
        await asyncio.sleep(self._wait_time_ms / 1000 + random_wait_extension)

        self._ready.set()
        self._wait_start_time = None
        await asyncio.sleep(slowduration)
        while self._received_busy_frames > 0:
            await asyncio.sleep(BUSY_DECREMENT_TIME)
            self._received_busy_frames -= 1

class Routing(Interface):
    """Class for handling KNXnet/IP multicast communication."""

    transport: UDPTransport

    def __init__(
        self,
        xknx: XKNX,
        individual_address: IndividualAddress | None,
        telegram_received_callback: TelegramCallbackType,
        local_ip: str,
        multicast_group: str = DEFAULT_MCAST_GRP,
        multicast_port: int = DEFAULT_MCAST_PORT,
    ):
        """Initialize Routing class."""
        self.xknx = xknx
        self.individual_address = individual_address or DEFAULT_INDIVIDUAL_ADDRESS
        self.telegram_received_callback = telegram_received_callback
        self.local_ip = local_ip
        self.multicast_group = multicast_group
        self.multicast_port = multicast_port

        self._init_transport()
        self.transport.register_callback(
            self._handle_frame,
            [
                KNXIPServiceType.ROUTING_INDICATION,
                KNXIPServiceType.ROUTING_BUSY,
                KNXIPServiceType.ROUTING_LOST_MESSAGE,
            ],
        )
        self._flow_control = _RoutingFlowControl()

    def _init_transport(self) -> None:
        """Initialize transport."""
        self.transport = UDPTransport(
            local_addr=(self.local_ip, 0),
            remote_addr=(self.multicast_group, self.multicast_port),
            multicast=True,
        )

    ####################
    #
    # CONNECT DISCONNECT
    #
    ####################

    async def connect(self) -> bool:
        """Start routing."""
        self.xknx.current_address = self.individual_address
        await self.xknx.connection_manager.connection_state_changed(
            XknxConnectionState.CONNECTING
        )
        try:
            await self.transport.connect()
        except OSError as ex:
            logger.debug(
                "Could not establish connection to KNXnet/IP network. %s: %s",
                type(ex).__name__,
                ex,
            )
            await self.xknx.connection_manager.connection_state_changed(
                XknxConnectionState.DISCONNECTED
            )
            # close udp transport to prevent open file descriptors
            self.transport.stop()
            raise CommunicationError("Routing could not be started") from ex
        await self.xknx.connection_manager.connection_state_changed(
            XknxConnectionState.CONNECTED
        )
        return True

    async def disconnect(self) -> None:
        """Stop routing."""
        self.transport.stop()
        await self.xknx.connection_manager.connection_state_changed(
            XknxConnectionState.DISCONNECTED
        )
        self._flow_control.cancel()

    ##################
    #
    # OUTGOING FRAMES
    #
    ##################

    async def send_telegram(self, telegram: Telegram) -> None:
        """Send Telegram to routing connected device."""
        cemi = CEMIFrame.init_from_telegram(
            telegram=telegram,
            code=CEMIMessageCode.L_DATA_IND,
            src_addr=self.individual_address,
        )
        routing_indication = RoutingIndication(cemi=cemi)

        async with self._flow_control.throttle():
            self._send_knxipframe(KNXIPFrame.init_from_body(routing_indication))

    def _send_knxipframe(self, knxipframe: KNXIPFrame) -> None:
        """Send KNXIPFrame to connected routing device."""
        self.transport.send(knxipframe)

    ##################
    #
    # INCOMING FRAMES
    #
    ##################

    def _handle_frame(
        self, knxipframe: KNXIPFrame, source: HPAI, _: KNXIPTransport
    ) -> None:
        """Handle incoming KNXIPFrames. Callback from internal transport."""
        if isinstance(knxipframe.body, RoutingIndication):
            self._handle_routing_indication(knxipframe.body)
        elif isinstance(knxipframe.body, RoutingBusy):
            self._flow_control.handle_routing_busy(knxipframe.body)
        elif isinstance(knxipframe.body, RoutingLostMessage):
            logger.warning(
                "RoutingLostMessage received from %s - %s lost messages.",
                source.ip_addr,
                knxipframe.body.lost_messages,
            )
        else:
            logger.warning("Service not implemented: %s", knxipframe)

    def _handle_routing_indication(self, routing_indication: RoutingIndication) -> None:
        """Handle incoming RoutingIndication."""
        if routing_indication.cemi is None:
            # Don't handle invalid cemi frames (None)
            return
        if routing_indication.cemi.src_addr == self.individual_address:
            logger.debug("Ignoring own packet")
            return

        # TODO: is cemi message code L_DATA.req or .con valid for routing? if not maybe warn and ignore
        asyncio.create_task(self.handle_cemi_frame(routing_indication.cemi))

    async def handle_cemi_frame(self, cemi: CEMIFrame) -> None:
        """Handle incoming telegram and send responses if applicable (device management)."""
        telegram = cemi.telegram
        telegram.direction = TelegramDirection.INCOMING

        if response_tgs := await self.telegram_received_callback(telegram):
            for response in response_tgs:
                await self.send_telegram(response)

class SecureRouting(Routing):
    """Class for handling KNXnet/IP secure multicast communication."""

    transport: SecureGroup

    def __init__(
        self,
        xknx: XKNX,
        individual_address: IndividualAddress | None,
        telegram_received_callback: TelegramCallbackType,
        local_ip: str,
        backbone_key: bytes,
        latency_ms: int | None = None,
        multicast_group: str = DEFAULT_MCAST_GRP,
        multicast_port: int = DEFAULT_MCAST_PORT,
    ):
        """Initialize SecureRouting class."""
        self.backbone_key = backbone_key
        self.latency_ms = latency_ms or DEFAULT_LATENCY_TOLERANCE_MS
        super().__init__(
            xknx,
            individual_address=individual_address,
            telegram_received_callback=telegram_received_callback,
            local_ip=local_ip,
            multicast_group=multicast_group,
            multicast_port=multicast_port,
        )

    def _init_transport(self) -> None:
        """Initialize transport."""
        self.transport = SecureGroup(
            local_addr=(self.local_ip, 0),
            remote_addr=(self.multicast_group, self.multicast_port),
            backbone_key=self.backbone_key,
            latency_ms=self.latency_ms,
        )


text:
package com.cky.learnandroiddetails.DesignPattern.SimpleFactory;

import android.util.Log;

import static com.cky.learnandroiddetails.DesignPattern.SimpleFactory.Constants.FRUIT_INTERFACE;

/**
 * Created by cuikangyuan on 2017/5/24.
 */

public class Apple implements Fruit {

    public int getTreeAge() {
        return mTreeAge;
    }

    public void setTreeAge(int treeAge) {
        mTreeAge = treeAge;
    }

    private int mTreeAge;

    @Override
    public void plant() {
        Log.d(FRUIT_INTERFACE, "apple plant");
    }

    @Override
    public void grow() {
        Log.d(FRUIT_INTERFACE, "apple grow");
    }

    @Override
    public void harvest() {
        Log.d(FRUIT_INTERFACE, "apple harvest");
    }
}


text:
<?php

namespace Kanboard\Controller;

use Kanboard\Core\Security\OAuthAuthenticationProviderInterface;

/**
 * OAuth controller
 *
 * @package  controller
 * @author   Frederic Guillot
 */
class Oauth extends Base
{
    /**
     * Redirect to the provider if no code received
     *
     * @access private
     * @param string $provider
     */
    protected function step1($provider)
    {
        $code = $this->request->getStringParam('code');
        $state = $this->request->getStringParam('state');

        if (! empty($code)) {
            $this->step2($provider, $code, $state);
        } else {
            $this->response->redirect($this->authenticationManager->getProvider($provider)->getService()->getAuthorizationUrl());
        }
    }

    /**
     * Link or authenticate the user
     *
     * @access protected
     * @param string $providerName
     * @param string $code
     * @param string $state
     */
    protected function step2($providerName, $code, $state)
    {
        $provider = $this->authenticationManager->getProvider($providerName);
        $provider->setCode($code);
        $hasValidState = $provider->getService()->isValidateState($state);

        if ($this->userSession->isLogged()) {
            if ($hasValidState) {
                $this->link($provider);
            } else {
                $this->flash->failure(t('The OAuth2 state parameter is invalid'));
                $this->response->redirect($this->helper->url->to('user', 'external', array('user_id' => $this->userSession->getId())));
            }
        } else {
            if ($hasValidState) {
                $this->authenticate($providerName);
            } else {
                $this->authenticationFailure(t('The OAuth2 state parameter is invalid'));
            }
        }
    }

    /**
     * Link the account
     *
     * @access protected
     * @param  OAuthAuthenticationProviderInterface $provider
     */
    protected function link(OAuthAuthenticationProviderInterface $provider)
    {
        if (! $provider->authenticate()) {
            $this->flash->failure(t('External authentication failed'));
        } else {
            $this->userProfile->assign($this->userSession->getId(), $provider->getUser());
            $this->flash->success(t('Your external account is linked to your profile successfully.'));
        }

        $this->response->redirect($this->helper->url->to('user', 'external', array('user_id' => $this->userSession->getId())));
    }

    /**
     * Unlink external account
     *
     * @access public
     */
    public function unlink()
    {
        $backend = $this->request->getStringParam('backend');
        $this->checkCSRFParam();

        if ($this->authenticationManager->getProvider($backend)->unlink($this->userSession->getId())) {
            $this->flash->success(t('Your external account is not linked anymore to your profile.'));
        } else {
            $this->flash->failure(t('Unable to unlink your external account.'));
        }

        $this->response->redirect($this->helper->url->to('user', 'external', array('user_id' => $this->userSession->getId())));
    }

    /**
     * Authenticate the account
     *
     * @access protected
     * @param string $providerName
     */
    protected function authenticate($providerName)
    {
        if ($this->authenticationManager->oauthAuthentication($providerName)) {
            $this->response->redirect($this->helper->url->to('app', 'index'));
        } else {
            $this->authenticationFailure(t('External authentication failed'));
        }
    }

    /**
     * Show login failure page
     *
     * @access protected
     * @param  string $message
     */
    protected function authenticationFailure($message)
    {
        $this->response->html($this->helper->layout->app('auth/index', array(
            'errors' => array('login' => $message),
            'values' => array(),
            'no_layout' => true,
            'title' => t('Login')
        )));
    }
}


text:
A computer vision controller for Sonos and Spotify

# Purpose
This project allows me to hold up a record cover to a camera, and have the album automatically start playing on my Sonos speakers.
It works using the OpenCV computer vision library and SimpleCV python module to recognise album covers from camera stills, and the SoCo python module to control Sonos.


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import uuid from 'uuid';

export default class OTSubscriber extends Component {
  constructor(props, context) {
    super(props);

    this.state = {
      subscriber: null,
      stream: props.stream || context.stream || null,
      session: props.session || context.session || null,
      currentRetryAttempt: 0,
    };
    this.maxRetryAttempts = props.maxRetryAttempts || 5;
    this.retryAttemptTimeout = props.retryAttemptTimeout || 1000;
  }

  componentDidMount() {
    this.createSubscriber();
  }

  componentDidUpdate(prevProps, prevState) {
    const cast = (value, Type, defaultValue) => (value === undefined ? defaultValue : Type(value));

    const updateSubscriberProperty = (key) => {
      const previous = cast(prevProps.properties[key], Boolean, true);
      const current = cast(this.props.properties[key], Boolean, true);
      if (previous !== current) {
        this.state.subscriber[key](current);
      }
    };

    updateSubscriberProperty('subscribeToAudio');
    updateSubscriberProperty('subscribeToVideo');

    if (prevState.session !== this.state.session || prevState.stream !== this.state.stream) {
      this.destroySubscriber(prevState.session);
      this.createSubscriber();
    }
  }

  componentWillUnmount() {
    this.destroySubscriber();
  }

  getSubscriber() {
    return this.state.subscriber;
  }

  createSubscriber() {
    if (!this.state.session || !this.state.stream) {
      this.setState({ subscriber: null });
      return;
    }
    const properties = this.props.properties || {};
    let container;
    if (properties.insertDefaultUI !== false) {
      container = document.createElement('div');
      container.setAttribute('class', 'OTSubscriberContainer');
      this.node.appendChild(container);
    }

    this.subscriberId = uuid();
    const { subscriberId } = this;

    const subscriber = this.state.session.subscribe(
            this.state.stream,
            container,
            this.props.properties,
            (err) => {
              if (subscriberId !== this.subscriberId) {
                    // Either this subscriber has been recreated or the
                    // component unmounted so don't invoke any callbacks
                return;
              }
              if (err &&
                this.props.retry &&
                this.state.currentRetryAttempt < (this.maxRetryAttempts - 1)) {
                // Error during subscribe function
                this.handleRetrySubscriber();
                // If there is a retry action, do we want to execute the onError props function?
                // return;
              }
              if (err && typeof this.props.onError === 'function') {
                this.props.onError(err);
              } else if (!err && typeof this.props.onSubscribe === 'function') {
                this.props.onSubscribe();
              }
            },
        );

    if (
            this.props.eventHandlers &&
            typeof this.props.eventHandlers === 'object'
        ) {
      subscriber.on(this.props.eventHandlers);
    }

    this.setState({ subscriber });
  }

  handleRetrySubscriber() {
    setTimeout(() => {
      this.setState(state => ({
        currentRetryAttempt: state.currentRetryAttempt + 1,
        subscriber: null,
      }));
      this.createSubscriber();
    }, this.retryAttemptTimeout);
  }

  destroySubscriber(session = this.props.session) {
    delete this.subscriberId;

    if (this.state.subscriber) {
      if (
                this.props.eventHandlers &&
                typeof this.props.eventHandlers === 'object'
            ) {
        this.state.subscriber.once('destroyed', () => {
          this.state.subscriber.off(this.props.eventHandlers);
        });
      }

      if (session) {
        session.unsubscribe(this.state.subscriber);
      }
    }
  }

  render() {
    const { className, style } = this.props;
    return <div className={className} style={style} ref={(node) => { this.node = node; }} />;
  }
}

OTSubscriber.propTypes = {
  stream: PropTypes.shape({
    streamId: PropTypes.string,
  }),
  session: PropTypes.shape({
    subscribe: PropTypes.func,
    unsubscribe: PropTypes.func,
  }),
  className: PropTypes.string,
  style: PropTypes.object, // eslint-disable-line react/forbid-prop-types
  properties: PropTypes.object, // eslint-disable-line react/forbid-prop-types
  retry: PropTypes.bool,
  maxRetryAttempts: PropTypes.number,
  retryAttemptTimeout: PropTypes.number,
  eventHandlers: PropTypes.objectOf(PropTypes.func),
  onSubscribe: PropTypes.func,
  onError: PropTypes.func,
};

OTSubscriber.defaultProps = {
  stream: null,
  session: null,
  className: '',
  style: {},
  properties: {},
  retry: false,
  maxRetryAttempts: 5,
  retryAttemptTimeout: 1000,
  eventHandlers: null,
  onSubscribe: null,
  onError: null,
};

OTSubscriber.contextTypes = {
  stream: PropTypes.shape({
    streamId: PropTypes.string,
  }),
  session: PropTypes.shape({
    subscribe: PropTypes.func,
    unsubscribe: PropTypes.func,
  }),
};


text:
#pragma once

#include <memory>
#include <string>
#include <unordered_map>
#include <vector>

#include "syms.h"
#include "vendor/optional.hpp"

struct bcc_usdt;

namespace USDT {

using std::experimental::optional;
using std::experimental::nullopt;
class ArgumentParser;

static const std::string USDT_PROGRAM_HEADER =
    "#include <uapi/linux/ptrace.h>\n";

class Argument {
private:
  optional<int> arg_size_;
  optional<int> constant_;
  optional<int> deref_offset_;
  optional<std::string> deref_ident_;
  optional<std::string> base_register_name_;
  optional<std::string> index_register_name_;
  optional<int> scale_;

  bool get_global_address(uint64_t *address, const std::string &binpath,
                          const optional<int> &pid) const;

public:
  Argument();
  ~Argument();

  bool assign_to_local(std::ostream &stream, const std::string &local_name,
                       const std::string &binpath,
                       const optional<int> &pid = nullopt) const;

  int arg_size() const { return arg_size_.value_or(sizeof(void *)); }
  std::string ctype() const;

  const optional<std::string> &deref_ident() const { return deref_ident_; }
  const optional<std::string> &base_register_name() const {
    return base_register_name_;
  }
  const optional<std::string> &index_register_name() const {
    return index_register_name_;
  }
  const optional<int> scale() const { return scale_; }
  const optional<int> constant() const { return constant_; }
  const optional<int> deref_offset() const { return deref_offset_; }

  friend class ArgumentParser;
};

class ArgumentParser {
  const char *arg_;
  ssize_t cur_pos_;

  void skip_whitespace_from(size_t pos);
  void skip_until_whitespace_from(size_t pos);

protected:
  virtual bool normalize_register(std::string *reg, int *reg_size) = 0;

  ssize_t parse_register(ssize_t pos, std::string &name, int &size);
  ssize_t parse_number(ssize_t pos, optional<int> *number);
  ssize_t parse_identifier(ssize_t pos, optional<std::string> *ident);
  ssize_t parse_base_register(ssize_t pos, Argument *dest);
  ssize_t parse_index_register(ssize_t pos, Argument *dest);
  ssize_t parse_scale(ssize_t pos, Argument *dest);
  ssize_t parse_expr(ssize_t pos, Argument *dest);
  ssize_t parse_1(ssize_t pos, Argument *dest);

  void print_error(ssize_t pos);

public:
  bool parse(Argument *dest);
  bool done() { return cur_pos_ < 0 || arg_[cur_pos_] == '\0'; }

  ArgumentParser(const char *arg) : arg_(arg), cur_pos_(0) {}
};

class ArgumentParser_x64 : public ArgumentParser {
  enum Register {
    REG_A,
    REG_B,
    REG_C,
    REG_D,
    REG_SI,
    REG_DI,
    REG_BP,
    REG_SP,
    REG_8,
    REG_9,
    REG_10,
    REG_11,
    REG_12,
    REG_13,
    REG_14,
    REG_15,
    REG_RIP,
  };

  struct RegInfo {
    Register reg;
    int size;
  };

  static const std::unordered_map<std::string, RegInfo> registers_;
  bool normalize_register(std::string *reg, int *reg_size);
  void reg_to_name(std::string *norm, Register reg);

public:
  ArgumentParser_x64(const char *arg) : ArgumentParser(arg) {}
};

struct Location {
  uint64_t address_;
  std::vector<Argument> arguments_;
  Location(uint64_t addr, const char *arg_fmt);
};

class Probe {
  std::string bin_path_;
  std::string provider_;
  std::string name_;
  uint64_t semaphore_;

  std::vector<Location> locations_;

  optional<int> pid_;
  optional<bool> in_shared_object_;

  optional<std::string> attached_to_;
  optional<uint64_t> attached_semaphore_;

  std::string largest_arg_type(size_t arg_n);

  bool add_to_semaphore(int16_t val);
  bool resolve_global_address(uint64_t *global, const uint64_t addr);
  bool lookup_semaphore_addr(uint64_t *address);
  void add_location(uint64_t addr, const char *fmt);

public:
  Probe(const char *bin_path, const char *provider, const char *name,
        uint64_t semaphore, const optional<int> &pid);

  size_t num_locations() const { return locations_.size(); }
  size_t num_arguments() const { return locations_.front().arguments_.size(); }
  uint64_t semaphore()   const { return semaphore_; }

  uint64_t address(size_t n = 0) const { return locations_[n].address_; }
  const Location &location(size_t n) const { return locations_[n]; }
  bool usdt_getarg(std::ostream &stream);
  std::string get_arg_ctype(int arg_index) {
    return largest_arg_type(arg_index);
  }

  bool need_enable() const { return semaphore_ != 0x0; }
  bool enable(const std::string &fn_name);
  bool disable();
  bool enabled() const { return !!attached_to_; }

  bool in_shared_object();
  const std::string &name() { return name_; }
  const std::string &bin_path() { return bin_path_; }
  const std::string &provider() { return provider_; }

  friend class Context;
};

class Context {
  std::vector<std::unique_ptr<Probe>> probes_;
  std::unordered_set<std::string> modules_;

  optional<int> pid_;
  optional<ProcStat> pid_stat_;
  bool loaded_;

  static void _each_probe(const char *binpath, const struct bcc_elf_usdt *probe,
                          void *p);
  static int _each_module(const char *modpath, uint64_t, uint64_t, bool, void *p);

  void add_probe(const char *binpath, const struct bcc_elf_usdt *probe);
  std::string resolve_bin_path(const std::string &bin_path);

public:
  Context(const std::string &bin_path);
  Context(int pid);
  ~Context();

  optional<int> pid() const { return pid_; }
  bool loaded() const { return loaded_; }
  size_t num_probes() const { return probes_.size(); }

  Probe *get(const std::string &probe_name);
  Probe *get(int pos) { return probes_[pos].get(); }

  bool enable_probe(const std::string &probe_name, const std::string &fn_name);
  bool generate_usdt_args(std::ostream &stream);

  typedef void (*each_cb)(struct bcc_usdt *);
  void each(each_cb callback);

  typedef void (*each_uprobe_cb)(const char *, const char *, uint64_t, int);
  void each_uprobe(each_uprobe_cb callback);
};
}


text:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Handpose Demo</title>

    <!-- Require the peer dependencies of handpose. -->
    <script src="./vendor/tf-core.js"></script>
    <script src="./vendor/tf-converter.js"></script>

    <!-- You must explicitly require a TF.js backend if you're not using the tfs union bundle. -->
    <script src="./vendor/tf-backend-webgl.js"></script>
    <!-- Alternatively you can use the WASM backend: <script src="https://unpkg.com/@tensorflow/tfjs-backend-wasm@2.1.0/dist/tf-backend-wasm.js"></script> -->

    <script src="./vendor/handpose.js"></script>
</head>

<body>
    <video id="videoElement" width="640" height="500" style="display: none;"></video>
    <canvas id="canvasElement" width="640" height="500"></canvas>

    <script>
        let model;
        let ctx;
        let video = document.getElementById("videoElement");
        let canvas = document.getElementById("canvasElement");

        function displayImagesAtFingerTop(landmarks) {
            for (let i = 0; i < landmarks.length; i++) {
                const x = landmarks[i][0];
                const y = landmarks[i][1];

                ctx.fillStyle = "#0000FF";
                ctx.fillRect(x - 2, y - 2, 4, 4);
            }
        }

        async function main() {
            model = await handpose.load();

            if (navigator.mediaDevices.getUserMedia) {
                navigator.mediaDevices.getUserMedia({ video: true })
                    .then(stream => {
                        video.srcObject = stream;
                        video.play();
                    })
                    .catch(e => {
                        console.log("Error Occurred in getting the video stream");
                    });
            }

            video.onloadedmetadata = () => {
                ctx = canvas.getContext('2d');
                ctx.translate(canvas.width, 0);
                ctx.scale(-1, 1);
                requestAnimationFrame(predict);
            };
        }

        async function predict() {
            ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

            const predictions = await model.estimateHands(video);
            if (predictions.length > 0) {
                const landmarks = predictions[0].landmarks;
                displayImagesAtFingerTop(landmarks);
            }

            requestAnimationFrame(predict);
        }

        main()
    </script>
</body>

</html>


text: Chrome extension frontend + Python backend bookmark downloader made for BridgehaCS 2016


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

namespace DesignScript.Parser
{
    class TestParser
    {
        static void Main()
        {
            ProtoCore.Core core = new ProtoCore.Core(new ProtoCore.Options());
            string filePath = @"C:\DSCode\autodeskresearch\branches\UIResearch\DesignScriptParser\DSParser\DSParser\scripts\test1.ds";
            DesignScript.Parser.Scanner s = new DesignScript.Parser.Scanner(filePath);
            DesignScript.Parser.Parser p = new DesignScript.Parser.Parser(s, core);
            p.Parse();
            DesignScript.Parser.Node c = p.root;
        }
    }
}


text:
using System;

namespace BEPUutilities.DataStructures
{
    /// <summary>
    /// Special datatype used for heapless lists without unsafe/stackalloc.
    /// Designed for object types or reference-sized structs (int, float...).
    /// Stores a maximum of 8 entries.
    /// </summary>
    /// <typeparam name="T">Struct type to use.</typeparam>
    public struct TinyList<T> where T : IEquatable<T>
    {
        private T entry1;
        private T entry2;
        private T entry3;
        private T entry4;

        private T entry5;
        private T entry6;
        private T entry7;
        private T entry8;

        internal int count;

        /// <summary>
        /// Gets the current number of elements in the list.
        /// </summary>
        public int Count
        {
            get { return count; }
        }

        /// <summary>
        /// Gets the item at the specified index.
        /// </summary>
        /// <param name="index">Index to retrieve.</param>
        /// <returns>Retrieved item.</returns>
        public T this[int index]
        {
            get
            {
                //Get
                if (index > count - 1 || index < 0)
                {
                    return default(T);
                }
                switch (index)
                {
                    case 0:
                        return entry1;
                    case 1:
                        return entry2;
                    case 2:
                        return entry3;
                    case 3:
                        return entry4;
                    case 4:
                        return entry5;
                    case 5:
                        return entry6;
                    case 6:
                        return entry7;
                    case 7:
                        return entry8;
                    default:
                        //Curious!
                        return default(T);
                }
            }
            set
            {
                //Replace
                if (index > count - 1 || index < 0)
                {
                    return;
                }
                switch (index)
                {
                    case 0:
                        entry1 = value;
                        break;
                    case 1:
                        entry2 = value;
                        break;
                    case 2:
                        entry3 = value;
                        break;
                    case 3:
                        entry4 = value;
                        break;
                    case 4:
                        entry5 = value;
                        break;
                    case 5:
                        entry6 = value;
                        break;
                    case 6:
                        entry7 = value;
                        break;
                    case 7:
                        entry8 = value;
                        break;
                }
            }
        }

        /// <summary>
        /// Creates a string representation of the list.
        /// </summary>
        /// <returns>String representation of the list.</returns>
        public override string ToString()
        {
            return "TinyList<" + typeof (T) + ">, Count: " + count;
        }

        /// <summary>
        /// Tries to add an element to the list.
        /// </summary>
        /// <param name="item">Item to add.</param>
        /// <returns>Whether or not the item could be added.
        /// Will return false when the list is full.</returns>
        public bool Add(T item)
        {
            switch (count)
            {
                case 0:
                    entry1 = item;
                    break;
                case 1:
                    entry2 = item;
                    break;
                case 2:
                    entry3 = item;
                    break;
                case 3:
                    entry4 = item;
                    break;
                case 4:
                    entry5 = item;
                    break;
                case 5:
                    entry6 = item;
                    break;
                case 6:
                    entry7 = item;
                    break;
                case 7:
                    entry8 = item;
                    break;
                default:
                    return false;
            }
            count++;
            return true;
        }

        /// <summary>
        /// Clears the list.
        /// </summary>
        public void Clear()
        {
            //Things aren't guaranteed to be structs in this list.
            //It would be bad if we kept a reference around, hidden.
            count = 0;
            entry1 = default(T);
            entry2 = default(T);
            entry3 = default(T);
            entry4 = default(T);
            entry5 = default(T);
            entry6 = default(T);
            entry7 = default(T);
            entry8 = default(T);
        }

        /// <summary>
        /// Gets the index of the item in the list, if it is present.
        /// </summary>
        /// <param name="item">Item to look for.</param>
        /// <returns>Index of the item, if present.  -1 otherwise.</returns>
        public int IndexOf(T item)
        {
            //This isn't a super fast operation.
            if (entry1.Equals(item))
                return 0;
            else if (entry2.Equals(item))
                return 1;
            else if (entry3.Equals(item))
                return 2;
            else if (entry4.Equals(item))
                return 3;
            else if (entry5.Equals(item))
                return 4;
            else if (entry6.Equals(item))
                return 5;
            else if (entry7.Equals(item))
                return 6;
            else if (entry8.Equals(item))
                return 7;
            return -1;
        }

        /// <summary>
        /// Tries to remove an element from the list.
        /// </summary>
        /// <param name="item">Item to remove.</param>
        /// <returns>Whether or not the item existed in the list.</returns>
        public bool Remove(T item)
        {
            //Identity-based removes aren't a super high priority feature, so can be a little slower.
            int index = IndexOf(item);
            if (index != -1)
            {
                RemoveAt(index);
                return true;
            }
            return false;
        }

        /// <summary>
        /// Removes the item at the specified index.
        /// </summary>
        /// <param name="index">Index of the element to remove.</param>
        /// <returns>Whether or not the item could be removed.
        /// Returns false if the index is out of bounds.</returns>
        public bool RemoveAt(int index)
        {
            if (index > count - 1 || index < 0)
                return false;
            switch (index)
            {
                case 0:
                    entry1 = entry2;
                    entry2 = entry3;
                    entry3 = entry4;
                    entry4 = entry5;
                    entry5 = entry6;
                    entry6 = entry7;
                    entry7 = entry8;
                    break;
                case 1:
                    entry2 = entry3;
                    entry3 = entry4;
                    entry4 = entry5;
                    entry5 = entry6;
                    entry6 = entry7;
                    entry7 = entry8;
                    break;
                case 2:
                    entry3 = entry4;
                    entry4 = entry5;
                    entry5 = entry6;
                    entry6 = entry7;
                    entry7 = entry8;
                    break;
                case 3:
                    entry4 = entry5;
                    entry5 = entry6;
                    entry6 = entry7;
                    entry7 = entry8;
                    break;
                case 4:
                    entry5 = entry6;
                    entry6 = entry7;
                    entry7 = entry8;
                    break;
                case 5:
                    entry6 = entry7;
                    entry7 = entry8;
                    break;
                case 6:
                    entry7 = entry8;
                    break;
            }
            count--;
            return true;
        }
    }
}


text:
"""
This is a command line utility to  generate ICs for the dust settling
test of Price & Laibe (2015) (see section 4.4 Dust settling in a
protoplanetary disc)

This will be SLOW!  The long part of the procedure is settling the gas
(IC.settleGas()).  This takes a long time because the simulation is run for
several dynamical times with ChaNGa in order to reach equilibrium before
adding the dust.

If you stop or things crash, you can load the ICs using
IC = testdust.settling.makeICs.IC(settingsfile)
and restart from where you left off.

To Generate these ICs, ChaNGa MUST be compiled with the glass damping option
(i.e. the damping force, proportional to the velocity)

Code units are specified in PL15

Created on Fri Oct 21 17:07:56 2016

@author: ibackus
"""
import sys

if __name__ == "__main__":

    if len(sys.argv) != 3:

        raise RuntimeError, "\n\nNEED 2 ARGUMENTS: <settings file> <output dir>"

    import testdust
    import os
    import shutil
    # It's a good idea to generate the ICs in a clean folder
    savedir = sys.argv[2]
    # IC settings are stored in this file
    settingsfile = sys.argv[1]
    # Initialize the ICs with the settings
    IC = testdust.settling.makeICs.IC(settingsfile)
    # Its a good idea to generate these ICs in their own folder
    if not os.path.exists(savedir):

        os.mkdir(savedir)

    cwd = os.getcwd()

    try:

        shutil.copyfile(settingsfile, os.path.join(savedir, settingsfile))
        os.chdir(savedir)
        # Generate initial snapshot
        IC.makeInitialSnap()
        print 'Initial snapshot successfully made'
        # Settle the ICs
        IC.setupGas()
        print 'Gas settling snapshot successfully made'
        IC.settleGas()
        print 'Gas settling successfully performed'
        # Set up the dust
        IC.setupDust()
        print 'Successfully made dust settling test ICs!'
        print 'Saved to directory:', savedir

    finally:

        os.chdir(cwd)