text:
from optparse import OptionParser
import datetime, glob, os, sys, itertools
from itertools import islice

import json, pprint
from collections import defaultdict

from iso8601.iso8601 import parse_date

def score_results(results):
    """Score list of detected events to list of ground truth items (from test_cases.py).
    See: J.A. Ward et al. (2011) http://dl.acm.org/citation.cfm?id=1889687

    returns dict containing:

    segments - ordered list of scored segments. segment is dict with t1, t2, score, and optional err
    """
    truth_time = 0
    truths = results["labels"]
    detected = results["detected"]

    for truth in truths:
        truth_time += (parse_date(truth["t2"]) - parse_date(truth["t1"])).seconds

    overlapped = False
    overlaps = defaultdict(list) #list of state index that overlap truth keyed on truth index

    segs = extract_segments(results)
    segs = score_segments(segs, truths, detected)

    return dict(segments=segs,
                frame_score=score_frames(segs),
                events=score_events(truths, detected, segs))

def extract_segments(results):
    """extract the time segments from labels and detected """
    tt = [ ( parse_date(x["t1"]), parse_date(x["t2"]) ) for x in results["labels"]+results["detected"] ]
    ts = sorted(itertools.chain.from_iterable( tt ))
    t1 = parse_date(results["t1"])
    if t1 < ts[0]:
        ts.insert(0, t1)
    t2 = parse_date(results["t2"])
    if t2 > ts[-1]:
        ts.append(t2)
    return [ dict(t1=x[0].isoformat(), t2=x[1].isoformat()) for x in list(sliding_window(ts, 2)) ]

def label_segments(segs, truths, detected):
    """for each segment, attach `label` from `truth` and `match=True` when truth detected label matches truth, else False if match fails"""
    for seg in segs:
        for truth in truths:
            if time_overlap(seg, truth):
                seg["label"] = truth["label"]
                for det in detected:
                    if time_overlap(seg, det):
                        if det["label"] == truth["label"]:
                            seg["match"] = True
                        else:
                            seg["match"] = False
    return segs

def score_frames(segs):
    """score the frame errors from the segments"""
    d = dict(D=0, I=0, F=0, M=0, Us=0, Ue=0, Os=0, Oe=0, TP=0, TN=0)
    for seg in segs:
        secs = (parse_date(seg["t2"]) - parse_date(seg["t1"])).total_seconds()
        if seg["score"] == "FP" or seg["score"] == "FN":
            if seg.get("err"):
                d[seg["err"]] += secs
        elif seg["score"] == "TP" or seg["score"] == "TN":
            d[seg["score"]] += secs

    d["P"] = d["D"] + d["F"] + d["Us"] + d["Ue"] + d["TP"] #positive frames
    d["N"] = d["I"] + d["M"] + d["Os"] + d["Oe"] + d["TN"] #negative frames

    #calculate frame ratessiter
    ret = dict(p_rates={}, n_rates={}, frame_counts=d)

    POS = ["D", "F", "Us", "Ue", "TP"]
    NEG = ["I", "M", "Os", "Oe", "TN"]

    if d["P"]:
        for i in POS:
            ret["p_rates"][i+"r"] = d[i]*1.0 / d["P"]

    if d["N"]:
        for i in NEG:
            ret["n_rates"][i+"r"] = d[i]*1.0 / d["N"]
    if d["P"] or d["N"]:
        ret["acc"] = (d["TP"]*1.0 + d["TN"]) / (d["P"]*1.0 + d["N"])
        ret["p_rate"] = d["P"]*1.0/(d["P"] + d["N"])
        ret["n_rate"] = d["N"]*1.0/(d["P"] + d["N"])
    return ret

def score_segments(segs, truths, detected):
    """score the segments extracted from truths and detected lists"""
    matches = 0
    for seg in segs:
        truth_match = detected_match = False
        for truth in truths:
            if time_overlap(seg, truth):
                truth_match = True
        for det in detected:
            if time_overlap(seg, det):
                detected_match = True

        #assign basic score to segment (TP|TN|FP|FN)
        if truth_match:
            if detected_match:
                seg["score"] = "TP"
            else:
                seg["score"] = "FN"
        else:
            if detected_match:
                seg["score"] = "FP"
            else:
                seg["score"] = "TN"

    # assign error class to all FN and FP. fig 3, ward et al 2011
    prev_score = next_score = None
    for i in range(len(segs)):
        score = segs[i]["score"]
        if score == "TP" or score == "TN":
            continue

        if i < len(segs)-1:
            next_score = segs[i+1]["score"]

        if i > 0:
            prev_score = segs[i-1]["score"]

        if i == 0: #beginning of sequence

            if score == "FP":
                if next_score is None or next_score == "TN" or next_score == "FN":
                    segs[i]["err"] = "I"
                elif next_score == "TP":
                    segs[i]["err"] = "Os"
                else:
                    warn("Unhandled error case: %s followed by %s" % (score, next_score))

            elif score == "FN":
                if next_score is None or next_score == "TN" or next_score == "FP":
                    segs[i]["err"] = "D"
                elif next_score == "TP":
                    segs[i]["err"] = "Us"
                else:
                    warn("Unhandled error case: %s followed by %s" % (score, next_score))

        elif i == len(segs) - 1: #end of sequence

            if score == "FP":
                if prev_score == "TN" or prev_score == "FN":
                    segs[i]["err"] = "I"
                elif prev_score == "TP":
                    segs[i]["err"] = "Oe"
                else:
                    warn("Unhandled error case: %s followed by %s" % (score, next_score))

            elif score == "FN":
                if prev_score == None or prev_score == "TN" or prev_score == "FP":
                    segs[i]["err"] = "D"
                elif prev_score == "TP":
                    segs[i]["err"] = "Ue"
                else:
                    warn("Unhandled error case: %s followed by %s" % (score, next_score))

        else: #middle sequence

            if score == "FP":
                if next_score == "TP":
                    if prev_score == "TP":
                        segs[i]["err"] = "M"
                    elif prev_score == "TN" or prev_score == "FN":
                        segs[i]["err"] = "Os"
                    else:
                        warn("Unhandled error case: %s %s %s" % (prev_score, score, next_score))

                elif next_score == "TN" or next_score == "FN":
                    if prev_score == "TN" or prev_score == "FN":
                        segs[i]["err"] = "I"
                    elif prev_score == "TP":
                        segs[i]["err"] = "Oe"
                    else:
                        warn("Unhandled error case: %s %s %s" % (prev_score, score, next_score))
                else:
                    warn("Unhandled error case: %s followed by %s" % (score, next_score))

            elif score == "FN":

                if next_score == "TP":
                    if prev_score == "TP":
                        segs[i]["err"] = "F"
                    elif prev_score == "TN" or prev_score == "FP":
                        segs[i]["err"] = "Us"
                    else:
                        warn("Unhandled error case: %s %s %s" % (prev_score, score, next_score))

                elif next_score == "TN" or next_score == "FP":
                    if prev_score == "TN" or prev_score == "FP":
                        segs[i]["err"] = "D"
                    elif prev_score == "TP":
                        segs[i]["err"] = "Ue"
                    else:
                        warn("Unhandled error case: %s %s %s" % (prev_score, score, next_score))

            else:
                raise warn("Unknown score: %s" % score)

    return segs

# Event types for Actual Events (ground truth) and Returned Events (detected)
EVENT_DELETION = "D"
FRAGMENTED_EVENT = "F"
MERGED_EVENT = "M"
FRAGMENTED_AND_MERGED = "FM"

INSERTION_RETURN = "I'"
MERGING_RETURN = "M'"
FRAGMENTING_RETURN = "F'"
FRAGMENTING_AND_MERGING = "FM'"

CORRECT = "C"

def score_events(truths, detected, segs):
    """score truth and detected events.
    returns dict of truth, detected, and stats
    """

    #1st pass, so-called 'trivial' assignments from segments
    for d in truths+detected:
        for seg in segs:
            if time_overlap(d, seg):
                if seg.get("err") == "D":
                    d["event_score"] = EVENT_DELETION
                elif seg.get("err") == "F":
                    d["event_score"] = FRAGMENTED_EVENT
                elif seg.get("err") == "I":
                    d["event_score"] = INSERTION_RETURN
                elif seg.get("err") == "M":
                    d["event_score"] = MERGING_RETURN

    #2nd pass, overlaps between scored events
    for d in detected:
        for t in truths:
            if time_overlap(d, t):
                if d.get("event_score") == MERGING_RETURN:
                    if t.get("event_score") == FRAGMENTED_EVENT:
                        t["event_score"] = FRAGMENTED_AND_MERGED
                    else:
                        t["event_score"] = MERGED_EVENT

                if t.get("event_score") == FRAGMENTED_EVENT:
                    if d.get("event_score") == MERGING_RETURN:
                        d["event_score"] = FRAGMENTING_AND_MERGING
                    else:
                        d["event_score"] = FRAGMENTING_RETURN

    #3rd pass, anything so far unscored is then Correct
    for d in detected+truths:
        if not d.get("event_score"):
            d["event_score"] = CORRECT

    #count up the scores
    d_counts = {CORRECT:0,
                FRAGMENTING_RETURN:0,
                MERGING_RETURN:0,
                FRAGMENTING_AND_MERGING:0,
                INSERTION_RETURN:0}

    t_counts = {CORRECT:0,
                EVENT_DELETION:0,
                FRAGMENTED_EVENT:0,
                FRAGMENTED_AND_MERGED:0,
                MERGED_EVENT:0}

    for d in detected:
        d_counts[d.get("event_score")] += 1

    for v in truths:
        t_counts[v.get("event_score")] += 1

    return dict(truths=truths, detected=detected, d_counts=d_counts, t_counts=t_counts, d_rates=pct_dict(d_counts), t_rates=pct_dict(t_counts))

DEFAULT_WINDOW_WIDTH=3

def sliding_window(seq, n=DEFAULT_WINDOW_WIDTH):
    """returns iterator over sliding window (of width n) over data from the sequence `seq`
    s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ...
    """
    it = iter(seq)
    result = tuple(islice(it, n))
    if len(result) == n:
        yield result
    for elem in it:
        result = result[1:] + (elem,)
        yield result

def pct_dict(d):
    #take int count values of dict d and return dict of each rate
    n = sum(d.itervalues())
    r = {}
    for k, v in d.iteritems():
        if n == 0:
            r[k] = None
        else:
            r[k] = d[k]*1.0/n
    return r

def warn(msg):
    print "WARNING:", msg

def time_overlap(d1, d2):
    """return True if the t1, t2 in d1 overlap t1, t2 in d2."""
    gt1, gt2, vt1, vt2 = parse_date(d1["t1"]), parse_date(d1["t2"]), parse_date(d2["t1"]), parse_date(d2["t2"])
    return (gt1 != vt2) and (vt1 != gt2) and (gt1 <= vt2) and (vt1 <= gt2)

def score_aggregate(results):
    """compute aggregate scores and stats from list of detection results"""
    scores = []
    truth_count = detected_count = segment_count = 0

    for res in results:
        scores.append(res["scores"])
        truth_count += len(res["labels"])
        detected_count += len(res["detected"])
        segment_count += len(res["scores"]["segments"])

    ret = dict()
    ret["scores"] = sum_scores(scores)
    ret["stats"] = dict(truth_count=truth_count, detected_count=detected_count, segment_count=segment_count)
    return ret

