text:
package android.app;

/**
 * A listener that is called when an Activity is paused. Since this is tracked client side
 * it should not be trusted to represent the exact current state, but can be used as a hint
 * for cleanup.
 *
 * @hide
 */
public interface OnActivityPausedListener {
    /**
     * Called when the given activity is paused.
     */
    public void onPaused(Activity activity);
}


text:
package org.jboss.summit2015.beacon.ssh;
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;
import org.jboss.logging.Logger;
import org.jboss.summit2015.beacon.scanner.AbstractParser;
import org.jboss.summit2015.beacon.Beacon;
import org.jboss.summit2015.beacon.scanner.ParserLogic;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * @author Scott Stark (sstark@redhat.com) (C) 2014 Red Hat Inc.
 */
public class SSHStreamParser extends AbstractParser {
   private static Logger log = Logger.getLogger(SSHStreamParser.class);

   private StreamSSHCommand streamCmd;
   private ChannelExec channel;
   private Session session;
   private LinkedBlockingDeque<Beacon> beacons;
   private ParserLogic parser;

   public SSHStreamParser(StreamSSHCommand streamCmd) {
      this.streamCmd = streamCmd;
   }

   @Override
   public boolean isRunning() {
      return parser.isRunning();
   }

   @Override
   public void setRunning(boolean running) {
      parser.setRunning(running);
   }

   @Override
   public InputStream getInputStream(String testDataPath) throws IOException {
      if (testDataPath != null)
         return super.getInputStream(testDataPath);

      // Enable verbose logging
      if (streamCmd.verbose) {
         JSch.setLogger(new com.jcraft.jsch.Logger() {
                           public boolean isEnabled(int level) {
                              return true;
                           }

                           public void log(int level, String message) {
                              log.debugf("%d: %s\n", level, message);
                           }
                        }
         );
      }
      JSch jsch = new JSch();
      InputStream is = null;
      try {
         session = jsch.getSession(streamCmd.sshUsername, streamCmd.host, streamCmd.port);

         // sshUsername and sshPassword passed in via UserInfo interface.
         session.setUserInfo(new UserInfo() {
            @Override
            public String getPassphrase() {
               return null;
            }

            @Override
            public String getPassword() {
               return streamCmd.sshPassword;
            }

            @Override
            public boolean promptPassword(String message) {
               return true;
            }

            @Override
            public boolean promptPassphrase(String message) {
               return false;
            }

            @Override
            public boolean promptYesNo(String message) {
               return true;
            }

            @Override
            public void showMessage(String message) {
               log.infof("showMessage: %s\n", message);
            }
         });
         session.connect();
         channel = (ChannelExec) session.openChannel("exec");
         channel.setCommand(streamCmd.hcidump);
         channel.setInputStream(null);
         channel.setErrStream(System.err);
         is = channel.getInputStream();
         channel.connect();
      } catch (JSchException e) {
         e.printStackTrace();
      }
      return is;
   }

   @Override
   public void processHCIStream(final InputStream is) throws Exception {
      parser = new ParserLogic(streamCmd.parserCmd);
      parser.setScannerID(getScannerID());
      parser.setBeacons(beacons);
      parser.processHCIStream(is);
   }

   @Override
   public void cleanup() {
      if(channel != null) {
         channel.disconnect();
         channel = null;
      }
      if(session != null) {
         session.disconnect();
         session = null;
      }
      if(parser != null) {
         parser.cleanup();
         parser = null;
      }
   }
   public LinkedBlockingDeque<Beacon> getBeacons() {
      return beacons;
   }

