text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using NuGetSearch.Common;

namespace NuGetSearch.IOS
{
    /// <summary>
    /// Search Result Table View Source implementation
    /// </summary>
    public class SearchResultTableViewSource : UITableViewSource
    {
        private const int InitialBatchSize = 50;
        private const int SubsequentBatchSize = 50;

        private const int IconWidth = 50;
        private const int IconHeight = 50;

        private const string SearchResultCellIdentifier = "1";
        private const string LoadingMoreCellIdentifier = "2";

        private INuGetGalleryClient nugetGalleryClient;
        private INetworkChecker networkChecker;

        private string searchTerm;
        private string orderBy;
        private bool includePrerelease;

        private int totalCount = 0;
        private List<SearchResultItem> items = new List<SearchResultItem>(InitialBatchSize + SubsequentBatchSize);

        private RowSelectedDelegate rowSelectedCallback;
        private RowChangedDelegate rowChangedCallback;

        /// <summary>
        /// Initializes a new instance of the <see cref="NuGetSearch.IOS.SearchResultTableViewSource"/> class.
        /// </summary>
        /// <param name="searchTerm">Search term.</param>
        /// <param name="orderBy">Order by.</param>
        /// <param name="includePrerelease">If set to <c>true</c> include prerelease.</param>
        /// <param name="rowSelectedCallback">Method to be called when a row is selected</param>
        /// <param name="rowChangedCallback">Method to be called when the content of a row has been changed</param>
        public SearchResultTableViewSource(
            string searchTerm,
            string orderBy,
            bool includePrerelease,
            RowSelectedDelegate rowSelectedCallback,
            RowChangedDelegate rowChangedCallback)
            : base()
        {
            this.searchTerm = searchTerm;
            this.orderBy = orderBy;
            this.includePrerelease = includePrerelease;
            this.rowSelectedCallback = rowSelectedCallback;
            this.rowChangedCallback = rowChangedCallback;

            this.nugetGalleryClient = new NuGetGalleryClient("http://www.nuget.org", new NetworkProvider());
            this.networkChecker = new IOSNetworkChecker();

            this.LoadSearchResultItems(InitialBatchSize, null);
        }

        public delegate void RowSelectedDelegate(SearchResultItem item);

        public delegate void RowChangedDelegate(NSIndexPath indexPath);

        /// <summary>
        /// Gets the total count of results reported by the NuGet Gallery server.
        /// </summary>
        /// <value>The number of results available to be retrieved</value>
        public int TotalCount
        {
            get
            {
                return this.totalCount;
            }
        }

        /// <summary>
        /// Gets a value indicating whether this instance has more results that have not yet been retrieved from the server.
        /// </summary>
        /// <value><c>true</c> if this instance has more results; otherwise, <c>false</c>.</value>
        private bool HasMore
        {
            get
            {
                return this.items.Count < this.totalCount;
            }
        }

        /// <summary>
        /// Called to populate the header for the specified section.
        /// </summary>
        /// <see langword="null"></see>
        /// <returns>The for header.</returns>
        /// <param name="tableView">Table view.</param>
        /// <param name="section">Section.</param>
        public override string TitleForHeader(UITableView tableView, int section)
        {
            return this.totalCount == 1 ?
                Resources.GetString(Resource.String.result_count_1) :
                string.Format(Resources.GetString(Resource.String.result_count_format), this.totalCount);
        }

        /// <summary>
        /// Determines how many rows are in the specified section of the table
        /// </summary>
        /// <returns>The in section.</returns>
        /// <param name="tableview">Tableview.</param>
        /// <param name="section">Section.</param>
        public override int RowsInSection(UITableView tableview, int section)
        {
            return this.HasMore ? this.items.Count + 1 : this.totalCount;
        }

        /// <summary>
        /// Method called when a row is selected
        /// </summary>
        /// <param name="tableView">Table view.</param>
        /// <param name="indexPath">Index path.</param>
        public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
        {
            if (this.rowSelectedCallback != null)
            {
                this.rowSelectedCallback(this.items[indexPath.Row]);
            }
        }