def sum_scores(scores):
    """sum up the scores"""
    segs = itertools.chain(*[x["segments"][:] for x in scores]) #all the segs in flat list
    d_counts = sum_dicts([x["events"]["d_counts"] for x in scores])
    t_counts = sum_dicts([x["events"]["t_counts"] for x in scores])
    d_rates = pct_dict(d_counts)
    t_rates = pct_dict(t_counts)
    return dict(frame_scores=score_frames(segs), event_scores=dict(d_counts=d_counts, t_counts=t_counts, d_rates=d_rates, t_rates=t_rates))

def sum_dicts(l):
    """sum dict vals in list l"""
    r = defaultdict(int)
    for d in l:
        for k, v in d.iteritems():
            r[k] += v
    return r

def update_scores_list(list_file, score_file):
    """update list of score files"""
    fnames = []
    head, tail = os.path.split(score_file)
    if os.path.exists(list_file):
        with open(list_file, "r") as f:
            fnames = json.loads(f.read())
            if tail not in fnames:
                fnames.append(tail)
            fnames.sort()
            fnames.reverse()
    else:
        fnames.append(tail)

    with open(list_file, "w") as f:
        print "writing %s..." % list_file
        f.write(json.dumps(fnames))

redpajama_set_name: RedPajamaGithub


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateEtapaProduccionTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('etapas_produccion', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
            $table->string('nombre_etapa');
            $table->string('codigo_etapa', 5)->nullable();
            $table->smallInteger('edo_reg')->default(1);

          //  $table->index(['codigo_etapa']);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('etapas_produccion');
    }
}


text:
namespace ash {

class FakeSamlIdpMixin final : public InProcessBrowserTestMixin {
 public:
  FakeSamlIdpMixin(InProcessBrowserTestMixinHost* host,
                   FakeGaiaMixin* gaia_mixin);

  FakeSamlIdpMixin(const FakeSamlIdpMixin&) = delete;
  FakeSamlIdpMixin& operator=(const FakeSamlIdpMixin&) = delete;
  ~FakeSamlIdpMixin() override;

  // InProcessBrowserTestMixin:
  void SetUpCommandLine(base::CommandLine* command_line) override;
  void SetUpOnMainThread() override;

  // TODO(crbug.com/1177416) - Improve comments
  void SetLoginHTMLTemplate(const std::string& template_file);
  void SetLoginAuthHTMLTemplate(const std::string& template_file);
  void SetRefreshURL(const GURL& refresh_url);
  void SetCookieValue(const std::string& cookie_value);
  void SetRequireHttpBasicAuth(bool require_http_basic_auth);
  void SetSamlResponseFile(const std::string& xml_file);
  bool DeviceTrustHeaderRecieved() const;
  bool IsLastChallengeResponseExists() const;
  void AssertChallengeResponseMatchesTpmResponse() const;

  std::string GetIdpHost() const;
  std::string GetIdpDomain() const;
  GURL GetSamlPageUrl() const;
  GURL GetHttpSamlPageUrl() const;
  GURL GetSamlWithDeviceAttestationUrl() const;
  GURL GetSamlWithDeviceTrustUrl() const;

 private:
  GURL GetSamlAuthPageUrl() const;
  GURL GetSamlWithCheckDeviceAnswerUrl() const;

  std::unique_ptr<net::test_server::HttpResponse> HandleRequest(
      const net::test_server::HttpRequest& request);

  enum class RequestType {
    // Not a known request.
    kUnknown,
    kLogin,
    kLoginAuth,
    kLoginWithDeviceAttestation,
    kLoginCheckDeviceAnswer,
    kLoginWithDeviceTrust
  };

  // Returns the RequestType that corresponds to `url`, or RequestType::Unknown
  // if this is not a request for the FakeSamlIdp.
  RequestType ParseRequestTypeFromRequestPath(const GURL& request_url) const;

  std::unique_ptr<net::test_server::HttpResponse> BuildResponseForLogin(
      const net::test_server::HttpRequest& request,
      const GURL& request_url) const;
  std::unique_ptr<net::test_server::HttpResponse> BuildResponseForLoginAuth(
      const net::test_server::HttpRequest& request,
      const GURL& request_url);
  std::unique_ptr<net::test_server::HttpResponse>
  BuildResponseForLoginWithDeviceAttestation(
      const net::test_server::HttpRequest& request,
      const GURL& request_url) const;
  std::unique_ptr<net::test_server::HttpResponse>
  BuildResponseForLoginWithDeviceTrust(
      const net::test_server::HttpRequest& request,
      const GURL& request_url);
  std::unique_ptr<net::test_server::HttpResponse>
  BuildResponseForCheckDeviceAnswer(
      const net::test_server::HttpRequest& request,
      const GURL& request_url);

  std::unique_ptr<net::test_server::HttpResponse> BuildHTMLResponse(
      const std::string& html_template,
      const std::string& relay_state,
      const std::string& next_path) const;

  void SaveChallengeResponse(const std::string& response);
  void ClearChallengeResponse();

  FakeGaiaMixin* const gaia_mixin_;
  net::EmbeddedTestServer saml_server_{net::EmbeddedTestServer::TYPE_HTTPS};
  net::EmbeddedTestServer saml_http_server_{net::EmbeddedTestServer::TYPE_HTTP};

  base::FilePath html_template_dir_;
  base::FilePath saml_response_dir_;
  GURL refresh_url_;
  std::string login_html_template_;
  std::string login_auth_html_template_;
  std::string cookie_value_;
  std::string saml_response_{"fake_response"};

  bool require_http_basic_auth_ = false;

  bool device_trust_header_recieved_ = false;
  absl::optional<std::string> challenge_response_;
};

}  // namespace ash

#endif  // CHROME_BROWSER_ASH_LOGIN_SAML_FAKE_SAML_IDP_MIXIN_H_


text:
//-CRE-

using System;
using System.Linq.Expressions;
using Sitecore.Data;

namespace Glass.Mapper.Sc.Configuration.Fluent
{
    /// <summary>
    /// Used to populate the property with data from a Sitecore field
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class SitecoreField<T> : AbstractPropertyBuilder<T, SitecoreFieldConfiguration>
    {

        /// <summary>
        /// Initializes a new instance of the <see cref="SitecoreField{T}"/> class.
        /// </summary>
        /// <param name="ex">The ex.</param>
        public SitecoreField(Expression<Func<T, object>> ex)
            : base(ex)
        {
            Configuration.FieldName = Configuration.PropertyInfo.Name;
        }

        /// <summary>
        /// Indicate that the field can be used with Code First
        /// </summary>
        public SitecoreField<T> IsCodeFirst()
        {
            Configuration.CodeFirst = true;
            return this;
        }

        /// <summary>
        /// The ID of the field to load or create in code first
        /// </summary>
        /// <param name="id">The id.</param>
        /// <returns>SitecoreField{`0}.</returns>
        public SitecoreField<T> FieldId(string id)
        {
            return FieldId(new ID(id));
        }
        /// <summary>
        /// The ID of the field to load or create in code first
        /// </summary>
        /// <param name="id">The id.</param>
        /// <returns>SitecoreField{`0}.</returns>
        public SitecoreField<T> FieldId(Guid id)
        {
            return FieldId(new ID(id));
        }

        /// <summary>
        /// The ID of the field to load or create in code first
        /// </summary>
        /// <param name="id">The id.</param>
        /// <returns>SitecoreField{`0}.</returns>
        public SitecoreField<T> FieldId(ID id)
        {
            Configuration.FieldId = id;
            return this;
        }

        /// <summary>
        /// The name of the field  to use if it is different to the property name
        /// </summary>
        /// <param name="name">The name.</param>
        /// <returns>SitecoreField{`0}.</returns>
        public SitecoreField<T> FieldName(string name)
        {
            Configuration.FieldName = name;
            return this;
        }

        /// <summary>
        /// The source for a code first field
        /// </summary>
        /// <param name="fieldSource">The field source.</param>
        /// <returns>SitecoreField{`0}.</returns>
        public SitecoreField<T> FieldSource(string fieldSource)
        {
            Configuration.FieldSource = fieldSource;
            return this;
        }

        /// <summary>
        /// The title for a code first field
        /// </summary>
        /// <param name="fieldTitle">The field title.</param>
        /// <returns>SitecoreField{`0}.</returns>
        public SitecoreField<T> FieldTitle(string fieldTitle)
        {
            Configuration.FieldTitle = fieldTitle;
            return this;
        }

        /// <summary>
        /// The Sitecore field type for a code first field
        /// </summary>
        /// <param name="fieldType">Type of the field.</param>
        /// <returns>SitecoreField{`0}.</returns>
        public SitecoreField<T> FieldType(SitecoreFieldType fieldType)
        {
            Configuration.FieldType = fieldType;
            return this;
        }

        /// <summary>
        /// The field should be shared between languages
        /// </summary>
        public SitecoreField<T> IsShared()
        {
            Configuration.IsShared = true;
            return this;
        }

        /// <summary>
        /// The field should be shared between versions
        /// </summary>
        public SitecoreField<T> IsUnversioned()
        {
            Configuration.IsUnversioned = true;
            return this;
        }

        /// <summary>
        /// The Sitecore custom field type for a code first field
        /// </summary>
        /// <param name="fieldType">Type of the field.</param>
        /// <returns>SitecoreField{`0}.</returns>
        public SitecoreField<T> CustomFieldType(string fieldType)
        {
            Configuration.CustomFieldType = fieldType;
            return this;
        }

        /// <summary>
        /// Options to override the behaviour of certain fields.
        /// </summary>
        /// <param name="setting">The setting.</param>
        /// <returns>SitecoreField{`0}.</returns>
        public SitecoreField<T> Setting(SitecoreFieldSettings setting)
        {
            Configuration.Setting = setting;
            return this;
        }

        /// <summary>
        /// The name of the section the field should appear in
        /// </summary>
        /// <param name="sectionName">Name of the section.</param>
        /// <returns>SitecoreField{`0}.</returns>
        public SitecoreField<T> SectionName(string sectionName)
        {
            Configuration.SectionName = sectionName;
            return this;
        }

        /// <summary>
        /// Indicate that the field can not be written to Sitecore
        /// </summary>
        /// <returns>SitecoreField{`0}.</returns>
        public SitecoreField<T> ReadOnly()
        {
            Configuration.ReadOnly = true;
            return this;
        }

        /// <summary>
        /// Fields the sort order.
        /// </summary>
        /// <param name="order">The order.</param>
        /// <returns>SitecoreField{`0}.</returns>
        public SitecoreField<T> FieldSortOrder(int order)
        {
            Configuration.FieldSortOrder = order;
            return this;
        }

        /// <summary>
        /// Sections the sort order.
        /// </summary>
        /// <param name="order">The order.</param>
        /// <returns>SitecoreField{`0}.</returns>
        public SitecoreField<T> SectionSortOrder(int order)
        {
            Configuration.SectionSortOrder = order;
            return this;
        }

        /// <summary>
        /// Validations the error text.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <returns>SitecoreField{`0}.</returns>
        public SitecoreField<T> ValidationErrorText(string text)
        {
            Configuration.ValidationErrorText = text;
            return this;
        }

        /// <summary>
        /// Validations the regular expression.
        /// </summary>
        /// <param name="regex">The regex.</param>
        /// <returns>SitecoreField{`0}.</returns>
        public SitecoreField<T> ValidationRegularExpression(string regex)
        {
            Configuration.ValidationRegularExpression = regex;
            return this;
        }

        /// <summary>
        /// Determines whether this instance is required.
        /// </summary>
        public SitecoreField<T> IsRequired()
        {
            Configuration.IsRequired = true;
           return this;
        }
    }
}


