text:
SYNONYM

#### According to
Index Fungorum

#### Published in
Mém. Soc. Imp. Sci. Nat. Cherbourg 3: 182 (1855)

#### Original name
Lichen exanthemicus Sm.

### Remarks
null


text:
#ifndef TENSORFLOW_KERNELS_CONDITIONAL_ACCUMULATOR_BASE_OP_H_
#define TENSORFLOW_KERNELS_CONDITIONAL_ACCUMULATOR_BASE_OP_H_

#define EIGEN_USE_THREADS

#include "tensorflow/core/kernels/conditional_accumulator_base.h"

#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/resource_mgr.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/thread_annotations.h"
#include "tensorflow/core/platform/types.h"

typedef Eigen::ThreadPoolDevice CPUDevice;

typedef std::function<void()> DoneCallback;

namespace tensorflow {

/**
 * Defines a ConditionalAccumulatorBaseOp, which constructs a
 * ConditionalAccumulatorBase (via sub-class's Creator) and returns its handle.
 */
class ConditionalAccumulatorBaseOp : public OpKernel {
 public:
  explicit ConditionalAccumulatorBaseOp(OpKernelConstruction* context)
      : OpKernel(context), accumulator_handle_set_(false) {
    OP_REQUIRES_OK(context,
                   context->allocate_persistent(DT_STRING, TensorShape({2}),
                                                &accumulator_handle_, nullptr));
    OP_REQUIRES_OK(context, context->GetAttr("shape", &shape_));
    OP_REQUIRES_OK(context, context->GetAttr("dtype", &dtype_));
  }

  void Compute(OpKernelContext* ctx) override {
    mutex_lock l(mu_);
    if (!accumulator_handle_set_) {
      OP_REQUIRES_OK(ctx, SetAccumulatorHandle(ctx));
    }
    ctx->set_output_ref(0, &mu_, accumulator_handle_.AccessTensor(ctx));
  }

 protected:
  ~ConditionalAccumulatorBaseOp() override {
    // If the accumulator object was not shared, delete it.
    if (accumulator_handle_set_ && cinfo_.resource_is_private_to_kernel()) {
      TF_CHECK_OK((cinfo_.resource_manager()
                       ->template Delete<ConditionalAccumulatorBase>(
                           cinfo_.container(), cinfo_.name())));
    }
  }

 protected:
  typedef std::function<Status(ConditionalAccumulatorBase**)> Creator;

  // Subclasses must override this
  virtual Creator GetCreator() const = 0;

  // Variables required to construct ConditionalAccumulator
  DataType dtype_;
  PartialTensorShape shape_;
  ContainerInfo cinfo_;

 private:
  Status SetAccumulatorHandle(OpKernelContext* ctx)
      EXCLUSIVE_LOCKS_REQUIRED(mu_) {
    TF_RETURN_IF_ERROR(cinfo_.Init(ctx->resource_manager(), def()));

    // Check input signature
    DataTypeVector expected_inputs = {};
    TF_RETURN_IF_ERROR(ctx->MatchSignature(expected_inputs, {DT_STRING_REF}));

    Creator creator = GetCreator();
    ConditionalAccumulatorBase* accumulator;
    TF_RETURN_IF_ERROR(
        (cinfo_.resource_manager()
             ->template LookupOrCreate<ConditionalAccumulatorBase>(
                 cinfo_.container(), cinfo_.name(), &accumulator, creator)));
    core::ScopedUnref unref_me(accumulator);

    // Verify that the shared accumulator is compatible
    // with the requested arguments.
    TF_RETURN_IF_ERROR(accumulator->MatchesNodeDef(def()));
    auto h = accumulator_handle_.AccessTensor(ctx)->template flat<string>();
    h(0) = cinfo_.container();
    h(1) = cinfo_.name();
    accumulator_handle_set_ = true;
    return Status::OK();
  }

  mutex mu_;
  PersistentTensor accumulator_handle_ GUARDED_BY(mu_);
  bool accumulator_handle_set_ GUARDED_BY(mu_);
};

/**
 * General OpKernel for ConditionalAccumulatorBase-related ops.
 */
class ConditionalAccumulatorBaseAsyncOpKernel : public AsyncOpKernel {
 public:
  explicit ConditionalAccumulatorBaseAsyncOpKernel(
      OpKernelConstruction* context)
      : AsyncOpKernel(context) {}

  void ComputeAsync(OpKernelContext* ctx, DoneCallback callback) final {
    ConditionalAccumulatorBase* accumulator;
    OP_REQUIRES_OK_ASYNC(
        ctx, GetResourceFromContext(ctx, "handle", &accumulator), callback);
    ComputeAsync(ctx, accumulator, [callback, accumulator]() {
      accumulator->Unref();
      callback();
    });
  }

 protected:
  virtual void ComputeAsync(OpKernelContext* ctx,
                            ConditionalAccumulatorBase* accumulator,
                            DoneCallback callback) = 0;
};

/**
 * General OpKernel for ConditionalAccumulatorBase-related ops.
 */
class ConditionalAccumulatorBaseSyncOpKernel : public OpKernel {
 public:
  explicit ConditionalAccumulatorBaseSyncOpKernel(OpKernelConstruction* context)
      : OpKernel(context) {}

  void Compute(OpKernelContext* ctx) final {
    ConditionalAccumulatorBase* accumulator;
    OP_REQUIRES_OK(ctx, GetResourceFromContext(ctx, "handle", &accumulator));
    Compute(ctx, accumulator);
    accumulator->Unref();
  }

 protected:
  virtual void Compute(OpKernelContext* ctx,
                       ConditionalAccumulatorBase* accumulator) = 0;
};

/**
 * Defines a AccumulateGradientOp, the execution of which adds a gradient to the
 * given ConditionalAccumulator.
 */
class ConditionalAccumulatorBaseApplyGradientOp
    : public ConditionalAccumulatorBaseSyncOpKernel {
 public:
  explicit ConditionalAccumulatorBaseApplyGradientOp(
      OpKernelConstruction* context)
      : ConditionalAccumulatorBaseSyncOpKernel(context) {}

 protected:
  virtual void CheckSignature(OpKernelContext* ctx,
                              ConditionalAccumulatorBase* accumulator) = 0;

  void Compute(OpKernelContext* ctx,
               ConditionalAccumulatorBase* accumulator) override {
    // Check input signature
    CheckSignature(ctx, accumulator);

    // Get input local_step
    const Tensor* local_step_tensor;
    OP_REQUIRES_OK(ctx, ctx->input("local_step", &local_step_tensor));
    if (!TensorShapeUtils::IsScalar(local_step_tensor->shape())) {
      ctx->CtxFailureWithWarning(errors::InvalidArgument(
          "Argument local_step must be scalar, but had bad shape ",
          local_step_tensor->shape().DebugString()));
    }

    // Actually try to apply gradient now
    accumulator->TryApplyGrad(local_step_tensor->scalar<int64>()(), ctx);
  }
};

/**
 * Defines a TakeAccumulatedGradientOp, the execution of which adds a gradient
 * to the given ConditionalAccumulator.
 */
class ConditionalAccumulatorBaseTakeGradientOp
    : public ConditionalAccumulatorBaseAsyncOpKernel {
 public:
  explicit ConditionalAccumulatorBaseTakeGradientOp(
      OpKernelConstruction* context)
      : ConditionalAccumulatorBaseAsyncOpKernel(context) {}

 protected:
  virtual void CheckSignature(OpKernelContext* ctx,
                              ConditionalAccumulatorBase* accumulator,
                              DoneCallback callback) = 0;

  void ComputeAsync(OpKernelContext* ctx,
                    ConditionalAccumulatorBase* accumulator,
                    DoneCallback callback) override {
    // Check signature
    CheckSignature(ctx, accumulator, callback);

    // Get input num_required
    const Tensor* num_required_tensor;
    OP_REQUIRES_OK_ASYNC(ctx, ctx->input("num_required", &num_required_tensor),
                         callback);
    if (!TensorShapeUtils::IsScalar(num_required_tensor->shape())) {
      ctx->CtxFailureWithWarning(errors::InvalidArgument(
          "Argument num_required must be scalar, but had bad shape ",
          num_required_tensor->shape().DebugString()));
      callback();
    }

    // Actually try to take gradient now
    accumulator->TryTakeGrad(num_required_tensor->scalar<int32>()(), ctx,
                             callback);
  }
};

}  // namespace tensorflow

#endif  // TENSORFLOW_KERNELS_CONDITIONAL_ACCUMULATOR_BASE_OP_H_

redpajama_set_name: RedPajamaGithub


text:
package com.ing.baker.runtime.recipe_manager

import com.ing.baker.runtime.common.RecipeRecord
import com.typesafe.scalalogging.LazyLogging

import scala.concurrent.{ExecutionContext, Future}

trait PollingAware extends RecipeManager with LazyLogging {

  implicit def ex: ExecutionContext

  abstract override def put(recipeRecord: RecipeRecord): Future[String] = {
    this.get(recipeRecord.recipeId).flatMap {
      maybeInCache =>
        if (maybeInCache.isEmpty || (maybeInCache.isDefined && maybeInCache.get.updated < recipeRecord.updated)) {
          logger.info(s"${if (maybeInCache.isEmpty) "Adding" else "Updating"} recipe ${recipeRecord.name} : ${recipeRecord.recipeId}")
          super.put(recipeRecord)
        } else {
          Future.successful(recipeRecord.recipeId)
        }
    }
  }
}


text:
namespace PoESkillTree.Computation.Views
{
    /// <summary>
    /// Interaction logic for GainOnActionStatsView.xaml
    /// </summary>
    public partial class GainOnActionStatsView
    {
        public GainOnActionStatsView()
        {
            InitializeComponent();
        }
    }
}


text:
package com.bitunified.cd.service

import akka.http.scaladsl.model.{HttpMethod, HttpMethods, HttpResponse}
import akka.http.scaladsl.server.{Directive0, MethodRejection}
import akka.http.scaladsl.server.RouteResult.Rejected
import org.apache.http.protocol.HttpService

import akka.http.scaladsl.model.HttpMethods._
import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.model.headers.`Access-Control-Allow-Credentials`
import akka.http.scaladsl.model.headers.`Access-Control-Allow-Methods`
import akka.http.scaladsl.model.headers.`Access-Control-Allow-Origin`
import akka.http.scaladsl.model.headers.Origin
import akka.http.scaladsl.server.Directive0
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.MethodRejection
import akka.http.scaladsl.server.RejectionHandler
import akka.http.scaladsl.model.{HttpHeader, HttpResponse}
import akka.http.scaladsl.server.{Directive0, MethodRejection, RejectionHandler}
import akka.http.scaladsl.model.headers._
import akka.http.scaladsl.server.Directives._
/**
  * Created by BertLenovo on 6-4-2017.
  */
trait CorsSupport2 {
//  this: HttpService =>
//  private val allowOriginHeader = `Access-Control-Allow-Origin`(AllOrigins)
//  private val optionsCorsHeaders = List(
//    `Access-Control-Allow-Headers`("Origin, X-Requested-With,Authorization,Content-Type, Accept, Accept-Encoding, Accept-Language, Host, Referer, User-Agent,apiKey"),
//    `Access-Control-Max-Age`(1728000))
//
//  def cors[T]: Directive0 = mapRequestContext { ctx => ctx.withRouteResponseHandling({
//    //It is an option requeset for a resource that responds to some other method
//    case Rejected(x) if (ctx.request.method.equals(HttpMethods.OPTIONS) && !x.filter(_.isInstanceOf[MethodRejection]).isEmpty) => {
//      val allowedMethods: List[HttpMethod] = x.filter(_.isInstanceOf[MethodRejection]).map(rejection => {
//        rejection.asInstanceOf[MethodRejection].supported
//      })
//      ctx.complete(HttpResponse().withHeaders(
//        `Access-Control-Allow-Methods`(OPTIONS, allowedMethods: _*) :: allowOriginHeader ::
//          optionsCorsHeaders
//      ))
//    }
//  }).withHttpResponseHeadersMapped { headers =>
//    allowOriginHeader :: headers
//  }
//  }
}