   /**
    * Set a queue to collect the beacons. Used when one is not immediately sending the beacons to the MQTT server.
    * @param beacons
    */
   public void setBeacons(LinkedBlockingDeque<Beacon> beacons) {
      this.beacons = beacons;
   }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Antares\Html\Form;

use Antares\Contracts\Html\Form\Presenter as PresenterContract;

interface PresenterInterface extends PresenterContract
{

}


text:
// The utility to check Cudnn dependency and set Cudnn-related flags.

#ifndef TENSORFLOW_CORE_UTIL_USE_CUDNN_H_
#define TENSORFLOW_CORE_UTIL_USE_CUDNN_H_

#include <cstdint>

#include "tensorflow/tsl/util/use_cudnn.h"

namespace tensorflow {

using tsl::CudnnDisableConv1x1Optimization;
using tsl::CudnnRnnUseAutotune;
using tsl::CudnnUseAutotune;
using tsl::CudnnUseFrontend;
using tsl::CudnnUseRuntimeFusion;
using tsl::DebugCudnnRnn;
using tsl::DebugCudnnRnnAlgo;
using tsl::DebugCudnnRnnUseTensorOps;
using tsl::ShouldCudnnGroupedConvolutionBeUsed;

}  // namespace tensorflow

#endif  // TENSORFLOW_CORE_UTIL_USE_CUDNN_H_


text:
Crackify
========

Easy protection for iOS apps from cracking.

## How to use

1. Import Crackify.h
2. If you want to check was device jailbroken write:
```
[Crackify isJailbroken];
```
3. If you want to check was app cracked write:
```
[Crackify isCracked];
```


text:
#ifndef ANDROID_GUI_RINGBUFFERCONSUMER_H
#define ANDROID_GUI_RINGBUFFERCONSUMER_H

#include <gui/ConsumerBase.h>

#include <ui/GraphicBuffer.h>

#include <utils/String8.h>
#include <utils/Vector.h>
#include <utils/threads.h>
#include <utils/List.h>

#define ANDROID_GRAPHICS_RINGBUFFERCONSUMER_JNI_ID "mRingBufferConsumer"

namespace android {

/**
 * The RingBufferConsumer maintains a ring buffer of BufferItem objects,
 * (which are 'acquired' as long as they are part of the ring buffer, and
 *  'released' when they leave the ring buffer).
 *
 * When new buffers are produced, the oldest non-pinned buffer item is immediately
 * dropped from the ring buffer, and overridden with the newest buffer.
 *
 * Users can only access a buffer item after pinning it (which also guarantees
 * that during its duration it will not be released back into the BufferQueue).
 *
 * Note that the 'oldest' buffer is the one with the smallest timestamp.
 *
 * Edge cases:
 *  - If ringbuffer is not full, no drops occur when a buffer is produced.
 *  - If all the buffers get filled or pinned then there will be no empty
 *    buffers left, so the producer will block on dequeue.
 */
class RingBufferConsumer : public ConsumerBase,
                           public ConsumerBase::FrameAvailableListener
{
  public:
    typedef ConsumerBase::FrameAvailableListener FrameAvailableListener;

    typedef BufferQueue::BufferItem BufferItem;

    enum { INVALID_BUFFER_SLOT = BufferQueue::INVALID_BUFFER_SLOT };
    enum { NO_BUFFER_AVAILABLE = BufferQueue::NO_BUFFER_AVAILABLE };

    // Create a new ring buffer consumer. The consumerUsage parameter determines
    // the consumer usage flags passed to the graphics allocator. The
    // bufferCount parameter specifies how many buffers can be pinned for user
    // access at the same time.
    RingBufferConsumer(const sp<IGraphicBufferConsumer>& consumer, uint32_t consumerUsage,
            int bufferCount = BufferQueue::MIN_UNDEQUEUED_BUFFERS);

    virtual ~RingBufferConsumer();

    // set the name of the RingBufferConsumer that will be used to identify it in
    // log messages.
    void setName(const String8& name);

    // setDefaultBufferSize is used to set the size of buffers returned by
    // requestBuffers when a with and height of zero is requested.
    status_t setDefaultBufferSize(uint32_t w, uint32_t h);

    // setDefaultBufferFormat allows the BufferQueue to create
    // GraphicBuffers of a defaultFormat if no format is specified
    // by the producer endpoint.
    status_t setDefaultBufferFormat(uint32_t defaultFormat);

    // setConsumerUsage allows the BufferQueue consumer usage to be
    // set at a later time after construction.
    status_t setConsumerUsage(uint32_t usage);

    // Buffer info, minus the graphics buffer/slot itself.
    struct BufferInfo {
        // mCrop is the current crop rectangle for this buffer slot.
        Rect mCrop;

        // mTransform is the current transform flags for this buffer slot.
        uint32_t mTransform;

        // mScalingMode is the current scaling mode for this buffer slot.
        uint32_t mScalingMode;

        // mTimestamp is the current timestamp for this buffer slot. This gets
        // to set by queueBuffer each time this slot is queued.
        int64_t mTimestamp;

        // mFrameNumber is the number of the queued frame for this slot.
        uint64_t mFrameNumber;

        // mPinned is whether or not the buffer has been pinned already.
        bool mPinned;
    };

    struct RingBufferComparator {
        // Return < 0 to select i1, > 0 to select i2, 0 for neither
        // i1 or i2 can be NULL.
        //
        // The comparator has to implement a total ordering. Otherwise
        // a linear scan won't find the most preferred buffer.
        virtual int compare(const BufferInfo* i1,
                            const BufferInfo* i2) const = 0;

        virtual ~RingBufferComparator() {}
    };

    struct PinnedBufferItem : public LightRefBase<PinnedBufferItem> {
        PinnedBufferItem(wp<RingBufferConsumer> consumer,
                         const BufferItem& item) :
                mConsumer(consumer),
                mBufferItem(item) {
        }

        ~PinnedBufferItem() {
            sp<RingBufferConsumer> consumer = mConsumer.promote();
            if (consumer != NULL) {
                consumer->unpinBuffer(mBufferItem);
            }
        }

        bool isEmpty() {
            return mBufferItem.mBuf == BufferQueue::INVALID_BUFFER_SLOT;
        }

        BufferItem& getBufferItem() { return mBufferItem; }
        const BufferItem& getBufferItem() const { return mBufferItem; }

      private:
        wp<RingBufferConsumer> mConsumer;
        BufferItem             mBufferItem;
    };

    // Find a buffer using the filter, then pin it before returning it.
    //
    // The filter will be invoked on each buffer item in the ring buffer,
    // passing the item that was selected from each previous iteration,
    // as well as the current iteration's item.
    //
    // Pinning will ensure that the buffer will not be dropped when a new
    // frame is available.
    sp<PinnedBufferItem> pinSelectedBuffer(const RingBufferComparator& filter,
                                           bool waitForFence = true);

    // Release all the non-pinned buffers in the ring buffer
    status_t clear();

  private:

    // Override ConsumerBase::onFrameAvailable
    virtual void onFrameAvailable();

    void pinBufferLocked(const BufferItem& item);
    void unpinBuffer(const BufferItem& item);

    // Releases oldest buffer. Returns NO_BUFFER_AVAILABLE
    // if all the buffers were pinned.
    // Returns NOT_ENOUGH_DATA if list was empty.
    status_t releaseOldestBufferLocked(size_t* pinnedFrames);

    struct RingBufferItem : public BufferItem {
        RingBufferItem() : BufferItem(), mPinCount(0) {}
        int mPinCount;
    };

    // List of acquired buffers in our ring buffer
    List<RingBufferItem>       mBufferItemList;
    const int                  mBufferCount;
};

} // namespace android

#endif // ANDROID_GUI_CPUCONSUMER_H


text:
(function () {
'use strict';
var module = angular.module('fim.base');
module.run(function (plugins, modals, $q, $timeout, db, nxt) {

  /* Global variables hidden from outside code | rely on the fact that
     there is one wallet opened each time */
  var gPassword = '';
  var gFile     = '';
  var gWallet   = null;
  var gDeferred = null;

  /* Register as plugin */
  plugins.register({
    id:       'wallet',
    label:    'Wallet',
    extends:  'settings',
    icon_class:   'glyphicon glyphicon-briefcase',
    templateURL:  'plugins/wallet/partials/wallet-manager.html',

    /* Returns the internal file object */
    getFile: function () {
      return gFile;
    },

    /* Returns a copy of the internal wallet object */
    getWallet: function () {
      return angular.copy(gWallet);
    },

    /* Returns all wallet entry keys */
    getKeys: function () {
      return gWallet ? Object.keys(gWallet) : [];
    },

    /* Do we have that key? */
    hasKey: function (key) {
      return gWallet ? !!gWallet[key] : false;
    },

    /* Remove an entry from the wallet */
    remove: function (key) {
      delete gWallet[key];
    },

    /* Returns the secretPhrase if any */
    getSecretPhrase: function (key) {
      return (gWallet && gWallet[key]) ? gWallet[key].secretPhrase : null;
    },

    /* Prompts the user to open a wallet */
    promptForWallet: function () {
      return promptForWallet();
    },

    /**
     * Returns an entry from the wallet. If no wallet is open the user is prompted to
     * select a wallet file and to provide his password to unlock it.
     *
     * @returns Promise
     */
    getEntry: function (id_rs) {
      var deferred    = $q.defer();

      /* Wallet is open and key is available */
      if (gWallet && _getEntry(id_rs)) {
        deferred.resolve(_getEntry(id_rs));
      }
      else {
        if (gWallet) {
          plugins.get('alerts').warn({ message: 'Key not found in wallet. Close dialog to select another wallet.'}).then(
            function () {
              promptForWallet().then(
                function () {
                  // recursive - try again now with other wallet
                  plugins.get('wallet').getEntry(id_rs).then(deferred.resolve, deferred.reject);
                },
                function () {
                  deferred.reject();
                }
              );
            }
          );
        }
        else {
          promptForWallet().then(
            function () {
              // recursive - try again now with other wallet
              plugins.get('wallet').getEntry(id_rs).then(deferred.resolve, deferred.reject);
            },
            function () {
              deferred.reject();
            }
          );
        }
      }
      return deferred.promise;
    },

    /**
     * Ads a new entry to the wallet and prompts the user to save it.
     * Returning a Promise is useless since we dont know when the saveas dialog completes.
     */
    addEntry: function (entry) {
      var self = this;
      var deferred = $q.defer();

      if (validateEntry(entry)) {
        if (gWallet) {
          gWallet[entry.id_rs] = entry;
          this.save(gFile.name, gPassword).then(deferred.resolve, deferred.reject);
        }
        else {
          plugins.get('alerts').confirm({ message: 'Do you want to store this secretphrase in an existing wallet?' }).then(
            function (value) {
              if (value) {
                promptForWallet().then(
                  function () {
                    // recursive - try again now with other wallet
                    plugins.get('wallet').addEntry(entry);
                  },
                  deferred.reject
                );
              }
              else {
                gWallet = {};
                gWallet[entry.id_rs] = entry;
                self.save().then(deferred.resolve, deferred.reject);
              }
            }
          );
        }
      }
      else {
        console.log('Invalid entry !!', entry);
        deferred.reject();
      }
      return deferred.promise;
    },

    /**
     * Creates a new Promise ($q.defer()) which is stored in the global gDeferred
     * variable. When the wallet is opened and decrypted in window.onWalletFileSelected
     * if the gDeferred variable is set it is called with resolve or reject result.
     */
    createOnWalletFileSelectedPromise: function () {
      gDeferred = $q.defer();
      return gDeferred.promise;
    },

    /**
     * @returns Promise
     * */
    save: function (fileName, password) {
      if (gWallet === null) {
        throw new Error('No wallet opened, cannot save.')
      }

      var deferred    = $q.defer();
      saveWallet(password).then(
        function (items) {
          try {
            var serialized  = JSON.stringify(addPadding(gWallet));
            var encrypted   = encrypt(items.password, serialized);
            var blob        = new Blob([encrypted], {type: "text/plain;charset=utf-8"});
            saveAs(blob, fileName||'mofo.wallet');
          }
          catch (e) {
            deferred.reject(e);
          }
          $timeout(function () {
            deferred.resolve();
          }, 1000);
        },
        function () {
          deferred.reject();
        }
      );
      return deferred.promise;
    },

    /* Opens wallet manager */
    manager: function () {
      var deferred = $q.defer();
      modals.open('walletManager', {
        resolve: {
          items: function () {
            return {};
          }
        },
        close: function () {
          deferred.resolve();
        }
      });
      return deferred.promise;
    }
  });

  /* Register modal dialogs */
  modals.register('walletManager', {
    templateUrl: 'plugins/wallet/partials/wallet-manager-modal.html',
    controller: 'WalletManagerModalController'
  });
  modals.register('walletPassword', {
    templateUrl: 'plugins/wallet/partials/wallet-password-modal.html',
    controller: 'WalletPasswordModalController'
  });
  modals.register('walletOpen', {
    templateUrl: 'plugins/wallet/partials/wallet-open-modal.html',
    controller: 'WalletOpenModalController'
  });
  modals.register('walletSave', {
    templateUrl: 'plugins/wallet/partials/wallet-save-modal.html',
    controller: 'WalletSaveModalController'
  });

  /**
   * Called from <input type="file" onchange="onWalletFileSelected(event)">
   * Prompts the user for a password, then decrypts the wallet.
   * You can register
   */
  window.onWalletFileSelected = function (event) {
    gWallet     = null;
    gPassword   = null;
    gFile       = null;

    var selectedFile = event.target.files[0];
    var reader    = new FileReader();
    reader.onload = function(event) {
      var cipherText = event.target.result;
      promptForPassword(selectedFile, cipherText).then(
        function (password) {
          try {
            var text    = decrypt(password, cipherText);
            gWallet     = removePadding(JSON.parse(text));
            gPassword   = password;
            gFile       = selectedFile;

            /* Add all entries in the wallet to the accounts database */
            db.accounts.toArray().then(
              function (accounts) {
                var map = {};
                angular.forEach(accounts, function (a) { map[a.id_rs] = a} );

                db.transaction('rw', db.accounts, function () {
                  angular.forEach(gWallet, function (entry) {
                    if (!(entry.id_rs in map)) {
                      db.accounts.put({
                        id_rs: entry.id_rs,
                        name: entry.name,
                        engine: nxt.get(entry.id_rs).type
                      });
                    }
                  });
                });
              }
            );

            if (gDeferred) {
              gDeferred.resolve({password: password, file: selectedFile});
              gDeferred = null;
            }
          }
          catch (e) {
            console.log('unlockWallet', e, e.stack);
            if (gDeferred) {
              gDeferred.reject();
              gDeferred = null;
            }
          }
        }
      );
    };
    reader.onerror = function (event) {
      if (gDeferred) {
        gDeferred.reject();
        gDeferred = null;
      }
    };
    reader.onabort = function (event) {
      if (gDeferred) {
        gDeferred.reject();
        gDeferred = null;
      }
    };
    reader.readAsText(selectedFile);
  }

  function promptForPassword(file, cipherText) {
    var deferred = $q.defer();
    modals.open('walletPassword', {
      resolve: {
        items: function () {
          return {
            password: '',
            file: file,
            isPasswordCorrect: function (password) {
              try {
                decrypt(password, cipherText);
                return true;
              }
              catch (e) {
                return false;
              }
            }
          };
        }
      },
      close: function (items) {
        deferred.resolve(items.password);
      },
      cancel: function () {
        deferred.reject();
      }
    });
    return deferred.promise;
  }

  /* Shows a modal with a `Open wallet` button once the user selected a wallet file he/she
     will be prompted for a password. If the decryption happens successfully the returned
     promise resolve is called otherwise reject is called.
     In the promise resolve the user can expect the wallet to be opened and decrypted. */
  function promptForWallet() {
    var deferred = $q.defer();
    modals.open('walletOpen', {
      resolve: {
        items: function () {
          return {};
        }
      },
      close: function () {
        deferred.resolve();
      },
      cancel: function () {
        deferred.reject();
      }
    });
    return deferred.promise;
  }

  function saveWallet(file, password) {
    var deferred = $q.defer();
    modals.open('walletSave', {
      resolve: {
        items: function () {
          return {
            password: password || '',
            file:     file || ''
          };
        }
      },
      close: function (items) {
        deferred.resolve(items);
      },
      cancel: function () {
        deferred.reject();
      }
    });
    return deferred.promise;
  }

  function _getEntry(id_rs) {
    return gWallet ? gWallet[id_rs] : null;
  }

});

var config   = {
  name:         String,
  id_rs:        String,
  secretPhrase: String
};
var configCount = Object.keys(config).length;

function validateEntry(entry) {
  var count = 0;
  for (var name in entry) {
    if (name in config) {
      if (new Object(entry[name]) instanceof config[name] && entry[name] !== undefined) {
        count++;
        continue;
      }
    }
    console.log('wallet.validateEntry Invalid entry for '+name, entry);
    return false;
  }
  return count == configCount;
}

// Formats and wraps the ciphertext, salt and iv as JSON document
var WalletFormatter = {
  stringify: function (cipherParams) {
    var jsonObj = {
      ct: cipherParams.ciphertext.toString(CryptoJS.enc.Base64)
    };
    if (cipherParams.iv) {
        jsonObj.iv = cipherParams.iv.toString();
    }
    if (cipherParams.salt) {
        jsonObj.s = cipherParams.salt.toString();
    }
    return JSON.stringify(jsonObj, undefined, 2);
  },

  parse: function (jsonStr) {
    var jsonObj = JSON.parse(jsonStr);
    var cipherParams = CryptoJS.lib.CipherParams.create({
        ciphertext: CryptoJS.enc.Base64.parse(jsonObj.ct)
    });
    if (jsonObj.iv) {
        cipherParams.iv = CryptoJS.enc.Hex.parse(jsonObj.iv)
    }
    if (jsonObj.s) {
        cipherParams.salt = CryptoJS.enc.Hex.parse(jsonObj.s)
    }
    return cipherParams;
  }
};

/**
 * @param passPhrase String
 * @param plaintext String
 * @returns String
 */
function encrypt(passPhrase, plainText) {
  if (!window.crypto && !window.msCrypto) {
    throw new Error('FIX ME !! Should use mouse initiated seed!!!'); //
  }

  var passByte  = converters.stringToByteArray(passPhrase);
  var key       = CryptoJS.SHA256(converters.byteArrayToWordArray(passByte));
  var tmp       = new Uint8Array(16);

  if (window.crypto) {
    window.crypto.getRandomValues(tmp);
  } else {
    window.msCrypto.getRandomValues(tmp);
  }

  var iv        = converters.byteArrayToWordArray(tmp);
  var encrypted = CryptoJS.AES.encrypt(plainText, key.toString(CryptoJS.enc.Hex), {
    iv: iv,
    format: WalletFormatter
  });
  return encrypted.toString();
}

/**
 * @param password String
 * @param cypherText String
 * @returns String
 */
function decrypt(passPhrase, cipherText) {
  var passByte  = converters.stringToByteArray(passPhrase);
  var key       = CryptoJS.SHA256(converters.byteArrayToWordArray(passByte));
  var decrypted = CryptoJS.AES.decrypt(cipherText, key.toString(CryptoJS.enc.Hex), {
    format: WalletFormatter
  });
  return decrypted.toString(CryptoJS.enc.Utf8);
}

function addPadding(obj) {
  obj = angular.copy(obj);
  obj.padding = new Array(20000).join('ABCD');
  return obj;
}

function removePadding(obj) {
  delete obj.padding;
  return angular.copy(obj);
}

})();


text:
package org.sunflow.core.primitive;

import org.sunflow.SunflowAPI;
import org.sunflow.core.IntersectionState;
import org.sunflow.core.ParameterList;
import org.sunflow.core.PrimitiveList;
import org.sunflow.core.Ray;
import org.sunflow.core.ShadingState;
import org.sunflow.math.BoundingBox;
import org.sunflow.math.Matrix4;

public class Background implements PrimitiveList {
    public Background() {
    }