text:
* Takahiko Ito<takahiko03 _at_ gmail.com>
* Junnosuke Moriya<pac.learner _at_ gmail.com>
* Jun Ohtani <johtani _at_ gmail.com>
* Mutsumi Ichihara


text:
<template name="login">

	        <form id="login-js-form" role="login">

					 <input type="text" autofocus name="username" id="login-username" placeholder="👽" required class="form-control login-input input-lg"/>
					 <input type="password" name="password" id="login-password" class="form-control input-lg login-input" placeholder="🔒" required="" />
		          <button type="submit" class="btn btn-lg btn-primary btn-block login-button">Sign in</button>
	        </form>

					 ITIL Templates

</template>


text:
@interface DZYAdViewController : UIViewController

@end


text:
import * as moment from "moment";

import {ROLE} from "../../role/role.enum";
import {UserMongooseModel} from "../model/user-mongoose.model";
import {UserModel} from "../model/user.model";
import {PasswordSecurity} from "../../../../utils/security";

export class DummyUsers {
    static get normalUserOne(): UserModel {
        let password = "normalUserOne";
        let salt = PasswordSecurity.salt();
        let hash = PasswordSecurity.encryptAsync(password, salt);

        return {
            key: "1",
            name: "normalUserOne",
            email: "normalUserOne",
            _salt: salt,
            _hashedPassword: hash,
            roles: [ROLE.USER],
            dateCreated: moment().subtract(1, "weeks"),
            dateLastModified: moment().subtract(1, "weeks")
        };
    };

    static get normalUserTwo(): UserModel {
        let password = "normalUserTwo";
        let salt = PasswordSecurity.salt();
        let hash = PasswordSecurity.encryptAsync(password, salt);

        return {
            key: "2",
            name: "normalUserTwo",
            email: "normalUserTwo",
            _salt: salt,
            _hashedPassword: hash,
            roles: [ROLE.USER],
            dateCreated: moment().subtract(1, "weeks"),
            dateLastModified: moment().subtract(1, "days")
        };
    };

    static get nonExistentUser(): UserModel {
        let password = "nonExistentUser";
        let salt = PasswordSecurity.salt();
        let hash = PasswordSecurity.encryptAsync(password, salt);

        return {
            key: "-34984984",
            name: "nonExistentUser",
            email: "nonExistentUser",
            _salt: salt,
            _hashedPassword: hash,
            roles: [ROLE.USER],
            dateCreated: moment().subtract(1, "days"),
            dateLastModified: moment().subtract(2, "hours")
        };
    };

    static get membershipUser(): UserModel {
        let password = "membershipUser";
        let salt = PasswordSecurity.salt();
        let hash = PasswordSecurity.encryptAsync(password, salt);

        return {
            key: "3",
            name: "membershipUser",
            email: "membershipUser",
            _salt: salt,
            _hashedPassword: hash,
            roles: [ROLE.USER, ROLE.MEMBERSHIP],
            dateCreated: moment().subtract(1, "weeks"),
            dateLastModified: moment().subtract(1, "weeks")
        };
    };

    static get adminUser(): UserModel {
        let password = "adminUser";
        let salt = PasswordSecurity.salt();
        let hash = PasswordSecurity.encryptAsync(password, salt);

        return {
            key: "4",
            name: "adminUser",
            email: "adminUser",
            _salt: salt,
            _hashedPassword: hash,
            roles: [ROLE.USER, ROLE.ADMIN],
            dateCreated: moment().subtract(1, "weeks"),
            dateLastModified: moment().subtract(1, "weeks")
        };
    };

    static get unActivatedUser(): UserModel {
        let password = "unActivatedUser";
        let salt = PasswordSecurity.salt();
        let hash = PasswordSecurity.encryptAsync(password, salt);

        return {
            key: "5",
            name: "unActivatedUser",
            email: "unActivatedUser",
            roles: [ROLE.USER],
            dateCreated: moment().subtract(1, "weeks"),
            dateLastModified: moment().subtract(1, "weeks")
        };
    };

    static get newUserOne(): UserModel {
        return {
            name: "newUserOne",
            email: "newUserOne",
            roles: [ROLE.USER]
        };
    };

    static users: UserModel[] = [DummyUsers.normalUserOne, DummyUsers.normalUserTwo, DummyUsers.membershipUser, DummyUsers.adminUser, DummyUsers.unActivatedUser];

    static create(): Promise<void> {
        let promises: Promise<UserModel>[] = [];

        DummyUsers.users.forEach(user => {
            promises.push(
                new UserMongooseModel(user).save()
            );
        });

        return Promise.all(promises);
    }
}


text:
#ifndef itkSumProjectionImageFilter_h
#define itkSumProjectionImageFilter_h

#include "itkProjectionImageFilter.h"
#include "itkConceptChecking.h"

namespace itk
{
/** \class SumProjectionImageFilter
 * \brief Sum projection
 *
 * This class was contributed to the Insight Journal by Gaetan Lehmann.
 * The original paper can be found at
 * https://www.insight-journal.org/browse/publication/71
 *
 * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction,
 * INRA de Jouy-en-Josas, France.
 *
 * \sa ProjectionImageFilter
 * \sa MedianProjectionImageFilter
 * \sa MeanProjectionImageFilter
 * \sa MeanProjectionImageFilter
 * \sa MaximumProjectionImageFilter
 * \sa MinimumProjectionImageFilter
 * \sa BinaryProjectionImageFilter
 * \sa StandardDeviationProjectionImageFilter
 * \ingroup ITKImageStatistics
 */

namespace Functor
{
template <typename TInputPixel, typename TOuputPixel>
class SumAccumulator
{
public:
  SumAccumulator(SizeValueType) {}
  ~SumAccumulator() = default;

  inline void
  Initialize()
  {
    m_Sum = NumericTraits<TOuputPixel>::ZeroValue();
  }

  inline void
  operator()(const TInputPixel & input)
  {
    m_Sum = m_Sum + input;
  }

  inline TOuputPixel
  GetValue()
  {
    return m_Sum;
  }

  TOuputPixel m_Sum;
};
} // namespace Functor

template <typename TInputImage, typename TOutputImage>
class SumProjectionImageFilter
  : public ProjectionImageFilter<
      TInputImage,
      TOutputImage,
      Functor::SumAccumulator<typename TInputImage::PixelType, typename TOutputImage::PixelType>>
{
public:
  ITK_DISALLOW_COPY_AND_MOVE(SumProjectionImageFilter);

  using Self = SumProjectionImageFilter;
  using Superclass =
    ProjectionImageFilter<TInputImage,
                          TOutputImage,
                          Functor::SumAccumulator<typename TInputImage::PixelType, typename TOutputImage::PixelType>>;

  using InputImageType = TInputImage;
  using InputPixelType = typename InputImageType::PixelType;

  using OutputImageType = TOutputImage;
  using OutputPixelType = typename OutputImageType::PixelType;

  using Pointer = SmartPointer<Self>;
  using ConstPointer = SmartPointer<const Self>;

  /** Runtime information support. */
  itkTypeMacro(SumProjectionImageFilter, ProjectionImageFilter);

  /** Method for creation through the object factory. */
  itkNewMacro(Self);

#ifdef ITK_USE_CONCEPT_CHECKING
  // Begin concept checking
  itkConceptMacro(InputPixelToOutputPixelTypeGreaterAdditiveOperatorCheck,
                  (Concept::AdditiveOperators<OutputPixelType, InputPixelType, OutputPixelType>));
  itkConceptMacro(InputHasNumericTraitsCheck, (Concept::HasNumericTraits<InputPixelType>));
  // End concept checking
#endif

protected:
  SumProjectionImageFilter() = default;
  ~SumProjectionImageFilter() override = default;
}; // end SumProjectionImageFilter
} // end namespace itk

#endif


text:
package cn.jxust.utils;

import java.util.Enumeration;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

import cn.jxust.orm.PageData;

/**
 * web工具类
 * @author yangzhibin
 *
 */
public class WebUtils
{
	public static Map<String, Object> getParametersStartingWith(HttpServletRequest request, String prefix)
	{
		Enumeration<?> paramNames = request.getParameterNames();
		Map<String, Object> params = new TreeMap<String, Object>();
		if (prefix == null)
		{
			prefix = "";
		}
		while (paramNames != null && paramNames.hasMoreElements())
		{
			String paramName = (String) paramNames.nextElement();
			if ("".equals(prefix) || paramName.startsWith(prefix))
			{
				String unprefixed = paramName.substring(prefix.length());
				String[] values = request.getParameterValues(paramName);
				if (values == null || values.length == 0)
				{
					// Do nothing, no values found at all.
				} else if (values.length > 1)
				{
					params.put(unprefixed, values);
				} else
				{
					params.put(unprefixed, values[0]);
				}
			}
		}
		return params;
	}

	public static void setPageDataParameter(HttpServletRequest request, PageData<?> pageData)
	{
		//第1步:设置当前页
		String pageNoStr = request.getParameter("pageNo");
		if (StringUtils.isNotBlank(pageNoStr))
		{
			Integer pageNo = Integer.parseInt(pageNoStr);
			pageData.setPageNo(pageNo);
		}
	}
}


text:
package citec.roboter;

public enum Actions {
	None,
	Eating,
	Sleeping,
	Playing,
	Healing,
	Cleaning
}


text:
<?php namespace Quark\Connector\Api;

use Quark\Connector\Files\ConfigManager;

class ModelsApi
{
    private $manager;

    public function __construct(ConfigManager $manager)
    {
        $this->manager = $manager;
    }

    public function getModels()
    {
        $tables = [];
        $files = $this->manager->scanPath('tables', '*.php');

        foreach($files as $file) {
            $table = substr($file, 0, -4);

            $model = $this->manager->getTableDefinition($table);

            $tables[] = [
                'table' => $table,
                'name'  => $model['name'],
                'model' => $model['model']
            ];
        }

        return $tables;
    }

    public function getModel($table)
    {
        return $this->manager->getTableDefinition($table);
    }

    public function postModel($model)
    {
        dd($model);
    }
}


text:
package com.salesmanager.shop.model.order.v0;

import java.io.Serializable;
import java.util.List;

import com.salesmanager.shop.model.entity.ReadableList;

@Deprecated
public class ReadableOrderList extends ReadableList implements Serializable {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	private List<ReadableOrder> orders;

	public List<ReadableOrder> getOrders() {
		return orders;
	}
	public void setOrders(List<ReadableOrder> orders) {
		this.orders = orders;
	}

}


text:
package com.gemstone.gemfire.internal.cache;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import com.gemstone.gemfire.cache.Cache;
import com.gemstone.gemfire.cache.CacheEvent;
import com.gemstone.gemfire.cache.Operation;
import com.gemstone.gemfire.cache.TransactionEvent;
import com.gemstone.gemfire.cache.TransactionId;
import com.gemstone.gemfire.distributed.DistributedMember;