        /// <summary>
        /// Gets the table cell of the specified index
        /// </summary>
        /// <returns>The cell.</returns>
        /// <param name="tableView">Table view.</param>
        /// <param name="indexPath">Index path.</param>
        public override UITableViewCell GetCell(UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath)
        {
            var position = indexPath.Row;

            if (this.IsLoadingMorePosition(position))
            {
                // Check if there is network connectivity, and if so, load more items
                if (this.networkChecker.HasNetworkConnectivity())
                {
                    Task.Run(() => { this.EnsurePositionLoaded(position + SubsequentBatchSize, () => { tableView.ReloadData(); }); });
                }

                // Re-use the cell that was passed in the convertView argument, or create a new cell if it was null
                UITableViewCell cell = tableView.DequeueReusableCell(LoadingMoreCellIdentifier)
                   ?? new UITableViewCell(UITableViewCellStyle.Subtitle, LoadingMoreCellIdentifier) { SelectionStyle = UITableViewCellSelectionStyle.None };

                cell.TextLabel.Text = Resources.GetString(Resource.String.wait_loading_more);

                return cell;
            }
            else
            {
                // Get the item at this position
                var item = this.items[position];

                // Re-use the cell that was passed in the convertView argument, or create a new cell if it was null
                SearchResultTableViewCell cell = tableView.DequeueReusableCell(SearchResultCellIdentifier) as SearchResultTableViewCell
                                                 ?? new SearchResultTableViewCell(SearchResultCellIdentifier);

                cell.TextLabel.Text = item.DisplayTitle;
                cell.DetailTextLabel.Text = item.Description;
                SearchResultTableViewSource.SetCellImageViewFrameSize(cell);

                if (item.UseDefaultIcon)
                {
                    SearchResultTableViewSource.SetDefaultIconImage(cell);
                }
                else
                {
                    SearchResultTableViewSource.SetIconImage(cell, item.IconUrl);
                }

                return cell;
            }
        }

        /// <summary>
        /// Sets the size of the cell image view frame.
        /// </summary>
        /// <param name="cell">Cell.</param>
        private static void SetCellImageViewFrameSize(UITableViewCell cell)
        {
            var frame = cell.ImageView.Frame;
            frame.Width = IconWidth;
            frame.Height = IconHeight;
            cell.ImageView.ContentMode = UIViewContentMode.ScaleAspectFit;
        }

        /// <summary>
        /// Sets the default icon image for an image view
        /// </summary>
        /// <param name="cell">Cell to set the image of</param>
        private static void SetDefaultIconImage(UITableViewCell cell)
        {
            cell.ImageView.Image = Resources.GetImage(Resource.Image.packageDefaultIconSmall_png);
        }

        /// <summary>
        /// Sets the image of the specified cell using the specified URL
        /// </summary>
        /// <param name="cell">Cell to set the image of</param>
        /// <param name="url">URL of the image to use</param>
        private static void SetIconImage(UITableViewCell cell, string url)
        {
            // Check whether the icon manager has loaded the image yet or not
            if (IOSIconManager.Current.IsLoaded(url))
            {
                // If the image has been loaded, then get it from the icon manager and set it on the image view
                var icon = IOSIconManager.Current.GetIcon(url);
                if (icon == null)
                {
                    SearchResultTableViewSource.SetDefaultIconImage(cell);
                }
                else
                {
                    try
                    {
                        cell.ImageView.Image = icon;
                    }
                    catch
                    {
                        SearchResultTableViewSource.SetDefaultIconImage(cell);
                    }
                }
            }
            else
            {
                // If the image has not yet been loaded, set the default icon for now.
                // It will be set to the real image later, after it has been loaded.
                SearchResultTableViewSource.SetDefaultIconImage(cell);
            }
        }

        /// <summary>
        /// Returns true if the specified position is the "Loading More..." position
        /// </summary>
        /// <returns><c>true</c> if the specified position is the "Loading More..." position; otherwise, <c>false</c>.</returns>
        /// <param name="position"></param>
        private bool IsLoadingMorePosition(int position)
        {
            return position >= this.items.Count;
        }

        /// <summary>
        /// Ensures the result item at the specified position has been loaded, and if not, loads a new batch of results
        /// </summary>
        /// <param name="position"></param>
        /// <param name="action"></param>
        private void EnsurePositionLoaded(int position, Action action)
        {
            // If this position is already loaded, then return immediately
            if (!this.IsLoadingMorePosition(position))
            {
                return;
            }

            lock (this.items)
            {
                // Since we might have been blocked, check again if the position is already loaded, and if so, return
                if (!this.IsLoadingMorePosition(position))
                {
                    return;
                }

                // Load the requested position PLUS a batch of additional results
                this.LoadSearchResultItems(position + SubsequentBatchSize, action);
            }
        }