text:
class SomeClass {
  // removedField is removed
  private visibilityChangedField: Namespace.Type;
  private readOnlyChangedField = "stuff";

  // removedMethod is removed
  changedParamType(firstParam: number): void {}
  changedReturnType(firstParam: string): number {
    return 311;
  }
  reorderedParams(secondParam: string, firstParam: string): void {}
  hasGenericParam<S>(genericParam: S): void {}
}

function someFunction(genericParam: number): string {
  return "test";
}

interface SomeInterface {}
class DifferentBaseClass {}

export class ExportedClass extends DifferentBaseClass implements SomeInterface {}

let SomeConst: SomeOtherUnion = "blue";


text:
#ifndef V8RecursionScope_h
#define V8RecursionScope_h

#include "ScriptExecutionContext.h"
#include "V8PerIsolateData.h"
#include <wtf/Noncopyable.h>

namespace WebCore {

// C++ calls into script contexts which are "owned" by WebKit (created in a
// process where WebKit.cpp initializes v8) must declare their type:
//
//   1. Calls into page/author script from a frame
//   2. Calls into page/author script from a worker
//   3. Calls into internal script (typically setup/teardown work)
//
// Debug-time checking of this is enforced via this class.
//
// Calls of type (1) should generally go through ScriptController, as inspector
// instrumentation is needed. Calls of type (2) should always stack-allocate a
// V8RecursionScope in the same block as the call into script. Calls of type (3)
// should stack allocate a V8RecursionScope::MicrotaskSuppression -- this
// skips work that is spec'd to happen at the end of the outer-most script stack
// frame of calls into page script:
//
// http://www.whatwg.org/specs/web-apps/current-work/#perform-a-microtask-checkpoint
class V8RecursionScope {
    WTF_MAKE_NONCOPYABLE(V8RecursionScope);
public:
    explicit V8RecursionScope(ScriptExecutionContext* context)
        : m_isDocumentContext(context && context->isDocument())
    {
        V8PerIsolateData::current()->incrementRecursionLevel();
    }

    ~V8RecursionScope()
    {
        if (!V8PerIsolateData::current()->decrementRecursionLevel())
            didLeaveScriptContext();
    }

    static int recursionLevel()
    {
        return V8PerIsolateData::current()->recursionLevel();
    }

#ifndef NDEBUG
    static bool properlyUsed()
    {
        return recursionLevel() > 0 || V8PerIsolateData::current()->internalScriptRecursionLevel() > 0;
    }
#endif

    class MicrotaskSuppression {
    public:
        MicrotaskSuppression()
        {
#ifndef NDEBUG
            V8PerIsolateData::current()->incrementInternalScriptRecursionLevel();
#endif
        }

        ~MicrotaskSuppression()
        {
#ifndef NDEBUG
            V8PerIsolateData::current()->decrementInternalScriptRecursionLevel();
#endif
        }
    };

private:
    void didLeaveScriptContext();

    bool m_isDocumentContext;
};

} // namespace WebCore

#endif // V8RecursionScope_h


text:
package schemaprocessor // import "github.com/open-telemetry/opentelemetry-collector-contrib/processor/schemaprocessor"

import (
	"errors"
	"fmt"

	"go.opentelemetry.io/collector/config"
	"go.opentelemetry.io/collector/config/confighttp"

	"github.com/open-telemetry/opentelemetry-collector-contrib/processor/schemaprocessor/internal/translation"
)

var (
	errRequiresTargets  = errors.New("requires schema targets")
	errDuplicateTargets = errors.New("duplicate targets detected")
)

// Config defines the user provided values for the Schema Processor
type Config struct {
	config.ProcessorSettings      `mapstructure:",squash"`
	confighttp.HTTPClientSettings `mapstructure:",squash"`

	// PreCache is a list of schema URLs that are downloaded
	// and cached at the start of the collector runtime
	// in order to avoid fetching data that later on could
	// block processing of signals. (Optional field)
	Prefetch []string `mapstructure:"prefetch"`

	// Targets define what schema families should be
	// translated to, allowing older and newer formats
	// to conform to the target schema identifier.
	Targets []string `mapstructure:"targets"`
}

func (c *Config) Validate() error {
	for _, schemaURL := range c.Prefetch {
		_, _, err := translation.GetFamilyAndVersion(schemaURL)
		if err != nil {
			return err
		}
	}
	// Not strictly needed since it would just pass on
	// any data that doesn't match targets, however defining
	// this processor with no targets is wasteful.
	if len(c.Targets) == 0 {
		return fmt.Errorf("no schema targets defined: %w", errRequiresTargets)
	}

	families := make(map[string]struct{})
	for _, target := range c.Targets {
		family, _, err := translation.GetFamilyAndVersion(target)
		if err != nil {
			return err
		}
		if _, exist := families[family]; exist {
			return errDuplicateTargets
		}
		families[family] = struct{}{}
	}

	return nil
}


text:
using System;

namespace Piranha.Extend.Serializers
{
    public class IntegerFieldSerializer<T> : ISerializer where T : Fields.SimpleField<int?>
    {
        /// <summary>
        /// Serializes the given object.
        /// </summary>
        /// <param name="obj">The object</param>
        /// <returns>The serialized value</returns>
        public string Serialize(object obj)
        {
            if (obj is T)
            {
                if (((T)obj).Value.HasValue)
                    return ((T)obj).Value.Value.ToString();
                return null;
            }
            throw new ArgumentException("The given object doesn't match the serialization type");
        }

        /// <summary>
        /// Deserializes the given string.
        /// </summary>
        /// <param name="str">The serialized value</param>
        /// <returns>The object</returns>
        public object Deserialize(string str)
        {
            var field = Activator.CreateInstance<T>();

            if (!string.IsNullOrWhiteSpace(str))
            {
                try
                {
                    field.Value = int.Parse(str);
                }
                catch { }
            }
            return field;
        }
    }
}


text:
<html>
<head></head>
<body>
<script type="text/javascript" src="lib/3rdparty/jquery.js"></script>
<script type="text/javascript" src="lib/3rdparty/oauth.js"></script>
<script type="text/javascript" src="lib/3rdparty/sha1.js"></script>

<script type="text/javascript" src="lib/math_utils.js"></script>
<script type="text/javascript" src="lib/persistence.js"></script>
<script type="text/javascript" src="lib/twitter_lib.js"></script>
<script type="text/javascript" src="lib/icon_creator.js"></script>
<script type="text/javascript" src="lib/expander_lib.js"></script>

<script type="text/javascript" src="lib/options_backend.js"></script>

<script type="text/javascript" src="lib/timeline_factory.js"></script>
<script type="text/javascript" src="lib/timeline_template.js"></script>

<script type="text/javascript" src="lib/timelines/timeline.js"></script>
<script type="text/javascript" src="lib/timelines/favorites_timeline.js"></script>
<script type="text/javascript" src="lib/timelines/unified_timeline.js"></script>
<script type="text/javascript" src="lib/timelines/unified_dms_timeline.js"></script>

<script type="text/javascript" src="lib/timelines/multiple_timeline.js"></script>
<script type="text/javascript" src="lib/timelines/lists_timeline.js"></script>
<script type="text/javascript" src="lib/timelines/search_timeline.js"></script>

<script type="text/javascript" src="lib/send_queue.js"></script>
<script type="text/javascript" src="lib/image_services.js"></script>
<script type="text/javascript" src="lib/locales.js"></script>
<script>
function initializeJQueryOptions() {
  $.ajaxSetup({
    timeout: OptionsBackend.get('request_timeout')
  });
}
initializeJQueryOptions();

urlExpander = new Expander();

function ComposerData() {
  this.saveMessage = '';
  this.urlShortener = '';
  this.isComposing = false;
  this.replyId = null;
  this.replyUser = null;
}

function TweetManager() {
  this.unreadTweets = {};
  this.readTweets = {};
  this.shouldNotReadMap = {};
  this.retweets = {};
  this.injectTweets = null;

  // Using an object instead of an array to take advantage of hash look-ups
  this.blockedUserIds = {};

  this.newTweetsCallback = null;

  this.composerData = new ComposerData();

  this.timelines = {};
  this.iconImg = null;
  this.listsCache = null;
  this.listsTabCount = OptionsBackend.get('lists_count');

  this.suspend = false;

  this.timelineOrderData = Persistence.timelineOrder();
  this.oauthTokenData = Persistence.oauthTokenData();
  this.oauthTokenService = Persistence.oauthTokenService();

  var currentService = OptionsBackend.get('microblogging_service');
  if(!this.oauthTokenService.val()) {
    this.oauthTokenService.save(currentService);
  } else if(currentService != this.oauthTokenService.val()) {
    this.oauthTokenService.save(currentService);
    this.oauthTokenData.remove();
  }

  var _this = this;

  TimelineTemplate.initTemplates(this);
  TimelineTemplate.eachTimelineTemplate(function(template) {
    var createdTimelines = template.createTimelines();
    for(var i in createdTimelines) {
      _this.timelines[createdTimelines[i].timelineId] = createdTimelines[i];
    }
  });

  this.orderedEachTimeline(function(timeline) {
    _this.currentTimelineId = timeline.timelineId;
    return false;
  }, true);

  this.warningsCallback = null;
  this.warningMessage = null;
  this.autoClearWarning = false;

  this.maxApiHitsStates = 30;
  this.apiHitsStates = [];
  this.firstPossibleWarnTime = null;

  this.authenticated = false;

  this.initIconAndAlerts();

  this.twitterBackend = new TwitterLib(
    function onAuthenticated() {
      TimelineTemplate.initAfterAuthentication();
      _this.authenticated = true;
      _this.retrieveBlockedUserIds();
      _this.lists();
      _this.eachTimeline(function(timeline) {
        timeline.init();
      }, true);
      _this.retrieveFollowingUsers();
    },
    function(remainingHits, nextHitsReset, hourlyLimit) {
      _this.onHitsUpdated.call(_this, remainingHits, nextHitsReset, hourlyLimit);
    },
    OptionsBackend.get('microblogging_service'),
    OptionsBackend.get('base_url'),
    OptionsBackend.get('base_oauth_url'),
    OptionsBackend.get('base_signing_url'),
    OptionsBackend.get('base_oauth_signing_url'),
    OptionsBackend.get('base_search_url'),
    this.oauthTokenData);

  this.sendQueue = new SendQueue(this.twitterBackend);
}