/**
 * <p>
 * The internal implementation of the {@link TransactionEvent}interface used by
 * the remote commit code.
 *
 * @author Darrel Schneider
 *
 * @since 4.0
 *
 */
public class TXRmtEvent implements TransactionEvent
{
  private final TransactionId txId;

  private Cache cache;

  private List events;

  TXRmtEvent(TransactionId txId, Cache cache) {
    this.txId = txId;
    this.cache = cache;
    this.events = null;
  }

  public TransactionId getTransactionId()
  {
    return this.txId;
  }

  private boolean isEventUserVisible(CacheEvent ce) {
    return BucketRegion.FORCE_LOCAL_LISTENERS_INVOCATION || !(ce.getRegion() instanceof PartitionedRegion);
  }

  public List getEvents()
  {
    if (this.events == null) {
      return Collections.EMPTY_LIST;
    }
    else {
      ArrayList result = new ArrayList(this.events.size());
      Iterator it = this.events.iterator();
      while (it.hasNext()) {
        CacheEvent ce = (CacheEvent)it.next();
        if (isEventUserVisible(ce)) {
          result.add(ce);
        }
      }
      if (result.isEmpty()) {
        return Collections.EMPTY_LIST;
      }
      else {
        return Collections.unmodifiableList(result);
      }
    }
  }

  public List getCreateEvents()
  {
    if (this.events == null) {
      return Collections.EMPTY_LIST;
    }
    else {
      ArrayList result = new ArrayList(this.events.size());
      Iterator it = this.events.iterator();
      while (it.hasNext()) {
        CacheEvent ce = (CacheEvent)it.next();
        if (ce.getOperation().isCreate() && isEventUserVisible(ce)) {
          result.add(ce);
        }
      }
      if (result.isEmpty()) {
        return Collections.EMPTY_LIST;
      }
      else {
        return Collections.unmodifiableList(result);
      }
    }
  }

  public List getPutEvents()
  {
    if (this.events == null) {
      return Collections.EMPTY_LIST;
    }
    else {
      ArrayList result = new ArrayList(this.events.size());
      Iterator it = this.events.iterator();
      while (it.hasNext()) {
        CacheEvent ce = (CacheEvent)it.next();
        if (ce.getOperation().isUpdate() && isEventUserVisible(ce)) {
          result.add(ce);
        }
      }
      if (result.isEmpty()) {
        return Collections.EMPTY_LIST;
      }
      else {
        return Collections.unmodifiableList(result);
      }
    }
  }

  public List getInvalidateEvents()
  {
    if (this.events == null) {
      return Collections.EMPTY_LIST;
    }
    else {
      ArrayList result = new ArrayList(this.events.size());
      Iterator it = this.events.iterator();
      while (it.hasNext()) {
        CacheEvent ce = (CacheEvent)it.next();
        if (ce.getOperation().isInvalidate() && isEventUserVisible(ce)) {
          result.add(ce);
        }
      }
      if (result.isEmpty()) {
        return Collections.EMPTY_LIST;
      }
      else {
        return Collections.unmodifiableList(result);
      }
    }
  }

  public List getDestroyEvents()
  {
    if (this.events == null) {
      return Collections.EMPTY_LIST;
    }
    else {
      ArrayList result = new ArrayList(this.events.size());
      Iterator it = this.events.iterator();
      while (it.hasNext()) {
        CacheEvent ce = (CacheEvent)it.next();
        if (ce.getOperation().isDestroy() && isEventUserVisible(ce)) {
          result.add(ce);
        }
      }
      if (result.isEmpty()) {
        return Collections.EMPTY_LIST;
      }
      else {
        return Collections.unmodifiableList(result);
      }
    }
  }

  private EntryEventImpl createEvent(LocalRegion r, Operation op,
      RegionEntry re, Object key, Object newValue,Object aCallbackArgument)
  {
    DistributedMember originator = ((TXId)this.txId).getMemberId();
    //TODO:ASIF :EventID will not be generated with this constructor . Check if
    // this is correct
    LocalRegion eventRegion = r;
    if (r.isUsedForPartitionedRegionBucket()) {
      eventRegion = r.getPartitionedRegion();
    }
    EntryEventImpl event = EntryEventImpl.create(
        eventRegion, op, key, newValue,
        aCallbackArgument, // callbackArg
        true, // originRemote
        originator);
    event.setOldValue(re.getValueInVM(r)); // OFFHEAP: copy into heap cd
    event.setTransactionId(getTransactionId());
    return event;
  }

  /**
   * Add an event to our internal list
   */
  private void addEvent(EntryEventImpl e)
  {
    synchronized (this) {
      if (this.events == null) {
        this.events = new ArrayList();
      }
      this.events.add(e);
    }
  }

  void addDestroy(LocalRegion r, RegionEntry re, Object key,Object aCallbackArgument)
  {
    addEvent(createEvent(r, Operation.DESTROY, re, key, null,aCallbackArgument));
  }

  void addInvalidate(LocalRegion r, RegionEntry re, Object key, Object newValue,Object aCallbackArgument)
  {
    addEvent(createEvent(r, Operation.INVALIDATE, re, key, newValue,aCallbackArgument));
  }

  void addPut(Operation putOp, LocalRegion r, RegionEntry re, Object key,
      Object newValue,Object aCallbackArgument)
  {
    addEvent(createEvent(r, putOp, re, key, newValue,aCallbackArgument));
  }

  public Cache getCache()
  {
    return this.cache;
  }

  public void freeOffHeapResources() {
    if (this.events != null) {
      for (EntryEventImpl e: (List<EntryEventImpl>)this.events) {
        e.release();
      }
    }
    // TODO Auto-generated method stub

  }
}


text:
#ifndef CORE_BINARY_HEAP_ARRAY_H
#define CORE_BINARY_HEAP_ARRAY_H

#include <core/structures/vector.h>

/**
 * @see http://www.stack.nl/~dimitri/doxygen/manual/docblocks.html
 */

/**
 * Binary heap.
 *
 * This is either a min-heap or a max-heap.
 *
 * The implementation is based on the Wikipedia page.
 *
 * @see http://en.wikipedia.org/wiki/Binary_heap
 */
struct core_binary_heap_array {
    struct core_vector vector;
    int key_size;
    int value_size;
    int size;
    int (*test_relation)(struct core_binary_heap_array *self, void *key1, void *key2);
};

struct core_memory_pool;

/**
 * @param flags setup flags, can include CORE_BINARY_HEAP_MIN or CORE_BINARY_HEAP_MAX.
 */
void core_binary_heap_array_init(struct core_binary_heap_array *self, int key_size,
                int value_size, uint32_t flags);
void core_binary_heap_array_destroy(struct core_binary_heap_array *self);

/**
 * Insert a key-value pair.
 *
 * @return true is inserted
 */
int core_binary_heap_array_insert(struct core_binary_heap_array *self, void *key, void *value);

/**
 *
 * @return true if there is a root.
 */
int core_binary_heap_array_get_root(struct core_binary_heap_array *self, void **key, void **value);

/**
 * Delete the root.
 */
int core_binary_heap_array_delete_root(struct core_binary_heap_array *self);

/**
 * @return the size of the heap (the number of key-value pairs).
 */
int core_binary_heap_array_size(struct core_binary_heap_array *self);

/**
 * @return true if empty, false otherwise.
 */
int core_binary_heap_array_empty(struct core_binary_heap_array *self);

void core_binary_heap_array_set_memory_pool(struct core_binary_heap_array *self,
                struct core_memory_pool *pool);

#endif


text:
name: Feature
about: If your issue suggests/proposes new features which improve howdoi
title: ''
labels: ''
assignees: ''

---

### Description
(Describe in detail what you want to work on)

### Additional Comments (if any)
### Have you read the Contributing Guidelines on Pull Requests on mkdocs?

(Write your answer here.)


text:
#import "UIViewController.h"

#import "ISOperationDelegate-Protocol.h"
#import <iTunesStoreUI/SUScriptNativeObject-Protocol.h>

@class NSArray, NSMutableArray, NSString, SUClientInterface, SUNavigationItem, SURotationController, SUViewControllerContext, SUViewControllerScriptProperties, UIBarButtonItem;

@interface SUViewController : UIViewController <SUScriptNativeObject, ISOperationDelegate>
{
    SUViewControllerScriptProperties *_cachedScriptProperties;
    _Bool _canBeWeakScriptReference;
    NSMutableArray *_cancelOnDeallocOperations;
    SUClientInterface *_clientInterface;
    _Bool _excludeFromNavigationHistory;
    UIBarButtonItem *_exitStoreButton;
    UIViewController *_footerViewController;
    UIViewController *_inputAccessoryViewController;
    _Bool _isEnteringForeground;
    _Bool _loading;
    SUViewControllerContext *_memoryPurgeContext;
    NSMutableArray *_operations;
    NSMutableArray *_pendingDialogs;
    SUViewControllerContext *_restoredContext;
    SURotationController *_rotationController;
    long long _rotationState;
    _Bool _shouldInvalidateForMemoryPurge;
    _Bool _showsLibraryButton;
    long long _transitionSafetyCount;
}