        /// <summary>
        /// Loads search results into the adapter up to a specified position
        /// </summary>
        /// <param name="toPosition"></param>
        /// <param name="action"></param>
        private void LoadSearchResultItems(int toPosition, Action action)
        {
            // Determine if this is the first load
            bool isFirstLoad = this.items.Count == 0;

            // Figure out how many rows to skip and how many to load
            int rowsToSkip = isFirstLoad ? 0 : this.items.Count;
            int rowsToLoad = toPosition - rowsToSkip;

            // Query the remote NuGet gallery server for results
            var searchResult = this.nugetGalleryClient
                .SearchAsync(this.searchTerm, this.orderBy, this.includePrerelease, rowsToSkip, rowsToLoad, isFirstLoad)
                .Result;

            this.InvokeOnMainThread(() =>
            {
                // Only set the total count if this is the first time results are returned (the total count is not there in subsequent requests)
                if (isFirstLoad)
                {
                    this.totalCount = searchResult.Count;
                }

                // Add the resulting items to the items list
                this.items.AddRange(searchResult.Items);

                if (action != null)
                {
                    action();
                }
            });

            // Tell the icon manager to make sure it has a bitmap for the icons, and if not, to start loading them
            IOSIconManager.Current.Load(
                searchResult.Items.Select(x => x.IconUrl).Distinct(),
                x =>
            {
                if (this.rowChangedCallback != null)
                {
                    for (int i = 0; i < this.items.Count; i++)
                    {
                        if (this.items[i].IconUrl == x)
                        {
                            this.rowChangedCallback(NSIndexPath.FromItemSection(i, 0));
                        }
                    }
                }
            });
        }
    }
}


text:
package ch.mlutz.plugins.t4e.i18n;

import java.util.MissingResourceException;
import java.util.ResourceBundle;

public class Messages {
	private static final String BUNDLE_NAME = "l10n.bundle"; //$NON-NLS-1$

	private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
			.getBundle(BUNDLE_NAME);

	private Messages() {
	}

	public static String getString(String key) {
		try {
			return RESOURCE_BUNDLE.getString(key);
		} catch (MissingResourceException e) {
			return '!' + key + '!';
		}
	}

	public static String getStringChecked(String key)
			throws MissingResourceException {
		return RESOURCE_BUNDLE.getString(key);
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?php
require_once __DIR__ . '/../../vendor/autoload.php';

use Ellumilel\ExcelWriter;

class XLSXTest extends PHPUnit\Framework\TestCase
{
    public function testConstruct()
    {
        $output_file = __DIR__ . "/unit_test_output_one.xlsx";

        if(file_exists($output_file)){
          unlink($output_file);
        }
        $this->assertFalse(file_exists($output_file));

        $header = [
            'test1' => 'integer',
            'test2' => 'integer',
            'test3' => 'integer',
            'test4' => 'integer',
        ];
        $writer = new Ellumilel\ExcelWriter();
        $writer->setAuthor('Tester');
        $writer->writeSheetHeader('Sheet1', $header);
        $writer->writeSheetRow('Sheet1', [1, 2, 3, 4]);
        $writer->writeToFile($output_file);

        $this->assertEquals(true, file_exists($output_file));

        unlink($output_file);
    }
}


text:
<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <xi:include href="layout.html" />
  <?python
    if _dgettext is not None:
        dgettext = _dgettext ?>

    <title>Login</title>

        <xi:include href="widget_alert.html"
            py:with="msglabel = 'Failed'; msgbody = login_error"/>

Login

      <form class="form-horizontal" method="post" id="acctmgr_loginform" action="">

          <input type="hidden" name="referer" value="${referer}" />

          Username:

            <input type="text" id="user" name="user" class="textwidget"
                size="20" placeholder="${_('User name')}" />

          Password:

            <input type="password" id="password" name="password"
                class="textwidget" size="20" placeholder="${_('Password')}"/>

                Forgot your password?

              <input type="checkbox" id="rememberme" name="rememberme"
                     value="1" />
              Remember me

              <input type="submit" value="${dgettext('acct_mgr', 'Login')}"
                  class="btn" />

                <py:choose py:if="registration_enabled">

                    Register

                    Register

                </py:choose>
                <py:choose py:if="reset_password_enabled">

                    Forgot your password?

                    Forgot your password?

                </py:choose>

      </form>


text:
/*
 * Test of connecting 2 clients together then one sending a message to the other.
 */

var request = require('request');
var latch = require('./dep/latch.js');

var prbody1 = undefined;
var prbody2 = undefined;

var pairRequest = function() {
    request({method: 'POST', uri: 'http://192.168.0.16/p', json: {key: 'reqPair'}}, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            prbody1 = body;
            latch.done();
        } else {
            console.log('pairRequest RESPONSE1 ERROR: ' + response.statusCode);
        }
    });