    public boolean update(ParameterList pl, SunflowAPI api) {
        return true;
    }

    public void prepareShadingState(ShadingState state) {
        if (state.getDepth() == 0)
            state.setShader(state.getInstance().getShader(0));
    }

    public int getNumPrimitives() {
        return 1;
    }

    public float getPrimitiveBound(int primID, int i) {
        return 0;
    }

    public BoundingBox getWorldBounds(Matrix4 o2w) {
        return null;
    }

    public void intersectPrimitive(Ray r, int primID, IntersectionState state) {
        if (r.getMax() == Float.POSITIVE_INFINITY)
            state.setIntersection(0, 0, 0);
    }

    public PrimitiveList getBakingPrimitives() {
        return null;
    }
}


text:
import * as $ from 'jquery';
import * as React from 'react';

import {AddToBookmarksClone} from 'src/components/addToBookmarksClone';
import {GenerateElement} from 'src/injectors/utils';

export function injectBookmarksClone(clickAction: Function, text?: string) {
    let container = $('.bookmark-container');
    let component = GenerateElement(
        React.createElement(AddToBookmarksClone, {clickAction, text}),
    );

    // Only replace the button if the add bookmark button is there, not the
    // edit bookmark button
    if ($('.add-bookmark._button').length > 0) {
        container.empty();
        container.append(component);
    }
}


text:
#include <stdio.h>
#include <stdlib.h>
#include <zlib.h>

#include "fasta.h"
#include "kseq.h"
#include "log.h"

KSEQ_INIT(gzFile, gzread)

/**
 * process a single fasta file
 * @param fasta_fh file handle containing fasta file
 * @param log where to write additional progress info
 * @param minlength only process sequences that are at least this length
 * @return structure containing fasta stats
 */
struct FastaStats processFasta(FILE *fasta_fh, FILE* log, int minlength) {
    struct FastaStats result;
    result.total_sequences = 0;
    result.sequences = 0;
    result.bases = 0;
    result.min = 1e9;
    result.max = 0;
    result.is_empty = 0; // not empty

    gzFile fp = gzdopen(fileno(fasta_fh), "r");
    kseq_t *seq = kseq_init(fp);
    while(kseq_read(seq) >= 0) {
        // process and/or store the sequences
        result.total_sequences += 1;
        int bases = strlen(seq->seq.s);
        if (bases >= minlength) {
            result.sequences += 1;
            result.bases += bases;
            result.min = result.min < bases ? result.min : bases;
            result.max = result.max > bases ? result.max : bases;
        }
    }
    result.is_empty = (seq->f->begin == 0);
    if (result.sequences > 0) {
        result.average = (float)result.bases / result.sequences;
    }
    else {
        result.average = 0;
    }
    kseq_destroy(seq);
    gzclose(fp);

    return result;
}


text:
package com.smash.up.Itens;
import com.google.firebase.database.*;
import java.util.*;

@IgnoreExtraProperties
public class User
{
	public String username;
	public User(){}
	public User(String s){
		this.username=s;
	}

	public static void addMusicas(Album album)
	{
		Album.getMusicas(album.key,new ValueEventListener(){

				@Override
				public void onDataChange(DataSnapshot p1)
				{
					for(DataSnapshot ds : p1.getChildren()){
						addMusica(ds.getValue(Musica.class));
					}
				}

				@Override
				public void onCancelled(DatabaseError p1)
				{
					// TODO: Implement this method
				}
			});
	}

	public static void addMusica(Musica mMusica)
	{
		Commons.mDefaultDatabaseRef.child("users").child(Commons.mAuthReference.getCurrentUser().getUid())
		.child("musicas").child(mMusica.key).setValue(mMusica.key);
		Commons.mDefaultDatabaseRef.child("users").child(Commons.mAuthReference.getCurrentUser().getUid())
		.child("albuns").child(mMusica.albumKey).setValue(mMusica.albumKey);
		Commons.mDefaultDatabaseRef.child("users").child(Commons.mAuthReference.getCurrentUser().getUid())
		.child("artistas").child(mMusica.artistaKey).setValue(mMusica.artistaKey);
	}
	public static void getMusicas(){
		Commons.mDefaultDatabaseRef.child("users").child(Commons.mAuthReference.getCurrentUser().getUid())
			.child("musicas").addListenerForSingleValueEvent(new ValueEventListener(){

				@Override
				public void onDataChange(DataSnapshot p1)
				{
					for(DataSnapshot ds : p1.getChildren()){
						Musica.findByKey(ds.getKey());
					}
				}

				@Override
				public void onCancelled(DatabaseError p1)
				{
					// TODO: Implement this method
				}
			});

	}
	public static boolean isFavorite(Musica get)
	{
		// TODO: Implement this method
		return false;
	}
}


text:
    #error "include 'stdafx.h' before including this file for PCH"
#endif

#include "resource.h"        // main symbols

// CCheckmateApp:
// See Checkmate.cpp for the implementation of this class
//

class CCheckmateApp : public CWinAppEx
{
public:
    CCheckmateApp();

// Overrides
    public:
    virtual BOOL InitInstance();

// Implementation

    DECLARE_MESSAGE_MAP()
};

extern CCheckmateApp theApp;


text:
package androidx.core.app;

import android.app.job.JobParameters;
import android.app.job.JobServiceEngine;
import android.app.job.JobWorkItem;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import androidx.annotation.RequiresApi;
import android.util.Log;

public abstract class SafeJobIntentService extends JobIntentService {