@property(nonatomic) _Bool showsLibraryButton; // @synthesize showsLibraryButton=_showsLibraryButton;
@property(nonatomic) _Bool shouldInvalidateForMemoryPurge; // @synthesize shouldInvalidateForMemoryPurge=_shouldInvalidateForMemoryPurge;
@property(nonatomic) _Bool shouldExcludeFromNavigationHistory; // @synthesize shouldExcludeFromNavigationHistory=_excludeFromNavigationHistory;
@property(readonly, nonatomic, getter=_restoredContext) SUViewControllerContext *_restoredContext; // @synthesize _restoredContext;
@property(readonly, nonatomic, getter=_pendingDialogs) NSArray *_pendingDialogs; // @synthesize _pendingDialogs;
@property(nonatomic, getter=isLoading) _Bool loading; // @synthesize loading=_loading;
@property(retain, nonatomic) UIViewController *inputAccessoryViewController; // @synthesize inputAccessoryViewController=_inputAccessoryViewController;
@property(readonly, nonatomic) UIViewController *footerViewController; // @synthesize footerViewController=_footerViewController;
@property(retain, nonatomic) SUClientInterface *clientInterface; // @synthesize clientInterface=_clientInterface;
@property(readonly, nonatomic, getter=_isEnteringForeground) _Bool _enteringForeground; // @synthesize _enteringForeground=_isEnteringForeground;
@property(readonly, nonatomic, getter=_cachedScriptProperties) SUViewControllerScriptProperties *_cachedScriptProperties; // @synthesize _cachedScriptProperties;
- (void)_reloadExitStoreButtonWithParentViewController:(id)arg1;
- (void)_invalidateForMemoryPurge;
- (void)_reloadLibraryButton;
- (void)_keyboardWillShowNotification:(id)arg1;
- (void)_keyboardWillHideNotification:(id)arg1;
- (void)_keyboardDidShowNotification:(id)arg1;
- (void)_keyboardDidHideNotification:(id)arg1;
- (void)_exitStoreButtonDidChangeNotification:(id)arg1;
- (void)_dialogFinishedNotification:(id)arg1;
- (void)_applicationWillEnterForegroundNotification:(id)arg1;
- (void)_applicationDidEnterBackgroundNotification:(id)arg1;
- (void)operationFinished:(id)arg1;
- (void)operation:(id)arg1 failedWithError:(id)arg2;
- (void)_presentFooterAnimationDidStop;
- (void)_dismissFooterAnimationDidStop:(id)arg1;
- (void)_exitStoreButtonAction:(id)arg1;
- (_Bool)clearsWeakScriptReferences;
- (_Bool)_shouldUseDefaultFirstResponder;
- (void)remoteControlReceivedWithEvent:(id)arg1;
- (id)inputAccessoryView;
- (_Bool)canPerformAction:(SEL)arg1 withSender:(id)arg2;
- (_Bool)canBecomeFirstResponder;
- (_Bool)becomeFirstResponder;
- (_Bool)window:(id)arg1 shouldAutorotateToInterfaceOrientation:(long long)arg2;
- (void)willRotateToInterfaceOrientation:(long long)arg1 duration:(double)arg2;
- (void)willAnimateRotationToInterfaceOrientation:(long long)arg1 duration:(double)arg2;
- (unsigned long long)supportedInterfaceOrientations;
- (id)_rotationController;
- (void)didRotateFromInterfaceOrientation:(long long)arg1;
- (void)willMoveToParentViewController:(id)arg1;
- (void)viewWillDisappear:(_Bool)arg1;
- (void)viewWillAppear:(_Bool)arg1;
- (void)viewDidDisappear:(_Bool)arg1;
- (void)viewDidAppear:(_Bool)arg1;
- (id)viewControllerFactory;
- (id)tabBarItem;
- (void)storePageProtocolDidChange;
- (void)setTitle:(id)arg1;
- (void)setParentViewController:(id)arg1;
- (void)_setExistingNavigationItem:(id)arg1;
- (void)restoreArchivableContext:(id)arg1;
- (void)resetRestoredContext;
@property(readonly, nonatomic) SUNavigationItem *navigationItem; // @dynamic navigationItem;
- (id)moreListSelectedImage;
- (id)moreListImage;
- (void)loadView;
- (long long)ITunesStoreUIBarStyle;
- (long long)interfaceOrientation;
- (id)_existingNavigationItem;
- (void)didReceiveMemoryWarning;
- (id)copyArchivableContext;
- (_Bool)_canReloadView;
- (void)applicationWillSuspend;
- (void)applicationDidResume;
- (void)trackOperation:(id)arg1 cancelOnDealloc:(_Bool)arg2;
- (void)setTitle:(id)arg1 changeTabBarItem:(_Bool)arg2;
- (void)setScriptProperties:(id)arg1;
- (void)setSection:(id)arg1;
- (void)reloadContentSizeForViewInPopover;
- (void)reload;
- (void)presentFooterViewController:(id)arg1 animated:(_Bool)arg2;
- (_Bool)presentDialogForError:(id)arg1 pendUntilVisible:(_Bool)arg2;
- (_Bool)presentDialog:(id)arg1 pendUntilVisible:(_Bool)arg2;
- (id)newRotationController;
@property(readonly, nonatomic, getter=isVisibleAndFrontmost) _Bool visibleAndFrontmost;
@property(readonly, nonatomic, getter=isVisible) _Bool visible;
- (void)invalidateForMemoryPurge;
- (void)invalidate;
- (void)handleApplicationURL:(id)arg1 withSourceApplication:(id)arg2 sourceURL:(id)arg3;
- (void)handleApplicationURL:(id)arg1;
- (void)enqueueOperation:(id)arg1 cancelOnDealloc:(_Bool)arg2;
- (void)dismissFooterViewControllerAnimated:(_Bool)arg1;
- (void)dismissAfterDialogs;
@property(readonly, nonatomic) NSString *defaultPNGName;
@property(readonly, nonatomic) double defaultPNGExpirationTime;
- (id)copyScriptProperties;
- (id)copyDefaultScriptProperties;
- (void)cancelOperations;
- (id)copyChildViewControllersForReason:(long long)arg1;
- (void)applicationWillEnterForeground;
- (void)applicationDidEnterBackground;
- (void)dealloc;
- (id)initWithSection:(id)arg1;
- (id)init;

@end


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

<title>Source code</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