    request({method: 'POST', uri: 'http://192.168.0.16/p', json: {key: 'reqPair'}}, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            prbody2 = body;
            latch.done();
        } else {
            console.log('pairRequest RESPONSE2 ERROR: ' + response.statusCode);
        }
    });
}

var msgRequest = function() {
    if(prbody1 === undefined || prbody2 === undefined) {
        throw new Exception("ABORTING: Message request failed.");
    } else {
        request({method: 'POST', uri: 'http://192.168.0.16/m', json: {uid: prbody2.uid, cid: prbody2.cid}}, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                console.log("Client2 msg response: " + JSON.stringify(body));
            } else {
                console.log('msgRequest RESPONSE1 ERROR: ' + response.statusCode);
            }
        });
    }
}

var msgSend = function() {
    request({method: 'POST', uri: 'http://192.168.0.16/s', json: {uid: prbody1.uid, cid: prbody1.cid, msg: 'test'}}, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log("Client1 msg SEND response: " + JSON.stringify(body));
        } else {
            console.log('msgSend RESPONSE1 ERROR: ' + response.statusCode);
        }
    });
}

var pairRequestFinished = function() {
    latch.reset();
    msgRequest();

    setTimeout(msgSend, 2000); // Give the server time to process the message requests before sending.
}

// Effectively make msgRequest wait until pairRequest is finished to begin execution.
latch.set(2, pairRequestFinished);
pairRequest();


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Command (ATG Java API)
</TITLE>

<META NAME="date" CONTENT="2013-04-01">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

atg.integrations

Interface Command

All Known Implementing Classes:
BaseCommand

public interface Command

Command is an interface for the actual end point in the generic
 RPC Framework that executes RPC. A command exposes two methods for
 execution execute() and invokeRPC().

 The execute() method is the one that determines how this
 command should actually be executed. It might determine that it is
 necessary to call a CommandHandler before the command is
 actually executed if CommandHandler
 is configured with any CommandHandler.  Or, it might
 determine that no  CommandHandler needs to be called and
 the Command can simply be executed and the results returned
 to the calling program if no CommandHandler() is configured.
 The invokeRPC() method is the one that actually executes
 the command by mapping the Command input onto the RPC defined
 in the transport layer.

 A Command's execute() and invokeRPC() method
 throw these exceptions; CommandInvocationException and
 CommandTimeoutException.  These exceptions are intended to wrap
 any underlying exceptions that might be thrown by a particular transport
 or back end. These exceptions needs to wrap the underlying Exception
 (as opposed to copying its message) so that stack trace printouts can
 contain the information from the underlying exception.
 CommandTimeoutException is a special case of exception, since
 time out doesn't indicate whether the RPC call is succeeded or not we need
 to handle timeouts differently and so this exception is provided to allow
 that.
InvalidInputException indicates the input object passed to
 the Command is invalid.

 Also, Command's execute() and invokeRPC()
 method returns CommandResult which is a transport independent
 representation of the results from a RPC call.

A Command also contains a context
 object which is a Properties property.  This property is
 intended to be used as a hook for additional configuration or hints to a
 transport/backend system that can not be captured in the standard input.

Field Summary

static java.lang.String
CLASS_VERSION

Method Summary

 CommandResult
execute(java.lang.Object pInput)

          Executes RPC Call at the configured back end system.

 CommandHandler
getCommandHandler()

          Returns CommandHandler property to do pre/post processing of RPC call.

 java.util.Map
getContext()

          Returns Hook for extra parameters

 CommandResult
invokeRPC(java.lang.Object pInput)

          Actual method that executes the RPC Call at the back end system.

Field Detail

CLASS_VERSION

static final java.lang.String CLASS_VERSION

See Also:
Constant Field Values

Method Detail

getCommandHandler

CommandHandler getCommandHandler()

Returns CommandHandler property to do pre/post processing of RPC call.

Returns:
CommandHandler

getContext

java.util.Map getContext()

Returns Hook for extra parameters

Returns:
the context object

execute