    @Override
    public void onCreate() {
        super.onCreate();
        if (Build.VERSION.SDK_INT >= 26) {
            mJobImpl = new SafeJobServiceEngineImpl(this);
        }
    }

    /**
     * Implementation of a safe JobServiceEngine for interaction with JobIntentService.
     */
    @RequiresApi(26)
    static final class SafeJobServiceEngineImpl extends JobServiceEngine
            implements JobIntentService.CompatJobEngine {
        static final String TAG = "JobServiceEngineImpl";

        static final boolean DEBUG = false;

        final JobIntentService mService;
        final Object mLock = new Object();
        JobParameters mParams;

        final class WrapperWorkItem implements JobIntentService.GenericWorkItem {
            final JobWorkItem mJobWork;

            WrapperWorkItem(JobWorkItem jobWork) {
                mJobWork = jobWork;
            }

            @Override
            public Intent getIntent() {
                return mJobWork.getIntent();
            }

            @Override
            public void complete() {
                synchronized (mLock) {
                    if (mParams != null) {
                        try {
                            mParams.completeWork(mJobWork);
                        } catch (SecurityException e) {
                            Log.e(TAG, Log.getStackTraceString(e));
                        }
                    }
                }
            }
        }

        SafeJobServiceEngineImpl(JobIntentService service) {
            super(service);
            mService = service;
        }

        @Override
        public IBinder compatGetBinder() {
            return getBinder();
        }

        @Override
        public boolean onStartJob(JobParameters params) {
            if (DEBUG) Log.d(TAG, "onStartJob: " + params);
            mParams = params;
            // We can now start dequeuing work!
            mService.ensureProcessorRunningLocked(false);
            return true;
        }

        @Override
        public boolean onStopJob(JobParameters params) {
            if (DEBUG) Log.d(TAG, "onStartJob: " + params);
            boolean result = mService.doStopCurrentWork();
            synchronized (mLock) {
                // Once we return, the job is stopped, so its JobParameters are no
                // longer valid and we should not be doing anything with them.
                mParams = null;
            }
            return result;
        }

        /**
         * Dequeue some work.
         */
        @Override
        public JobIntentService.GenericWorkItem dequeueWork() {
            JobWorkItem work = null;
            synchronized (mLock) {
                if (mParams == null) {
                    return null;
                }
                try {
                    work = mParams.dequeueWork();
                } catch (SecurityException e) {
                    Log.e(TAG, Log.getStackTraceString(e));
                }
            }
            if (work != null) {
                work.getIntent().setExtrasClassLoader(mService.getClassLoader());
                return new WrapperWorkItem(work);
            } else {
                return null;
            }
        }
    }
}


text:
<?php

declare(strict_types=1);

namespace SensioLabs\Deptrac\AstRunner\AstMap;

class AstClassReference
{
    /** @var ClassLikeName */
    private $classLikeName;

    /** @var AstFileReference|null */
    private $fileReference;

    /** @var AstDependency[] */
    private $dependencies;

    /** @var AstInherit[] */
    private $inherits;

    /**
     * @param AstInherit[]    $inherits
     * @param AstDependency[] $dependencies
     */
    public function __construct(ClassLikeName $classLikeName, array $inherits = [], array $dependencies = [])
    {
        $this->classLikeName = $classLikeName;
        $this->dependencies = $dependencies;
        $this->inherits = $inherits;
    }

    public function withFileReference(AstFileReference $astFileReference): self
    {
        $instance = clone $this;
        $instance->fileReference = $astFileReference;

        return $instance;
    }

    public function getFileReference(): ?AstFileReference
    {
        return $this->fileReference;
    }

    public function getClassLikeName(): ClassLikeName
    {
        return $this->classLikeName;
    }

    /**
     * @return AstDependency[]
     */
    public function getDependencies(): array
    {
        return $this->dependencies;
    }

    /**
     * @return AstInherit[]
     */
    public function getInherits(): array
    {
        return $this->inherits;
    }
}


text:
using System;
using System.ComponentModel;

namespace Azure.ResourceManager.DataMigration.Models
{
    /// <summary> The state of the task. This is ignored if submitted. </summary>
    public readonly partial struct TaskState : IEquatable<TaskState>
    {
        private readonly string _value;

        /// <summary> Initializes a new instance of <see cref="TaskState"/>. </summary>
        /// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception>
        public TaskState(string value)
        {
            _value = value ?? throw new ArgumentNullException(nameof(value));
        }

        private const string UnknownValue = "Unknown";
        private const string QueuedValue = "Queued";
        private const string RunningValue = "Running";
        private const string CanceledValue = "Canceled";
        private const string SucceededValue = "Succeeded";
        private const string FailedValue = "Failed";
        private const string FailedInputValidationValue = "FailedInputValidation";
        private const string FaultedValue = "Faulted";

        /// <summary> Unknown. </summary>
        public static TaskState Unknown { get; } = new TaskState(UnknownValue);
        /// <summary> Queued. </summary>
        public static TaskState Queued { get; } = new TaskState(QueuedValue);
        /// <summary> Running. </summary>
        public static TaskState Running { get; } = new TaskState(RunningValue);
        /// <summary> Canceled. </summary>
        public static TaskState Canceled { get; } = new TaskState(CanceledValue);
        /// <summary> Succeeded. </summary>
        public static TaskState Succeeded { get; } = new TaskState(SucceededValue);
        /// <summary> Failed. </summary>
        public static TaskState Failed { get; } = new TaskState(FailedValue);
        /// <summary> FailedInputValidation. </summary>
        public static TaskState FailedInputValidation { get; } = new TaskState(FailedInputValidationValue);
        /// <summary> Faulted. </summary>
        public static TaskState Faulted { get; } = new TaskState(FaultedValue);
        /// <summary> Determines if two <see cref="TaskState"/> values are the same. </summary>
        public static bool operator ==(TaskState left, TaskState right) => left.Equals(right);
        /// <summary> Determines if two <see cref="TaskState"/> values are not the same. </summary>
        public static bool operator !=(TaskState left, TaskState right) => !left.Equals(right);
        /// <summary> Converts a string to a <see cref="TaskState"/>. </summary>
        public static implicit operator TaskState(string value) => new TaskState(value);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override bool Equals(object obj) => obj is TaskState other && Equals(other);
        /// <inheritdoc />
        public bool Equals(TaskState other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override int GetHashCode() => _value?.GetHashCode() ?? 0;
        /// <inheritdoc />
        public override string ToString() => _value;
    }
}


text:
<?php

namespace WonderPush\Obj;

if (count(get_included_files()) === 1) { http_response_code(403); exit(); } // Prevent direct access

/**
 * DTO part for `notification.push.android`.
 * @see NotificationPush
 * @codeCoverageIgnore
 */
class NotificationPushAndroid extends NotificationPush {

  /** @var boolean */
  private $delayWhileIdle;
  /** @var string */
  private $collapseKey;
  /** @var string */
  private $restrictedPackageName;

  /**
   * @return boolean
   */
  public function getDelayWhileIdle() {
    return $this->delayWhileIdle;
  }

  /**
   * @param boolean $delayWhileIdle
   * @return $this
   */
  public function setDelayWhileIdle($delayWhileIdle) {
    $this->delayWhileIdle = $delayWhileIdle;
    return $this;
  }

  /**
   * @return string
   */
  public function getCollapseKey() {
    return $this->collapseKey;
  }

  /**
   * @param string $collapseKey
   * @return $this
   */
  public function setCollapseKey($collapseKey) {
    $this->collapseKey = $collapseKey;
    return $this;
  }

  /**
   * @return string
   */
  public function getRestrictedPackageName() {
    return $this->restrictedPackageName;
  }

  /**
   * @param string $restrictedPackageName
   * @return $this
   */
  public function setRestrictedPackageName($restrictedPackageName) {
    $this->restrictedPackageName = $restrictedPackageName;
    return $this;
  }

}


text:
package org.keycloak.sessions;

import java.util.Map;

import org.keycloak.models.ClientModel;
import org.keycloak.models.RealmModel;
import org.keycloak.storage.SearchableModelField;

/**
 * Represents usually one browser session with potentially many browser tabs. Every browser tab is represented by
 * {@link AuthenticationSessionModel} of different client.
 *
 * @author Marek Posolda
 */
public interface RootAuthenticationSessionModel {

    public static class SearchableFields {
        public static final SearchableModelField<RootAuthenticationSessionModel> ID              = new SearchableModelField<>("id", String.class);
        public static final SearchableModelField<RootAuthenticationSessionModel> REALM_ID        = new SearchableModelField<>("realmId", String.class);
        public static final SearchableModelField<RootAuthenticationSessionModel> TIMESTAMP       = new SearchableModelField<>("timestamp", Long.class);
    }

    /**
     * Returns id of the root authentication session.
     * @return {@code String}
     */
    String getId();

    /**
     * Returns realm associated to the root authentication session.
     * @return {@code RealmModel}
     */
    RealmModel getRealm();

    /**
     * Returns timestamp when the root authentication session was created or updated.
     * @return {@code int}
     */
    int getTimestamp();

    /**
     * Sets a timestamp when the root authentication session was created or updated.
     * @param timestamp {@code int}
     */
    void setTimestamp(int timestamp);

    /**
     * Returns authentication sessions for the root authentication session.
     * Key is tabId, Value is AuthenticationSessionModel.
     * @return {@code Map<String, AuthenticationSessionModel>} authentication sessions or empty map if no
     * authentication sessions are present. Never return null.
     */
    Map<String, AuthenticationSessionModel> getAuthenticationSessions();