001package com.github.sarxos.webcam;
002
003import java.awt.Point;
004import java.awt.image.BufferedImage;
005import java.util.ArrayList;
006import java.util.List;
007import java.util.concurrent.ExecutorService;
008import java.util.concurrent.Executors;
009import java.util.concurrent.ThreadFactory;
010import java.util.concurrent.atomic.AtomicBoolean;
011import java.util.concurrent.atomic.AtomicInteger;
012
013import org.slf4j.Logger;
014import org.slf4j.LoggerFactory;
015
016import com.github.sarxos.webcam.util.jh.JHBlurFilter;
017import com.github.sarxos.webcam.util.jh.JHGrayFilter;
018
019
020/**
021 * Webcam motion detector.
022 *
023 * @author Bartosz Firyn (SarXos)
024 */
025public class WebcamMotionDetector {
026
027        /**
028         * Logger.
029         */
030        private static final Logger LOG = LoggerFactory.getLogger(WebcamMotionDetector.class);
031
032        /**
033         * Thread number in pool.
034         */
035        private static final AtomicInteger NT = new AtomicInteger(0);
036
037        /**
038         * Thread factory.
039         */
040        private static final ThreadFactory THREAD_FACTORY = new DetectorThreadFactory();
041
042        /**
043         * Default pixel difference intensity threshold (set to 25).
044         */
045        public static final int DEFAULT_PIXEL_THREASHOLD = 25;
046
047        /**
048         * Default check interval, in milliseconds, set to 500 ms.
049         */
050        public static final int DEFAULT_INTERVAL = 500;
051
052        /**
053         * Default percentage image area fraction threshold (set to 0.2%).
054         */
055        public static final double DEFAULT_AREA_THREASHOLD = 0.2;
056
057        /**
058         * Create new threads for detector internals.
059         *
060         * @author Bartosz Firyn (SarXos)
061         */
062        private static final class DetectorThreadFactory implements ThreadFactory {
063
064                @Override
065                public Thread newThread(Runnable runnable) {
066                        Thread t = new Thread(runnable, String.format("motion-detector-%d", NT.incrementAndGet()));
067                        t.setUncaughtExceptionHandler(WebcamExceptionHandler.getInstance());
068                        t.setDaemon(true);
069                        return t;
070                }
071        }
072
073        /**
074         * Run motion detector.
075         *
076         * @author Bartosz Firyn (SarXos)
077         */
078        private class Runner implements Runnable {
079
080                @Override
081                public void run() {
082
083                        running.set(true);
084
085                        while (running.get() && webcam.isOpen()) {
086                                try {
087                                        detect();
088                                        Thread.sleep(interval);
089                                } catch (InterruptedException e) {
090                                        break;
091                                } catch (Exception e) {
092                                        WebcamExceptionHandler.handle(e);
093                                }
094                        }
095
096                        running.set(false);
097                }
098        }
099
100        /**
101         * Change motion to false after specified number of seconds.
102         *
103         * @author Bartosz Firyn (SarXos)
104         */
105        private class Inverter implements Runnable {
106
107                @Override
108                public void run() {
109
110                        int delay = 0;
111
112                        while (running.get()) {
113
114                                try {
115                                        Thread.sleep(10);
116                                } catch (InterruptedException e) {
117                                        break;
118                                }
119
120                                delay = inertia != -1 ? inertia : 2 * interval;
121
122                                if (lastMotionTimestamp + delay < System.currentTimeMillis()) {
123                                        motion = false;
124                                }
125                        }
126                }
127        }
128
129        /**
130         * Executor.
131         */
132        private final ExecutorService executor = Executors.newFixedThreadPool(2, THREAD_FACTORY);
133
134        /**
135         * Motion listeners.
136         */
137        private final List<WebcamMotionListener> listeners = new ArrayList<WebcamMotionListener>();
138
139        /**
140         * Is detector running?
141         */
142        private final AtomicBoolean running = new AtomicBoolean(false);
143
144        /**
145         * Is motion?
146         */
147        private volatile boolean motion = false;
148
149        /**
150         * Previously captured image.
151         */
152        private BufferedImage previous = null;
153
154        /**
155         * Webcam to be used to detect motion.
156         */
157        private Webcam webcam = null;
158
159        /**
160         * Motion check interval (1000 ms by default).
161         */
162        private volatile int interval = DEFAULT_INTERVAL;
163
164        /**
165         * Pixel intensity threshold (0 - 255).
166         */
167        private volatile int pixelThreshold = DEFAULT_PIXEL_THREASHOLD;
168
169        /**
170         * Pixel intensity threshold (0 - 100).
171         */
172        private volatile double areaThreshold = DEFAULT_AREA_THREASHOLD;
173
174        /**
175         * How long motion is valid (in milliseconds). Default value is 2 seconds.
176         */
177        private volatile int inertia = -1;
178
179        /**
180         * Motion strength (0 = no motion, 100 = full image covered by motion).
181         */
182        private double area = 0;
183
184        /**
185         * Center of motion gravity.
186         */
187        private Point cog = null;
188
189        /**
190         * Timestamp when motion has been observed last time.
191         */
192        private volatile long lastMotionTimestamp = 0;
193
194        /**
195         * Blur filter instance.
196         */
197        private final JHBlurFilter blur = new JHBlurFilter(6, 6, 1);
198
199        /**
200         * Gray filter instance.
201         */
202        private final JHGrayFilter gray = new JHGrayFilter();
203
204        /**
205         * Create motion detector. Will open webcam if it is closed.
206         *
207         * @param webcam web camera instance
208         * @param pixelThreshold intensity threshold (0 - 255)
209         * @param areaThreshold percentage threshold of image covered by motion
210         * @param interval the check interval
211         */
212        public WebcamMotionDetector(Webcam webcam, int pixelThreshold, double areaThreshold, int interval) {
213
214                this.webcam = webcam;
215
216                setPixelThreshold(pixelThreshold);
217                setAreaThreshold(areaThreshold);
218                setInterval(interval);
219
220                int w = webcam.getViewSize().width;
221                int h = webcam.getViewSize().height;
222
223                cog = new Point(w / 2, h / 2);
224        }
225
226        /**
227         * Create motion detector with default parameter inertia = 0.
228         *
229         * @param webcam web camera instance
230         * @param pixelThreshold intensity threshold (0 - 255)
231         * @param areaThreshold percentage threshold of image covered by motion (0 - 100)
232         */
233        public WebcamMotionDetector(Webcam webcam, int pixelThreshold, double areaThreshold) {
234                this(webcam, pixelThreshold, areaThreshold, DEFAULT_INTERVAL);
235        }
236
237        /**
238         * Create motion detector with default parameter inertia = 0.
239         *
240         * @param webcam web camera instance
241         * @param pixelThreshold intensity threshold (0 - 255)
242         */
243        public WebcamMotionDetector(Webcam webcam, int pixelThreshold) {
244                this(webcam, pixelThreshold, DEFAULT_AREA_THREASHOLD);
245        }
246
247        /**
248         * Create motion detector with default parameters - threshold = 25, inertia = 0.
249         *
250         * @param webcam web camera instance
251         */
252        public WebcamMotionDetector(Webcam webcam) {
253                this(webcam, DEFAULT_PIXEL_THREASHOLD);
254        }
255
256        public void start() {
257                if (running.compareAndSet(false, true)) {
258                        webcam.open();
259                        executor.submit(new Runner());
260                        executor.submit(new Inverter());
261                }
262        }
263
264        public void stop() {
265                if (running.compareAndSet(true, false)) {
266                        webcam.close();
267                        executor.shutdownNow();
268                }
269        }
270
271        protected void detect() {
272
273                if (!webcam.isOpen()) {
274                        motion = false;
275                        return;
276                }
277
278                BufferedImage current = webcam.getImage();
279
280                if (current == null) {
281                        motion = false;
282                        return;
283                }
284
285                current = blur.filter(current, null);
286                current = gray.filter(current, null);
287
288                int p = 0;
289
290                int cogX = 0;
291                int cogY = 0;
292
293                int w = current.getWidth();
294                int h = current.getHeight();
295
296                if (previous != null) {
297                        for (int x = 0; x < w; x++) {
298                                for (int y = 0; y < h; y++) {
299
300                                        int cpx = current.getRGB(x, y);
301                                        int ppx = previous.getRGB(x, y);
302                                        int pid = combinePixels(cpx, ppx) & 0x000000ff;
303
304                                        if (pid >= pixelThreshold) {
305                                                cogX += x;
306                                                cogY += y;
307                                                p += 1;
308                                        }
309                                }
310                        }
311                }
312
313                area = p * 100d / (w * h);
314
315                if (area >= areaThreshold) {
316
317                        cog = new Point(cogX / p, cogY / p);
318
319                        motion = true;
320                        lastMotionTimestamp = System.currentTimeMillis();
321
322                        notifyMotionListeners();
323
324                } else {
325                        cog = new Point(w / 2, h / 2);
326                }
327
328                previous = current;
329        }
330
331        /**
332         * Will notify all attached motion listeners.
333         */
334        private void notifyMotionListeners() {
335                WebcamMotionEvent wme = new WebcamMotionEvent(this, area, cog);
336                for (WebcamMotionListener l : listeners) {
337                        try {
338                                l.motionDetected(wme);
339                        } catch (Exception e) {
340                                WebcamExceptionHandler.handle(e);
341                        }
342                }
343        }
344
345        /**
346         * Add motion listener.
347         *
348         * @param l listener to add
349         * @return true if listeners list has been changed, false otherwise
350         */
351        public boolean addMotionListener(WebcamMotionListener l) {
352                return listeners.add(l);
353        }
354
355        /**
356         * @return All motion listeners as array
357         */
358        public WebcamMotionListener[] getMotionListeners() {
359                return listeners.toArray(new WebcamMotionListener[listeners.size()]);
360        }
361
362        /**
363         * Removes motion listener.
364         *
365         * @param l motion listener to remove
366         * @return true if listener was available on the list, false otherwise
367         */
368        public boolean removeMotionListener(WebcamMotionListener l) {
369                return listeners.remove(l);
370        }
371
372        /**
373         * @return Motion check interval in milliseconds
374         */
375        public int getInterval() {
376                return interval;
377        }
378
379        /**
380         * Motion check interval in milliseconds. After motion is detected, it's valid for time which is
381         * equal to value of 2 * interval.
382         *
383         * @param interval the new motion check interval (ms)
384         * @see #DEFAULT_INTERVAL
385         */
386        public void setInterval(int interval) {
387
388                if (interval < 100) {
389                        throw new IllegalArgumentException("Motion check interval cannot be less than 100 ms");
390                }
391
392                this.interval = interval;
393        }
394
395        /**
396         * Set pixel intensity difference threshold above which pixel is classified as "moved". Minimum
397         * value is 0 and maximum is 255. Default value is 10. This value is equal for all RGB
398         * components difference.
399         *
400         * @param threshold the pixel intensity difference threshold
401         * @see #DEFAULT_PIXEL_THREASHOLD
402         */
403        public void setPixelThreshold(int threshold) {
404                if (threshold < 0) {
405                        throw new IllegalArgumentException("Pixel intensity threshold cannot be negative!");
406                }
407                if (threshold > 255) {
408                        throw new IllegalArgumentException("Pixel intensity threshold cannot be higher than 255!");
409                }
410                this.pixelThreshold = threshold;
411        }
412
413        /**
414         * Set percentage fraction of detected motion area threshold above which it is classified as
415         * "moved". Minimum value for this is 0 and maximum is 100, which corresponds to full image
416         * covered by spontaneous motion.
417         *
418         * @param threshold the percentage fraction of image area
419         * @see #DEFAULT_AREA_THREASHOLD
420         */
421        public void setAreaThreshold(double threshold) {
422                if (threshold < 0) {
423                        throw new IllegalArgumentException("Area fraction threshold cannot be negative!");
424                }
425                if (threshold > 100) {
426                        throw new IllegalArgumentException("Area fraction threshold cannot be higher than 100!");
427                }
428                this.areaThreshold = threshold;
429        }
430
431        /**
432         * Set motion inertia (time when motion is valid). If no value specified this is set to 2 *
433         * interval. To reset to default value, {@link #clearInertia()} method must be used.
434         *
435         * @param inertia the motion inertia time in milliseconds
436         * @see #clearInertia()
437         */
438        public void setInertia(int inertia) {
439                if (inertia < 0) {
440                        throw new IllegalArgumentException("Inertia time must not be negative!");
441                }
442                this.inertia = inertia;
443        }
444
445        /**
446         * Reset inertia time to value calculated automatically on the base of interval. This value will
447         * be set to 2 * interval.
448         */
449        public void clearInertia() {
450                this.inertia = -1;
451        }
452
453        /**
454         * Get attached webcam object.
455         *
456         * @return Attached webcam
457         */
458        public Webcam getWebcam() {
459                return webcam;
460        }
461
462        public boolean isMotion() {
463                if (!running.get()) {
464                        LOG.warn("Motion cannot be detected when detector is not running!");
465                }
466                return motion;
467        }
468
469        /**
470         * Get percentage fraction of image covered by motion. 0 means no motion on image and 100 means
471         * full image covered by spontaneous motion.
472         *
473         * @return Return percentage image fraction covered by motion
474         */
475        public double getMotionArea() {
476                return area;
477        }
478
479        /**
480         * Get motion center of gravity. When no motion is detected this value points to the image
481         * center.
482         *
483         * @return Center of gravity point
484         */
485        public Point getMotionCog() {
486                return cog;
487        }
488
489        private static int combinePixels(int rgb1, int rgb2) {
490
491                // first ARGB
492
493                int a1 = (rgb1 >> 24) & 0xff;
494                int r1 = (rgb1 >> 16) & 0xff;
495                int g1 = (rgb1 >> 8) & 0xff;
496                int b1 = rgb1 & 0xff;
497
498                // second ARGB
499
500                int a2 = (rgb2 >> 24) & 0xff;
501                int r2 = (rgb2 >> 16) & 0xff;
502                int g2 = (rgb2 >> 8) & 0xff;
503                int b2 = rgb2 & 0xff;
504
505                r1 = clamp(Math.abs(r1 - r2));
506                g1 = clamp(Math.abs(g1 - g2));
507                b1 = clamp(Math.abs(b1 - b2));
508
509                // in case if alpha is enabled (translucent image)
510
511                if (a1 != 0xff) {
512                        a1 = a1 * 0xff / 255;
513                        int a3 = (255 - a1) * a2 / 255;
514                        r1 = clamp((r1 * a1 + r2 * a3) / 255);
515                        g1 = clamp((g1 * a1 + g2 * a3) / 255);
516                        b1 = clamp((b1 * a1 + b2 * a3) / 255);
517                        a1 = clamp(a1 + a3);
518                }
519
520                return (a1 << 24) | (r1 << 16) | (g1 << 8) | b1;
521        }
522
523        /**
524         * Clamp a value to the range 0..255
525         */
526        private static int clamp(int c) {
527                if (c < 0) {
528                        return 0;
529                }
530                if (c > 255) {
531                        return 255;
532                }
533                return c;
534        }
535
536}


text:
package ml.combust.mleap.bundle.ops.feature

import ml.combust.bundle.BundleContext
import ml.combust.bundle.dsl._
import ml.combust.bundle.op.OpModel
import ml.combust.mleap.bundle.ops.MleapOp
import ml.combust.mleap.core.feature.{BinaryOperation, MathBinaryModel}
import ml.combust.mleap.runtime.MleapContext
import ml.combust.mleap.runtime.transformer.feature.MathBinary

/**
  * Created by hollinwilkins on 12/27/16.
  */
class MathBinaryOp extends MleapOp[MathBinary, MathBinaryModel] {
  override val Model: OpModel[MleapContext, MathBinaryModel] = new OpModel[MleapContext, MathBinaryModel] {
    override val klazz: Class[MathBinaryModel] = classOf[MathBinaryModel]

    override def opName: String = Bundle.BuiltinOps.feature.math_binary

    override def store(model: Model, obj: MathBinaryModel)
                      (implicit context: BundleContext[MleapContext]): Model = {
      model.withValue("operation", Value.string(obj.operation.name)).
        withValue("da", obj.da.map(Value.double)).
        withValue("db", obj.db.map(Value.double))
    }

    override def load(model: Model)
                     (implicit context: BundleContext[MleapContext]): MathBinaryModel = {
      MathBinaryModel(operation = BinaryOperation.forName(model.value("operation").getString),
        da = model.getValue("da").map(_.getDouble),
        db = model.getValue("db").map(_.getDouble))
    }
  }

  override def model(node: MathBinary): MathBinaryModel = node.model
}


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="64dp">

    <LinearLayout
        android:id="@+id/root"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#00000000"
        android:baselineAligned="false"
        android:orientation="horizontal"
        tools:ignore="UselessParent">

        <FrameLayout
            android:layout_width="@dimen/notification_large_icon_width"
            android:layout_height="@dimen/notification_large_icon_height"
            android:layout_weight="0">

            <ImageView
                android:id="@+id/icon_player"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginBottom="12dp"
                android:layout_marginEnd="12dp"
                android:layout_marginStart="12dp"
                android:layout_marginTop="12dp"
                android:scaleType="centerInside"
                tools:ignore="ContentDescription" />

        </FrameLayout>

        <LinearLayout
            android:id="@+id/media_titles"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="fill_vertical"
            android:layout_weight="1"
            android:minHeight="@dimen/notification_large_icon_height"
            android:orientation="vertical">

            <TextView
                android:id="@+id/txt_current_music_notification"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:ellipsize="marquee"
                android:fadingEdge="horizontal"
                android:gravity="bottom"
                android:singleLine="true"
                android:textAppearance="@style/Theme.Phonograph.Notification.Title"
                tools:ignore="NestedWeights" />

            <TextView
                android:id="@+id/txt_duration_notification"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_weight="1"
                android:ellipsize="marquee"
                android:fadingEdge="horizontal"
                android:singleLine="true"
                android:textAppearance="@style/Theme.Phonograph.Notification" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/media_actions"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="center_vertical|end"
            android:layout_marginEnd="6dp"
            android:layout_marginRight="6dp"
            android:layoutDirection="ltr"
            android:orientation="horizontal"
            tools:ignore="UnusedAttribute">

            <!-- media buttons will be added here -->
            <ImageButton
                android:id="@+id/btn_prev_notification"
                style="@style/Widget.AppCompat.Button.Borderless"
                android:layout_width="48dp"
                android:layout_height="match_parent"
                android:layout_marginLeft="2dp"
                android:layout_marginRight="2dp"
                android:layout_weight="1"
                android:background="@drawable/notification_selector"
                android:gravity="center"
                android:padding="8dp"
                android:src="@drawable/ic_previous_white"
                android:scaleType="fitCenter"
                tools:ignore="ContentDescription" />

            <ImageButton
                android:id="@+id/btn_pause_notification"
                style="@style/Widget.AppCompat.Button.Borderless"
                android:layout_width="48dp"
                android:layout_height="match_parent"
                android:layout_marginLeft="2dp"
                android:layout_marginRight="2dp"
                android:layout_weight="1"
                android:background="@drawable/notification_selector"
                android:gravity="center"
                android:src="@drawable/ic_pause_white"
                android:padding="8dp"
                android:scaleType="fitCenter"
                tools:ignore="ContentDescription" />

            <ImageButton
                android:id="@+id/btn_next_notification"
                style="@style/Widget.AppCompat.Button.Borderless"
                android:layout_width="48dp"
                android:layout_height="match_parent"
                android:layout_marginLeft="2dp"
                android:layout_marginRight="2dp"
                android:layout_weight="1"
                android:background="@drawable/notification_selector"
                android:gravity="center"
                android:src="@drawable/ic_next_white"
                android:padding="8dp"
                android:scaleType="fitCenter"
                tools:ignore="ContentDescription" />

        </LinearLayout>

    </LinearLayout>