TweetManager.prototype = {

  showTimelineTemplate: function(timelineTemplateId, showOnly) {
    var template = TimelineTemplate.getTemplate(timelineTemplateId);
    template.setVisible(true);
    return this.createTimelineTemplate(template, showOnly);
  },

  hideTimelineTemplate: function(timelineTemplateId) {
    var template = TimelineTemplate.getTemplate(timelineTemplateId);
    template.setVisible(false);
    var toDelete = [];
    this.eachTimeline(function(timeline) {
      if(timeline.template.id == timelineTemplateId) {
        timeline.killTimeline();
        toDelete.push(timeline);
      }
    }, true);
    for(var i = 0, len = toDelete.length; i < len; ++i) {
      var timeline = toDelete[i];
      delete this.timelines[timeline.timelineId];
    }
  },

  createTimelineTemplate: function(template, showOnly) {
    var createdTimelines = [];
    var shownTimelines = [];
    if(template.multipleTimelines && !showOnly) {
      createdTimelines = [template.addTimeline()];
    } else {
      var createTimelines = true;
      this.eachTimeline(function(timeline) {
        if(timeline.template.id == template.id) {
          createTimelines = false;
          shownTimelines.push(timeline);
        }
      });
      if(createTimelines) {
        createdTimelines = template.createTimelines();
      }
    }
    for(var i = 0, len = createdTimelines.length; i < len; ++i) {
      var timeline = createdTimelines[i];
      this.timelines[timeline.timelineId] = timeline;
      if(this.authenticated) {
        timeline.init();
      }
      shownTimelines.push(timeline);
    }
    return shownTimelines;
  },

  hideTimeline: function(timelineId){
    var timeline = this.timelines[timelineId];
    var shouldDelete = timeline.remove();
    if(shouldDelete) {
      delete this.timelines[timelineId];
    }
  },

  toggleUnified: function(templateId, forcedState) {
    var template = TimelineTemplate.getTemplate(templateId);
    var newState = !template.includeInUnified;
    if(forcedState !== undefined) {
      newState = forcedState;
    }
    template.setIncludeInUnified(newState);
    if(template.multipleTimelines || template.visible) {
      return;
    }
    if(template.includeInUnified) {
      this.createTimelineTemplate(template);
    } else {
      this.hideTimeline(template.id);
    }
  },

  toggleNotify: function(templateId) {
    var template = TimelineTemplate.getTemplate(templateId);
    var newState = !template.showOnPageNotification;
    template.setShowOnPageNotification(newState);
  },

  toggleChangeIcon: function(templateId) {
    var template = TimelineTemplate.getTemplate(templateId);
    var newState = !template.showIconNotification;
    template.setShowIconNotification(newState);
  },

  setWarning: function(msg) {
    this.warningMessage = msg;
    try {
      if(this.warningCallback) {
        this.warningCallback(msg);
      }
    } catch(e) {
      /* ignoring, the popup window might be closed. */
    }
  },

  clearWarning: function() {
    this.warningMessage = null;
  },

  registerWarningsCallback: function(callback) {
    this.warningsCallback = callback;
    if(this.warningMessage && this.warningsCallback) {
      this.warningsCallback(this.warningMessage);
    }
  },

  /**
  * Update this.blockedUserIds and schedule another update after
  * "blockedusers_refresh_interval" time has elapsed.
  */
  retrieveBlockedUserIds: function() {
    var _this = this;
    this.twitterBackend.blockedUserIds(function(success, data, status, context) {
        if(success) {
          _this.blockedUserIds = {};
          for(var i in data) {
            _this.blockedUserIds[data[i]] = data[i];
          }
        }
        setTimeout(function() { _this.retrieveBlockedUserIds(); }, OptionsBackend.get('blockedusers_refresh_interval'));
    });
  },

  eachTimeline: function(callback, includeHidden) {
    for(var tId in this.timelines) {
      var timeline = this.timelines[tId];
      if(!includeHidden && (!timeline.template.visible || timeline.template.hiddenTemplate)) {
        continue;
      }
      if(callback.call(tId, timeline) === false) {
        break;
      }
    }
  },

  /* Lists timelines won't be included as they'll only be shown later */
  orderedEachTimeline: function(callback, includeLists) {
    var retList = [], tId, timeline;
    for(tId in this.timelines) {
      timeline = this.timelines[tId];
      if(!includeLists && timeline.template.id == TimelineTemplate.LISTS) {
        continue;
      }
      var orderedPos = this.getTimelinePosition(tId);
      if(orderedPos == -1) {
        orderedPos = retList.length;
      }
      if(retList[orderedPos]) {
        retList.splice(orderedPos, 0, tId);
      } else {
        retList[orderedPos] = tId;
      }
    }
    for(var i = 0; i < retList.length; ++i) {
      tId = retList[i];
      if(tId) {
        timeline = this.timelines[tId];
        if(timeline.template.visible && !timeline.template.hiddenTemplate) {
          var ret = callback.call(tId, timeline);
          if(ret === false) {
            break;
          }
        }
      }
    }
  },

  getTimelinePosition: function(timelineId) {
    if(!this.timelineOrderCache) {
      var storedOrder = this.timelineOrderData.val();
      if(storedOrder) {
        this.timelineOrderCache = JSON.parse(storedOrder);
      } else {
        this.timelineOrderCache = [];
      }
    }
    for(var i = 0; i < this.timelineOrderCache.length; ++i) {
      if(timelineId == this.timelineOrderCache[i]) {
        return i;
      }
    }
    return -1;
  },

  setTimelineOrder: function(sortedTimelinesArray) {
    this.timelineOrderCache = sortedTimelinesArray;
    this.timelineOrderData.save(JSON.stringify(sortedTimelinesArray));
  },

  initIconAndAlerts: function() {
    var $icon = $('<img>').attr('src', 'img/icon19.png');
    this.iconImg = $icon[0];
    var _this = this;
    $icon.load(function() {
      _this.updateAlert();
    });
  },

  unique: function(srcList) {
    var newList = [];
    for(var i = 0; i < srcList.length; ++i) {
      if($.inArray(srcList[i], newList) == -1) {
        newList[newList.length] = srcList[i];
      }
    }
    return newList;
  },

  updateAlert: function() {
    var colors = [];
    var unreadNewTweets = [];
    var totalUnreadNewIds = [];
    this.eachTimeline(function(timeline) {
      var timelineId = this;
      var unreadNewIds = timeline.getNewUnreadIds();
      var timelineTemplate = timeline.template;
      if(timelineTemplate.showIconNotification) {
        totalUnreadNewIds = totalUnreadNewIds.concat(unreadNewIds);
        if(unreadNewIds.length > 0) {
          colors.push(timelineTemplate.iconNotificationColor);
        }
      }
      if(timelineTemplate.showOnPageNotification) {
        unreadNewTweets = unreadNewTweets.concat(timeline.getNewUnreadTweets());
      }
    }, true);
    var totalUnreadNewCount = this.unique(totalUnreadNewIds).length;
    if(colors.length === 0) {
      chrome.browserAction.setTitle({title: "Chromed Bird"});
      chrome.browserAction.setIcon({imageData: IconCreator.paintIcon(this.iconImg, OptionsBackend.get('idle_color'))});
      chrome.browserAction.setBadgeText({text: ''});
    } else {
      var tweet_string = totalUnreadNewCount > 1 ? 'newtweets_plural' : 'newtweets_singular';
      var title = chrome.i18n.getMessage("newTweets", [totalUnreadNewCount, chrome.i18n.getMessage(tweet_string)]);
      chrome.browserAction.setTitle({title: title});
      chrome.browserAction.setIcon({imageData: IconCreator.paintIcon(this.iconImg, colors)});
      chrome.browserAction.setBadgeBackgroundColor({color: [255, 0, 0, 0]});
      chrome.browserAction.setBadgeText({text: '' + totalUnreadNewCount});
    }
    if(unreadNewTweets.length > 0) {
      this.showTweetsNotifications(unreadNewTweets);
    }
  },

  safeTweetsNotifications: function(tweetsToNotify, shouldChangeOption) {
    if(shouldChangeOption) {
      OptionsBackend.saveOption('tweets_notification_style', 'on_page');
    }
    this.showTweetsNotifications(tweetsToNotify, true);
  },

  showTweetsNotifications: function(tweetsToNotify, forceOnPage) {
    if(!tweetsToNotify || tweetsToNotify.length === 0) {
      return;
    }
    var maxTweetsNotifications = OptionsBackend.get('notification_max_popups');
    if(maxTweetsNotifications != -1 && tweetsToNotify.length > maxTweetsNotifications) {
      tweetsToNotify.splice(maxTweetsNotifications, tweetsToNotify.length - maxTweetsNotifications);
    }
    this.injectTweets = tweetsToNotify;

    var notificationStyle = OptionsBackend.get('tweets_notification_style');
    if(!forceOnPage && notificationStyle == 'desktop') {
      try {
        var notificationCenter = window.notifications || window.webkitNotifications;
        if(!notificationCenter) {
          throw 'NotificationCenter not available';
        }
        var authStatus = notificationCenter.checkPermission();
        if(authStatus == 1 || authStatus == 2) { //Not Allowed or Denied
          throw 'Desktop notifications not allowed';
        }

        // FIXME: This check is here because stable channel releases
        // currently silently fail in showing html notifications
        var notificationDisplayed = false;
        var onDisplayFunc = function() {
          notificationDisplayed = true;
        };
        var _this = this;
        setTimeout(function() {
          if(!notificationDisplayed) {
            for(var i = 0; i < tweetsToNotify.length; ++i) {
              _this.shouldNotReadMap[tweetsToNotify[i].id] = true;
            }
            _this.safeTweetsNotifications(tweetsToNotify, false);
          }
        }, 1000);

        for(var i = 0; i < tweetsToNotify.length; ++i) {
          var notification = notificationCenter.createHTMLNotification(
            chrome.extension.getURL('tweets_notifier.html'));
          (function inClosure(tweet) {
            notification.onclose = function(e) {
              setTimeout(function() {
                _this.readTweet(tweet.id);
              }, 200);
            };
          })(tweetsToNotify[i]);
          notification.ondisplay = onDisplayFunc;
          notification.show();
        }
      } catch(e) {
        console.warn(e);
        // Fallback to 'on page' notifications
        this.safeTweetsNotifications(tweetsToNotify, true);
      }
    } else {
      var injectHelper = function(action, file, allFrames, callback) {
        var method;
        if(action == 'script') {
          method = chrome.tabs.executeScript;
        } else if(action == 'css') {
          method = chrome.tabs.insertCSS;
        } else {
          return;
        }
        var params = {file: file};
        if(allFrames) {
          params.allFrames = true;
        }
        try {
          method.call(chrome.tabs, null, params, callback);
        } catch(e) {
          // Maybe this exception is due to allFrames = true, let's try without it
          if(allFrames) {
            try {
              method.call(chrome.tabs, null, {file: file}, callback);
            } catch(e) {
              // This time something really bad happened, logging and ignoring
              console.log(e);
            }
          } else {
            // We don't know the motive, logging and ignoring
            console.log(e);
          }
        }
      };
      injectHelper('script', 'lib/3rdparty/jquery.js', true, function() {
        injectHelper('css', 'css/injectedTweets.css', true, function() {
          injectHelper('script', 'lib/any_click.js', true, function() {
            injectHelper('script', 'lib/tweet_transforms.js', true, function() {
              injectHelper('script', 'lib/timeline_template.js', true, function() {
                injectHelper('script', 'lib/tweets_assembler.js', true);
              });
            });
          });
        });
      });
    }
  },

  registerNewTweetsCallback: function(callback) {
    this.newTweetsCallback = callback;
  },

  readTweet: function(id) {
    if(this.shouldNotReadMap[id]) {
      delete this.shouldNotReadMap[id];
      return;
    }
    this.readTweets[id] = true;
    delete this.unreadTweets[id];
    this.notifyNewTweets();
  },

  isTweetRead: function(id) {
    return !this.unreadTweets[id];
  },

  isRetweet: function(id) {
    return this.retweets[id];
  },

  notifyNewTweets: function() {
    if(this.newTweetsCallback) {
      var _this = this;
      this.eachTimeline(function(timeline) {
        var newTweets = timeline.newTweetsCount();
        try {
          // The callback might be invalid (popup not active), so let's ignore errors for now.
          _this.newTweetsCallback(newTweets[0], newTweets[1], timeline.timelineId);
        } catch(e) { /* ignoring */ }
      });
    }

    this.updateAlert();
  },

  enqueueTweet: function(msg, replyId) {
    this.sendQueue.enqueueTweet(msg, replyId);
  },

  postRetweet: function(callback, id) {
    var _this = this;
    return this.twitterBackend.retweet(function(success, data, status) {
      if(success) {
        _this.retweets[id] = true;
      }
      callback(success, data, status);
    }, id);
  },

  getInReplyToTweet: function(callback, tweet) {
    if(tweet.inReplyToTweet) {
      callback(true, tweet.inReplyToTweet);
      return;
    }
    var _this = this;
    this.twitterBackend.showTweet(function(success, data, status) {
      if(success) {
        tweet.inReplyToTweet = data;
      }
      callback(success, data, status);
    }, tweet.in_reply_to_status_id);
  },

  destroy: function(callback, tweetTimelineId, id) {
    var _this = this;
    var firstCallback = function(success, data, status) {
      if(success) {
        _this.eachTimeline(function(timeline) {
          timeline.removeFromCache(id);
        }, true);
      }
      callback(success, data, status);
    };
    if(tweetTimelineId == TimelineTemplate.RECEIVED_DMS || tweetTimelineId == TimelineTemplate.SENT_DMS) {
      return this.twitterBackend.destroyDM(firstCallback, id);
    } else {
      return this.twitterBackend.destroy(firstCallback, id);
    }
  },

  favorite: function(callback, id) {
    var _this = this;
    var firstCallback = function(success, data, status) {
      if(success) {
        var favTimeline = _this.timelines[TimelineTemplate.FAVORITES];
        if(favTimeline) {
          favTimeline.pushTweet(data);
        }
        _this.eachTimeline(function(timeline) {
          var tweet = timeline.findTweet(id);
          if(tweet)
            tweet.favorited = true;
        }, true);
      }
      callback(success, data, status);
    };
    return this.twitterBackend.favorite(firstCallback, id);
  },

  unFavorite: function(callback, id) {
    var _this = this;
    var firstCallback = function(success, data, status) {
      if(success) {
        var favTimeline = _this.timelines[TimelineTemplate.FAVORITES];
        if(favTimeline) {
          favTimeline.removeFromCache(id);
        }
        _this.eachTimeline(function(timeline) {
          var tweet = timeline.findTweet(id);
          if(tweet)
            tweet.favorited = false;
        }, true);
      }
      callback(success, data, status);
    };
    return this.twitterBackend.unFavorite(firstCallback, id);
  },

  lists: function(force, callback) {
    if(!TimelineTemplate.getTemplate(TimelineTemplate.LISTS).visible) {
      /* No lists tab should be shown, let's just ignore the callback */
      return;
    }
    if(force) {
      this.listsCache = null;
    }
    if(!this.listsCache) {
      var _this = this;
      this.twitterBackend.lists(function(success, data, status) {
        if(success) {
          if(!data.lists) {
            data.lists = [];
          }
          _this.listsCache = data.lists;
          _this.twitterBackend.subs(function(success, data, status) {
            if(success) {
              if(!data.lists) {
                data.lists = [];
              }
              _this.listsCache = _this.listsCache.concat(data.lists);
            }
            if(callback) {
              callback(success, _this.listsCache, status);
            }
          });
        } else {
          if(callback) {
            callback(success, _this.listsCache, status);
          }
        }
      });
      return;
    }
    if(callback) {
      callback(true, this.listsCache, null);
    }
  },

  changeSearch: function(timelineId, searchQuery) {
    var timeline = this.timelines[timelineId];
    if(!timeline) {
      return false;
    }
    return timeline.changeSearchQuery(searchQuery);
  },

  getSearchQuery: function(timelineId) {
    var timeline = this.timelines[timelineId];
    if(!timeline) {
      return null;
    }
    return timeline.getSearchQuery();
  },

  changeList: function(timelineId, listId) {
    var timeline = this.timelines[timelineId];
    if(!timeline) {
      return null;
    }
    timeline.changeList(listId);
    return undefined;
  },

  getListId: function(timelineId) {
    if(!timelineId) {
      timelineId = this.currentTimelineId;
    }
    var timeline = this.timelines[timelineId];
    if(!timeline) {
      return null;
    }
    var listId = timeline.getListId();
    if(listId && this.listsCache) {
      // Check if the listId really exists
      for(var i = 0; i < this.listsCache.length; ++i) {
        if(this.listsCache[i].uri == listId) {
          return listId;
        }
      }
    }
    return null;
  },

  getList: function(timelineId) {
    if(!timelineId) {
      timelineId = this.currentTimelineId;
    }
    var timeline = this.timelines[timelineId];
    if(!timeline) {
      return null;
    }
    var listId = timeline.getListId();
    if(listId && this.listsCache) {
      for(var i = 0; i < this.listsCache.length; ++i) {
        if(this.listsCache[i].uri == listId) {
          return this.listsCache[i];
        }
      }
    }
    return null;
  },

  giveMeTweets: function(timelineId, callback, syncNew, cacheOnly) {
    var timeline = this.timelines[timelineId];
    if(!timeline) {
      callback([], timelineId);
      return undefined;
    }
    if(syncNew && timeline.template.includeInUnified) {
      var originalCallback = callback;
      var _this = this;
      callback = function(tweets, timelineId) {
        originalCallback(tweets, timelineId);
        _this.timelines[TimelineTemplate.UNIFIED].giveMeTweets(originalCallback, false, true);
      };
    }
    return timeline.giveMeTweets(callback, syncNew, cacheOnly);
  },

  newTweetsCount: function(timelineId) {
    return this.timelines[timelineId].newTweetsCount();
  },

  updateNewTweets: function() {
    var currentTimeline = this.timelines[this.currentTimelineId];
    if(currentTimeline.template.id == TimelineTemplate.FAVORITES) {
      var newTweets = this.timelines[this.currentTimelineId].getNewTweetsCache();
      for(var i = 0, len = newTweets.length; i < len; ++i) {
        var id = newTweets[i].id;
        this.eachTimeline(function(timeline) {
          var tweet = timeline.findTweet(id);
          if(tweet)
            tweet.favorited = true;
        }, true);
      }
    }
    currentTimeline.updateNewTweets();
    this.updateAlert();
  },

  getCurrentTimeline: function() {
    return this.timelines[this.currentTimelineId];
  },

  getTimeline: function(timelineId) {
    return this.timelines[timelineId];
  },

  currentError: function() {
    return this.timelines[this.currentTimelineId].getError();
  },

  stopAll: function() {
    this.eachTimeline(function(timeline) {
      timeline.killTimeline();
      delete timeline;
    }, true);
  },

  signout: function() {
    this.oauthTokenData.remove();
    this.stopAll();
    TweetManager.instance = new TweetManager();
  },

  restart: function() {
    this.stopAll();
    initializeJQueryOptions();
    TweetManager.instance = new TweetManager();
  },

  markTimelineAsRead: function() {
    var tweetsToRead = this.getCurrentTimeline().getTweetsCache();
    for(var i = 0; i < tweetsToRead.length; ++i) {
      this.readTweet(tweetsToRead[i].id);
    }
  },

  onHitsUpdated: function(remainingHits, nextHitsReset, hourlyLimit) {
    var nextResetDate = new Date();
    nextResetDate.setTime(parseInt(nextHitsReset, 10) * 1000);
    if(remainingHits === 0) {
      this.autoClearWarning = true;
      this.setWarning(chrome.i18n.getMessage("exceededAPIHits", [chrome.extension.getURL('options.html'), nextResetDate.toLocaleDateString(), nextResetDate.toLocaleTimeString()]));
      return;
    }
    if(this.autoClearWarning) {
      this.autoClearWarning = false;
      this.clearWarning();
    }

    if(this.apiHitsStates.length > 0) {
      if(remainingHits > this.apiHitsStates[this.apiHitsStates.length - 1][1]) {
        // Rate limit was reset
        this.apiHitsStates = [];
      }
    }

    this.apiHitsStates.push([(new Date()).getTime(), parseInt(remainingHits, 10)]);
    if(this.apiHitsStates.length > this.maxApiHitsStates) {
      this.apiHitsStates.shift();
    }
    if(this.apiHitsStates.length > 20) {
      var offset = this.apiHitsStates[0][0];
      var tendencyFunction = Math.linearLeastSquares(this.apiHitsStates, offset);
      var projectedRemainingHits = tendencyFunction(nextResetDate.getTime() - offset);
      if(projectedRemainingHits < 0) {
        if(this.firstPossibleWarnTime) {
          var timeDiff = new Date() - this.firstPossibleWarnTime;
          if(timeDiff > 3 * 60 * 1000) {
            // We've been keeping this tendency for 5 minutes, so we'll probably
            // exceed the limit if we keep this same rate, let's warn users.
            this.setWarning(chrome.i18n.getMessage("warmingAPIHits", [chrome.extension.getURL('options.html'), remainingHits, nextResetDate.toLocaleDateString(), nextResetDate.toLocaleTimeString()]));
            this.firstPossibleWarnTime = null;
          }
        } else {
          this.firstPossibleWarnTime = new Date();
        }
      } else {
        this.firstPossibleWarnTime = null;
      }
    }
  },

  retrieveUsersData: function(usersIdList) {
    var _this = this;
    this.twitterBackend.lookupUsers(function(success, users) {
      if(!success) {
        // Try again in a while...
        setTimeout(function() {
          _this.retrieveUsersData(usersIdList);
        }, 120000);
        return;
      }
      for(var i = 0, len = users.length; i < len; ++i) {
        var user = users[i];
        _this.followingUsersMap[user.screen_name] = user;
        _this.followingUsersNames.push(user.screen_name);
      }
      _this.followingUsersNames.sort(function(a, b) {
        return a.toUpperCase().localeCompare(b.toUpperCase());
      });
    }, usersIdList);
  },

  retrieveFollowingUsers: function() {
    this.followingUsersNames = [];
    this.followingUsersMap = {};
    var _this = this;
    this.twitterBackend.friendsIds(function(success, usersData) {
      if(!success) {
        // Try again in a while...
        setTimeout(function() {
          _this.retrieveFollowingUsers();
        }, 120000);
        return;
      }
      var idsList = usersData.ids;
      if(!idsList) {
        idsList = [];
      }
      for(var i = 0, len = Math.ceil(idsList.length / 100.0); i < len; ++i) {
        var firstIndex = i * 100;
        var idsListSlice = idsList.slice(firstIndex, firstIndex + 100);
        _this.retrieveUsersData(idsListSlice);
      }
    });
  },

  getFollowingUsers: function() {
    return this.followingUsersNames;
  },

  getFollowingUsersMap: function() {
    return this.followingUsersMap;
  },

  resetTimeline: function(timelineId) {
    var timeline = this.getTimeline(timelineId);
    if(timeline) {
      timeline.reset();
    }
  },

  followUser: function(callback, username) {
    var _this = this;
    this.twitterBackend.follow(function(success, userData) {
      if(success) {
        _this.followingUsersMap[userData.screen_name] = userData;
        _this.followingUsersNames.push(userData.screen_name);
        _this.followingUsersNames.sort(function(a, b) {
          return a.toUpperCase().localeCompare(b.toUpperCase());
        });
        _this.resetTimeline(TimelineTemplate.HOME);
        _this.resetTimeline(TimelineTemplate.UNIFIED);
      }
      callback(success, userData);
    }, username);
  },

  unfollowUser: function(callback, username) {
    var _this = this;
    this.twitterBackend.unfollow(function(success, userData) {
      if(success) {
        delete _this.followingUsersMap[userData.screen_name];
        var position = $.inArray(userData.screen_name);
        if(position > -1) {
          _this.followingUsersNames.splice(position, 1);
        }
        _this.resetTimeline(TimelineTemplate.HOME);
        _this.resetTimeline(TimelineTemplate.UNIFIED);
      }
      callback(success, userData);
    }, username);
  },
};