    /**
     * Returns an authentication session for the particular client and tab or null if it doesn't yet exists.
     * @param client {@code ClientModel} If {@code null} is provided the method will return {@code null}.
     * @param tabId {@code String} If {@code null} is provided the method will return {@code null}.
     * @return {@code AuthenticationSessionModel} or {@code null} in no authentication session is found.
     */
    AuthenticationSessionModel getAuthenticationSession(ClientModel client, String tabId);

    /**
     * Create a new authentication session and returns it. Overwrites existing session for particular client if already exists.
     * @param client {@code ClientModel} Can't be {@code null}.
     * @return {@code AuthenticationSessionModel} non-null fresh authentication session. Never returns {@code null}.
     */
    AuthenticationSessionModel createAuthenticationSession(ClientModel client);

    /**
     * Removes the authentication session specified by tab id from the root authentication session.
     * If there's no child authentication session left in the root authentication session, it's removed as well.
     * @param tabId {@code String} Can't be {@code null}.
     */
    void removeAuthenticationSessionByTabId(String tabId);

    /**
     * Will completely restart whole state of authentication session. It will just keep same ID. It will setup it with provided realm.
     * @param realm {@code RealmModel} Associated realm to the root authentication session.
     */
    void restartSession(RealmModel realm);

}


text:
title: Telerik.Pdf.PdfPageTree
page_title: Telerik.Pdf.PdfPageTree
description: Telerik.Pdf.PdfPageTree
---

# Telerik.Pdf.PdfPageTree

The pages of a document are accessed through a structure known
                as the page tree.

#### Remarks
The page tree is described in section 3.6.2 of the PDF specification.

## Inheritance Hierarchy

* System.Object
* Telerik.Pdf.PdfObject
* Telerik.Pdf.PdfDictionary : IEnumerable
* Telerik.Pdf.PdfPageTree


text:
package swarm.server.thirdparty.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import swarm.server.account.ServerAccountManager;
import swarm.server.app.A_ServerApp;
import swarm.server.app.A_ServerJsonFactory;
import swarm.server.app.ServerContext;
import swarm.server.session.SessionManager;

@SuppressWarnings("serial")
public abstract class A_BaseServlet extends HttpServlet
{
	@Override
	public void init()
	{

	}

	private void startScope()
	{
		ServerContext context = A_ServerApp.getInstance().getContext();

		SessionManager sessionMngr = context.sessionMngr;
		sessionMngr.onEnterScope();
		((A_ServerJsonFactory)context.jsonFactory).startScope(true);
	}