</FrameLayout>

<!--
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="70dp"
    android:orientation="horizontal"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <ImageView
        android:id="@+id/icon_player"
        android:layout_width="@dimen/icon_with"
        android:layout_height="@dimen/icon_with"/>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginStart="5dp"
        android:layout_marginLeft="5dp">

        <ImageButton
            android:id="@+id/btn_prev_notification"
            android:layout_width="@dimen/touch_default"
            android:layout_height="@dimen/touch_default"
            android:background="@drawable/ic_previous_white"
            android:layout_centerVertical="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentLeft="true" />

        <TextView
            android:id="@+id/txt_current_music_notification"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="@dimen/text_size"
            android:marqueeRepeatLimit ="marquee_forever"
            android:maxLines="1"
            android:focusable="false"
            android:requiresFadingEdge="horizontal"
            android:textAlignment="center"
            android:gravity="center"
            android:ellipsize="marquee"
            android:scrollHorizontally="true"
            android:textColor="@android:color/white"
            android:text="@string/text_test"
            android:layout_alignParentTop="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentLeft="true">
            <requestFocus/>
        </TextView>

        <ImageButton
            android:id="@+id/btn_next_notification"
            android:layout_width="@dimen/touch_default"
            android:layout_height="@dimen/touch_default"
            android:background="@drawable/ic_next_white"
            android:layout_alignTop="@+id/btn_pause_notification"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true" />

        <TextView
            android:id="@+id/txt_duration_notification"
            android:textColor="@android:color/white"
            android:layout_width="wrap_content"
            android:textSize="@dimen/text_size"
            android:layout_gravity="center"
            android:layout_height="wrap_content"
            android:ellipsize="marquee"
            android:scrollHorizontally="true"
            android:maxLines="1"
            android:text="@string/text_test"
            android:layout_below="@+id/btn_pause_notification"
            android:layout_centerHorizontal="true" />

        <ImageButton
            android:id="@+id/btn_pause_notification"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:background="@drawable/ic_pause_white"
            android:layout_gravity="center"
            android:layout_alignTop="@+id/btn_prev_notification"
            android:layout_centerHorizontal="true" />
    </RelativeLayout>
</LinearLayout>-->


text:
UNIX_SecurityServiceUsesAccountProvider::UNIX_SecurityServiceUsesAccountProvider()
{
}

UNIX_SecurityServiceUsesAccountProvider::~UNIX_SecurityServiceUsesAccountProvider()
{
}

CIMInstance UNIX_SecurityServiceUsesAccountProvider::constructInstance(
	const CIMName &className,
	const CIMNamespaceName &nameSpace,
	const UNIX_SecurityServiceUsesAccount &_p)
{
	CIMProperty p;

	CIMInstance inst(className);

	// Set path
	inst.setPath(CIMObjectPath(String(""), // hostname
			nameSpace,
			CIMName("UNIX_SecurityServiceUsesAccount"),
			constructKeyBindings(_p)));

	//CIM_Dependency Properties
	if (_p.getAntecedent(p)) inst.addProperty(p);
	if (_p.getDependent(p)) inst.addProperty(p);

	//CIM_SecurityServiceUsesAccount Properties

	return inst;
}

Array<CIMKeyBinding> UNIX_SecurityServiceUsesAccountProvider::constructKeyBindings(const UNIX_SecurityServiceUsesAccount& _p)

{

	Array<CIMKeyBinding> keys;

	keys.append(CIMKeyBinding(
		PROPERTY_ANTECEDENT,
		CIMValue(_p.getAntecedent()).toString(),
		CIMKeyBinding::REFERENCE));
	keys.append(CIMKeyBinding(
		PROPERTY_DEPENDENT,
		CIMValue(_p.getDependent()).toString(),
		CIMKeyBinding::REFERENCE));

	return keys;
}

#define UNIX_PROVIDER UNIX_SecurityServiceUsesAccountProvider
#define UNIX_PROVIDER_NAME "UNIX_SecurityServiceUsesAccountProvider"
#define CLASS_IMPLEMENTATION UNIX_SecurityServiceUsesAccount
#define CLASS_IMPLEMENTATION_NAME "UNIX_SecurityServiceUsesAccount"
#define BASE_CLASS_NAME "CIM_SecurityServiceUsesAccount"
#define NUMKEYS_CLASS_IMPLEMENTATION 0

#include "UNIXProviderBase.hpp"


text:
@protocol BGAFResponseSerializerDelegate;

@interface BGAFResponseSerializer : AFHTTPResponseSerializer
@property (nonatomic, weak) id<BGAFResponseSerializerDelegate> delegate;
@end

@protocol BGAFResponseSerializerDelegate <NSObject>
@required

- (id)responseSerializer:(BGAFResponseSerializer *)responseSerializer response:(NSURLResponse *)response data:(NSData *)data error:(NSError *__autoreleasing *)error;

@end


text:
package com.google.errorprone.matchers;

import static org.junit.Assert.assertEquals;

import com.google.errorprone.VisitorState;
import com.google.errorprone.scanner.Scanner;

import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;

import org.junit.After;
import org.junit.Before;

import java.util.ArrayList;
import java.util.List;

public class DescendantOfAbstractTest extends CompilerBasedAbstractTest {

  final List<ScannerTest> tests = new ArrayList<ScannerTest>();

  @Before
  public void setUp() throws Exception {
    writeFile("com/google/A.java",
        "package com.google;",
        "public class A { ",
        "  public int count() {",
        "    return 1;",
        "  }",
        "  public static int staticCount() {",
        "    return 2;",
        "  }",
        "}"
    );
  }

  @After
  public void tearDown() {
    for (ScannerTest test : tests) {
      test.assertDone();
    }
  }

  protected abstract class ScannerTest extends Scanner {
    public abstract void assertDone();
  }

  protected Scanner memberSelectMatches(final boolean shouldMatch,
                                        final DescendantOf toMatch) {
    ScannerTest test = new ScannerTest() {
      private boolean matched = false;

      @Override
      public Void visitMethodInvocation(MethodInvocationTree node, VisitorState visitorState) {
        visitorState = visitorState.withPath(getCurrentPath());
        ExpressionTree methodSelect = node.getMethodSelect();
        if (toMatch.matches(methodSelect, visitorState)) {
          matched = true;
        }
        return super.visitMethodInvocation(node, visitorState);
      }

      @Override
      public void assertDone() {
        assertEquals(matched, shouldMatch);
      }
    };
    tests.add(test);
    return test;
  }
}


text:
namespace {

const std::array<uint8_t, kBlockSizeBytes> kResponseBytes = {
    0x01, 0x5E, 0x3F, 0x45, 0x61, 0xC3, 0x32, 0x1D,
    0xA0, 0xBA, 0xF0, 0xBB, 0x95, 0x1F, 0xF7, 0xB6};

const std::array<uint8_t, kBlockSizeBytes> kPasskeyBytes = {
    0x02, 0x5E, 0x3F, 0x45, 0x61, 0xC3, 0x32, 0x1D,
    0xA0, 0xBA, 0xF0, 0xBB, 0x95, 0x1F, 0xF7, 0xB6};

const std::vector<uint8_t> kAccountKey = {0xA0, 0xBA, 0xF0, 0xBB, 0x95, 0x1F,
                                          0xF7, 0xB6, 0xCF, 0x5E, 0x3F, 0x45,
                                          0x61, 0xC3, 0x32, 0x1D};

const char kPublicAntiSpoof[] =
    "Wuyr48lD3txnUhGiMF1IfzlTwRxxe+wMB1HLzP+"
    "0wVcljfT3XPoiy1fntlneziyLD5knDVAJSE+RM/zlPRP/Jg==";
const char kInvalidPublicAntiSpoof[] = "";

constexpr char kValidModelId[] = "718c17";
constexpr char kTestAddress[] = "test_address";

}  // namespace

namespace ash {
namespace quick_pair {

// This controls the protocol we use to test.
using TestParam = bool;

class FastPairDataEncryptorImplTest : public testing::TestWithParam<TestParam> {
 public:
  void SetUp() override {
    data_parser_ = std::make_unique<ash::quick_pair::FastPairDataParser>(
        fast_pair_data_parser_.InitWithNewPipeAndPassReceiver());

    data_parser_remote_.Bind(std::move(fast_pair_data_parser_),
                             task_environment_.GetMainThreadTaskRunner());

    process_manager_ = std::make_unique<MockQuickPairProcessManager>();
    quick_pair_process::SetProcessManager(process_manager_.get());
  }

  void TearDown() override { data_encryptor_.reset(); }

  void FailedSetUpNoMetadata() {
    repository_ = std::make_unique<FakeFastPairRepository>();
    // Not using the param here to control the type of device because only
    // the kFastPairInitial protocol can fail.
    device_ = base::MakeRefCounted<Device>(kValidModelId, kTestAddress,
                                           Protocol::kFastPairInitial);
    FastPairDataEncryptorImpl::Factory::CreateAsync(
        device_, base::BindOnce(
                     &FastPairDataEncryptorImplTest::OnDataEncryptorCreateAsync,
                     weak_ptr_factory_.GetWeakPtr()));
  }

  void SuccessfulSetUp() {
    repository_ = std::make_unique<FakeFastPairRepository>();
    nearby::fastpair::Device metadata;

    std::string decoded_key;
    base::Base64Decode(kPublicAntiSpoof, &decoded_key);
    metadata.mutable_anti_spoofing_key_pair()->set_public_key(decoded_key);
    repository_->SetFakeMetadata(kValidModelId, metadata);

    // The param controls which protocol we use.
    if (GetParam()) {
      device_ = base::MakeRefCounted<Device>(kValidModelId, kTestAddress,
                                             Protocol::kFastPairInitial);
    } else {
      device_ = base::MakeRefCounted<Device>(kValidModelId, kTestAddress,
                                             Protocol::kFastPairSubsequent);
      device_->SetAdditionalData(Device::AdditionalDataType::kAccountKey,
                                 kAccountKey);
    }

    FastPairDataEncryptorImpl::Factory::CreateAsync(
        device_, base::BindOnce(
                     &FastPairDataEncryptorImplTest::OnDataEncryptorCreateAsync,
                     weak_ptr_factory_.GetWeakPtr()));
  }