/* Clean up old versions mess */
Persistence.cleanupOldData();

function compareVersions(v1, v2) {
  if(!v1) return -1;
  if(!v2) return 1;
  var maxLen = Math.max(v1.length, v2.length);
  for(var i = 0; i < maxLen; ++i) {
    if(v1[i] === undefined) return -1;
    if(v2[i] === undefined) return 1;
    if(parseInt(v1[i], 10) > parseInt(v2[i], 10)) return 1;
    if(parseInt(v1[i], 10) < parseInt(v2[i], 10)) return -1;
  }
  return 0;
}

function checkVersionChanges(manifest) {
  try {
    var currentVersion = manifest.version.split('.');
    var storageData = Persistence.version();
    var storageVersion = storageData.val();
    var options, baseUrl;
    if(storageVersion) {
      storageVersion = JSON.parse(storageVersion);
    } else {
      // No previous version data let's just assume we're running the latest version
      storageData.save(JSON.stringify(currentVersion));
      return;
    }

    if(compareVersions(currentVersion, storageVersion) !== 0) {
      // if last version is < 1.3.0
      if(compareVersions(storageVersion, [1, 3, 0]) < 0) {
        //Old default refresh interval, let's update it for the new version
        if(OptionsBackend.get('home_refresh_interval') == 60000) {
          options = OptionsBackend.load();
          options['home_refresh_interval'] = OptionsBackend.defaultOptions['home_refresh_interval'];
          OptionsBackend.save(options);
        }
      }
      if(compareVersions(storageVersion, [1, 5, 1]) <= 0) {
        var timelineOrderData = Persistence.timelineOrder();
        var storedOrder = timelineOrderData.val();
        if(storedOrder) {
          storedOrder = JSON.parse(storedOrder);
        } else {
          storedOrder = [];
        }
        storedOrder.unshift('unified');
        timelineOrderData.save(JSON.stringify(storedOrder));
      }
      if(compareVersions(storageVersion, [1, 6, 1]) <= 0) {
        options = OptionsBackend.load();
        baseUrl = options['base_url'];
        if(baseUrl.match(/http:\/\/twitter\.com/)) {
          options['base_url'] = 'http://api.twitter.com/1/';
          options['base_signing_url'] = 'http://api.twitter.com/1/';
        } else if(baseUrl.match(/https:\/\/twitter\.com/)) {
          options['base_url'] = 'https://api.twitter.com/1/';
          options['base_signing_url'] = 'https://api.twitter.com/1/';
        }
        OptionsBackend.save(options);
      }
      if(compareVersions(storageVersion, [1, 7, 0]) <= 0) {
        var selectedListsData = Persistence.selectedLists();
        var selectedListsInfo = selectedListsData.val();
        if(selectedListsInfo) {
          var selectedObj = JSON.parse(selectedListsInfo);
          if(selectedObj) {
            var listsIdList = [];
            for(var key in selectedObj) {
              var listId = selectedObj[key];
              listsIdList.push(listId);
            }
            TweetManager.instance.hideTimelineTemplate(TimelineTemplate.LISTS);
            var listsTemplate = TimelineTemplate.getTemplate(TimelineTemplate.LISTS);
            listsTemplate.setUserData(listsIdList);
            TweetManager.instance.showTimelineTemplate(TimelineTemplate.LISTS, true);
          }
        }
        selectedListsData.remove();
      }
      if(compareVersions(storageVersion, [1, 8, 0]) <= 0) {
        var requestTimeout = OptionsBackend.get('request_timeout');
        if(requestTimeout == 6000) {
          // Twitter itself recomends a bigger timeout value, so
          // let's update the default value
          requestTimeout = OptionsBackend.defaultOptions['request_timeout'];
          OptionsBackend.saveOption('request_timeout', requestTimeout);
          initializeJQueryOptions();
        }

        baseUrl = OptionsBackend.get('base_url');
        var baseSigningUrl = OptionsBackend.get('base_signing_url');
        if(baseUrl == baseSigningUrl && baseUrl == 'http://api.twitter.com/1/') {
          // This days the SSL endpoint seems more reliable, let's make it the
          // default one unless users have manually changed it.
          baseUrl = OptionsBackend.defaultOptions['base_url'];
          baseSigningUrl = OptionsBackend.defaultOptions['base_signing_url'];
          OptionsBackend.saveOption('base_url', baseUrl);
          OptionsBackend.saveOption('base_signing_url', baseSigningUrl);
          TwitterLib.URLS.BASE = baseUrl;
          TwitterLib.URLS.BASE_SIGNING = baseSigningUrl;
        }
      }
      if(compareVersions(storageVersion, [1, 8, 5]) <= 0) {
        // Enabling desktop notifications as the default option,
        // users may switch back to onpage notifications latter if they wish.
        OptionsBackend.saveOption('tweets_notification_style', 'desktop');
      }
      if(compareVersions(storageVersion, [1, 9, 5, 1]) <= 0) {
        var maxNotifications = OptionsBackend.get('notification_max_popups');
        if(maxNotifications == -1) {
          // Set new default value if we're using unlimited notifications,
          // otherwise there might have been thousands of notifications
          // to be shown, mainly after we fixed the way we fetch new
          // tweets.
          OptionsBackend.saveOption('notification_max_popups', OptionsBackend.defaultOptions['notification_max_popups']);
        }
      }
      storageData.save(JSON.stringify(currentVersion));
    }
  } catch(e) {
    /* experimental code, something can go wrong */
    console.log(e);
  }
}