CommandResult execute(java.lang.Object pInput)
                      throws CommandInvocationException,
                             CommandTimeoutException,
                             InvalidInputException

Executes RPC Call at the configured back end system. This method is
 called by application code to execute a RPC call at the back end.
 An implementation of this  method will be the same across implementing
 classes.  It will check to see if it has a configured CommandHandler
 If it does then calls the executeCommand() on
 the configured  CommandHandler.  Eventually there will be
 a CommandHandler that will call the invokeRPC() method on
 this command.  If no CommandHandler is configured on this  component then
 the execute() method just calls the invokeRPC()
 method directly.

Parameters:
pInput - the input Map to pass as a input to RPC Call.

Returns:
the result of invoking the RPC call at the back end.

Throws:

CommandInvocationException - if an error occurs in the middleware
         or at the back end.

CommandTimeoutException - if timeout occurs while invoking the command.

InvalidInputException - if input object passed is invalid.

invokeRPC

CommandResult invokeRPC(java.lang.Object pInput)
                        throws CommandInvocationException,
                               CommandTimeoutException,
                               InvalidInputException

Actual method that executes the RPC Call at the back end system. This
 method is expected to actually map the input onto a particular transport

Parameters:
pInput - the input to map onto transport format and pass to back end.

Throws:

CommandInvocationException - if an error occurs in the middleware
         or at the back end.

CommandTimeoutException - if timeout occurs while invoking the command.

InvalidInputException - if input object passed is invalid.

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using FiapTodoApp;

namespace FiapTodoApp.Migrations
{
    [DbContext(typeof(AppDbContext))]
    [Migration("20171125171204_InitialMigration")]
    partial class InitialMigration
    {
        protected override void BuildTargetModel(ModelBuilder modelBuilder)
        {
            modelBuilder
                .HasAnnotation("ProductVersion", "1.1.3");

            modelBuilder.Entity("FiapTodoApp.Models.Appointment", b =>
                {
                    b.Property<int>("Id");

                    b.Property<double>("Reminder");

                    b.HasKey("Id");

                    b.ToTable("Appointments");
                });

            modelBuilder.Entity("FiapTodoApp.Models.Category", b =>
                {
                    b.Property<string>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("Color");

                    b.Property<string>("Description");

                    b.HasKey("Id");

                    b.ToTable("Categories");
                });

            modelBuilder.Entity("FiapTodoApp.Models.TodoItem", b =>
                {
                    b.Property<string>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<int?>("AppointmentId");

                    b.Property<string>("CategoryId");

                    b.Property<string>("Details");

                    b.Property<bool?>("IsComplete");

                    b.Property<bool>("IsInkPicture");

                    b.Property<string>("Location");

                    b.Property<byte[]>("Picture");

                    b.Property<DateTime?>("StartDate");

                    b.Property<string>("Title");

                    b.HasKey("Id");

                    b.HasIndex("AppointmentId");

                    b.HasIndex("CategoryId");

                    b.ToTable("TodoItems");
                });

            modelBuilder.Entity("FiapTodoApp.Models.TodoItem", b =>
                {
                    b.HasOne("FiapTodoApp.Models.Appointment", "Appointment")
                        .WithMany()
                        .HasForeignKey("AppointmentId");

                    b.HasOne("FiapTodoApp.Models.Category", "Category")
                        .WithMany()
                        .HasForeignKey("CategoryId");
                });
        }
    }
}


text:
layout: "fluid/docs_base"
version: "4.20.0"
versionHref: "/docs/native"
path: ""
category: native
id: "zip"
title: "Zip"
header_sub_title: "Class in module "
doc: "Zip"
docType: "class"
---

Zip

  Improve this doc

A Cordova plugin to unzip files in Android and iOS.

Repo:

    https://github.com/MobileChromeApps/cordova-plugin-zip

Installation

Install the Cordova and Ionic Native plugins:

$ ionic cordova plugin add cordova-plugin-zip
$ npm install --save @ionic-native/zip@4

Add this plugin to your app's module

Supported platforms

Android

iOS

Usage

import { Zip } from '@ionic-native/zip';

constructor(private zip: Zip) { }

...

this.zip.unzip('path/to/source.zip', 'path/to/dest', (progress) => console.log('Unzipping, ' + Math.round((progress.loaded / progress.total) * 100) + '%'))
 .then((result) => {
   if(result === 0) console.log('SUCCESS');
   if(result === -1) console.log('FAILED');
 });

Instance Members