  void SuccessfulSetUpToTestPublicKey() {
    repository_ = std::make_unique<FakeFastPairRepository>();
    nearby::fastpair::Device metadata;

    std::string decoded_key;
    base::Base64Decode(kPublicAntiSpoof, &decoded_key);
    metadata.mutable_anti_spoofing_key_pair()->set_public_key(decoded_key);
    repository_->SetFakeMetadata(kValidModelId, metadata);

    // Not using the param here to control the type of device because the
    // public key expectations differ for protocols
    device_ = base::MakeRefCounted<Device>(kValidModelId, kTestAddress,
                                           Protocol::kFastPairInitial);

    FastPairDataEncryptorImpl::Factory::CreateAsync(
        device_, base::BindOnce(
                     &FastPairDataEncryptorImplTest::OnDataEncryptorCreateAsync,
                     weak_ptr_factory_.GetWeakPtr()));
  }

  void FailedSetUpNoKeyPair() {
    repository_ = std::make_unique<FakeFastPairRepository>();
    nearby::fastpair::Device metadata;

    std::string decoded_key;
    base::Base64Decode(kInvalidPublicAntiSpoof, &decoded_key);
    metadata.mutable_anti_spoofing_key_pair()->set_public_key(decoded_key);
    repository_->SetFakeMetadata(kValidModelId, metadata);

    // Not using the param here to control the type of device because only
    // the kFastPairInitial protocol can fail..
    device_ = base::MakeRefCounted<Device>(kValidModelId, kTestAddress,
                                           Protocol::kFastPairInitial);
    FastPairDataEncryptorImpl::Factory::CreateAsync(
        device_, base::BindOnce(
                     &FastPairDataEncryptorImplTest::OnDataEncryptorCreateAsync,
                     weak_ptr_factory_.GetWeakPtr()));
  }

  void OnDataEncryptorCreateAsync(
      std::unique_ptr<FastPairDataEncryptor> fast_pair_data_encryptor) {
    data_encryptor_ = std::move(fast_pair_data_encryptor);
  }

  const std::array<uint8_t, kBlockSizeBytes> EncryptBytes() {
    return data_encryptor_->EncryptBytes(kResponseBytes);
  }

  void ParseDecryptedResponse() {
    const std::array<uint8_t, kBlockSizeBytes> bytes =
        data_encryptor_->EncryptBytes(kResponseBytes);

    data_encryptor_->ParseDecryptedResponse(
        std::vector<uint8_t>(bytes.begin(), bytes.end()),
        base::BindOnce(
            &FastPairDataEncryptorImplTest::ParseDecryptedResponseCallback,
            weak_ptr_factory_.GetWeakPtr()));
  }

  void ParseDecryptedResponseInvalidBytes() {
    const std::array<uint8_t, kBlockSizeBytes> bytes =
        data_encryptor_->EncryptBytes(kResponseBytes);

    data_encryptor_->ParseDecryptedResponse(
        std::vector<uint8_t>(bytes.begin() + 3, bytes.end()),
        base::BindOnce(
            &FastPairDataEncryptorImplTest::ParseDecryptedResponseCallback,
            weak_ptr_factory_.GetWeakPtr()));
  }

  void ParseDecryptedResponseCallback(
      const absl::optional<DecryptedResponse>& response) {
    response_ = response;
  }

  void ParseDecryptedPasskey() {
    const std::array<uint8_t, kBlockSizeBytes> bytes =
        data_encryptor_->EncryptBytes(kPasskeyBytes);

    data_encryptor_->ParseDecryptedPasskey(
        std::vector<uint8_t>(bytes.begin(), bytes.end()),
        base::BindOnce(
            &FastPairDataEncryptorImplTest::ParseDecryptedPasskeyCallback,
            weak_ptr_factory_.GetWeakPtr()));
  }

  void ParseDecryptedPasskeyInvalidBytes() {
    const std::array<uint8_t, kBlockSizeBytes> bytes =
        data_encryptor_->EncryptBytes(kPasskeyBytes);

    data_encryptor_->ParseDecryptedPasskey(
        std::vector<uint8_t>(bytes.begin() + 3, bytes.end()),
        base::BindOnce(
            &FastPairDataEncryptorImplTest::ParseDecryptedPasskeyCallback,
            weak_ptr_factory_.GetWeakPtr()));
  }

  void ParseDecryptedPasskeyCallback(
      const absl::optional<DecryptedPasskey>& passkey) {
    passkey_ = passkey;
  }

 protected:
  std::unique_ptr<FastPairDataEncryptor> data_encryptor_;
  absl::optional<DecryptedResponse> response_ = absl::nullopt;
  absl::optional<DecryptedPasskey> passkey_ = absl::nullopt;
  std::unique_ptr<MockQuickPairProcessManager> process_manager_;
  mojo::SharedRemote<ash::quick_pair::mojom::FastPairDataParser>
      data_parser_remote_;
  mojo::PendingRemote<ash::quick_pair::mojom::FastPairDataParser>
      fast_pair_data_parser_;
  std::unique_ptr<ash::quick_pair::FastPairDataParser> data_parser_;

 private:
  scoped_refptr<Device> device_;
  std::unique_ptr<FakeFastPairRepository> repository_;
  base::test::TaskEnvironment task_environment_;
  base::WeakPtrFactory<FastPairDataEncryptorImplTest> weak_ptr_factory_{this};
};

TEST_P(FastPairDataEncryptorImplTest, FailedSetUpNoMetadata) {
  EXPECT_FALSE(data_encryptor_);
  FailedSetUpNoMetadata();
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(data_encryptor_);
}

TEST_P(FastPairDataEncryptorImplTest, SuccessfulSetUp) {
  EXPECT_FALSE(data_encryptor_);
  SuccessfulSetUp();
  base::RunLoop().RunUntilIdle();
  EXPECT_TRUE(data_encryptor_);
}

TEST_P(FastPairDataEncryptorImplTest, EncryptBytes) {
  SuccessfulSetUp();
  base::RunLoop().RunUntilIdle();
  EXPECT_TRUE(data_encryptor_);
  EXPECT_FALSE(EncryptBytes().empty());
}

TEST_P(FastPairDataEncryptorImplTest, ParseDecryptedResponse) {
  SuccessfulSetUp();
  base::RunLoop().RunUntilIdle();
  EXPECT_TRUE(data_encryptor_);
  EXPECT_CALL(*process_manager_, GetProcessReference);
  ParseDecryptedResponse();
  base::RunLoop().RunUntilIdle();
}

TEST_P(FastPairDataEncryptorImplTest, ParseDecryptedPasskey) {
  SuccessfulSetUp();
  base::RunLoop().RunUntilIdle();
  EXPECT_TRUE(data_encryptor_);
  EXPECT_CALL(*process_manager_, GetProcessReference);
  ParseDecryptedPasskey();
  base::RunLoop().RunUntilIdle();
}

TEST_P(FastPairDataEncryptorImplTest, ParseDecryptedPasskey_InvalidInputSize) {
  SuccessfulSetUp();
  base::RunLoop().RunUntilIdle();
  EXPECT_TRUE(data_encryptor_);
  EXPECT_CALL(*process_manager_, GetProcessReference).Times(0);
  ParseDecryptedPasskeyInvalidBytes();
  base::RunLoop().RunUntilIdle();
}

TEST_P(FastPairDataEncryptorImplTest, ParseDecryptedResponse_InvalidInputSize) {
  SuccessfulSetUp();
  base::RunLoop().RunUntilIdle();
  EXPECT_TRUE(data_encryptor_);
  EXPECT_CALL(*process_manager_, GetProcessReference).Times(0);
  ParseDecryptedResponseInvalidBytes();
  base::RunLoop().RunUntilIdle();
}

TEST_P(FastPairDataEncryptorImplTest, NoKeyPair) {
  FailedSetUpNoKeyPair();
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(data_encryptor_);
}

// TODO(crbug.com/1298377) flaky on ASan + LSan bots
#if defined(ADDRESS_SANITIZER) && defined(LEAK_SANITIZER)
#define MAYBE_ParseDecryptedPasskey_ProcessStopped \
  DISABLED_ParseDecryptedPasskey_ProcessStopped
#else
#define MAYBE_ParseDecryptedPasskey_ProcessStopped \
  ParseDecryptedPasskey_ProcessStopped
#endif
TEST_P(FastPairDataEncryptorImplTest,
       MAYBE_ParseDecryptedPasskey_ProcessStopped) {
  SuccessfulSetUp();
  base::RunLoop().RunUntilIdle();
  EXPECT_TRUE(data_encryptor_);
  EXPECT_CALL(*process_manager_, GetProcessReference)
      .WillRepeatedly(
          [&](QuickPairProcessManager::ProcessStoppedCallback callback) {
            std::move(callback).Run(
                QuickPairProcessManager::ShutdownReason::kCrash);
            return std::make_unique<
                QuickPairProcessManagerImpl::ProcessReferenceImpl>(
                data_parser_remote_, base::DoNothing());
          });
  ParseDecryptedPasskey();
  base::RunLoop().RunUntilIdle();
}

// TODO(crbug.com/1298377) flaky on ASan + LSan bots
#if defined(ADDRESS_SANITIZER) && defined(LEAK_SANITIZER)
#define MAYBE_ParseDecryptedResponse_ProcessStopped \
  DISABLED_ParseDecryptedResponse_ProcessStopped
#else
#define MAYBE_ParseDecryptedResponse_ProcessStopped \
  ParseDecryptedResponse_ProcessStopped
#endif
TEST_P(FastPairDataEncryptorImplTest,
       MAYBE_ParseDecryptedResponse_ProcessStopped) {
  SuccessfulSetUp();
  base::RunLoop().RunUntilIdle();
  EXPECT_TRUE(data_encryptor_);
  EXPECT_CALL(*process_manager_, GetProcessReference)
      .WillRepeatedly(
          [&](QuickPairProcessManager::ProcessStoppedCallback callback) {
            std::move(callback).Run(
                QuickPairProcessManager::ShutdownReason::kCrash);
            return std::make_unique<
                QuickPairProcessManagerImpl::ProcessReferenceImpl>(
                data_parser_remote_, base::DoNothing());
          });
  ParseDecryptedResponse();
  base::RunLoop().RunUntilIdle();
}

TEST_P(FastPairDataEncryptorImplTest, GetPublicKey) {
  SuccessfulSetUpToTestPublicKey();
  base::RunLoop().RunUntilIdle();
  EXPECT_TRUE(data_encryptor_);
  EXPECT_CALL(*process_manager_, GetProcessReference);
  ParseDecryptedPasskey();
  base::RunLoop().RunUntilIdle();
  EXPECT_NE(data_encryptor_->GetPublicKey(), absl::nullopt);
}

INSTANTIATE_TEST_SUITE_P(FastPairDataEncryptorImplTest,
                         FastPairDataEncryptorImplTest,
                         testing::Bool());

}  // namespace quick_pair
}  // namespace ash