initializeExtension();
$.ajax({
  type: 'GET',
  url: 'manifest.json',
  data: {},
  dataType: "json",
  timeout: 5000,
  success: function(data, status) {
    checkVersionChanges(data);
  },
  error: function (request, status, error) {
    try {
      // Ugly hack, but currently Chrome is returning an error
      checkVersionChanges(JSON.parse(request.responseText));
    } catch(e) {
      /* Something can go wrong, ignoring... */
    }
  }
});

function initializeExtension() {
  TweetManager.instance = new TweetManager();

  var waitingFirstRequest = true;
  var selectedResponse = null;
  var biggestArea = -1;
  chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    if(request.cb_requesting_tweets) {
      if(waitingFirstRequest) {
        waitingFirstRequest = false;
        setTimeout(function() {
          if(selectedResponse) {
            selectedResponse({
              tweets: TweetManager.instance.injectTweets,
              nameAttribute: OptionsBackend.get('name_attribute'),
              fadeTimeout: OptionsBackend.get('notification_fade_timeout')
            });
          }
          waitingFirstRequest = true;
          TweetManager.instance.injectTweets = null;
          biggestArea = -1;
        }, 200);
      }
      var area = request.frame_area;
      if(area >= biggestArea) {
        biggestArea = area;
        selectedResponse = sendResponse;
      }
      return;
    }
  });
}
</script>
</body>
</html>


text:
'use strict';

angular.module('tracks').directive('dropdown', [
  function () {
    return {
      restrict: 'E',
      require: '^ngModel',
      scope: {
        ngModel: '=', // selection
        items: '=',   // items to select from
        callback: '&' // callback
      },
      link: function (scope, element, attrs) {
        element.on('click', function (event) {
          event.preventDefault();
        });

        scope.default = 'Choose genre';
        scope.isButton = 'isButton' in attrs;

        // selection changed handler
        scope.select = function (item) {
          scope.ngModel = item;
          if (scope.callback) {
            scope.callback({item: item});
          }
        };
      },
      templateUrl: 'modules/tracks/views/templates/dropdown.client.view.html'
    };
  }
]);


text:
AFL is well known evolutionary file fuzzer, capable of operating in both white-box and black-box modes.
It is designed primarily for programs written in the C family languages, and integrates well with the LLVM toolchain.

## Design Principles
AFL is designed for practicality above all else. It is extremely easy to use, often requiring no configuration at all.

## Workings
AFL stores uses binary files as test cases, and tracks behavior by injecting code to detect branches.
Each transition between branches is represented by a tuple of the form (START_BRANCH, END_BRANCH), and a series of these tuples represent an execution path.
The performance of input test cases is measured by the number of tuple transitions is causes the program to go through.
Input test cases are stored in a queue.
AFL does not perform crossovers, relying entirely on bit manipulation and other mutations.
If a mutated test cases produces a significant difference in the number of tuples, it is added to the queue.
AFL also routinely culls the input queue, to remove test cases who's edge coverage is a strict superset of another test case.

The actual fuzzing process and test case generation/mutation can vary.
In the beginning, AFL tends to use more deterministic methods, such as:
- Sequential bit flips with varying lengths and stepovers
- Sequential addition and subtraction of small integers
- Sequential insertion of known interesting integers (0, 1, INT_MAX, etc)
This helps since deterministic methods tend to produce more compact test cases, with small differences between .
It then proceeds to more non-deterministic strategies such as stacked bit-flips, insertions, deletions, arithmetic, and so on.

AFL also periodically trims test cases to reduce their file size, to combat the gradual growth that iterative mutations produce.
This drastically improves performance, both because smaller files are easier to test, and to increase the effectiveness of further mutations(if the test cases was not trimmed, mutations may happen in irrelevant blocks, wasting time and space).
If the trimmed file produces the same execution trace as its parent, it replaces the parent file.

AFL can also run in black-box mode, using QEMU (in user emulation mode) to track branches.


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

<title>ElasticConstants (apache-nutch 2.3 API)</title>
<meta name="date" content="2015-01-09">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.nutch.indexwriter.elastic

Interface ElasticConstants

public interface ElasticConstants

Field Summary

Fields

Modifier and Type
Field and Description

static String
CLUSTER

static String
ELASTIC_PREFIX

static String
HOST

static String
INDEX

static String
MAX_BULK_DOCS

static String
MAX_BULK_LENGTH

static String
PORT

Field Detail

ELASTIC_PREFIX

static final String ELASTIC_PREFIX

See Also:

Constant Field Values

HOST

static final String HOST

See Also:

Constant Field Values

PORT

static final String PORT

See Also:

Constant Field Values

CLUSTER

static final String CLUSTER

See Also:

Constant Field Values

INDEX

static final String INDEX

See Also:

Constant Field Values

MAX_BULK_DOCS

static final String MAX_BULK_DOCS

See Also:

Constant Field Values

MAX_BULK_LENGTH

static final String MAX_BULK_LENGTH

See Also:

Constant Field Values

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2015 The Apache Software Foundation


text:
Display the kubernetes dashboard URL

### Synopsis

Display the kubernetes dashboard URL

```
kismatic dashboard url [flags]
```

### Options

```
  -h, --help   help for url
```

### Options inherited from parent commands