	private void endScope()
	{
		ServerContext context = A_ServerApp.getInstance().getContext();

		SessionManager sessionMngr = context.sessionMngr;
		((A_ServerJsonFactory)context.jsonFactory).endScope();
		sessionMngr.onExitScope();
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
	{
		startScope();

		try
		{
			doGetOrPost(req, resp, true);
		}
		finally
		{
			endScope();
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
	{
		startScope();
		try
		{
			doGetOrPost(req, resp, false);
		}
		finally
		{
			endScope();
		}
	}

	protected abstract void doGetOrPost(HttpServletRequest nativeRequest, HttpServletResponse nativeResponse, boolean isGet) throws ServletException, IOException;
}


text:
package com.mmnaseri.utils.spring.data.domain;

import com.mmnaseri.utils.spring.data.store.DataStore;

/**
 * This interface is used to inject {@link DataStore the data store} into a concrete class aiming to
 * provide method mapping for a repository.
 *
 * @author Milad Naseri (m.m.naseri@gmail.com)
 * @since 1.0 (9/29/15)
 */
public interface DataStoreAware<E, K> {

  <J extends K, F extends E> void setDataStore(DataStore<J, F> dataStore);
}


text:
<?php

/**
 * This is the model class for table "{{specification}}".
 *
 * The followings are the available columns in table '{{specification}}':
 * @property integer $spec_id
 * @property string $spec_name
 * @property string $spec_show_type
 * @property string $spec_type
 * @property string $spec_memo
 * @property integer $sort_order
 * @property string $disabled
 */
class Specification extends CActiveRecord {

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Specification the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return '{{specification}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('spec_name', 'required'),
            array('sort_order', 'numerical', 'integerOnly' => true),
            array('spec_name, spec_memo', 'length', 'max' => 50),
            array('spec_show_type', 'length', 'max' => 6),
            array('spec_type, disabled', 'length', 'max' => 5),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('spec_id, spec_name, spec_show_type, spec_type, spec_memo, sort_order, disabled', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'spec_id' => 'ID',
            'spec_name' => '规格名称',
            'spec_show_type' => '显示方式',
            'spec_type' => '类型',
            'spec_memo' => '规格备注',
            'spec.spec_value' => '规格值',
            'sort_order' => '排序',
            'disabled' => '禁用',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search() {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('spec_id', $this->spec_id);
        $criteria->compare('spec_name', $this->spec_name, true);
        $criteria->compare('spec_show_type', $this->spec_show_type, true);
        $criteria->compare('spec_type', $this->spec_type, true);
        $criteria->compare('spec_memo', $this->spec_memo, true);
        $criteria->compare('sort_order', $this->sort_order);
        $criteria->compare('disabled', $this->disabled, true);

        return new CActiveDataProvider($this, array(
                    'criteria' => $criteria,
                ));
    }

    public function getShowType() {
        if ($this->spec_show_type == 'select') {
            echo '下拉';
        } elseif ($this->spec_show_type == 'flat') {
            echo '平铺';
        }
    }

    public function getType() {
        if ($this->spec_type == 'text') {
            echo '文字';
        } elseif ($this->spec_type == 'image') {
            echo '图片';
        }
    }

    public function getDisabled() {
        if ($this->disabled == 'false') {
            echo '否';
        } elseif ($this->disabled == 'true') {
            echo '是';
        }
    }

    /*
     * 循环遍历SpecValue[spec_value][]插入数据库
     * 群Zend Framework(95700611) zwp(279795206)友情提示
     */

    public function setSpecValues($SpecValues) {
        $db = Yii::app()->db;
        $db->createCommand()->delete('{{spec_values}}', 'spec_id = :spec_id', array(
            ':spec_id' => $this->spec_id));

        if ($SpecValues['spec_value'] != '') {
            for ($i = 0; $i < count($SpecValues['spec_value']); $i++) {
                $db->createCommand()->insert('{{spec_values}}', array(
                    'spec_id' => $this->spec_id,
                    'spec_value' => $SpecValues['spec_value'][$i],
                    'spec_image' => $SpecValues['spec_image'][$i],
                    'sort_order' => $SpecValues['sort_order'][$i],
                ));
            }
        }
    }

    public function getSpecValues() {
        $cri = new CDbCriteria(array(
                    'condition' => 'spec_id =' . $this->spec_id,
                    'order' => 'sort_order asc, spec_value_id asc'
                ));
        $SpecValues = SpecValue::model()->findAll($cri);

        foreach ($SpecValues as $sv) {
            echo $sv->spec_value.',';
        }
    }

}


text:
int Factorial(int n);

// Returns true iff n is a prime number.
bool IsPrime(int n);


text:
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>org.discotools.gwt.leaflet</groupId>
		<artifactId>gwtl</artifactId>
		<version>0.4-SNAPSHOT</version>
	</parent>

	<artifactId>gwtl-ellipse</artifactId>
	<name>gwtl-ellipse</name>
	<packaging>jar</packaging>

	<dependencies>
		<!-- Google Window Toolkit (GWT) -->
		<dependency>
			<groupId>com.google.gwt</groupId>
			<artifactId>gwt-user</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>

		<!-- GWT Leaflet dependencies -->
		<dependency>
			<groupId>org.discotools.gwt.leaflet</groupId>
			<artifactId>gwtl-core</artifactId>
			<version>0.4-SNAPSHOT</version>
		</dependency>

	</dependencies>

	<build>
		<!-- Generate compiled stuff in the folder used for developing mode -->
		<outputDirectory>${project.build.directory}/${project.build.finalName}/WEB-INF/classes</outputDirectory>

		<plugins>

			<!-- GWT Maven Plugin -->
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>gwt-maven-plugin</artifactId>
			</plugin>

			<!-- Copy static web files before executing gwt:run -->
			<plugin>
				<artifactId>maven-resources-plugin</artifactId>
			</plugin>

		</plugins>
	</build>

</project>


text:
FROM ubuntu:trusty
MAINTAINER Boris Gorbylev <ekho@ekho.name>

ADD http://download-lb.utorrent.com/endpoint/btsync/os/linux-x64/track/stable /btsync.tar.gz
ADD start.sh /start.sh

ENV LANG en_US.UTF-8
RUN locale-gen $LANG && \
    tar xf /btsync.tar.gz && \
    rm /btsync.tar.gz

VOLUME ["/data"]
EXPOSE 3369/udp 8888

CMD ["/start.sh"]


text:
package derpatiel.manafluidics.spell.cantrip;

import derpatiel.manafluidics.spell.BlockTargetedSpell;
import derpatiel.manafluidics.spell.SpellAttribute;
import derpatiel.manafluidics.spell.parameters.SpellParameterChoices;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.SoundEvents;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;

import java.util.Collection;

public class SetFlame extends BlockTargetedSpell {
    public SetFlame() {
        super("setflame",0, 5, SpellAttribute.FIRE,SpellAttribute.EVOCATION);
    }

    @Override
    public boolean doCastOnHit(BlockPos hitBlock, EnumFacing hitFace, World world, EntityPlayer player, boolean boosted, Collection<SpellParameterChoices> parameters) {
        BlockPos adjBlockPos = hitBlock.offset(hitFace);
        IBlockState state = world.getBlockState(adjBlockPos);
        if (state.getMaterial() == Material.AIR) {
            world.playSound(player, adjBlockPos, SoundEvents.ITEM_FLINTANDSTEEL_USE, SoundCategory.BLOCKS, 1.0F, 0.4F + 0.8F);
            world.setBlockState(adjBlockPos, Blocks.FIRE.getDefaultState(), 11);
            return true;
        }
        return false;
    }

}


text:
import Ember from 'ember';
import resolver from './helpers/resolver';
import {
  setResolver
} from 'ember-qunit';

var run = Ember.run;

function focus(el) {
  if (el && el.is(':input, [contenteditable=true]')) {
    var type = el.prop('type');
    if (type !== 'checkbox' && type !== 'radio' && type !== 'hidden') {
      run(el, function() {
        // Firefox does not trigger the `focusin` event if the window
        // does not have focus. If the document doesn't have focus just
        // use trigger('focusin') instead.
        if (!document.hasFocus || document.hasFocus()) {
          this.focus();
        } else {
          this.trigger('focusin');
        }
      });
    }
  }
}

function fillInWithInputEvent(app, selector, contextOrText, textOrEvents, event) {
  var $el, context, text;

  if (typeof event === 'undefined') {
    context = null;
    text = contextOrText;
    event = textOrEvents;
  } else {
    context = contextOrText;
    text = textOrEvents;
  }

  $el = app.testHelpers.findWithAssert(selector, context);

  $el.val('');

  focus($el);

  function fillInWithEvent(character) {
    var val = $el.val();
    var charCode = character.charCodeAt(0);

    val += character;

    run(function() {
      $el.val(val).change();
    });

    run($el, "trigger", event, { keyCode: charCode, which: charCode });
  }

  for (var i = 0, l = text.length; i < l; i++) {
    fillInWithEvent(text[i]);
  }

  return app.testHelpers.wait();
}

Ember.Test.registerAsyncHelper('fillInWithInputEvent', fillInWithInputEvent);

setResolver(resolver);


text:
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <link rel="stylesheet" type="text/css" href="../css/aui.css" />

分享弹出框


text:
<!DOCTYPE html>

  <title>SchoolHero</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

				Descubre tu perfil academico y se parte de nuestra comunidad

       Realizar Test

Twitter

Facebook

Google Plus


text:
'use strict';

const cache = require('../lib/cache.js')();

/* eslint no-unused-expressions: 1 */

describe('cache', () => {
  it('should put and retrieve element from the cache', () => {
    const expectedElement = 'element';

    cache.cache(1, expectedElement);
    const actualElement = cache.find(1);

    expect(actualElement).to.be.equal(expectedElement);
  });
});


text:
from cumulusci.core.exceptions import ApexCompilationException
from cumulusci.core.exceptions import ApexException
from cumulusci.core.exceptions import SalesforceException
from cumulusci.core.exceptions import TaskOptionsError
from cumulusci.core.utils import process_bool_arg
from cumulusci.tasks.salesforce import BaseSalesforceApiTask
from cumulusci.utils import in_directory, inject_namespace
from cumulusci.utils.http.requests_utils import safe_json_from_response

class AnonymousApexTask(BaseSalesforceApiTask):
    """ Executes anonymous apex from a file or string."""

    task_docs = """
    Use the `apex` option to run a string of anonymous Apex.
    Use the `path` option to run anonymous Apex from a file.
    Or use both to concatenate the string to the file contents.
    """

    task_options = {
        "path": {"description": "The path to an Apex file to run.", "required": False},
        "apex": {
            "description": "A string of Apex to run (after the file, if specified).",
            "required": False,
        },
        "managed": {
            "description": (
                "If True, will insert the project's namespace prefix.  "
                "Defaults to False or no namespace."
            ),
            "required": False,
        },
        "namespaced": {
            "description": (
                "If True, the tokens %%%NAMESPACED_RT%%% and %%%namespaced%%% "
                "will get replaced with the namespace prefix for Record Types."
            ),
            "required": False,
        },
        "param1": {
            "description": (
                "Parameter to pass to the Apex. Use as %%%PARAM_1%%% in the Apex code."
                "Defaults to an empty value."
            ),
            "required": False,
        },
        "param2": {
            "description": (
                "Parameter to pass to the Apex. Use as %%%PARAM_2%%% in the Apex code."
                "Defaults to an empty value."
            ),
            "required": False,
        },
    }

    def _validate_options(self):
        super(AnonymousApexTask, self)._validate_options()

        if not self.options.get("path") and not self.options.get("apex"):
            raise TaskOptionsError(
                "You must specify either the `path` or `apex` option."
            )

    def _run_task(self):
        apex = ""
        apex_path = self.options.get("path")
        if apex_path:
            if not in_directory(apex_path, self.project_config.repo_root):
                raise TaskOptionsError(
                    "Please specify a path inside your project repository. "
                    "You specified: {}".format(apex_path)
                )
            self.logger.info("Executing anonymous Apex from {}".format(apex_path))
            try:
                with open(apex_path, "r", encoding="utf-8") as f:
                    apex = f.read()
            except IOError:
                raise TaskOptionsError(
                    "Could not find or read file: {}".format(apex_path)
                )
        else:
            self.logger.info("Executing anonymous Apex")

        apex_string = self.options.get("apex")
        if apex_string:
            apex = apex + "\n" + apex_string

        apex = self._prepare_apex(apex)
        result = self.tooling._call_salesforce(
            method="GET",
            url="{}executeAnonymous".format(self.tooling.base_url),
            params={"anonymousBody": apex},
        )
        self._check_result(result)

        self.logger.info("Anonymous Apex Success")

    def _prepare_apex(self, apex):
        # Process namespace tokens
        namespace = self.project_config.project__package__namespace
        if "managed" in self.options:
            managed = process_bool_arg(self.options["managed"])
        else:
            managed = (
                bool(namespace) and namespace in self.org_config.installed_packages
            )
        if "namespaced" in self.options:
            namespaced = process_bool_arg(self.options["namespaced"])
        else:
            namespaced = bool(namespace) and namespace == self.org_config.namespace

        _, apex = inject_namespace(
            "",
            apex,
            namespace=namespace,
            managed=managed,
            namespaced_org=namespaced,
        )

        # This is an extra token which is not handled by inject_namespace.
        apex = apex.replace(
            "%%%NAMESPACED_RT%%%", namespace + "." if namespaced else ""
        )

        # Process optional parameter token replacement
        param1 = self.options.get("param1") or ""
        apex = apex.replace("%%%PARAM_1%%%", param1)
        param2 = self.options.get("param2") or ""
        apex = apex.replace("%%%PARAM_2%%%", param2)

        return apex

    def _check_result(self, result):
        # anon_results is an ExecuteAnonymous Result
        # https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/sforce_api_calls_executeanonymous_result.htm
        anon_results = safe_json_from_response(result)

        # A result of `None` (body == "null") with a 200 status code
        # means that a gack occurred.
        if anon_results is None:
            raise SalesforceException(
                "Anonymous Apex returned the result `null`. "
                "This often indicates a gack occurred."
            )
        if not anon_results["compiled"]:
            raise ApexCompilationException(
                anon_results["line"], anon_results["compileProblem"]
            )
        if not anon_results["success"]:
            raise ApexException(
                anon_results["exceptionMessage"], anon_results["exceptionStackTrace"]
            )


text:
"use strict" ;

const doormen = require( 'doormen' ) ;
const Attachment = require( './Attachment.js' ) ;
const AttachmentSet = require( './AttachmentSet.js' ) ;
const Document = require( './Document.js' ) ;

// /!\ Forced to do that ATM... because of multiLink, needing a true MongoDB object ID
const mongodb = require( 'mongodb' ) ;

function checkObjectId( data ) {
	if ( data && typeof data === 'object' && ( data.constructor.name === 'ObjectID' || data.constructor.name === 'ObjectId' ) ) {
		return true ;
	}

	return typeof data === 'string' && ( data === '/' || ( data.length === 24 && /^[0-9a-f]{24}$/.test( data ) ) ) ;
}

function checkLink( data , schema ) {
	//console.log( "checkLink:" , data ) ;
	if ( data === undefined || data === null ) { return true ; }
	if ( typeof data !== 'object' ) { return false ; }
	if ( ! schema.anyCollection ) { return checkObjectId( data._id ) ; }
	return data._collection && typeof data._collection === 'string' && checkObjectId( data._id ) ;
}

function checkRequiredLink( data ) {
	//console.log( "checkRequiredLink:" , data ) ;
	if ( ! data ) { return false ; }
	if ( typeof data !== 'object' ) { return false ; }
	return checkObjectId( data._id ) ;
}

function checkMultiLink( data ) {
	// Now it's done using:   of: { type: 'link' } and constraints, as override, see "typeOverrides" in Collection.js
	return Array.isArray( data ) ;
}

const backLinkSchema = {
	type: 'object' ,
	optional: true ,
	properties: {
		batch: {
			optional: true ,
			type: 'array' ,
			of: { type: 'object' }
		}
	}
} ;

// /!\ This is sub-optimal! Filename should filter bad name, contentType should check for valid content-type
const attachmentSchema = {
	type: 'object' ,
	properties: {
		id: { type: 'string' } ,
		filename: { type: 'string' } ,
		extension: { type: 'string' } ,
		contentType: { type: 'string' } ,
		fileSize: { optional: true , type: 'integer' } ,
		hash: { optional: true , type: 'string' } ,
		hashType: { optional: true , type: 'string' } ,
		metadata: { type: 'object' , default: {} }
	}
} ;

const attachmentSetSchema = {
	type: 'object' ,
	properties: {
		attachments: { type: 'object' , of: attachmentSchema } ,
		metadata: { type: 'object' , default: {} }
	}
} ;

doormen.extendTypeCheckers( {
	"objectId": checkObjectId ,
	"link": checkLink ,
	"requiredLink": checkRequiredLink ,
	"multiLink": checkMultiLink ,
	"backLink": data => {
		try {
			doormen( backLinkSchema , data ) ;
			return true ;
		}
		catch ( error ) {
			return false ;
		}
	} ,
	"attachment": data => {
		if ( data instanceof Attachment ) { return true ; }

		try {
			doormen( attachmentSchema , data ) ;
			return true ;
		}
		catch ( error ) {
			return false ;
		}
	} ,
	"attachmentSet": data => {
		if ( data instanceof AttachmentSet ) { return true ; }

		try {
			doormen( attachmentSetSchema , data ) ;
			return true ;
		}
		catch ( error ) {
			return false ;
		}
	}
} ) ;

// Allow one to pass the whole linked target object
function toObjectId( data ) {
	if ( typeof data === 'string' ) {
		try {
			return mongodb.ObjectID( data ) ;
		}
		catch ( error ) {}
	}

	return data ;
}

const LINK_INNER_PROPERTIES = new Set( [ '_id' , '_collection' ] ) ;

// Allow one to pass the whole linked target object
function toLink( data , schema ) {
	if ( data && typeof data === 'object' ) {
		if ( data.constructor.name === 'ObjectID' || data.constructor.name === 'ObjectId' ) {
			return { _id: data } ;
		}

		if ( data._ && ( data._ instanceof Document ) ) {
			data = schema.anyCollection ?
				{ _id: toObjectId( data._id ) , _collection: data._.collection && data._.collection.name } :
				{ _id: toObjectId( data._id ) } ;
		}
		else if ( data instanceof Document ) {
			data = schema.anyCollection ?
				{ _id: toObjectId( data.raw._id ) , _collection: data.collection && data.collection.name } :
				{ _id: toObjectId( data.raw._id ) } ;
		}
		else {
			// Remove extra properties? Or create a new object?
			data._id = toObjectId( data._id ) ;
			for ( let key in data ) {
				if ( ! LINK_INNER_PROPERTIES.has( key ) ) { delete data[ key ] ; }
			}

			/*
			data = schema.anyCollection ?
				{ _id: toObjectId( data._id ) , _collection: data._collection } :
				{ _id: toObjectId( data._id ) } ;
			*/
		}
	}
	else if ( typeof data === 'string' ) {
		try {
			data = { _id: mongodb.ObjectID( data ) } ;
		}
		catch ( error ) {}
	}

	return data ;
}

// Allow one to pass the whole array (batch) of linked target object
function toMultiLink( data ) {
	// Now it's done using:   of: { type: 'link' , sanitize: 'toLink' } and constraints
	if ( ! data ) { return [] ; }
	if ( ! Array.isArray( data ) ) { return [ data ] ; }
	return data ;
}

function toBackLink( data ) {
	if ( ! data || typeof data !== 'object' ) {
		return {} ;
	}

	if ( Array.isArray( data ) ) { data = { batch: data } ; }

	return data ;
}

doormen.extendSanitizers( {
	"toObjectId": toObjectId ,
	"toLink": toLink ,
	"toMultiLink": toMultiLink ,
	"toBackLink": toBackLink ,
	"toBackMultiLink": toBackLink
} ) ;


text:
package org.jbpm.workbench.es.client.editors.errorlist;

import com.google.gwtmockito.GwtMockitoTestRunner;
import org.jbpm.workbench.common.client.filters.basic.AbstractBasicFiltersPresenterTest;
import org.jbpm.workbench.es.client.i18n.Constants;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.InjectMocks;

import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.*;

@RunWith(GwtMockitoTestRunner.class)
public class ExecutionErrorListBasicFiltersPresenterTest extends AbstractBasicFiltersPresenterTest {

    @InjectMocks
    ExecutionErrorListBasicFiltersPresenter presenter;

    @Override
    public ExecutionErrorListBasicFiltersPresenter getPresenter() {
        return presenter;
    }

    @Override
    @Test
    public void testLoadFilters() {
        presenter.loadFilters();

        final InOrder inOrder = inOrder(getView());

        inOrder.verify(getView()).addNumericFilter(eq(Constants.INSTANCE.Process_Instance_Id()),
                                                   any(),
                                                   any());
        inOrder.verify(getView()).addNumericFilter(eq(Constants.INSTANCE.JobId()),
                                                   any(),
                                                   any());
        inOrder.verify(getView()).addTextFilter(eq(Constants.INSTANCE.Id()),
                                                any(),
                                                any());
        inOrder.verify(getView()).addMultiSelectFilter(eq(Constants.INSTANCE.Type()),
                                                       any(),
                                                       any());
        inOrder.verify(getView()).addSelectFilter(eq(Constants.INSTANCE.Acknowledged()),
                                                  any(),
                                                  any());
        inOrder.verify(getView()).addDateRangeFilter(eq(Constants.INSTANCE.ErrorDate()),
                                                     any(),
                                                     any(),
                                                     any());
    }
}


text:
package io.undertow.spdy;

import org.xnio.Pool;

import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * Parser that supports push back when not all data can be read.
 *
 * @author Stuart Douglas
 */
public abstract class PushBackParser {

    private final Pool<ByteBuffer> bufferPool;
    private byte[] pushedBackData;
    private boolean finished;
    protected int streamId = -1;
    private int remainingData;

    public PushBackParser(Pool<ByteBuffer> bufferPool, int frameLength) {
        this.bufferPool = bufferPool;
        this.remainingData = frameLength;
    }

    public void parse(ByteBuffer data) throws IOException {
        int used = 0;
        ByteBuffer dataToParse = data;
        int oldLimit = dataToParse.limit();
        try {
            if (pushedBackData != null) {
                dataToParse = ByteBuffer.wrap(new byte[pushedBackData.length + data.remaining()]);
                dataToParse.put(pushedBackData);
                dataToParse.put(data);
                dataToParse.flip();
                oldLimit = dataToParse.limit();
            }
            if(dataToParse.remaining() > remainingData) {
                dataToParse.limit(dataToParse.position() + remainingData);
            }
            int rem = dataToParse.remaining();
            handleData(dataToParse);
            used = rem - dataToParse.remaining();

        } finally {
            int leftOver = dataToParse.remaining();
            if(leftOver > 0) {
                pushedBackData = new byte[leftOver];
                dataToParse.get(pushedBackData);
            } else {
                pushedBackData = null;
            }
            dataToParse.limit(oldLimit);
            remainingData -= used;
            if(remainingData == 0) {
                finished = true;
                finished();
            }
        }
    }

    protected void finished() throws IOException {

    }

    protected abstract void handleData(ByteBuffer resource) throws IOException;

    public boolean isFinished() {
        return finished;
    }

    public int getStreamId() {
        return streamId;
    }
}


text:
require 'test_helper'

class LocaleTest < ActiveSupport::TestCase
  test "turning locale without nested phrases into a hash" do
    assert_equal({ "se" => { "hello_world" => "Hejsan Verdon" } }, tolk_locales(:se).to_hash)
  end

  test "turning locale with nested phrases into a hash" do
    assert_equal({ "en" => {
      "number"=>{"human"=>{"format"=>{"precision"=>1}}},
      "hello_world" => "Hello World",
      "nested" => {
        "hello_world" => "Nested Hello World",
        "hello_country" => "Nested Hello Country"
      }
    }}, tolk_locales(:en).to_hash)
  end

  test "phrases without translations" do
    assert tolk_locales(:en).phrases_without_translation.include?(tolk_phrases(:cozy))
  end

  test "searching phrases without translations" do
    # assert tolk_locales(:en).search_phrases_without_translation("cozy").include?(tolk_phrases(:cozy))
    assert !tolk_locales(:en).search_phrases_without_translation("cozy").include?(tolk_phrases(:hello_world))
  end

  test "paginating phrases without translations" do
    Tolk::Phrase.per_page = 2
    locale = tolk_locales(:se)

    page1 = locale.phrases_without_translation
    assert_equal [4, 3], page1.map(&:id)

    page2 = locale.phrases_without_translation(2)
    assert_equal [2, 5], page2.map(&:id)

    page3 = locale.phrases_without_translation(3)
    assert page3.blank?
  end

  test "paginating phrases with translations" do
    Tolk::Phrase.per_page = 4
    locale = tolk_locales(:en)

    page1 = locale.phrases_with_translation
    assert_equal [1, 3, 2, 5], page1.map(&:id)

    page2 = locale.phrases_with_translation(2)
    assert page2.blank?
  end

  test "counting missing translations" do
    assert_equal 2, tolk_locales(:da).count_phrases_without_translation
    assert_equal 4, tolk_locales(:se).count_phrases_without_translation
  end

  test "dumping all locales to yml" do
    Tolk::Locale.primary_locale_name = 'en'
    Tolk::Locale.primary_locale(true)

    begin
      FileUtils.mkdir_p(File.join(Rails.root, "tmp/locales"))
      Tolk::Locale.dump_all(File.join(Rails.root, "tmp/locales"))

      %w( da se ).each do |locale|
        assert_equal \
          File.read(File.join(Rails.root, "test/locales/basic/#{locale}.yml")),
          File.read(File.join(Rails.root, "tmp/locales/#{locale}.yml"))
      end

      # Make sure dump doesn't generate en.yml
      assert ! File.exists?(File.join(Rails.root, "tmp/locales/en.yml"))
    ensure
      FileUtils.rm_rf(File.join(Rails.root, "tmp/locales"))
    end
  end

  test "human language name" do
    assert_equal 'English', tolk_locales(:en).language_name
    assert_equal 'pirate', Tolk::Locale.new(:name => 'pirate').language_name
  end
end


text:
package rx.internal.operators;

import java.util.*;

import rx.*;
import rx.Observable;
import rx.Observable.OnSubscribe;
import rx.Observer;
import rx.exceptions.Exceptions;
import rx.functions.*;
import rx.observers.*;
import rx.subjects.*;
import rx.subscriptions.*;

/**
 * Correlates two sequences when they overlap and groups the results.
 *
 * @see MSDN: Observable.GroupJoin
 * @param <T1> the left value type
 * @param <T2> the right value type
 * @param <D1> the value type of the left duration
 * @param <D2> the value type of the right duration
 * @param <R> the result value type
 */
public final class OnSubscribeGroupJoin<T1, T2, D1, D2, R> implements OnSubscribe<R> {
    final Observable<T1> left;
    final Observable<T2> right;
    final Func1<? super T1, ? extends Observable<D1>> leftDuration;
    final Func1<? super T2, ? extends Observable<D2>> rightDuration;
    final Func2<? super T1, ? super Observable<T2>, ? extends R> resultSelector;

    public OnSubscribeGroupJoin(
            Observable<T1> left,
            Observable<T2> right,
            Func1<? super T1, ? extends Observable<D1>> leftDuration,
            Func1<? super T2, ? extends Observable<D2>> rightDuration,
            Func2<? super T1, ? super Observable<T2>, ? extends R> resultSelector) {
        this.left = left;
        this.right = right;
        this.leftDuration = leftDuration;
        this.rightDuration = rightDuration;
        this.resultSelector = resultSelector;
    }

    @Override
    public void call(Subscriber<? super R> child) {
        ResultManager ro = new ResultManager(new SerializedSubscriber<R>(child));
        child.add(ro);
        ro.init();
    }

    /** Manages sub-observers and subscriptions. */
    final class ResultManager extends HashMap<Integer, Observer<T2>>implements Subscription {
        // HashMap aspect of `this` refers to `leftMap`

        private static final long serialVersionUID = -3035156013812425335L;

        final RefCountSubscription cancel;
        final Subscriber<? super R> subscriber;
        final CompositeSubscription group;
        /** Guarded by this. */
        int leftIds;
        /** Guarded by this. */
        int rightIds;
        /** Guarded by this. */
        final Map<Integer, T2> rightMap = new HashMap<Integer, T2>(); // NOPMD
        /** Guarded by this. */
        boolean leftDone;
        /** Guarded by this. */
        boolean rightDone;

        public ResultManager(Subscriber<? super R> subscriber) {
            super();
            this.subscriber = subscriber;
            this.group = new CompositeSubscription();
            this.cancel = new RefCountSubscription(group);
        }

        public void init() {

            Subscriber<T1> s1 = new LeftObserver();
            Subscriber<T2> s2 = new RightObserver();

            group.add(s1);
            group.add(s2);

            left.unsafeSubscribe(s1);
            right.unsafeSubscribe(s2);
        }

        @Override
        public void unsubscribe() {
            cancel.unsubscribe();
        }

        @Override
        public boolean isUnsubscribed() {
            return cancel.isUnsubscribed();
        }

        Map<Integer, Observer<T2>> leftMap() {
            return this;
        }

        /**
         * Notify everyone and cleanup.
         * @param e the exception
         */
        void errorAll(Throwable e) {
            List<Observer<T2>> list;
            synchronized (ResultManager.this) {
                list = new ArrayList<Observer<T2>>(leftMap().values());
                leftMap().clear();
                rightMap.clear();
            }
            for (Observer<T2> o : list) {
                o.onError(e);
            }
            subscriber.onError(e);
            cancel.unsubscribe();
        }
        /**
         * Notify only the main subscriber and cleanup.
         * @param e  the exception
         */
        void errorMain(Throwable e) {
            synchronized (ResultManager.this) {
                leftMap().clear();
                rightMap.clear();
            }
            subscriber.onError(e);
            cancel.unsubscribe();
        }
        void complete(List<Observer<T2>> list) {
            if (list != null) {
                for (Observer<T2> o : list) {
                    o.onCompleted();
                }
                subscriber.onCompleted();
                cancel.unsubscribe();
            }
        }

        /** Observe the left source. */
        final class LeftObserver extends Subscriber<T1> {
            @Override
            public void onNext(T1 args) {
                try {
                    int id;
                    Subject<T2, T2> subj = PublishSubject.create();
                    Observer<T2> subjSerial = new SerializedObserver<T2>(subj);

                    synchronized (ResultManager.this) {
                        id = leftIds++;
                        leftMap().put(id, subjSerial);
                    }

                    Observable<T2> window = Observable.create(new WindowObservableFunc<T2>(subj, cancel));

                    Observable<D1> duration = leftDuration.call(args);

                    Subscriber<D1> d1 = new LeftDurationObserver(id);
                    group.add(d1);
                    duration.unsafeSubscribe(d1);

                    R result = resultSelector.call(args, window);

                    List<T2> rightMapValues;
                    synchronized (ResultManager.this) {
                        rightMapValues = new ArrayList<T2>(rightMap.values());
                    }

                    subscriber.onNext(result);
                    for (T2 t2 : rightMapValues) {
                        subjSerial.onNext(t2);
                    }

                } catch (Throwable t) {
                    Exceptions.throwOrReport(t, this);
                }
            }

            @Override
            public void onCompleted() {
                List<Observer<T2>> list = null;
                synchronized (ResultManager.this) {
                    leftDone = true;
                    if (rightDone) {
                        list = new ArrayList<Observer<T2>>(leftMap().values());
                        leftMap().clear();
                        rightMap.clear();
                    }
                }
                complete(list);
            }

            @Override
            public void onError(Throwable e) {
                errorAll(e);
            }

        }

        /** Observe the right source. */
        final class RightObserver extends Subscriber<T2> {
            @Override
            public void onNext(T2 args) {
                try {
                    int id;
                    synchronized (ResultManager.this) {
                        id = rightIds++;
                        rightMap.put(id, args);
                    }
                    Observable<D2> duration = rightDuration.call(args);

                    Subscriber<D2> d2 = new RightDurationObserver(id);

                    group.add(d2);
                    duration.unsafeSubscribe(d2);

                    List<Observer<T2>> list;
                    synchronized (ResultManager.this) {
                        list = new ArrayList<Observer<T2>>(leftMap().values());
                    }
                    for (Observer<T2> o : list) {
                        o.onNext(args);
                    }
                } catch (Throwable t) {
                    Exceptions.throwOrReport(t, this);
                }
            }

            @Override
            public void onCompleted() {
                List<Observer<T2>> list = null;
                synchronized (ResultManager.this) {
                    rightDone = true;
                    if (leftDone) {
                        list = new ArrayList<Observer<T2>>(leftMap().values());
                        leftMap().clear();
                        rightMap.clear();
                    }
                }
                complete(list);
            }

            @Override
            public void onError(Throwable e) {
                errorAll(e);
            }
        }

        /** Observe left duration and apply termination. */
        final class LeftDurationObserver extends Subscriber<D1> {
            final int id;
            boolean once = true;

            public LeftDurationObserver(int id) {
                this.id = id;
            }

            @Override
            public void onCompleted() {
                if (once) {
                    once = false;
                    Observer<T2> gr;
                    synchronized (ResultManager.this) {
                        gr = leftMap().remove(id);
                    }
                    if (gr != null) {
                        gr.onCompleted();
                    }
                    group.remove(this);
                }
            }

            @Override
            public void onError(Throwable e) {
                errorMain(e);
            }

            @Override
            public void onNext(D1 args) {
                onCompleted();
            }
        }

        /** Observe right duration and apply termination. */
        final class RightDurationObserver extends Subscriber<D2> {
            final int id;
            boolean once = true;
            public RightDurationObserver(int id) {
                this.id = id;
            }

            @Override
            public void onCompleted() {
                if (once) {
                    once = false;
                    synchronized (ResultManager.this) {
                        rightMap.remove(id);
                    }
                    group.remove(this);
                }
            }

            @Override
            public void onError(Throwable e) {
                errorMain(e);
            }

            @Override
            public void onNext(D2 args) {
                onCompleted();
            }
        }

    }

    /**
     * The reference-counted window observable.
     * Subscribes to the underlying Observable by using a reference-counted
     * subscription.
     */
    final static class WindowObservableFunc<T> implements OnSubscribe<T> {
        final RefCountSubscription refCount;
        final Observable<T> underlying;

        public WindowObservableFunc(Observable<T> underlying, RefCountSubscription refCount) {
            this.refCount = refCount;
            this.underlying = underlying;
        }

        @Override
        public void call(Subscriber<? super T> t1) {
            Subscription ref = refCount.get();
            WindowSubscriber wo = new WindowSubscriber(t1, ref);
            wo.add(ref);

            underlying.unsafeSubscribe(wo);
        }

        /** Observe activities on the window. */
        final class WindowSubscriber extends Subscriber<T> {
            final Subscriber<? super T> subscriber;
            private final Subscription ref;

            public WindowSubscriber(Subscriber<? super T> subscriber, Subscription ref) {
                super(subscriber);
                this.subscriber = subscriber;
                this.ref = ref;
            }

            @Override
            public void onNext(T args) {
                subscriber.onNext(args);
            }

            @Override
            public void onError(Throwable e) {
                subscriber.onError(e);
                ref.unsubscribe();
            }

            @Override
            public void onCompleted() {
                subscriber.onCompleted();
                ref.unsubscribe();
            }
        }
    }
}