unzip(sourceZip, destUrl, onProgress)

Extracts files from a ZIP archive

    Param
    Type
    Details

      sourceZip

      string

Source ZIP file

      destUrl

      string

Destination folder

      onProgress

      Function

optional callback to be called on progress update

  Returns: Promise<number> returns a promise that resolves with a number. 0 is success, -1 is error


text:
package edu.uw.zookeeper.safari.peer;

import org.apache.logging.log4j.Logger;
import org.apache.zookeeper.Watcher;

import com.google.common.base.Optional;
import com.google.common.util.concurrent.ListenableFuture;

import edu.uw.zookeeper.client.ClientExecutor;
import edu.uw.zookeeper.client.FixedQuery;
import edu.uw.zookeeper.client.LoggingWatchMatchListener;
import edu.uw.zookeeper.client.PathToRequests;
import edu.uw.zookeeper.client.Watchers;
import edu.uw.zookeeper.common.Promise;
import edu.uw.zookeeper.common.SettableFuturePromise;
import edu.uw.zookeeper.data.Operations;
import edu.uw.zookeeper.data.WatchEvent;
import edu.uw.zookeeper.data.WatchListeners;
import edu.uw.zookeeper.data.WatchMatcher;
import edu.uw.zookeeper.data.ZNodePath;
import edu.uw.zookeeper.protocol.Operation;
import edu.uw.zookeeper.protocol.proto.Records;
import edu.uw.zookeeper.safari.Identifier;
import edu.uw.zookeeper.safari.control.schema.ControlSchema;

public final class PresenceExpired extends LoggingWatchMatchListener implements Runnable {

    public static <O extends Operation.ProtocolResponse<?>> ListenableFuture<Identifier> create(
            final Identifier peer,
            final ClientExecutor<? super Records.Request, O, ?> client,
            final WatchListeners notifications,
            final Logger logger) {
        final Promise<Identifier> promise = SettableFuturePromise.create();
        final ZNodePath path = ControlSchema.Safari.Peers.Peer.Presence.pathOf(peer);
        final Runnable set = new Runnable() {
            @Override
            public void run() {
                if (!promise.isDone()) {
                    promise.set(peer);
                }
            }
        };
        @SuppressWarnings("unchecked")
        final Watchers.FixedQueryRunnable<O,?> query = Watchers.FixedQueryRunnable.create(
                FixedQuery.forIterable(
                        client,
                        PathToRequests.forRequests(
                                Operations.Requests.sync(),
                                Operations.Requests.exists().setWatch(true)).apply(path)),
                        Watchers.MaybeErrorProcessor.maybeNoNode(),
                        new Watchers.SetExceptionCallback<Optional<Operation.Error>, Identifier>(promise) {
                            @Override
                            public void onSuccess(Optional<Operation.Error> result) {
                                if (result.isPresent()) {
                                    set.run();
                                }
                            }
                        });
        PresenceExpired listener = new PresenceExpired(
                set,
                query,
                WatchMatcher.exact(
                        path,
                        Watcher.Event.EventType.NodeCreated,
                        Watcher.Event.EventType.NodeDeleted),
                logger);
        Watchers.UnsubscribeWhenDone.subscribe(promise, listener, notifications);
        listener.run();
        return promise;
    }

    private final Runnable set;
    private final Runnable query;

    private PresenceExpired(
            Runnable set,
            Runnable query,
            WatchMatcher match,
            Logger logger) {
        super(match, logger);
        this.set = set;
        this.query = query;
    }

    @Override
    public void run() {
        query.run();
    }

    @Override
    public void handleWatchEvent(WatchEvent event) {
        super.handleWatchEvent(event);
        if (event.getEventType() == Watcher.Event.EventType.NodeDeleted) {
            set.run();
        }
        run();
    }
}


text:
#ifndef HALM_USB_USB_TRACE_H_
#define HALM_USB_USB_TRACE_H_
/*----------------------------------------------------------------------------*/
#include <halm/timer.h>
#include <xcore/interface.h>
/*----------------------------------------------------------------------------*/
BEGIN_DECLS

enum Result usbTraceInit(struct Interface *, struct Timer *);
void usbTraceDeinit(void);

#ifdef CONFIG_USB_TRACE
void usbTrace(const char *, ...);
#else
#define usbTrace(...) do {} while (0)
#endif

END_DECLS
/*----------------------------------------------------------------------------*/
#endif /* HALM_USB_USB_TRACE_H_ */