```
      --generated-assets-dir string   path to the directory where assets generated during the installation process will be stored (default "generated")
  -f, --plan-file string              path to the installation plan file (default "kismatic-cluster.yaml")
```

### SEE ALSO

* [kismatic dashboard](kismatic_dashboard.md)	 - Opens the kubernetes dashboard URL of the cluster

###### Auto generated by spf13/cobra on 13-Jun-2018


text:
<?php

namespace Prelude\Tests;

use function Prelude\map;

class MapTest extends \PHPUnit\Framework\TestCase
{
    /**
     * @test
     */
    public function shouldMappedNamesToUpperCase()
    {
        $names = ['James', 'Kirk'];

        $upper = map('strtoupper');

        $this->assertEquals(['JAMES', 'KIRK'], $upper($names));
    }
}


text:
module Admin::Controllers::Course
  class Import
    include Admin::Action
    include OldNoteshare

    expose :active_item

    def call(params)
      redirect_if_not_admin('Attempt to import course (admin, course, import)')
      @active_item = 'admin'
    end
  end
end


text:
from django.core.management.base import BaseCommand, CommandError

class Command(BaseCommand):
    help = "Useless command."

    def add_arguments(self, parser):
        parser.add_argument('args', metavar='app_label', nargs='*',
            help='Specify the app label(s) to works on.')
        parser.add_argument('--empty', action='store_true', dest='empty', default=False,
            help="Do nothing.")

    def handle(self, *app_labels, **options):
        app_labels = set(app_labels)

        if options['empty']:
            self.stdout.write("Dave, I can't do that.")
            return

        if not app_labels:
            raise CommandError("I'm sorry Dave, I'm afraid I can't do that.")

        # raise an error if some --parameter is flowing from options to args
        for app_label in app_labels:
            if app_label.startswith('--'):
                raise CommandError("Sorry, Dave, I can't let you do that.")

        self.stdout.write("Dave, my mind is going. I can feel it. I can feel it.")


text:
var browserStorage = require('browser-storage');

function LocalStorage() {
  this.$storage = browserStorage;
}

LocalStorage.prototype.set = function set(key, value) {
  this.$storage.setItem(key, JSON.stringify(value));
};

LocalStorage.prototype.get = function get(key) {
  return JSON.parse(this.$storage.getItem(key));
};

LocalStorage.prototype.remove = function remove(key) {
  this.$storage.removeItem(key);
};

LocalStorage.isAvailable = function isAvailable() {
  return !!browserStorage;
};

module.exports = LocalStorage;


text:
<resources>
    <string name="app_name">Ting</string>
    <string name="song_info">歌曲详细信息以及评论</string>
    <string name="user_profile">用户简介信息</string>

    <string name="action_about">关于我</string>
    <string name="action_setting">设置</string>
    <string name="action_share">分享</string>
    <string name="action_download">下载</string>
    <string name="action_download_setting">下载管理</string>

    <string name="download_progress">下载进度</string>
    <string name="download_start">下载开始</string>
    <string name="download_pause">暂停下载</string>
    <string name="download_cancel">取消下载</string>
    <string name="download_not">没有歌曲正在下载</string>

    <string name="open">打开</string>
    <string name="close">关闭</string>

    <string name="user_name">用户名</string>
    <string name="user_bio">用户个性签名</string>
    <string name="user_image">用户头像</string>
    <string name="user_email">用户邮箱</string>

    <string name="song_name">歌曲名</string>
    <string name="song_artist">歌手</string>
    <string name="song_bio">歌曲描述</string>
    <string name="song_empty">很抱歉,没有扫描到歌曲</string>

    <string name="comment">评论</string>
    <string name="comment_user_pic">评论人头像</string>
    <string name="comment_user_name">评论人名称</string>
    <string name="comment_content">评论信息</string>

    <string name="songs">Songs</string>
    <string name="likes">Likes</string>
    <string name="comments">Comments</string>
    <string name="songs_count">100</string>
    <string name="likes_count">200</string>
    <string name="comments_count">100</string>

</resources>


text:
function BranchData() {
    this.position = -1;
    this.nodeLength = -1;
    this.src = null;
    this.evalFalse = 0;
    this.evalTrue = 0;

    this.init = function(position, nodeLength, src) {
        this.position = position;
        this.nodeLength = nodeLength;
        this.src = src;
        return this;
    }

    this.ranCondition = function(result) {
        if (result)
            this.evalTrue++;
        else
            this.evalFalse++;
    };

    this.pathsCovered = function() {
        var paths = 0;
        if (this.evalTrue > 0)
          paths++;
        if (this.evalFalse > 0)
          paths++;
        return paths;
    };

    this.covered = function() {
        return this.evalTrue > 0 && this.evalFalse > 0;
    };

    this.toJSON = function() {
        return '{"position":' + this.position
            + ',"nodeLength":' + this.nodeLength
            + ',"src":' + jscoverage_quote(this.src)
            + ',"evalFalse":' + this.evalFalse
            + ',"evalTrue":' + this.evalTrue + '}';
    };

    this.message = function() {
        if (this.evalTrue === 0 && this.evalFalse === 0)
            return 'Condition never evaluated         :\t' + this.src;
        else if (this.evalTrue === 0)
            return 'Condition never evaluated to true :\t' + this.src;
        else if (this.evalFalse === 0)
            return 'Condition never evaluated to false:\t' + this.src;
        else
            return 'Condition covered';
    };
}

BranchData.fromJson = function(jsonString) {
    var json = eval('(' + jsonString + ')');
    var branchData = new BranchData();
    branchData.init(json.position, json.nodeLength, json.src);
    branchData.evalFalse = json.evalFalse;
    branchData.evalTrue = json.evalTrue;
    return branchData;
};

BranchData.fromJsonObject = function(json) {
    var branchData = new BranchData();
    branchData.init(json.position, json.nodeLength, json.src);
    branchData.evalFalse = json.evalFalse;
    branchData.evalTrue = json.evalTrue;
    return branchData;
};

function buildBranchMessage(conditions) {
    var message = 'The following was not covered:';
    for (var i = 0; i < conditions.length; i++) {
        if (conditions[i] !== undefined && conditions[i] !== null && !conditions[i].covered())
          message += '\n- '+ conditions[i].message();
    }
    return message;
};

function convertBranchDataConditionArrayToJSON(branchDataConditionArray) {
    var array = [];
    var length = branchDataConditionArray.length;
    for (var condition = 0; condition < length; condition++) {
        var branchDataObject = branchDataConditionArray[condition];
        if (branchDataObject === undefined || branchDataObject === null) {
            value = 'null';
        } else {
            value = branchDataObject.toJSON();
        }
        array.push(value);
    }
    return '[' + array.join(',') + ']';
}

function convertBranchDataLinesToJSON(branchData) {
    if (branchData === undefined) {
        return '{}'
    }
    var json = '';
    for (var line in branchData) {
        if (json !== '')
            json += ','
        json += '"' + line + '":' + convertBranchDataConditionArrayToJSON(branchData[line]);
    }
    return '{' + json + '}';
}

function convertBranchDataLinesFromJSON(jsonObject) {
    if (jsonObject === undefined) {
        return {};
    }
    for (var line in jsonObject) {
        var branchDataJSON = jsonObject[line];
        if (branchDataJSON !== null) {
            for (var conditionIndex = 0; conditionIndex < branchDataJSON.length; conditionIndex ++) {
                var condition = branchDataJSON[conditionIndex];
                if (condition !== null) {
                    branchDataJSON[conditionIndex] = BranchData.fromJsonObject(condition);
                }
            }
        }
    }
    return jsonObject;
}
function jscoverage_quote(s) {
    return '"' + s.replace(/[\u0000-\u001f"\\\u007f-\uffff]/g, function (c) {
        switch (c) {
            case '\b':
                return '\\b';
            case '\f':
                return '\\f';
            case '\n':
                return '\\n';
            case '\r':
                return '\\r';
            case '\t':
                return '\\t';
            // IE doesn't support this
            /*
             case '\v':
             return '\\v';
             */
            case '"':
                return '\\"';
            case '\\':
                return '\\\\';
            default:
                return '\\u' + jscoverage_pad(c.charCodeAt(0).toString(16));
        }
    }) + '"';
}

function getArrayJSON(coverage) {
    var array = [];
    if (coverage === undefined)
        return array;

    var length = coverage.length;
    for (var line = 0; line < length; line++) {
        var value = coverage[line];
        if (value === undefined || value === null) {
            value = 'null';
        }
        array.push(value);
    }
    return array;
}

function jscoverage_serializeCoverageToJSON() {
    var json = [];
    for (var file in _$jscoverage) {
        var lineArray = getArrayJSON(_$jscoverage[file].lineData);
        var fnArray = getArrayJSON(_$jscoverage[file].functionData);

        json.push(jscoverage_quote(file) + ':{"lineData":[' + lineArray.join(',') + '],"functionData":[' + fnArray.join(',') + '],"branchData":' + convertBranchDataLinesToJSON(_$jscoverage[file].branchData) + '}');
    }
    return '{' + json.join(',') + '}';
}

function jscoverage_pad(s) {
    return '0000'.substr(s.length) + s;
}

function jscoverage_html_escape(s) {
    return s.replace(/[<>\&\"\']/g, function (c) {
        return '&#' + c.charCodeAt(0) + ';';
    });
}
try {
  if (typeof top === 'object' && top !== null && typeof top.opener === 'object' && top.opener !== null) {
    // this is a browser window that was opened from another window

    if (! top.opener._$jscoverage) {
      top.opener._$jscoverage = {};
    }
  }
}
catch (e) {}

try {
  if (typeof top === 'object' && top !== null) {
    // this is a browser window

    try {
      if (typeof top.opener === 'object' && top.opener !== null && top.opener._$jscoverage) {
        top._$jscoverage = top.opener._$jscoverage;
      }
    }
    catch (e) {}

    if (! top._$jscoverage) {
      top._$jscoverage = {};
    }
  }
}
catch (e) {}

try {
  if (typeof top === 'object' && top !== null && top._$jscoverage) {
    this._$jscoverage = top._$jscoverage;
  }
}
catch (e) {}
if (! this._$jscoverage) {
  this._$jscoverage = {};
}
if (! _$jscoverage['/base/observer.js']) {
  _$jscoverage['/base/observer.js'] = {};
  _$jscoverage['/base/observer.js'].lineData = [];
  _$jscoverage['/base/observer.js'].lineData[6] = 0;
  _$jscoverage['/base/observer.js'].lineData[13] = 0;
  _$jscoverage['/base/observer.js'].lineData[14] = 0;
  _$jscoverage['/base/observer.js'].lineData[34] = 0;
  _$jscoverage['/base/observer.js'].lineData[44] = 0;
  _$jscoverage['/base/observer.js'].lineData[45] = 0;
  _$jscoverage['/base/observer.js'].lineData[46] = 0;
  _$jscoverage['/base/observer.js'].lineData[57] = 0;
  _$jscoverage['/base/observer.js'].lineData[59] = 0;
  _$jscoverage['/base/observer.js'].lineData[60] = 0;
  _$jscoverage['/base/observer.js'].lineData[62] = 0;
  _$jscoverage['/base/observer.js'].lineData[64] = 0;
  _$jscoverage['/base/observer.js'].lineData[74] = 0;
  _$jscoverage['/base/observer.js'].lineData[76] = 0;
  _$jscoverage['/base/observer.js'].lineData[77] = 0;
  _$jscoverage['/base/observer.js'].lineData[79] = 0;
  _$jscoverage['/base/observer.js'].lineData[88] = 0;
  _$jscoverage['/base/observer.js'].lineData[92] = 0;
  _$jscoverage['/base/observer.js'].lineData[93] = 0;
  _$jscoverage['/base/observer.js'].lineData[96] = 0;
  _$jscoverage['/base/observer.js'].lineData[101] = 0;
}
if (! _$jscoverage['/base/observer.js'].functionData) {
  _$jscoverage['/base/observer.js'].functionData = [];
  _$jscoverage['/base/observer.js'].functionData[0] = 0;
  _$jscoverage['/base/observer.js'].functionData[1] = 0;
  _$jscoverage['/base/observer.js'].functionData[2] = 0;
  _$jscoverage['/base/observer.js'].functionData[3] = 0;
  _$jscoverage['/base/observer.js'].functionData[4] = 0;
  _$jscoverage['/base/observer.js'].functionData[5] = 0;
  _$jscoverage['/base/observer.js'].functionData[6] = 0;
}
if (! _$jscoverage['/base/observer.js'].branchData) {
  _$jscoverage['/base/observer.js'].branchData = {};
  _$jscoverage['/base/observer.js'].branchData['46'] = [];
  _$jscoverage['/base/observer.js'].branchData['46'][1] = new BranchData();
  _$jscoverage['/base/observer.js'].branchData['46'][2] = new BranchData();
  _$jscoverage['/base/observer.js'].branchData['59'] = [];
  _$jscoverage['/base/observer.js'].branchData['59'][1] = new BranchData();
  _$jscoverage['/base/observer.js'].branchData['60'] = [];
  _$jscoverage['/base/observer.js'].branchData['60'][1] = new BranchData();
  _$jscoverage['/base/observer.js'].branchData['76'] = [];
  _$jscoverage['/base/observer.js'].branchData['76'][1] = new BranchData();
  _$jscoverage['/base/observer.js'].branchData['92'] = [];
  _$jscoverage['/base/observer.js'].branchData['92'][1] = new BranchData();
  _$jscoverage['/base/observer.js'].branchData['92'][2] = new BranchData();
}
_$jscoverage['/base/observer.js'].branchData['92'][2].init(184, 47, '!self.groups || !(self.groups.match(_ksGroups))');
function visit12_92_2(result) {
  _$jscoverage['/base/observer.js'].branchData['92'][2].ranCondition(result);
  return result;
}_$jscoverage['/base/observer.js'].branchData['92'][1].init(170, 62, '_ksGroups && (!self.groups || !(self.groups.match(_ksGroups)))');
function visit11_92_1(result) {
  _$jscoverage['/base/observer.js'].branchData['92'][1].ranCondition(result);
  return result;
}_$jscoverage['/base/observer.js'].branchData['76'][1].init(133, 13, 'ret === false');
function visit10_76_1(result) {
  _$jscoverage['/base/observer.js'].branchData['76'][1].ranCondition(result);
  return result;
}_$jscoverage['/base/observer.js'].branchData['60'][1].init(151, 9, 'self.once');
function visit9_60_1(result) {
  _$jscoverage['/base/observer.js'].branchData['60'][1].ranCondition(result);
  return result;
}_$jscoverage['/base/observer.js'].branchData['59'][1].init(82, 32, 'self.context || ce.currentTarget');
function visit8_59_1(result) {
  _$jscoverage['/base/observer.js'].branchData['59'][1].ranCondition(result);
  return result;
}_$jscoverage['/base/observer.js'].branchData['46'][2].init(30, 15, 's1[k] === s2[k]');
function visit7_46_2(result) {
  _$jscoverage['/base/observer.js'].branchData['46'][2].ranCondition(result);
  return result;
}_$jscoverage['/base/observer.js'].branchData['46'][1].init(24, 22, 'v && (s1[k] === s2[k])');
function visit6_46_1(result) {
  _$jscoverage['/base/observer.js'].branchData['46'][1].ranCondition(result);
  return result;
}_$jscoverage['/base/observer.js'].lineData[6]++;
KISSY.add(function(S) {
  _$jscoverage['/base/observer.js'].functionData[0]++;
  _$jscoverage['/base/observer.js'].lineData[13]++;
  function Observer(cfg) {
    _$jscoverage['/base/observer.js'].functionData[1]++;
    _$jscoverage['/base/observer.js'].lineData[14]++;
    S.mix(this, cfg);
  }
  _$jscoverage['/base/observer.js'].lineData[34]++;
  Observer.prototype = {
  constructor: Observer,
  equals: function(s2) {
  _$jscoverage['/base/observer.js'].functionData[2]++;
  _$jscoverage['/base/observer.js'].lineData[44]++;
  var s1 = this;
  _$jscoverage['/base/observer.js'].lineData[45]++;
  return !!S.reduce(s1.keys, function(v, k) {
  _$jscoverage['/base/observer.js'].functionData[3]++;
  _$jscoverage['/base/observer.js'].lineData[46]++;
  return visit6_46_1(v && (visit7_46_2(s1[k] === s2[k])));
}, 1);
},
  simpleNotify: function(event, ce) {
  _$jscoverage['/base/observer.js'].functionData[4]++;
  _$jscoverage['/base/observer.js'].lineData[57]++;
  var ret, self = this;
  _$jscoverage['/base/observer.js'].lineData[59]++;
  ret = self.fn.call(visit8_59_1(self.context || ce.currentTarget), event, self.data);
  _$jscoverage['/base/observer.js'].lineData[60]++;
  if (visit9_60_1(self.once)) {
    _$jscoverage['/base/observer.js'].lineData[62]++;
    ce.removeObserver(self);
  }
  _$jscoverage['/base/observer.js'].lineData[64]++;
  return ret;
},
  notifyInternal: function(event, ce) {
  _$jscoverage['/base/observer.js'].functionData[5]++;
  _$jscoverage['/base/observer.js'].lineData[74]++;
  var ret = this.simpleNotify(event, ce);
  _$jscoverage['/base/observer.js'].lineData[76]++;
  if (visit10_76_1(ret === false)) {
    _$jscoverage['/base/observer.js'].lineData[77]++;
    event.halt();
  }
  _$jscoverage['/base/observer.js'].lineData[79]++;
  return ret;
},
  notify: function(event, ce) {
  _$jscoverage['/base/observer.js'].functionData[6]++;
  _$jscoverage['/base/observer.js'].lineData[88]++;
  var self = this, _ksGroups = event._ksGroups;
  _$jscoverage['/base/observer.js'].lineData[92]++;
  if (visit11_92_1(_ksGroups && (visit12_92_2(!self.groups || !(self.groups.match(_ksGroups)))))) {
    _$jscoverage['/base/observer.js'].lineData[93]++;
    return undefined;
  }
  _$jscoverage['/base/observer.js'].lineData[96]++;
  return self.notifyInternal(event, ce);
}};
  _$jscoverage['/base/observer.js'].lineData[101]++;
  return Observer;
});


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/aiplatform/v1beta1/featurestore_online_service.proto

package com.google.cloud.aiplatform.v1beta1;

public interface ReadFeatureValuesRequestOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.aiplatform.v1beta1.ReadFeatureValuesRequest)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Required. The resource name of the EntityType for the entity being read.
   * Value format:
   * `projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entityType}`.
   * For example, for a machine learning model predicting user clicks on a
   * website, an EntityType ID could be `user`.
   *

   *
   *
   * string entity_type = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
   *
   *
   * @return The entityType.
   */
  java.lang.String getEntityType();
  /**
   *
   *
   *

   * Required. The resource name of the EntityType for the entity being read.
   * Value format:
   * `projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entityType}`.
   * For example, for a machine learning model predicting user clicks on a
   * website, an EntityType ID could be `user`.
   *

   *
   *
   * string entity_type = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
   *
   *
   * @return The bytes for entityType.
   */
  com.google.protobuf.ByteString getEntityTypeBytes();

  /**
   *
   *
   *

   * Required. ID for a specific entity. For example,
   * for a machine learning model predicting user clicks on a website, an entity
   * ID could be `user_123`.
   *

   *
   * string entity_id = 2 [(.google.api.field_behavior) = REQUIRED];
   *
   * @return The entityId.
   */
  java.lang.String getEntityId();
  /**
   *
   *
   *

   * Required. ID for a specific entity. For example,
   * for a machine learning model predicting user clicks on a website, an entity
   * ID could be `user_123`.
   *

   *
   * string entity_id = 2 [(.google.api.field_behavior) = REQUIRED];
   *
   * @return The bytes for entityId.
   */
  com.google.protobuf.ByteString getEntityIdBytes();

  /**
   *
   *
   *

   * Required. Selector choosing Features of the target EntityType.
   *

   *
   *
   * .google.cloud.aiplatform.v1beta1.FeatureSelector feature_selector = 3 [(.google.api.field_behavior) = REQUIRED];
   *
   *
   * @return Whether the featureSelector field is set.
   */
  boolean hasFeatureSelector();
  /**
   *
   *
   *

   * Required. Selector choosing Features of the target EntityType.
   *

   *
   *
   * .google.cloud.aiplatform.v1beta1.FeatureSelector feature_selector = 3 [(.google.api.field_behavior) = REQUIRED];
   *
   *
   * @return The featureSelector.
   */
  com.google.cloud.aiplatform.v1beta1.FeatureSelector getFeatureSelector();
  /**
   *
   *
   *

   * Required. Selector choosing Features of the target EntityType.
   *

   *
   *
   * .google.cloud.aiplatform.v1beta1.FeatureSelector feature_selector = 3 [(.google.api.field_behavior) = REQUIRED];
   *
   */
  com.google.cloud.aiplatform.v1beta1.FeatureSelectorOrBuilder getFeatureSelectorOrBuilder();
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using CodeOwls.PowerShell.Provider.PathNodeProcessors;
using CodeOwls.PowerShell.Provider.PathNodes;
using Microsoft.SqlServer.Dts.Runtime;

namespace CodeOwls.BIPS
{
    public class PrecedenceConstraintCollectionNodeFactory : CollectionNodeFactory<PrecedenceConstraint>, INewItem
    {
        private readonly PrecedenceConstraints _items;
        private readonly Executables _executables;

        public PrecedenceConstraintCollectionNodeFactory(string collectionName, PrecedenceConstraints items, Executables executables, Converter<PrecedenceConstraint, INodeFactory> adapter)
            : base(collectionName, items.Cast<PrecedenceConstraint>().ToList(), adapter)
        {
            _items = items;
            _executables = executables;
        }

        private const string Success = "Success";
        private const string Failure = "Failure";
        private const string Completion = "Completion";
        private const string Cancel = "Cancel";

        public IEnumerable<string> NewItemTypeNames
        {
            get
            {
                return new[]
                {
                    Success, Failure, Completion, Cancel
                };
            }
        }
        public object NewItemParameters { get; private set; }
        public IPathNode NewItem(IContext context, string path, string itemTypeName, object newItemValue)
        {
            Executable from = null;
            Executable to = null;

            string fromName = null;
            string toName = null;

            var map = new Dictionary<string, DTSExecResult>(StringComparer.InvariantCultureIgnoreCase)
            {
                {Success, DTSExecResult.Success},
                {Failure, DTSExecResult.Failure},
                {Completion, DTSExecResult.Completion},
                {Cancel, DTSExecResult.Canceled}
            };

            if (! map.ContainsKey(itemTypeName))
            {
                throw new ArgumentException( String.Format(
@"The specified item type '{0}' is not valid.  Please use one of the following values: {1}",
                    itemTypeName, String.Join( ", ", NewItemTypeNames)));
            }

            var valueType = newItemValue.GetType();
            if (valueType == typeof (string))
            {
                GetConstraintTaskNames(newItemValue, out fromName, out toName);
            }
            else if (valueType == typeof (object[]))
            {
                var names = (object[]) newItemValue;
                fromName = names[0].ToString();
                toName = names[1].ToString();
            }

            var exes = _executables.Cast<TaskHost>().ToList();
            from = exes.FirstOrDefault(e => StringComparer.InvariantCultureIgnoreCase.Equals(fromName, e.Name));
            to = exes.FirstOrDefault(e => StringComparer.InvariantCultureIgnoreCase.Equals(toName, e.Name));

            if (null == from)
            {
                throw new ArgumentException( "The task name '" + fromName + "' could not be found in the executables for this component");
            }
            if (null == to)
            {
                throw new ArgumentException("The task name '" + toName + "' could not be found in the executables for this component");
            }

            var constraint = _items.Add(from, to);
            constraint.Name = path;

            constraint.Value = map[itemTypeName];
            var resolvedItem = context.ResolvePath(context.Path);
            return resolvedItem.GetNodeValue();
        }

        private static void GetConstraintTaskNames(object newItemValue, out string fromName, out string toName)
        {
            var drawing = newItemValue.ToString();
            // my from task -> my to task
            // task <- task
            // task to task
            // task from task
            var re = new Regex(@"(?<firstTaskName>[\w\s]+?)\s*((?<to>to|.?>)|(?<from>)from|<.?)\s*(?<secondTaskName>[\w\s]+)");

            var matches = re.Match(drawing);
            if (! matches.Success)
            {
                throw new ArgumentException(
                    @"The value parameter is in an incorrect format.  Please specify the constraint relationship between two tasks:
Predecence -> Constrained
Constrained <- Predecence
Predecence to Constrained
Constrained from Predecence
");
            }

            fromName = matches.Groups["firstTaskName"].Value;
            toName = matches.Groups["secondTaskName"].Value;

            if (matches.Groups["from"].Success)
            {
                var swap = toName;
                toName = fromName;
                fromName = swap;
            }
        }
    }
}


text:
<!doctype html>

		<meta charset="utf-8">

		<title>charmCityJs</title>

		<meta name="description" content="A framework for easily creating beautiful presentations using HTML">
		<meta name="author" content="Hakim El Hattab">

		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">

		<link rel="stylesheet" href="css/reveal.css">
		<link rel="stylesheet" href="css/theme/charmcity.css" id="theme">

		<link rel="stylesheet" href="lib/css/zenburn.css">

NodeSchool!

Next one: Sunday, November 20th 1-4pm

Still need TAs and attendees!!!

REGISTER

Announcements from the crowd?

SPONSORS


text:
<?php

$_lang['preg_match_activate_plugin'] = '/trama di(.*)/';
$_lang['no_results'] = 'Mi dispiace, signore. Non ho trovato il film che mi ha indicato.';


text:
<bill session="115" type="h" number="3806" updated="2017-10-13T07:17:20Z">
  <state datetime="2017-09-18">REFERRED</state>
  <status>
    <introduced datetime="2017-09-18"/>
  </status>
  <introduced datetime="2017-09-18"/>
  <titles>
    <title type="short" as="introduced">Personal Data Notification and Protection Act of 2017</title>
    <title type="short" as="introduced">Personal Data Notification and Protection Act of 2017</title>
    <title type="official" as="introduced">To establish a national data breach notification standard, and for other purposes.</title>
    <title type="display">Personal Data Notification and Protection Act of 2017</title>
  </titles>
  <sponsor bioguide_id="L000559"/>
  <cosponsors>
    <cosponsor bioguide_id="D000627" joined="2017-10-12"/>
    <cosponsor bioguide_id="K000389" joined="2017-09-25"/>
    <cosponsor bioguide_id="L000582" joined="2017-09-18"/>
    <cosponsor bioguide_id="R000576" joined="2017-10-10"/>
    <cosponsor bioguide_id="S001170" joined="2017-09-25"/>
    <cosponsor bioguide_id="S000480" joined="2017-10-12"/>
    <cosponsor bioguide_id="T000472" joined="2017-10-03"/>
  </cosponsors>
  <actions>
    <action datetime="2017-09-18">
      <text>Introduced in House</text>
    </action>
    <action datetime="2017-09-18" state="REFERRED">
      <text>Referred to the Committee on Energy and Commerce, and in addition to the Committee on the Judiciary, for a period to be subsequently determined by the Speaker, in each case for consideration of such provisions as fall within the jurisdiction of the committee concerned.</text>
    </action>
    <action datetime="2017-09-18">
      <text>Referred to the Committee on Energy and Commerce, and in addition to the Committee on the Judiciary, for a period to be subsequently determined by the Speaker, in each case for consideration of such provisions as fall within the jurisdiction of the committee concerned.</text>
    </action>
  </actions>
  <committees>
    <committee subcommittee="" code="HSJU" name="House Judiciary" activity="Referral"/>
    <committee subcommittee="" code="HSIF" name="House Energy and Commerce" activity="Referral"/>
  </committees>
  <relatedbills>
    <bill type="h" session="115" relation="unknown" number="3904"/>
  </relatedbills>
  <subjects>
    <term name="Science, technology, communications"/>
  </subjects>
  <amendments/>
  <committee-reports/>
</bill>


text:
package com.jamesdube.laravelnewsapp.posts;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jamesdube.laravelnewsapp.App;
import com.jamesdube.laravelnewsapp.MainActivity;
import com.jamesdube.laravelnewsapp.R;
import com.jamesdube.laravelnewsapp.adapters.PostAdapter;
import com.jamesdube.laravelnewsapp.models.Post;
import com.jamesdube.laravelnewsapp.models.PostRepository;
import com.jamesdube.laravelnewsapp.sync.SyncAdapter;
import com.jamesdube.laravelnewsapp.util.RecyclerViewEmptySupport;

import io.realm.RealmChangeListener;
import io.realm.RealmResults;

import static com.jamesdube.laravelnewsapp.MainActivity.Title;
import static com.jamesdube.laravelnewsapp.util.Constants.CATEGORY_PACKAGES;
import static com.jamesdube.laravelnewsapp.util.Constants.CATEGORY_TUTORIALS;
import static com.jamesdube.laravelnewsapp.util.Constants.POSTS_ACTIVE;
import static com.jamesdube.laravelnewsapp.util.Constants.POSTS_ARCHIVED;
import static com.jamesdube.laravelnewsapp.util.Constants.POSTS_FAVOURITES;
import static com.jamesdube.laravelnewsapp.util.Constants.POSTS_PACKAGES;
import static com.jamesdube.laravelnewsapp.util.Constants.POSTS_TUTORIALS;

public class PostsFragment extends Fragment {

    RecyclerViewEmptySupport recyclerView;
    PostAdapter adapter;
    LinearLayout emptyView;
    BroadcastReceiver syncSuccess,syncError;
    RealmChangeListener<RealmResults<Post>> changeListener;
    SwipeRefreshLayout swipeRefreshLayout;
    public static String POSTS = "POSTS";

    public static PostsFragment newInstance() {

        Bundle args = new Bundle();

        PostsFragment fragment = new PostsFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onStart() {
        super.onStart();
        boot();

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_posts,container,false);
    }

    private void boot() {

        RealmResults <Post> posts = getPosts();

        recyclerView = (RecyclerViewEmptySupport) getActivity().findViewById(R.id.postsRecyclerview);
        swipeRefreshLayout = (SwipeRefreshLayout) getActivity().findViewById(R.id.postsSwipeLayout);
        emptyView = (LinearLayout) getActivity().findViewById(R.id.postsEmptyView);
        emptyView = (LinearLayout) getActivity().findViewById(R.id.postsEmptyView);
        emptyView = (LinearLayout) getActivity().findViewById(R.id.postsEmptyView);

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Log.d(App.Tag,"posts fragment onRefresh");
                registerReceivers();
                SyncAdapter.syncImmediately(App.getAppContext());
            }
        });

        syncSuccess = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                Log.d("xxxx ", "Sync finished, should refresh now");
                swipeRefreshLayout.setRefreshing(false);
                //repopulate
                adapter.notifyDataSetChanged();
                unRegisterReceivers();
                MainActivity.showSnackBar("Refresh complete...");

            }
        };

        syncError = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                Log.d(App.Tag, "Sync finished with error");
                swipeRefreshLayout.setRefreshing(false);
                //repopulate
                adapter.notifyDataSetChanged();
                //notify the user
                MainActivity.showSnackBar("Cannot refresh feed at the moment...");
                unRegisterReceivers();

            }
        };

        changeListener = new RealmChangeListener<RealmResults<Post>>() {

            @Override
            public void onChange(RealmResults<Post> element) {
                Log.d(App.Tag,"posts fragment onChange posts("+element.size()+")");
                adapter.notifyDataSetChanged(); // Update the UI
                swipeRefreshLayout.setRefreshing(false);
            }
        };

        ItemTouchHelper.SimpleCallback simpleCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT){

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                final Post post = adapter.getPost(viewHolder.getAdapterPosition());
                PostRepository.archive(post);
                adapter.notifyDataSetChanged();

                //show notification
                MainActivity.showSnackBarWithAction("Post archived", "Undo", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PostRepository.unArchive(post);
                        adapter.notifyDataSetChanged();
                    }
                });
            }
        };

        ItemTouchHelper touchHelper = new ItemTouchHelper(simpleCallback);
        touchHelper.attachToRecyclerView(recyclerView);
        // Tell Realm to notify our listener when the posts results
        // have changed (items added, removed, updated, anything of the sort).

        setupAdapter(posts);

    }

    public void setPosts(String criteria) {

        POSTS = criteria;

        //change the title
        Title = (POSTS);

        RealmResults<Post> posts = getPosts();

        posts.addChangeListener(changeListener);

        adapter = new PostAdapter(posts);

        recyclerView.setAdapter(adapter);
    }

    @NonNull
    private RealmResults<Post> getPosts() {

        switch (POSTS) {
            case POSTS_ACTIVE: {
                return PostRepository.getActive();
            }
            case POSTS_ARCHIVED: {
                return PostRepository.getArchived();
            }
            case POSTS_PACKAGES: {
                return PostRepository.getByCategory(CATEGORY_PACKAGES);
            }
            case POSTS_TUTORIALS: {
                return PostRepository.getByCategory(CATEGORY_TUTORIALS);
            }
            case POSTS_FAVOURITES: {
                return PostRepository.getFavourites();
            }
            default: {
                return PostRepository.getActive();
            }
        }
    }

    public void setupAdapter(RealmResults<Post> posts) {
        posts.addChangeListener(changeListener);
        adapter = new PostAdapter(posts);
        recyclerView.setLayoutManager(new LinearLayoutManager(App.getAppContext()));
        recyclerView.setEmptyView(emptyView);
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();

    }

    private void registerReceivers() {
        getActivity().registerReceiver(syncSuccess,new IntentFilter(SyncAdapter.SYNC_FINISHED));
        getActivity().registerReceiver(syncError,new IntentFilter(SyncAdapter.SYNC_FINISHED_ERROR));
    }

    private void unRegisterReceivers() {
        try {
            getActivity().unregisterReceiver(syncSuccess);
            getActivity().unregisterReceiver(syncError);
        }catch (IllegalArgumentException e){
            MainActivity.showSnackBar("Error syncing posts");
        }
    }

}