text:
package io.github.simonxianyu.util.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

/**
 * Use this to facade operations of Shiro.
 * Created by Simon Xianyu on 2015/11/20 0020.
 */
public class ShiroUtil {

    public static boolean isLogin() {
        return getSubject().isAuthenticated();
    }

    public static Session getSession() {
        return getSubject().getSession();
    }

    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    public static boolean isPermitted(String permissionName) {
        return getSubject().isPermitted(permissionName);
    }
}

redpajama_set_name: RedPajamaGithub


text:
"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.styles = void 0;

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var React = _interopRequireWildcard(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _clsx = _interopRequireDefault(require("clsx"));

var _withStyles = _interopRequireDefault(require("../styles/withStyles"));

var _capitalize = _interopRequireDefault(require("../utils/capitalize"));

var styles = function styles(theme) {
  return {
    /* Styles applied to the root element. */
    root: (0, _defineProperty2.default)({
      width: '100%',
      marginLeft: 'auto',
      boxSizing: 'border-box',
      marginRight: 'auto',
      paddingLeft: theme.spacing(2),
      paddingRight: theme.spacing(2)
    }, theme.breakpoints.up('sm'), {
      paddingLeft: theme.spacing(3),
      paddingRight: theme.spacing(3)
    }),

    /* Styles applied to the root element if `disableGutters={true}`. */
    disableGutters: {
      paddingLeft: 0,
      paddingRight: 0
    },

    /* Styles applied to the root element if `fixed={true}`. */
    fixed: Object.keys(theme.breakpoints.values).reduce(function (acc, breakpoint) {
      var value = theme.breakpoints.values[breakpoint];

      if (value !== 0) {
        acc[theme.breakpoints.up(breakpoint)] = {
          maxWidth: value
        };
      }

      return acc;
    }, {}),

    /* Styles applied to the root element if `maxWidth="xs"`. */
    maxWidthXs: (0, _defineProperty2.default)({}, theme.breakpoints.up('xs'), {
      maxWidth: Math.max(theme.breakpoints.values.xs, 444)
    }),

    /* Styles applied to the root element if `maxWidth="sm"`. */
    maxWidthSm: (0, _defineProperty2.default)({}, theme.breakpoints.up('sm'), {
      maxWidth: theme.breakpoints.values.sm
    }),

    /* Styles applied to the root element if `maxWidth="md"`. */
    maxWidthMd: (0, _defineProperty2.default)({}, theme.breakpoints.up('md'), {
      maxWidth: theme.breakpoints.values.md
    }),

    /* Styles applied to the root element if `maxWidth="lg"`. */
    maxWidthLg: (0, _defineProperty2.default)({}, theme.breakpoints.up('lg'), {
      maxWidth: theme.breakpoints.values.lg
    }),

    /* Styles applied to the root element if `maxWidth="xl"`. */
    maxWidthXl: (0, _defineProperty2.default)({}, theme.breakpoints.up('xl'), {
      maxWidth: theme.breakpoints.values.xl
    })
  };
};

exports.styles = styles;
var Container = React.forwardRef(function Container(props, ref) {
  var classes = props.classes,
      className = props.className,
      _props$component = props.component,
      Component = _props$component === void 0 ? 'div' : _props$component,
      _props$disableGutters = props.disableGutters,
      disableGutters = _props$disableGutters === void 0 ? false : _props$disableGutters,
      _props$fixed = props.fixed,
      fixed = _props$fixed === void 0 ? false : _props$fixed,
      _props$maxWidth = props.maxWidth,
      maxWidth = _props$maxWidth === void 0 ? 'lg' : _props$maxWidth,
      other = (0, _objectWithoutProperties2.default)(props, ["classes", "className", "component", "disableGutters", "fixed", "maxWidth"]);
  return React.createElement(Component, (0, _extends2.default)({
    className: (0, _clsx.default)(classes.root, className, fixed && classes.fixed, disableGutters && classes.disableGutters, maxWidth !== false && classes["maxWidth".concat((0, _capitalize.default)(String(maxWidth)))]),
    ref: ref
  }, other));
});
process.env.NODE_ENV !== "production" ? Container.propTypes = {
  children: _propTypes.default.node.isRequired,

  /**
   * Override or extend the styles applied to the component.
   * See [CSS API](#css) below for more details.
   */
  classes: _propTypes.default.object.isRequired,

  /**
   * @ignore
   */
  className: _propTypes.default.string,

  /**
   * The component used for the root node.
   * Either a string to use a DOM element or a component.
   */
  component: _propTypes.default.elementType,

  /**
   * If `true`, the left and right padding is removed.
   */
  disableGutters: _propTypes.default.bool,

  /**
   * Set the max-width to match the min-width of the current breakpoint.
   * This is useful if you'd prefer to design for a fixed set of sizes
   * instead of trying to accommodate a fully fluid viewport.
   * It's fluid by default.
   */
  fixed: _propTypes.default.bool,

  /**
   * Determine the max-width of the container.
   * The container width grows with the size of the screen.
   * Set to `false` to disable `maxWidth`.
   */
  maxWidth: _propTypes.default.oneOf(['xs', 'sm', 'md', 'lg', 'xl', false])
} : void 0;

var _default = (0, _withStyles.default)(styles, {
  name: 'MuiContainer'
})(Container);

exports.default = _default;


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta name="copyright" content="(C) Copyright 2005" />
<meta name="DC.rights.owner" content="(C) Copyright 2005" />
<meta content="public" name="security" />
<meta content="index,follow" name="Robots" />
<meta http-equiv="PICS-Label" content='(PICS-1.1 "http://www.icra.org/ratingsv02.html" l gen true r (cz 1 lz 1 nz 1 oz 1 vz 1) "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v 0 l 0) "http://www.classify.org/safesurf/" l gen true r (SS~~000 1))' />
<meta content="reference" name="DC.Type" />
<meta name="DC.Title" content="Letras maiúsculas e caracteres especiais" />
<meta content="Diferenciação de letras maiúsculas e minúsculas em palavras chave e identificadores, Palavras chave, diferenciação de letras maiúsculas e minúsculas, escapes nas instruções SQL, para apóstrofo, delimitadas por apóstrofos nas instruções SQL, suporte nas instruções SQL, diferenciação de letras maiúsculas e minúsculas no SQL, * como curinga no SELECT do SQL, % como curinga no SQL, _ como curinga no SQL, Caracteres curinga no SQL, Delimitadores de comentários no SQL, -- (delimitador de cmentário no SQL)" name="DC.subject" />
<meta content="Diferenciação de letras maiúsculas e minúsculas em palavras chave e identificadores, Palavras chave, diferenciação de letras maiúsculas e minúsculas, escapes nas instruções SQL, para apóstrofo, delimitadas por apóstrofos nas instruções SQL, suporte nas instruções SQL, diferenciação de letras maiúsculas e minúsculas no SQL, * como curinga no SELECT do SQL, % como curinga no SQL, _ como curinga no SQL, Caracteres curinga no SQL, Delimitadores de comentários no SQL, -- (delimitador de cmentário no SQL)" name="keywords" />
<meta scheme="URI" name="DC.Relation" content="crefsqlj23296.html" />
<meta scheme="URI" name="DC.Relation" content="crefsqlj18919.html" />
<meta scheme="URI" name="DC.Relation" content="crefsqlj39374.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj29026.html" />
<meta scheme="URI" name="DC.Relation" content="crefsqlbuiltinsystemfunctions.html" />
<meta scheme="URI" name="DC.Relation" content="crefsqlbuiltinsystemprocedures.html" />
<meta scheme="URI" name="DC.Relation" content="crefsqlj31068.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj19433.html" />
<meta content="XHTML" name="DC.Format" />
<meta content="rrefsqlj28468" name="DC.Identifier" />
<meta content="pt-br" name="DC.Language" />
<link href="commonltr.css" type="text/css" rel="stylesheet" />
<title>Letras maiúsculas e caracteres especiais</title>

Letras maiúsculas e caracteres especiais

Ao utilizar classes e métodos do JDBC, são submetidas instruções SQL ao
Derby
na forma de cadeias.
O conjunto de caracteres permitido nas cadeias contendo instruções SQL é o
Unicode.
Nestas cadeias se aplicam as seguintes regras:

Aspas delimitam os identificadores especiais, referidos no SQL-92 como
identificadores delimitados.

Apóstrofos delimitam cadeias de caracteres.

Na cadeia de caracteres, para representar um apóstrofo (também chamado de
aspas simples) são usados dois apóstrofos (Em outras palavras, o apóstrofo é o
caractere de escape do apóstrofo).

As aspas não necessitam de caractere de escape.
Para representar aspas deve-se, simplesmente, utilizar aspas.
Entretanto, deve ser observado que no programa Java as aspas necessitam do
caractere de escape contrabarra (\).

Exemplo:

-- o apóstrofo é o caractere de escape do apóstrofo

VALUES 'Maria D''Almeida'

-- no ij não há necessidade de caractere de escape para aspas

VALUES 'Ele disse, "Bom dia!"'

-- no programa Java aspas necessitam de escape

n = stmt.executeUpdate(
    "UPDATE minhaTabela SET stringCol = 'Ele disse, \"Bom dia!\"'");

As palavras chave do SQL não são sensíveis a letras maiúsculas e minúsculas.
Por exemplo, a palavra chave SELECT pode ser escrita como SELECT, Select,
select, ou sELECT.

Os identificadores no estilo SQL-92 não são sensíveis a letras maiúsculas e
minúsculas
(consulte IdentificadorSQL92),
a menos que estejam delimitados.

Os identificadores no estilo Java são sensíveis a letras maiúsculas e
minúsculas.

O * é um caractere curinga na
ExpressãoSeleção.
Consulte O curinga *.
Também pode ser o operador de multiplicação.
Em todos os outros casos é um meta-símbolo da sintaxe, sinalizando itens que
podem ser repetidos zero ou mais vezes.

% e _ são caracteres curinga quando utilizados nas cadeias de caracteres
após o operador LIKE (exceto quando precedidos pelo caractere de escape).
Consulte Expressão booleana.

De acordo com o padrão SQL-92, dois hífens (--) e o caractere de nova-linha
delimitam um comentário.
Os dois hífens iniciam o comentário, e o caractere de nova-linha termina o
comentário.

Tópico pai: Referência da linguagem SQL

Conceitos relacionados

Identificadores SQL

Instruções

Funções do sistema nativas

Procedimentos do sistema nativos

Tipos de dado

Referências relacionadas

Funções nativas

Expressões SQL


text:
@interface OutLoginViewController ()

@end

@implementation OutLoginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    login = [[OutLoginView alloc] initWithFrame:CGRectMake(0, 0, 320, SCREEN_HEIGHT)];
    login.delegate = self;
    [self.view addSubview:login];
    [login release];
}

-(void)outloginInServer:(id)sender
{
    NSLog(@"login  %@,%@",login.nameField.text,login.passField.text);
    VerifyOutsideLoginReqBody *reqBody = [[VerifyOutsideLoginReqBody alloc] init];
    reqBody.name = login.nameField.text;
    reqBody.password = login.passField.text;

    NSMutableURLRequest *request = [[AFHttpRequestUtils shareInstance] requestWithBody:reqBody
                                                                            andReqType:VERITY_OUT];
    [reqBody release];

    AFHTTPRequestOperation *theOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [theOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

        VerifyOutsideLoginRespBody *respBody = (VerifyOutsideLoginRespBody *)[[AFHttpRequestUtils shareInstance] jsonConvertObject:(NSData *)responseObject withReqType:VERITY_OUT];
        [self checkData:respBody];

    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error : %@", [error localizedDescription]);
        alertMessage(@"请求出错,请稍后重试.");
    }];

    [theOperation start];
    [theOperation release];
}

-(void) checkData:(VerifyOutsideLoginRespBody *) respBody
{
    if (![@"\"0\"" isEqualToString:respBody.isVerify]) {
        [DataCenter shareInstance].isOutLogin = YES;
        [DataCenter shareInstance].outLoginName = login.nameField.text;
        [DataCenter shareInstance].outLoginId = [[[respBody.isVerify substringToIndex:[respBody.isVerify length]-1] substringFromIndex:1] stringByReplacingOccurrencesOfString:@" " withString:@""];
        [self dismissViewControllerAnimated:YES completion:^{}];
    } else {
        alertMessage(@"登录失败,账户或密码错误.");
    }
}

-(void)outregisterInService:(NSString *) name WithMobile:(NSString *)mobile
{
    NSLog(@"%@%@",name,mobile);

    AddPeopleAccountReqBody *reqBody = [[AddPeopleAccountReqBody alloc] init];
    reqBody.PeopleName = name;
    reqBody.peopleMobileNo = mobile;
    nameReg = [name retain];
    NSMutableURLRequest *request = [[AFHttpRequestUtils shareInstance] requestWithBody:reqBody
                                                                            andReqType:ADD_PEOACCOUNT];
    [reqBody release];

    AFHTTPRequestOperation *theOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [theOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

        AddPeopleAccountRespBody *respBody = (AddPeopleAccountRespBody *)[[AFHttpRequestUtils shareInstance] jsonConvertObject:(NSData *)responseObject withReqType:ADD_PEOACCOUNT];
        [self checkRegster:respBody];

    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error : %@", [error localizedDescription]);
        alertMessage(@"请求出错,请稍后重试.");
    }];

    [theOperation start];
    [theOperation release];
}

-(void) checkRegster:(AddPeopleAccountRespBody *)respBody
{
    if (![@"\"0\"" isEqualToString:respBody.result]) {
        alertMessage(@"注册成功! 请登录");
    } else {
        alertMessage(@"注册失败,请重新提交注册.");
    }
}

-(void)outcancleLogin:(id)sender
{
    NSLog(@"cancle");
    [self dismissViewControllerAnimated:YES completion:^{}];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
#ifndef PC_RTCSTATSCOLLECTOR_H_
#define PC_RTCSTATSCOLLECTOR_H_

#include <map>
#include <memory>
#include <set>
#include <string>
#include <vector>

#include BOSS_ABSEILCPP_U_absl__types__optional_h //original-code:"absl/types/optional.h"
#include BOSS_WEBRTC_U_api__stats__rtcstats_objects_h //original-code:"api/stats/rtcstats_objects.h"
#include BOSS_WEBRTC_U_api__stats__rtcstatscollectorcallback_h //original-code:"api/stats/rtcstatscollectorcallback.h"
#include BOSS_WEBRTC_U_api__stats__rtcstatsreport_h //original-code:"api/stats/rtcstatsreport.h"
#include BOSS_WEBRTC_U_call__call_h //original-code:"call/call.h"
#include BOSS_WEBRTC_U_media__base__mediachannel_h //original-code:"media/base/mediachannel.h"
#include BOSS_WEBRTC_U_pc__datachannel_h //original-code:"pc/datachannel.h"
#include BOSS_WEBRTC_U_pc__peerconnectioninternal_h //original-code:"pc/peerconnectioninternal.h"
#include BOSS_WEBRTC_U_pc__trackmediainfomap_h //original-code:"pc/trackmediainfomap.h"
#include BOSS_WEBRTC_U_rtc_base__asyncinvoker_h //original-code:"rtc_base/asyncinvoker.h"
#include BOSS_WEBRTC_U_rtc_base__refcount_h //original-code:"rtc_base/refcount.h"
#include BOSS_WEBRTC_U_rtc_base__scoped_ref_ptr_h //original-code:"rtc_base/scoped_ref_ptr.h"
#include BOSS_WEBRTC_U_rtc_base__sslidentity_h //original-code:"rtc_base/sslidentity.h"
#include BOSS_WEBRTC_U_rtc_base__third_party__sigslot__sigslot_h //original-code:"rtc_base/third_party/sigslot/sigslot.h"
#include BOSS_WEBRTC_U_rtc_base__timeutils_h //original-code:"rtc_base/timeutils.h"

namespace webrtc {

class RtpSenderInternal;
class RtpReceiverInternal;

// All public methods of the collector are to be called on the signaling thread.
// Stats are gathered on the signaling, worker and network threads
// asynchronously. The callback is invoked on the signaling thread. Resulting
// reports are cached for |cache_lifetime_| ms.
class RTCStatsCollector : public virtual rtc::RefCountInterface,
                          public sigslot::has_slots<> {
 public:
  static rtc::scoped_refptr<RTCStatsCollector> Create(
      PeerConnectionInternal* pc,
      int64_t cache_lifetime_us = 50 * rtc::kNumMicrosecsPerMillisec);

  // Gets a recent stats report. If there is a report cached that is still fresh
  // it is returned, otherwise new stats are gathered and returned. A report is
  // considered fresh for |cache_lifetime_| ms. const RTCStatsReports are safe
  // to use across multiple threads and may be destructed on any thread.
  // If the optional selector argument is used, stats are filtered according to
  // stats selection algorithm before delivery.
  // https://w3c.github.io/webrtc-pc/#dfn-stats-selection-algorithm
  void GetStatsReport(rtc::scoped_refptr<RTCStatsCollectorCallback> callback);
  // If |selector| is null the selection algorithm is still applied (interpreted
  // as: no RTP streams are sent by selector). The result is empty.
  void GetStatsReport(rtc::scoped_refptr<RtpSenderInternal> selector,
                      rtc::scoped_refptr<RTCStatsCollectorCallback> callback);
  // If |selector| is null the selection algorithm is still applied (interpreted
  // as: no RTP streams are received by selector). The result is empty.
  void GetStatsReport(rtc::scoped_refptr<RtpReceiverInternal> selector,
                      rtc::scoped_refptr<RTCStatsCollectorCallback> callback);
  // Clears the cache's reference to the most recent stats report. Subsequently
  // calling |GetStatsReport| guarantees fresh stats.
  void ClearCachedStatsReport();

  // If there is a |GetStatsReport| requests in-flight, waits until it has been
  // completed. Must be called on the signaling thread.
  void WaitForPendingRequest();

 protected:
  RTCStatsCollector(PeerConnectionInternal* pc, int64_t cache_lifetime_us);
  ~RTCStatsCollector();

  // Stats gathering on a particular thread. Calls |AddPartialResults| before
  // returning. Virtual for the sake of testing.
  virtual void ProducePartialResultsOnSignalingThread(int64_t timestamp_us);
  virtual void ProducePartialResultsOnNetworkThread(int64_t timestamp_us);

  // Can be called on any thread.
  void AddPartialResults(
      const rtc::scoped_refptr<RTCStatsReport>& partial_report);

 private:
  class RequestInfo {
   public:
    enum class FilterMode { kAll, kSenderSelector, kReceiverSelector };

    // Constructs with FilterMode::kAll.
    explicit RequestInfo(
        rtc::scoped_refptr<RTCStatsCollectorCallback> callback);
    // Constructs with FilterMode::kSenderSelector. The selection algorithm is
    // applied even if |selector| is null, resulting in an empty report.
    RequestInfo(rtc::scoped_refptr<RtpSenderInternal> selector,
                rtc::scoped_refptr<RTCStatsCollectorCallback> callback);
    // Constructs with FilterMode::kReceiverSelector. The selection algorithm is
    // applied even if |selector| is null, resulting in an empty report.
    RequestInfo(rtc::scoped_refptr<RtpReceiverInternal> selector,
                rtc::scoped_refptr<RTCStatsCollectorCallback> callback);

    FilterMode filter_mode() const { return filter_mode_; }
    rtc::scoped_refptr<RTCStatsCollectorCallback> callback() const {
      return callback_;
    }
    rtc::scoped_refptr<RtpSenderInternal> sender_selector() const {
      RTC_DCHECK(filter_mode_ == FilterMode::kSenderSelector);
      return sender_selector_;
    }
    rtc::scoped_refptr<RtpReceiverInternal> receiver_selector() const {
      RTC_DCHECK(filter_mode_ == FilterMode::kReceiverSelector);
      return receiver_selector_;
    }

   private:
    RequestInfo(FilterMode filter_mode,
                rtc::scoped_refptr<RTCStatsCollectorCallback> callback,
                rtc::scoped_refptr<RtpSenderInternal> sender_selector,
                rtc::scoped_refptr<RtpReceiverInternal> receiver_selector);

    FilterMode filter_mode_;
    rtc::scoped_refptr<RTCStatsCollectorCallback> callback_;
    rtc::scoped_refptr<RtpSenderInternal> sender_selector_;
    rtc::scoped_refptr<RtpReceiverInternal> receiver_selector_;
  };

  void GetStatsReportInternal(RequestInfo request);

  struct CertificateStatsPair {
    std::unique_ptr<rtc::SSLCertificateStats> local;
    std::unique_ptr<rtc::SSLCertificateStats> remote;
  };

  // Structure for tracking stats about each RtpTransceiver managed by the
  // PeerConnection. This can either by a Plan B style or Unified Plan style
  // transceiver (i.e., can have 0 or many senders and receivers).
  // Some fields are copied from the RtpTransceiver/BaseChannel object so that
  // they can be accessed safely on threads other than the signaling thread.
  // If a BaseChannel is not available (e.g., if signaling has not started),
  // then |mid| and |transport_name| will be null.
  struct RtpTransceiverStatsInfo {
    rtc::scoped_refptr<RtpTransceiver> transceiver;
    cricket::MediaType media_type;
    absl::optional<std::string> mid;
    absl::optional<std::string> transport_name;
    std::unique_ptr<TrackMediaInfoMap> track_media_info_map;
  };

  void AddPartialResults_s(rtc::scoped_refptr<RTCStatsReport> partial_report);
  void DeliverCachedReport(
      rtc::scoped_refptr<const RTCStatsReport> cached_report,
      std::vector<RequestInfo> requests);

  // Produces |RTCCertificateStats|.
  void ProduceCertificateStats_n(
      int64_t timestamp_us,
      const std::map<std::string, CertificateStatsPair>& transport_cert_stats,
      RTCStatsReport* report) const;
  // Produces |RTCCodecStats|.
  void ProduceCodecStats_n(
      int64_t timestamp_us,
      const std::vector<RtpTransceiverStatsInfo>& transceiver_stats_infos,
      RTCStatsReport* report) const;
  // Produces |RTCDataChannelStats|.
  void ProduceDataChannelStats_s(int64_t timestamp_us,
                                 RTCStatsReport* report) const;
  // Produces |RTCIceCandidatePairStats| and |RTCIceCandidateStats|.
  void ProduceIceCandidateAndPairStats_n(
      int64_t timestamp_us,
      const std::map<std::string, cricket::TransportStats>&
          transport_stats_by_name,
      const Call::Stats& call_stats,
      RTCStatsReport* report) const;
  // Produces |RTCMediaStreamStats|.
  void ProduceMediaStreamStats_s(int64_t timestamp_us,
                                 RTCStatsReport* report) const;
  // Produces |RTCMediaStreamTrackStats|.
  void ProduceMediaStreamTrackStats_s(int64_t timestamp_us,
                                      RTCStatsReport* report) const;
  // Produces |RTCPeerConnectionStats|.
  void ProducePeerConnectionStats_s(int64_t timestamp_us,
                                    RTCStatsReport* report) const;
  // Produces |RTCInboundRTPStreamStats| and |RTCOutboundRTPStreamStats|.
  void ProduceRTPStreamStats_n(
      int64_t timestamp_us,
      const std::vector<RtpTransceiverStatsInfo>& transceiver_stats_infos,
      RTCStatsReport* report) const;
  void ProduceAudioRTPStreamStats_n(int64_t timestamp_us,
                                    const RtpTransceiverStatsInfo& stats,
                                    RTCStatsReport* report) const;
  void ProduceVideoRTPStreamStats_n(int64_t timestamp_us,
                                    const RtpTransceiverStatsInfo& stats,
                                    RTCStatsReport* report) const;
  // Produces |RTCTransportStats|.
  void ProduceTransportStats_n(
      int64_t timestamp_us,
      const std::map<std::string, cricket::TransportStats>&
          transport_stats_by_name,
      const std::map<std::string, CertificateStatsPair>& transport_cert_stats,
      RTCStatsReport* report) const;

  // Helper function to stats-producing functions.
  std::map<std::string, CertificateStatsPair>
  PrepareTransportCertificateStats_n(
      const std::map<std::string, cricket::TransportStats>&
          transport_stats_by_name) const;
  std::vector<RtpTransceiverStatsInfo> PrepareTransceiverStatsInfos_s() const;
  std::set<std::string> PrepareTransportNames_s() const;

  // Slots for signals (sigslot) that are wired up to |pc_|.
  void OnDataChannelCreated(DataChannel* channel);
  // Slots for signals (sigslot) that are wired up to |channel|.
  void OnDataChannelOpened(DataChannel* channel);
  void OnDataChannelClosed(DataChannel* channel);

  PeerConnectionInternal* const pc_;
  rtc::Thread* const signaling_thread_;
  rtc::Thread* const worker_thread_;
  rtc::Thread* const network_thread_;
  rtc::AsyncInvoker invoker_;

  int num_pending_partial_reports_;
  int64_t partial_report_timestamp_us_;
  rtc::scoped_refptr<RTCStatsReport> partial_report_;
  std::vector<RequestInfo> requests_;

  // Set in |GetStatsReport|, read in |ProducePartialResultsOnNetworkThread| and
  // |ProducePartialResultsOnSignalingThread|, reset after work is complete. Not
  // passed as arguments to avoid copies. This is thread safe - when we
  // set/reset we know there are no pending stats requests in progress.
  std::vector<RtpTransceiverStatsInfo> transceiver_stats_infos_;
  std::set<std::string> transport_names_;

  Call::Stats call_stats_;

  // A timestamp, in microseconds, that is based on a timer that is
  // monotonically increasing. That is, even if the system clock is modified the
  // difference between the timer and this timestamp is how fresh the cached
  // report is.
  int64_t cache_timestamp_us_;
  int64_t cache_lifetime_us_;
  rtc::scoped_refptr<const RTCStatsReport> cached_report_;

  // Data recorded and maintained by the stats collector during its lifetime.
  // Some stats are produced from this record instead of other components.
  struct InternalRecord {
    InternalRecord() : data_channels_opened(0), data_channels_closed(0) {}

    // The opened count goes up when a channel is fully opened and the closed
    // count goes up if a previously opened channel has fully closed. The opened
    // count does not go down when a channel closes, meaning (opened - closed)
    // is the number of channels currently opened. A channel that is closed
    // before reaching the open state does not affect these counters.
    uint32_t data_channels_opened;
    uint32_t data_channels_closed;
    // Identifies by address channels that have been opened, which remain in the
    // set until they have been fully closed.
    std::set<uintptr_t> opened_data_channels;
  };
  InternalRecord internal_record_;
};

const char* CandidateTypeToRTCIceCandidateTypeForTesting(
    const std::string& type);
const char* DataStateToRTCDataChannelStateForTesting(
    DataChannelInterface::DataState state);

}  // namespace webrtc

#endif  // PC_RTCSTATSCOLLECTOR_H_


text:
/**
 * @file   gameLocal.cpp
 * @brief  共通で使用するものを置いている
 *
 * @author y.akria
 * @date   2017.01.02
 */

#include "precompiled.h"

// -----------------------------------------------------------
unique_ptr<GameLocal> g_local = make_unique<GameLocal>();

GameLocal::GameLocal()
  : width_    ( 0     )
  , height_   ( 0     )
  , lastFrame_( 0     )
  , frameAcc_ ( 0     )
  , Stop      ( false )
{}

void GameLocal::Setup() {
  ofxJSON json;
  json.open("game.json");

  frameAcc_ = json["acceleration"].asFloat();

  width_  = ofGetWidth();
  height_ = ofGetHeight();

  ofAddListener(ofEvents().update,        this, &GameLocal::update);
  ofAddListener(ofEvents().windowResized, this, &GameLocal::windowResized);
}

void GameLocal::update(ofEventArgs &args) {
  lastFrame_ = ofGetLastFrameTime();
  frameRate_ = ofGetFrameRate();
}

void GameLocal::windowResized(ofResizeEventArgs &resize) {
  width_  = resize.width;
  height_ = resize.height;
}

int GameLocal::Width()  const { return width_;  }
int GameLocal::Height() const { return height_; }

int GameLocal::HalfWidth()  const { return int(width_  * 0.5f); }
int GameLocal::HalfHeight() const { return int(height_ * 0.5f); }

ofVec2f GameLocal::WindowSize()     const { return ofVec2f(width_, height_); }
ofVec2f GameLocal::WindowHalfSize() const { return ofVec2f(width_ * 0.5f, height_ * 0.5f); }

float GameLocal::LastFrame() const      { return lastFrame_; }
float GameLocal::AccedLastFrame() const { return lastFrame_ * frameAcc_; }
float GameLocal::FrameAcc()  const      { return frameAcc_;  }
float GameLocal::FrameRate() const      { return frameRate_; }

void GameLocal::SetFrameAcc(float acc) {
  frameAcc_ = acc;
}


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

	<modelVersion>4.0.0</modelVersion>

	<groupId>com.github.lukas_v.cdi.settings</groupId>
	<artifactId>cdi-settings</artifactId>
	<version>0.9.1</version>
	<packaging>jar</packaging>

	<licenses>
		<license>
			<name>Apache License, Version 2.0</name>
			<url>https://www.apache.org/licenses/LICENSE-2.0.txt</url>
		</license>
	</licenses>

	<developers>
		<developer>
			<id>lukas-v</id>
			<url>https://github.com/lukas-v</url>
		</developer>
	</developers>

	<scm>
		<url>https://github.com/lukas-v/cdi-settings</url>
	</scm>

	<issueManagement>
		<url>https://github.com/lukas-v/cdi-settings/issues</url>
	</issueManagement>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>

		<version.slf4j>1.7.7</version.slf4j>
		<version.typesafe>1.3.1</version.typesafe>

		<version.junit>4.12</version.junit>
		<version.mockito>2.7.22</version.mockito>

		<version.arquillian>1.1.13.Final</version.arquillian>
		<version.arquillian.wildfly-managed>2.0.2.Final</version.arquillian.wildfly-managed>

		<version.plugin.resources>3.0.2</version.plugin.resources>
		<version.plugin.compiler>3.6.1</version.plugin.compiler>
		<version.plugin.jar>3.0.2</version.plugin.jar>
		<version.plugin.surefire>2.20</version.plugin.surefire>
		<version.plugin.failsafe>2.20</version.plugin.failsafe>
	</properties>

	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.jboss.arquillian</groupId>
				<artifactId>arquillian-bom</artifactId>
				<version>${version.arquillian}</version>
				<scope>import</scope>
				<type>pom</type>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<dependencies>
		<dependency>
			<groupId>javax</groupId>
			<artifactId>javaee-api</artifactId>
			<version>7.0</version>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${version.slf4j}</version>
		</dependency>

		<dependency>
			<groupId>com.typesafe</groupId>
			<artifactId>config</artifactId>
			<version>${version.typesafe}</version>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-nop</artifactId>
			<version>${version.slf4j}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${version.junit}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.mockito</groupId>
			<artifactId>mockito-core</artifactId>
			<version>${version.mockito}</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.jboss.arquillian.junit</groupId>
			<artifactId>arquillian-junit-container</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.jboss.shrinkwrap.resolver</groupId>
			<artifactId>shrinkwrap-resolver-api-maven</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<finalName>cdi-settings</finalName>
		<testResources>
			<testResource>
				<directory>src/test/resources</directory>
				<excludes>
					<exclude>arquillian.xml</exclude>
				</excludes>
				<filtering>false</filtering>
			</testResource>
			<testResource>
				<directory>src/test/resources</directory>
				<includes>
					<include>arquillian.xml</include>
				</includes>
				<filtering>true</filtering>
			</testResource>
		</testResources>
		<plugins>
			<plugin>
				<artifactId>maven-resources-plugin</artifactId>
				<version>${version.plugin.resources}</version>
			</plugin>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>${version.plugin.compiler}</version>
			</plugin>
			<plugin>
				<artifactId>maven-jar-plugin</artifactId>
				<version>${version.plugin.jar}</version>
			</plugin>
			<plugin>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>${version.plugin.surefire}</version>
			</plugin>
		</plugins>
	</build>

	<profiles>
		<profile>
			<id>arquillian-wildfly-managed</id>
			<dependencies>
				<dependency>
					<groupId>org.wildfly.arquillian</groupId>
					<artifactId>wildfly-arquillian-container-managed</artifactId>
					<version>${version.arquillian.wildfly-managed}</version>
					<scope>test</scope>
				</dependency>
				<dependency>
					<groupId>org.jboss.shrinkwrap.resolver</groupId>
					<artifactId>shrinkwrap-resolver-impl-maven</artifactId>
					<scope>test</scope>
				</dependency>
			</dependencies>
			<build>
				<plugins>
					<plugin>
						<artifactId>maven-failsafe-plugin</artifactId>
						<version>${version.plugin.failsafe}</version>
						<configuration>
							<forkCount>1</forkCount>
							<reuseForks>false</reuseForks>
							<systemPropertyVariables>
								<java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
								<arquillian.launch>arquillian-wildfly-managed</arquillian.launch>
								<jboss.home>${wildfly.home}</jboss.home>
							</systemPropertyVariables>
							<includes>
								<include>**/*_Wildfly_IT.java</include>
							</includes>
						</configuration>
						<executions>
							<execution>
								<goals>
									<goal>integration-test</goal>
									<goal>verify</goal>
								</goals>
							</execution>
						</executions>
					</plugin>
				</plugins>
			</build>
		</profile>
	</profiles>
</project>


text:
struct chisq_dist {
    int mode;
    double *covmat;
    double *c;
    double *slope;
    double *pivotmag;
    double *refmag;
    double *refmagerr;
    double *magerr;
    double *color;
    double *col_err_ratio;
    double *lupcorr;
    int ncalc;
    int ngal;
    int nz;
    int ncol;

    double sigint;
    //    long do_chisq;
    //long nophotoerr;
};

int chisq_dist(int mode, int do_chisq, int nophotoerr, int ncalc, int ncol, double *covmat, double *c, double *slope, double *pivotmag, double *refmag, double *refmagerr, double *magerr, double *color, double *lupcorr, double *dist, double sigint);

int check_and_fix_covmat(gsl_matrix *covmat);

#endif


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Web;

namespace SmugMugModel.oAuth
{
    /// <summary>
    /// Contains methods used in calculating the oAuth signature for the request
    /// </summary>
    internal class oAuthUtility
    {
        const string oauth_consumer_key = "oauth_consumer_key";
        const string oauth_token = "oauth_token";
        const string oauth_signature_method = "oauth_signature_method";
        const string oauth_timestamp = "oauth_timestamp";
        const string oauth_nonce = "oauth_nonce";
        const string oauth_signature = "oauth_signature";
        const string oauth_token_secret = "oauth_token_secret";
        const string oauth_version = "oauth_version";

        /// <summary>
        /// Normalizes the parameters according to the oAuth spec:
        /// - Sort the parameters lexicografically
        /// - Concatenate them into a query string
        /// </summary>
        static string NormalizeParameters(List<KeyValuePair<string, string>> parameters)
        {
            // create the encoded list of parameters.
            List<KeyValuePair<string, string>> encodedParameters = new List<KeyValuePair<string, string>>();
            foreach (var pair in parameters)
            {
                // The key/value should be Encoded.
                // This does mean that we will encode this twice but this is according to the way SmugMug
                // and oAuth works.
                KeyValuePair<string, string> newPair = new KeyValuePair<string, string>(
                    EncodeValue(pair.Key),
                    EncodeValue(pair.Value)
                );
                encodedParameters.Add(newPair);
            }

            encodedParameters.Sort(new Comparison<KeyValuePair<string, string>>((param1, param2) =>
                {
                    if (param1.Key == param2.Key)
                    {
                        return string.Compare(param1.Value, param2.Value, StringComparison.Ordinal);
                    }
                    else
                    {
                        return string.Compare(param1.Key, param2.Key, StringComparison.Ordinal);
                    }
                }));

            StringBuilder normalizedParameters = new StringBuilder();
            foreach (var param in encodedParameters)
            {
                normalizedParameters.AppendFormat("{0}={1}&", param.Key, param.Value);
            }
            normalizedParameters.Remove(normalizedParameters.Length - 1, 1);

            return normalizedParameters.ToString();
        }

        /// <summary>
        /// Encodes the value in the manner required by the oAuth
        /// All values not permitted are encoded as % followed by
        /// the value of the character in HEX
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        static string EncodeValue(string value)
        {
            // unreserved  = ALPHA / DIGIT / "-" / "." / "_" / "~"
            string acceptedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";

            StringBuilder encodedValue = new StringBuilder();
            for (int i = 0; i < value.Length; i++)
            {
                if (acceptedChars.IndexOf(value[i]) >= 0)
                {
                    encodedValue.Append(value[i]);
                }
                else
                {
                    // encode it
                    var bytes = Encoding.UTF8.GetBytes(new char[] { value[i] });
                    for (int j = 0; j < bytes.Length; j++)
                    {
                        encodedValue.Append('%' + bytes[j].ToString("X2"));
                    }
                }
            }

            return encodedValue.ToString();
        }

        /// <summary>
        /// Gets the absolute URI for a request ( no query strings )
        /// </summary>
        static string GenerateBaseStringUri(string host)
        {
            return new Uri(host).AbsoluteUri;
        }

        /// <summary>
        /// Generates the base string for the oAuth request
        /// </summary>
        static string GenerateBaseString(string host, string httpMethod, List<KeyValuePair<string, string>> parameters)
        {
            httpMethod = httpMethod.ToUpperInvariant();
            host = EncodeValue(GenerateBaseStringUri(host));
            string param = EncodeValue(NormalizeParameters(parameters));

            return string.Format("{0}&{1}&{2}", httpMethod, host, param);
        }

        /// <summary>
        /// Gets the timestamp in seconds since January 1970 00:00:00AM
        /// </summary>
        static string GenerateTimestamp()
        {
            DateTime jan1970 = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);

            TimeSpan ts = DateTime.Now.ToUniversalTime() - jan1970;
            return ((long)ts.TotalSeconds).ToString();
        }

        /// <summary>
        /// Generate a unique string for each request
        /// </summary>
        static string GenerateNonce()
        {
            return Guid.NewGuid().ToString("N");
        }

        /// <summary>
        /// Calculate the HMAC-SHA1 digest for the base string
        /// </summary>
        static string GenerateHMACDigest(string data, string clientSecret, string tokenSecret = "")
        {
            HMACSHA1 hash = new HMACSHA1();
            string key = string.Format("{0}&{1}", EncodeValue(clientSecret), EncodeValue(tokenSecret));

            //the key is the client secret+ "&" + token_secret
            hash.Key = Encoding.UTF8.GetBytes(key);

            byte[] digest = hash.ComputeHash(Encoding.UTF8.GetBytes(data));

            return Convert.ToBase64String(digest);
        }

        /// <summary>
        /// Calculates the message parameters, including the oaut_signature
        /// </summary>
        internal static string GetMessageParameters(string APIKey, string Secret, string methodName, Token tok, params object[] args)
        {
            List<KeyValuePair<string, string>> parameters = new List<KeyValuePair<string, string>>()
            {
                new KeyValuePair<string,string>(oauth_timestamp, oAuthUtility.GenerateTimestamp() ),
                new KeyValuePair<string,string>(oauth_nonce, oAuthUtility.GenerateNonce() ),
                new KeyValuePair<string,string>(oauth_consumer_key, APIKey),
                new KeyValuePair<string,string>(oauth_signature_method, "HMAC-SHA1"),
                new KeyValuePair<string,string>(oauth_version, "1.0")
            };

            //parameters.Add(new KeyValuePair<string, string>("pretty", "true"));

            var method = new KeyValuePair<string, string>("method", methodName);
            var apikey = new KeyValuePair<string, string>("APIKey", APIKey);

            parameters.Add(method);
            parameters.Add(apikey);

            // add the access token if present
            if (tok != null)
            {
                parameters.Add(new KeyValuePair<string, string>(oauth_token, tok.id));
            }

            for (int i = 0; i < args.Length; i += 2)
            {
                parameters.Add(new KeyValuePair<string, string>(args[i].ToString(), args[i + 1].ToString()));
            }

            string baseString = oAuthUtility.GenerateBaseString(CommunicationHelper.baseAddrSecure1_3_0, "POST", parameters);
            string sig = oAuthUtility.EncodeValue(oAuthUtility.GenerateHMACDigest(baseString, Secret, tok == null ? "" : tok.Secret));

            parameters.Add(new KeyValuePair<string, string>(oauth_signature, sig));

            parameters.Remove(method);
            parameters.Remove(apikey);

            StringBuilder sb = new StringBuilder();

            sb.AppendFormat("method={0}&APIKey={1}", methodName, APIKey);

            foreach (var param in parameters)
            {
                sb.AppendFormat("&{0}={1}", param.Key, HttpUtility.HtmlEncode(param.Value));
            }

            return sb.ToString();
        }

        /// <summary>
        /// Calculates teh Authorization header to use with the oAuth authentication
        /// </summary>
        internal static string GetAuthorizationHeader(Token tok, string endpoint, params object[] args)
        {
            List<KeyValuePair<string, string>> parameters = new List<KeyValuePair<string, string>>()
            {
                new KeyValuePair<string,string>(oauth_timestamp, oAuthUtility.GenerateTimestamp() ),
                new KeyValuePair<string,string>(oauth_nonce, oAuthUtility.GenerateNonce() ),
                new KeyValuePair<string,string>(oauth_consumer_key, Site.APIKey),
                new KeyValuePair<string,string>(oauth_signature_method, "HMAC-SHA1"),
                new KeyValuePair<string,string>(oauth_token, tok.id),
                new KeyValuePair<string,string>(oauth_token_secret, tok.Secret)
            };

            // Add of the other parameters to the mix
            for (int i = 0; i < args.Length; i += 2)
            {
                parameters.Add(new KeyValuePair<string, string>(args[i].ToString(), args[i + 1].ToString()));
            }

            string baseString = oAuthUtility.GenerateBaseString(endpoint, "PUT", parameters);
            string sig = oAuthUtility.EncodeValue(oAuthUtility.GenerateHMACDigest(baseString, Site.ApplicationSecret, tok == null ? "" : tok.Secret));

            parameters.Add(new KeyValuePair<string, string>(oauth_signature, sig));

            // the authorization header only consists of oauth_ tokens

            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("OAuth ");

            foreach (var param in parameters)
            {
                if (param.Key.StartsWith("oauth", StringComparison.OrdinalIgnoreCase))
                {
                    sb.AppendFormat("{0}=\"{1}\",", param.Key, param.Value);
                }
            }
            // remove the trailing ,
            sb.Remove(sb.Length - 1, 1);

            return sb.ToString();
        }
    }
}


text:
Documentation

Coming Soon...

        <button class="btn" data-bind="click:changeButtonState, css:{'btn-primary' : btnActive}, html : btnText" />

                <button data-bind="visible:!currentUser(), click:loadLoginPage" class="btn btn-primary">Login</button>
                <button data-bind="visible:currentUser, click:logoutUser" class="btn btn-primary">LogOut</button>

                <button data-bind="click:loadSecurePage" class="btn btn-danger">Load Secure Page</button>


text:
class A{
  String toHex(int i) {<error descr="Missing return statement">}</error>
  String toHex(short i) {<error descr="Missing return statement">}</error>

  void f(){
    String result = toHex((short)'i');
  }
}


text:
package stateengine

import ()

const (
	BOOLOUT   string = "boolout"
	BOOLIN    string = "boolin"
	ANALOGOUT string = "analogout"
	ANALOGIN  string = "analogin"
)

type EventHandler func(eventName string, id string, arguments interface{})

type DeviceComm interface {
	ID() string
	RegisterChannel(id string, address string, chType string)
	RegisterEventHandler(handler EventHandler)
	Start()
	Stop()
	Status() *Status
	GetValue(chAddress string) (ValueMap, error)
	SetValue(chAddress string, value ValueMap) error
}

type ValueMap map[string]string

func NewValueMap(value string) ValueMap {
	r1 := make(ValueMap)
	r1["value"] = value
	return r1
}

func (this ValueMap) Value() string {
	if val1, ok := this["value"]; ok {
		return val1
	}
	return ""
}

type Status struct {
	StatusCode int
	StatusText string
}

func NewStatus() *Status {
	return &Status{}
}

func (this *Status) SetError(err error) {
	if err != nil {
		this.SetErrorStr(err.Error())
	}
}

func (this *Status) SetErrorStr(err string) {
	this.StatusCode = 1
	this.StatusText = err
}

func (this *Status) SetOk(message string) {
	this.StatusCode = 0
	this.StatusText = message
}

func (this *Status) IsOk() bool {
	return this.StatusCode == 0
}

type Logger interface {
	Write(msg string)
}


text:
package local.vqvu.util;

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

public class Iterables {
    private Iterables() {}

    public static <T> List<T> asList(Iterable<? extends T> iterable) {
        return asList(iterable.iterator());
    }

    public static <T> List<T> asList(Iterator<? extends T> iterator) {
        List<T> ret = new ArrayList<>();
        while (iterator.hasNext()) {
            ret.add(iterator.next());
        }
        return ret;
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Druid — Apache Superset  documentation</title>

    <link rel="stylesheet" href="_static/css/theme.css" type="text/css" />

        <link rel="index" title="Index"
              href="genindex.html"/>
        <link rel="search" title="Search" href="search.html"/>
    <link rel="top" title="Apache Superset  documentation" href="index.html"/>
        <link rel="next" title="FAQ" href="faq.html"/>
        <link rel="prev" title="Gallery" href="gallery.html"/>

             Apache Superset

  <form id="rtd-search-form" class="wy-form" action="search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

Installation & Configuration

Tutorial for Superset Administrators

Security

SQL Lab

Visualization Tools

Videos

Gallery

Druid

Supported

Aggregations

Post-Aggregations

Not yet supported

FAQ

        Apache Superset

Docs »

Druid

Druid¶

Superset works well with Druid, though currently not all
advanced features out of Druid are covered. This page clarifies what is
covered and what isn’t and explains how to use some of the features.

Note

Currently Airbnb runs against Druid 0.8.x and previous /
following versions are not tested against.

Supported¶

Aggregations¶

Common aggregations, or Druid metrics can be defined and used in Superset.
The first and simpler use case is to use the checkbox matrix expose in your
datasource’s edit view (Sources -> Druid Datasources ->
[your datasource] -> Edit -> [tab] List Druid Column).
Clicking the GroupBy and Filterable checkboxes will make the column
appear in the related dropdowns while in explore view. Checking
Count Distinct, Min, Max or Sum will result in creating
new metrics that will appear in the List Druid Metric tab upon saving the
datasource. By editing these metrics, you’ll notice that they their json
element correspond to Druid aggregation definition. You can create your own
aggregations manually from the List Druid Metric tab following Druid
documentation.

Post-Aggregations¶

Druid supports post aggregation and this works in Superset. All you have to
do is creating a metric, much like you would create an aggregation manually,
but specify postagg as a Metric Type. You then have to provide a valid
json post-aggregation definition (as specified in the Druid docs) in the
Json field.

Not yet supported¶

Regex filters

Lookups / joins

        Next

         Previous

  Built with Sphinx using a theme provided by Read the Docs.


text:
package ch.zhaw.icclab.tnova.expressionsolver;

/*
 *     Author: Piyush Harsh,
 *     URL: piyush-harsh.info
 */

import org.apache.log4j.Logger;

import java.util.HashMap;

public class Init {
    final static Logger logger = Logger.getLogger(Init.class);
    //global init variables
    public static HashMap<String, String> tableScripts = new HashMap<String, String>();
    public static String tableList[] = {"template", "expression", "oplist", "vnfinstance"};
    public static String opList[] = {"min", "max", "gt", "lt", "ge", "le", "add", "avg", "mul"};

    public Init()
    {
        if(App.dbEngine.equalsIgnoreCase("sqlite") || App.dbEngine.equalsIgnoreCase("sqlite3")) {
            tableScripts.put("template", "create table template (id INTEGER PRIMARY KEY AUTOINCREMENT, nsdid VARCHAR(128), expression VARCHAR(512))");
            tableScripts.put("expression", "create table expression (id INTEGER PRIMARY KEY AUTOINCREMENT, templateid INT, nsinstid VARCHAR(128), outeropid INT, inneropid INT, constant INT, innervalresult DOUBLE, outervalresult VARCHAR(32), timestamp VARCHAR(45))");
            tableScripts.put("oplist", "create table oplist (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(32), supported INT)");
            tableScripts.put("vnfinstance", "create table vnfinstance (id INTEGER PRIMARY KEY AUTOINCREMENT, monparam VARCHAR(32), value DOUBLE, timestamp VARCHAR(32), expressionid INT)");
        }
        logger.info("Support variables have been initialized.");
    }
}


text:
from vitrage.common.constants import VertexProperties as VProps

class PropsConverter(object):

    PROPS_CONVERSION = {
        'category': VProps.VITRAGE_CATEGORY,
        'type': VProps.VITRAGE_TYPE,
        'resource_id': VProps.VITRAGE_RESOURCE_ID,
        'sample_timestamp': VProps.VITRAGE_SAMPLE_TIMESTAMP,
        'is_deleted': VProps.VITRAGE_IS_DELETED,
        'is_placeholder': VProps.VITRAGE_IS_PLACEHOLDER,
        'aggregated_state': VProps.VITRAGE_AGGREGATED_STATE,
        'operational_state': VProps.VITRAGE_OPERATIONAL_STATE,
        'aggregated_severity': VProps.VITRAGE_AGGREGATED_SEVERITY,
        'operational_severity': VProps.VITRAGE_OPERATIONAL_SEVERITY
    }

    @classmethod
    def convert_props_with_set(cls, properties):
        converted_properties = set()
        for key, value in properties:
            new_key = cls.PROPS_CONVERSION[key] if key in \
                cls.PROPS_CONVERSION else key
            converted_properties.add((new_key, value))
        return converted_properties

    @classmethod
    def convert_props_with_dictionary(cls, properties):
        converted_properties = {}
        for key, value in properties.items():
            new_key = cls.PROPS_CONVERSION[key] if key in \
                cls.PROPS_CONVERSION else key
            converted_properties[new_key] = value
        return converted_properties


text:
package calendar

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"strings"

	"github.com/gin-gonic/gin"
)

// ========== middleware

// CORSMiddleware middleware headers for any RESTful requests {{{
func CORSMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
		c.Writer.Header().Set("Content-Type", "application/json")

		if c.Request.Method == "OPTIONS" {
			fmt.Println("OPTIONS")
			c.AbortWithStatus(200)
		} else {
			c.Next()
		}
	}
} // }}}

func Start(args []string) {
	// Selecting port
	port := "8000"
	if len(args) == 3 {
		port = args[2]
	}

	// Current path
	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		log.Fatal(err)
	}

	// Info
	fmt.Println("---------------")
	fmt.Println("Selected port: " + port)
	fmt.Println("---------------")

	// Creating router
	router := gin.Default()
	router.LoadHTMLGlob(dir + "/front/calendar/index.html")

	router.Static("/src", dir+"/front/calendar/static/")
	router.StaticFile("/favicon.ico", dir+"/favicon/favicon.ico")

	// add headers middleware
	router.Use(CORSMiddleware())

	getApiRouter(router)

	router.NoRoute(func(c *gin.Context) {
		path := strings.Split(c.Request.URL.Path, "/")
		if (path[1] != "") && (path[1] == "api") {
			c.JSON(404, gin.H{
				"status":  10,
				"message": "Not found",
				"body":    nil,
			})
		} else {
			c.Writer.Header().Set("Content-Type", "text/html; charset=utf-8")
			c.HTML(http.StatusOK, "index.html", "")
		}
	})

	// Starting
	router.Run(":" + port)
}

func getApiRouter(baseRouter *gin.Engine) {
	api := baseRouter.Group("/api")
	{
		get := api.Group("/get")
		{
			get.GET("/all", GetAllEvents)
			get.GET("/short", GetShortEvents)
			get.GET("/long", GetLongEvents)
			get.GET("/category_events", GetCategoryEvents)
			get.GET("/all_categories", GetAllCategories)
			get.GET("/day", GetDayData)
		}

		short := api.Group("/short")
		{
			short.POST("/create", CreateShortEvent)
			short.POST("/edit", EditShortEvent)
			short.POST("/delete", DeleteShortEvent)
		}

		long := api.Group("/long")
		{
			long.POST("/create", CreateLongEvent)
			long.POST("/edit", EditLongEvent)
			long.POST("/delete", DeleteLongEvent)
		}

		categories := api.Group("/categories")
		{
			categories.POST("/create", CreateCategory)
			categories.POST("/edit", EditCategory)
			categories.POST("/delete", DeleteCategory)
		}
	}
}


text:
package java.lang

final class Void private ()

object Void {
  final val TYPE = classOf[scala.Unit]
}


text:
package Q8_02_Robot_in_a_Grid;

public class Point {
	public int row, column;
	public Point(int row, int column) {
		this.row = row;
		this.column = column;
	}

	@Override
	public String toString() {
		return "(" + row + ", " + column + ")";
	}

	@Override
	 public int hashCode() {
        return this.toString().hashCode();
    }

	@Override
	public boolean equals(Object o) {
		if ((o instanceof Point) && (((Point) o).row == this.row) && (((Point) o).column == this.column)) {
            return true;
        } else {
            return false;
        }
	}
}


text:
package edu.depaul.armada.service;

import java.util.List;

import edu.depaul.armada.model.Metric;
import edu.depaul.armada.model.ThresholdMetric;

/**
 * An interface which specifies methods used for storing and receiving Container metrics over time.
 *
 * @author ptrzyna
 */
public interface MetricService {

	public enum ContainerState {OK, WARN, ERR};

	/**
	 * Gives us counts over time of how containers behaved
	 *
	 * NOTE: for each hourly interval we will count how many containers breached a threshold
	 *
	 * Example of returned data: 1am {up:3, error:4, warn:7}, 2am ...
	 *
	 * @param periodInHours	how far back do we want to get data (each data point is for an hour interval)
	 * @return list of counts for a 24h period
	 */
	public List<ThresholdMetric> getMetrics(int periodInHours);

	/**
	 * Gives us counts over time of how many containers were running
	 *
	 * NOTE: for each hourly interval we will count how many containers are running
	 *
	 * Example of returned data: 1am {count:3}
	 *
	 * @param periodInHours	how far back do we want to get data (each data point is for an hour interval)
	 * @return list of counts for a 24h period
	 */
	public List<Metric> getContainerCount(int periodInHours);

}


text:
using UnityEngine;
using System.Collections;

public class LoadOnClick : MonoBehaviour {

	public void Start () {
		Cursor.visible = true;
	}

	public void LoadScene (int level) {
		Application.LoadLevel (level);
	}
}


text:
layout: single
title: "Python: Check available modules with pydoc"
date: 2017-04-05 05:23
modified: 2017-04-05 05:34
categories: til
tags:
  - python
  - til
---

Find a list of all python modules installed on a machine by running the following command
in a terminal:

```python
pydoc modules
```

or:

```python
help('modules')
```

inside of a python interactive shell.

Via [enki.com](https://app.enkipro.com/#/insight/55ed77e3ed2a613a005bddc9).


text:
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#import "TargetConditionals.h"

#if !TARGET_OS_TV

 #import "FBSDKLoginManagerLogger.h"

 #import "FBSDKCoreKitBasicsImportForLoginKit.h"
 #import "FBSDKLoginError.h"
 #import "FBSDKLoginManagerLoginResult+Internal.h"
 #import "FBSDKLoginUtility.h"
 #import "FBSDKMonotonicTime.h"

NSString *const FBSDKLoginManagerLoggerAuthMethod_Native = @"fb_application_web_auth";
NSString *const FBSDKLoginManagerLoggerAuthMethod_Browser = @"browser_auth";
NSString *const FBSDKLoginManagerLoggerAuthMethod_SFVC = @"sfvc_auth";
NSString *const FBSDKLoginManagerLoggerAuthMethod_Applink = @"applink_auth";

static NSString *const FBSDKLoginManagerLoggingClientStateKey = @"state";
static NSString *const FBSDKLoginManagerLoggingClientStateIsClientState = @"com.facebook.sdk_client_state";

static NSString *const FBSDKLoginManagerLoggerParamIdentifierKey = @"0_auth_logger_id";
static NSString *const FBSDKLoginManagerLoggerParamTimestampKey = @"1_timestamp_ms";
static NSString *const FBSDKLoginManagerLoggerParamResultKey = @"2_result";
static NSString *const FBSDKLoginManagerLoggerParamAuthMethodKey = @"3_method";
static NSString *const FBSDKLoginManagerLoggerParamErrorCodeKey = @"4_error_code";
static NSString *const FBSDKLoginManagerLoggerParamErrorMessageKey = @"5_error_message";
static NSString *const FBSDKLoginManagerLoggerParamExtrasKey = @"6_extras";
static NSString *const FBSDKLoginManagerLoggerParamLoggingTokenKey = @"7_logging_token";

static NSString *const FBSDKLoginManagerLoggerValueEmpty = @"";

static NSString *const FBSDKLoginManagerLoggerResultSuccessString = @"success";
static NSString *const FBSDKLoginManagerLoggerResultCancelString = @"cancelled";
static NSString *const FBSDKLoginManagerLoggerResultErrorString = @"error";
static NSString *const FBSDKLoginManagerLoggerResultSkippedString = @"skipped";

static NSString *const FBSDKLoginManagerLoggerTryNative = @"tryFBAppAuth";
static NSString *const FBSDKLoginManagerLoggerTryBrowser = @"trySafariAuth";

/** Use to log the result of the App Switch OS AlertView. Only available on OS >= iOS10 */
FBSDKAppEventName const FBSDKAppEventNameFBSessionFASLoginDialogResult = @"fb_mobile_login_fas_dialog_result";

/** Use to log the start of an auth request that cannot be fulfilled by the token cache */
FBSDKAppEventName const FBSDKAppEventNameFBSessionAuthStart = @"fb_mobile_login_start";

/** Use to log the end of an auth request that was not fulfilled by the token cache */
FBSDKAppEventName const FBSDKAppEventNameFBSessionAuthEnd = @"fb_mobile_login_complete";

/** Use to log the start of a specific auth method as part of an auth request */
FBSDKAppEventName const FBSDKAppEventNameFBSessionAuthMethodStart = @"fb_mobile_login_method_start";

/** Use to log the end of the last tried auth method as part of an auth request */
FBSDKAppEventName const FBSDKAppEventNameFBSessionAuthMethodEnd = @"fb_mobile_login_method_complete";

/** Use to log the post-login heartbeat event after  the end of an auth request*/
FBSDKAppEventName const FBSDKAppEventNameFBSessionAuthHeartbeat = @"fb_mobile_login_heartbeat";

@implementation FBSDKLoginManagerLogger
{
  @private
  NSString *_identifier;
  NSMutableDictionary *_extras;

  NSString *_lastResult;
  NSError *_lastError;

  NSString *_authMethod;
  NSString *_loggingToken;
}

+ (FBSDKLoginManagerLogger *)loggerFromParameters:(NSDictionary *)parameters
                                         tracking:(FBSDKLoginTracking)tracking
{
  NSDictionary<id, id> *clientState = [FBSDKBasicUtility objectForJSONString:parameters[FBSDKLoginManagerLoggingClientStateKey] error:NULL];

  id isClientState = clientState[FBSDKLoginManagerLoggingClientStateIsClientState];
  if ([isClientState isKindOfClass:[NSNumber class]] && [isClientState boolValue]) {
    FBSDKLoginManagerLogger *logger = [[self alloc] initWithLoggingToken:nil tracking:tracking];
    if (logger != nil) {
      logger->_identifier = clientState[FBSDKLoginManagerLoggerParamIdentifierKey];
      logger->_authMethod = clientState[FBSDKLoginManagerLoggerParamAuthMethodKey];
      logger->_loggingToken = clientState[FBSDKLoginManagerLoggerParamLoggingTokenKey];
      return logger;
    }
  }
  return nil;
}

- (instancetype)initWithLoggingToken:(NSString *)loggingToken
                            tracking:(FBSDKLoginTracking)tracking
{
  switch (tracking) {
    case FBSDKLoginTrackingEnabled:
      break;
    case FBSDKLoginTrackingLimited:
      return nil;
  }

  if ((self = [super init]) != nil) {
    _identifier = [NSUUID UUID].UUIDString;
    _extras = [NSMutableDictionary dictionary];
    _loggingToken = [loggingToken copy];
  }
  return self;
}

- (void)startSessionForLoginManager:(FBSDKLoginManager *)loginManager
{
  BOOL isReauthorize = ([FBSDKAccessToken currentAccessToken] != nil);
  BOOL willTryNative = NO;
  BOOL willTryBrowser = YES;
  NSString *behaviorString = @"FBSDKLoginBehaviorBrowser";

  [_extras addEntriesFromDictionary:@{
     FBSDKLoginManagerLoggerTryNative : @(willTryNative),
     FBSDKLoginManagerLoggerTryBrowser : @(willTryBrowser),
     @"isReauthorize" : @(isReauthorize),
     @"login_behavior" : behaviorString,
     @"default_audience" : [FBSDKLoginUtility stringForAudience:loginManager.defaultAudience],
     @"permissions" : [loginManager.requestedPermissions.allObjects componentsJoinedByString:@","] ?: @""
   }];

  [self logEvent:FBSDKAppEventNameFBSessionAuthStart params:[self _parametersForNewEvent]];
}

- (void)endSession
{
  [self logEvent:FBSDKAppEventNameFBSessionAuthEnd result:_lastResult error:_lastError];
  if (FBSDKAppEvents.flushBehavior != FBSDKAppEventsFlushBehaviorExplicitOnly) {
    [FBSDKAppEvents flush];
  }
}

- (void)startAuthMethod:(NSString *)authMethod
{
  _authMethod = [authMethod copy];
  [self logEvent:FBSDKAppEventNameFBSessionAuthMethodStart params:[self _parametersForNewEvent]];
}

- (void)endLoginWithResult:(FBSDKLoginManagerLoginResult *)result error:(NSError *)error
{
  NSString *resultString = @"";

  if (error != nil) {
    resultString = FBSDKLoginManagerLoggerResultErrorString;
  } else if (result.isCancelled) {
    resultString = FBSDKLoginManagerLoggerResultCancelString;
  } else if (result.isSkipped) {
    resultString = FBSDKLoginManagerLoggerResultSkippedString;
  } else if (result.token) {
    resultString = FBSDKLoginManagerLoggerResultSuccessString;
    if (result.declinedPermissions.count) {
      [FBSDKTypeUtility dictionary:_extras setObject:[result.declinedPermissions.allObjects componentsJoinedByString:@","] forKey:@"declined_permissions"];
    }
  }

  _lastResult = resultString;
  _lastError = error;
  [_extras addEntriesFromDictionary:result.loggingExtras];

  [self logEvent:FBSDKAppEventNameFBSessionAuthMethodEnd result:resultString error:error];
}

- (void)postLoginHeartbeat
{
  [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(heartbestTimerDidFire) userInfo:nil repeats:NO];
}

- (void)heartbestTimerDidFire
{
  [self logEvent:FBSDKAppEventNameFBSessionAuthHeartbeat result:_lastResult error:_lastError];
}

+ (NSDictionary *)parametersWithTimeStampAndClientState:(NSDictionary *)loginParams
                                          forAuthMethod:(NSString *)authMethod
                                                 logger:(FBSDKLoginManagerLogger *)logger
{
  NSMutableDictionary *params = [loginParams mutableCopy];

  NSTimeInterval timeValue = (NSTimeInterval)FBSDKMonotonicTimeGetCurrentSeconds();
  NSString *e2eTimestampString = [FBSDKBasicUtility JSONStringForObject:@{ @"init" : @(timeValue) }
                                                                  error:NULL
                                                   invalidObjectHandler:NULL];
  [FBSDKTypeUtility dictionary:params setObject:e2eTimestampString forKey:@"e2e"];

  NSDictionary<id, id> *existingState = [FBSDKBasicUtility objectForJSONString:params[FBSDKLoginManagerLoggingClientStateKey] error:NULL];
  [FBSDKTypeUtility dictionary:params
                     setObject:[FBSDKLoginManagerLogger clientStateForAuthMethod:authMethod
                                                                andExistingState:existingState
                                                                          logger:logger]
                        forKey:FBSDKLoginManagerLoggingClientStateKey];
  return params;
}

- (void)willAttemptAppSwitchingBehavior
{
  NSString *defaultUrlScheme = [NSString stringWithFormat:@"fb%@%@", [FBSDKSettings appID], [FBSDKSettings appURLSchemeSuffix] ?: @""];
  BOOL isURLSchemeRegistered = [FBSDKInternalUtility isRegisteredURLScheme:defaultUrlScheme];

  BOOL isFacebookAppCanOpenURLSchemeRegistered = [FBSDKInternalUtility isRegisteredCanOpenURLScheme:FBSDK_CANOPENURL_FACEBOOK];
  BOOL isMessengerAppCanOpenURLSchemeRegistered = [FBSDKInternalUtility isRegisteredCanOpenURLScheme:FBSDK_CANOPENURL_MESSENGER];

  [_extras addEntriesFromDictionary:@{
     @"isURLSchemeRegistered" : @(isURLSchemeRegistered),
     @"isFacebookAppCanOpenURLSchemeRegistered" : @(isFacebookAppCanOpenURLSchemeRegistered),
     @"isMessengerAppCanOpenURLSchemeRegistered" : @(isMessengerAppCanOpenURLSchemeRegistered),
   }];
}

- (void)logNativeAppDialogResult:(BOOL)result dialogDuration:(NSTimeInterval)dialogDuration
{
  NSOperatingSystemVersion iOS10Version = { .majorVersion = 10, .minorVersion = 0, .patchVersion = 0 };
  if ([NSProcessInfo.processInfo isOperatingSystemAtLeastVersion:iOS10Version]) {
    [FBSDKTypeUtility dictionary:_extras setObject:@(dialogDuration) forKey:@"native_app_login_dialog_duration"];
    [FBSDKTypeUtility dictionary:_extras setObject:@(result) forKey:@"native_app_login_dialog_result"];
    [self logEvent:FBSDKAppEventNameFBSessionFASLoginDialogResult params:[self _parametersForNewEvent]];
  }
}

- (void)addSingleLoggingExtra:(id)extra forKey:(NSString *)key
{
  [FBSDKTypeUtility dictionary:_extras setObject:extra forKey:key];
}

 #pragma mark - Private

- (NSString *)identifier
{
  return _identifier;
}

+ (NSString *)clientStateForAuthMethod:(NSString *)authMethod
                      andExistingState:(NSDictionary *)existingState
                                logger:(FBSDKLoginManagerLogger *)logger
{
  NSDictionary *clientState = @{
    FBSDKLoginManagerLoggerParamAuthMethodKey : authMethod ?: @"",
    FBSDKLoginManagerLoggerParamIdentifierKey : logger.identifier ?: NSUUID.UUID.UUIDString,
    FBSDKLoginManagerLoggingClientStateIsClientState : @YES,
  };

  if (existingState) {
    NSMutableDictionary *mutableState = [clientState mutableCopy];
    [mutableState addEntriesFromDictionary:existingState];
    clientState = mutableState;
  }

  return [FBSDKBasicUtility JSONStringForObject:clientState error:NULL invalidObjectHandler:NULL];
}

- (NSMutableDictionary *)_parametersForNewEvent
{
  NSMutableDictionary *eventParameters = [NSMutableDictionary new];

  // NOTE: We ALWAYS add all params to each event, to ensure predictable mapping on the backend.
  [FBSDKTypeUtility dictionary:eventParameters setObject:_identifier ?: FBSDKLoginManagerLoggerValueEmpty forKey:FBSDKLoginManagerLoggerParamIdentifierKey];
  [FBSDKTypeUtility dictionary:eventParameters setObject:@(round(1000 * [NSDate date].timeIntervalSince1970)) forKey:FBSDKLoginManagerLoggerParamTimestampKey];
  [FBSDKTypeUtility dictionary:eventParameters setObject:FBSDKLoginManagerLoggerValueEmpty forKey:FBSDKLoginManagerLoggerParamResultKey];
  [FBSDKTypeUtility dictionary:eventParameters setObject:_authMethod forKey:FBSDKLoginManagerLoggerParamAuthMethodKey];
  [FBSDKTypeUtility dictionary:eventParameters setObject:FBSDKLoginManagerLoggerValueEmpty forKey:FBSDKLoginManagerLoggerParamErrorCodeKey];
  [FBSDKTypeUtility dictionary:eventParameters setObject:FBSDKLoginManagerLoggerValueEmpty forKey:FBSDKLoginManagerLoggerParamErrorMessageKey];
  [FBSDKTypeUtility dictionary:eventParameters setObject:FBSDKLoginManagerLoggerValueEmpty forKey:FBSDKLoginManagerLoggerParamExtrasKey];
  [FBSDKTypeUtility dictionary:eventParameters setObject:_loggingToken ?: FBSDKLoginManagerLoggerValueEmpty forKey:FBSDKLoginManagerLoggerParamLoggingTokenKey];

  return eventParameters;
}

- (void)logEvent:(NSString *)eventName params:(NSMutableDictionary *)params
{
  if (_identifier) {
    NSString *extrasJSONString = [FBSDKBasicUtility JSONStringForObject:_extras
                                                                  error:NULL
                                                   invalidObjectHandler:NULL];
    if (extrasJSONString) {
      [FBSDKTypeUtility dictionary:params setObject:extrasJSONString forKey:FBSDKLoginManagerLoggerParamExtrasKey];
    }
    [_extras removeAllObjects];

    [FBSDKAppEvents logInternalEvent:eventName
                          parameters:params
                  isImplicitlyLogged:YES];
  }
}

- (void)logEvent:(NSString *)eventName result:(NSString *)result error:(NSError *)error
{
  NSMutableDictionary *params = [self _parametersForNewEvent];

  [FBSDKTypeUtility dictionary:params setObject:result forKey:FBSDKLoginManagerLoggerParamResultKey];

  if ([error.domain isEqualToString:FBSDKErrorDomain] || [error.domain isEqualToString:FBSDKLoginErrorDomain]) {
    // tease apart the structure.

    // first see if there is an explicit message in the error's userInfo. If not, default to the reason,
    // which is less useful.
    NSString *value = error.userInfo[@"error_message"] ?: error.userInfo[FBSDKErrorLocalizedDescriptionKey];
    [FBSDKTypeUtility dictionary:params setObject:value forKey:FBSDKLoginManagerLoggerParamErrorMessageKey];

    value = error.userInfo[FBSDKGraphRequestErrorGraphErrorCodeKey] ?: [NSString stringWithFormat:@"%ld", (long)error.code];
    [FBSDKTypeUtility dictionary:params setObject:value forKey:FBSDKLoginManagerLoggerParamErrorCodeKey];

    NSError *innerError = error.userInfo[NSUnderlyingErrorKey];
    if (innerError != nil) {
      value = innerError.userInfo[@"error_message"] ?: innerError.userInfo[NSLocalizedDescriptionKey];
      [FBSDKTypeUtility dictionary:_extras setObject:value forKey:@"inner_error_message"];

      value = innerError.userInfo[FBSDKGraphRequestErrorGraphErrorCodeKey] ?: [NSString stringWithFormat:@"%ld", (long)innerError.code];
      [FBSDKTypeUtility dictionary:_extras setObject:value forKey:@"inner_error_code"];
    }
  } else if (error) {
    [FBSDKTypeUtility dictionary:params setObject:@(error.code) forKey:FBSDKLoginManagerLoggerParamErrorCodeKey];
    [FBSDKTypeUtility dictionary:params setObject:error.localizedDescription forKey:FBSDKLoginManagerLoggerParamErrorMessageKey];
  }

  [self logEvent:eventName params:params];
}

@end

#endif


text:
"""
Tests for IBM Model 4 training methods
"""

import unittest
from collections import defaultdict

from nltk.translate import AlignedSent, IBMModel, IBMModel4
from nltk.translate.ibm_model import AlignmentInfo

class TestIBMModel4(unittest.TestCase):
    def test_set_uniform_distortion_probabilities_of_max_displacements(self):
        # arrange
        src_classes = {"schinken": 0, "eier": 0, "spam": 1}
        trg_classes = {"ham": 0, "eggs": 1, "spam": 2}
        corpus = [
            AlignedSent(["ham", "eggs"], ["schinken", "schinken", "eier"]),
            AlignedSent(["spam", "spam", "spam", "spam"], ["spam", "spam"]),
        ]
        model4 = IBMModel4(corpus, 0, src_classes, trg_classes)

        # act
        model4.set_uniform_probabilities(corpus)

        # assert
        # number of displacement values =
        #     2 *(number of words in longest target sentence - 1)
        expected_prob = 1.0 / (2 * (4 - 1))

        # examine the boundary values for (displacement, src_class, trg_class)
        self.assertEqual(model4.head_distortion_table[3][0][0], expected_prob)
        self.assertEqual(model4.head_distortion_table[-3][1][2], expected_prob)
        self.assertEqual(model4.non_head_distortion_table[3][0], expected_prob)
        self.assertEqual(model4.non_head_distortion_table[-3][2], expected_prob)

    def test_set_uniform_distortion_probabilities_of_non_domain_values(self):
        # arrange
        src_classes = {"schinken": 0, "eier": 0, "spam": 1}
        trg_classes = {"ham": 0, "eggs": 1, "spam": 2}
        corpus = [
            AlignedSent(["ham", "eggs"], ["schinken", "schinken", "eier"]),
            AlignedSent(["spam", "spam", "spam", "spam"], ["spam", "spam"]),
        ]
        model4 = IBMModel4(corpus, 0, src_classes, trg_classes)

        # act
        model4.set_uniform_probabilities(corpus)

        # assert
        # examine displacement values that are not in the training data domain
        self.assertEqual(model4.head_distortion_table[4][0][0], IBMModel.MIN_PROB)
        self.assertEqual(model4.head_distortion_table[100][1][2], IBMModel.MIN_PROB)
        self.assertEqual(model4.non_head_distortion_table[4][0], IBMModel.MIN_PROB)
        self.assertEqual(model4.non_head_distortion_table[100][2], IBMModel.MIN_PROB)

    def test_prob_t_a_given_s(self):
        # arrange
        src_sentence = ["ich", "esse", "ja", "gern", "räucherschinken"]
        trg_sentence = ["i", "love", "to", "eat", "smoked", "ham"]
        src_classes = {"räucherschinken": 0, "ja": 1, "ich": 2, "esse": 3, "gern": 4}
        trg_classes = {"ham": 0, "smoked": 1, "i": 3, "love": 4, "to": 2, "eat": 4}
        corpus = [AlignedSent(trg_sentence, src_sentence)]
        alignment_info = AlignmentInfo(
            (0, 1, 4, 0, 2, 5, 5),
            [None] + src_sentence,
            ["UNUSED"] + trg_sentence,
            [[3], [1], [4], [], [2], [5, 6]],
        )

        head_distortion_table = defaultdict(
            lambda: defaultdict(lambda: defaultdict(float))
        )
        head_distortion_table[1][None][3] = 0.97  # None, i
        head_distortion_table[3][2][4] = 0.97  # ich, eat
        head_distortion_table[-2][3][4] = 0.97  # esse, love
        head_distortion_table[3][4][1] = 0.97  # gern, smoked

        non_head_distortion_table = defaultdict(lambda: defaultdict(float))
        non_head_distortion_table[1][0] = 0.96  # ham

        translation_table = defaultdict(lambda: defaultdict(float))
        translation_table["i"]["ich"] = 0.98
        translation_table["love"]["gern"] = 0.98
        translation_table["to"][None] = 0.98
        translation_table["eat"]["esse"] = 0.98
        translation_table["smoked"]["räucherschinken"] = 0.98
        translation_table["ham"]["räucherschinken"] = 0.98

        fertility_table = defaultdict(lambda: defaultdict(float))
        fertility_table[1]["ich"] = 0.99
        fertility_table[1]["esse"] = 0.99
        fertility_table[0]["ja"] = 0.99
        fertility_table[1]["gern"] = 0.99
        fertility_table[2]["räucherschinken"] = 0.999
        fertility_table[1][None] = 0.99

        probabilities = {
            "p1": 0.167,
            "translation_table": translation_table,
            "head_distortion_table": head_distortion_table,
            "non_head_distortion_table": non_head_distortion_table,
            "fertility_table": fertility_table,
            "alignment_table": None,
        }

        model4 = IBMModel4(corpus, 0, src_classes, trg_classes, probabilities)

        # act
        probability = model4.prob_t_a_given_s(alignment_info)

        # assert
        null_generation = 5 * pow(0.167, 1) * pow(0.833, 4)
        fertility = 1 * 0.99 * 1 * 0.99 * 1 * 0.99 * 1 * 0.99 * 2 * 0.999
        lexical_translation = 0.98 * 0.98 * 0.98 * 0.98 * 0.98 * 0.98
        distortion = 0.97 * 0.97 * 1 * 0.97 * 0.97 * 0.96
        expected_probability = (
            null_generation * fertility * lexical_translation * distortion
        )
        self.assertEqual(round(probability, 4), round(expected_probability, 4))


text:
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { setupIntl } from 'ember-intl/test-support';
import { render } from '@ember/test-helpers';
import { hbs } from 'ember-cli-htmlbars';
import { setupMirage } from 'ember-cli-mirage/test-support';
import { component } from 'ilios/tests/pages/components/learner-groups/list';
import Service from '@ember/service';
import a11yAudit from 'ember-a11y-testing/test-support/audit';

module('Integration | Component | learner-groups/list', function (hooks) {
  setupRenderingTest(hooks);
  setupIntl(hooks, 'en-us');
  setupMirage(hooks);

  hooks.beforeEach(async function () {
    this.permissionCheckerMock = class extends Service {
      async canDeleteLearnerGroup() {
        return true;
      }
      async canCreateLearnerGroup() {
        return true;
      }
    };
    this.owner.register('service:permissionChecker', this.permissionCheckerMock);
    const school = this.server.create('school');
    const program = this.server.create('program', { school });
    const programYear = this.server.create('program-year', { program });
    this.cohort = this.server.create('cohort', { programYear });
  });

  test('it renders', async function (assert) {
    this.server.createList('learner-group', 3, { cohort: this.cohort });
    this.server.createList('learner-group', 3, { cohort: this.cohort, parentId: 2 });
    this.server.createList('learner-group', 3, { cohort: this.cohort, parentId: 5 });
    const store = this.owner.lookup('service:store');
    const learnerGroupModels = [
      await store.findRecord('learner-group', 1),
      await store.findRecord('learner-group', 2),
      await store.findRecord('learner-group', 3),
    ];
    this.set('learnerGroups', learnerGroupModels);
    await render(hbs`<LearnerGroups::List
      @learnerGroups={{this.learnerGroups}}
      @sortBy="title"
      @setSortBy={{(noop)}}
    />`);

    assert.strictEqual(component.items.length, 3);
    assert.strictEqual(component.items[0].title, 'learner group 0');
    assert.strictEqual(component.items[0].users, '0');
    assert.strictEqual(component.items[0].children, '0');
    assert.strictEqual(component.items[1].title, 'learner group 1');
    assert.strictEqual(component.items[1].users, '0');
    assert.strictEqual(component.items[1].children, '3');
    assert.strictEqual(component.items[2].title, 'learner group 2');
    assert.strictEqual(component.items[2].users, '0');
    assert.strictEqual(component.items[2].children, '0');
    await a11yAudit(this.element);
  });

  test('sort', async function (assert) {
    const group1 = this.server.create('learner-group', {
      cohort: this.cohort,
      users: this.server.createList('user', 5),
    });
    const group2 = this.server.create('learner-group', {
      cohort: this.cohort,
      users: this.server.createList('user', 3),
    });
    const group3 = this.server.create('learner-group', {
      cohort: this.cohort,
      users: this.server.createList('user', 4),
    });
    this.server.createList('learner-group', 2, { parent: group1 });
    this.server.createList('learner-group', 5, { parent: group2 });
    this.server.createList('learner-group', 4, { parent: group3 });
    const store = this.owner.lookup('service:store');
    const learnerGroupModels = [
      await store.findRecord('learner-group', group1.id),
      await store.findRecord('learner-group', group2.id),
      await store.findRecord('learner-group', group3.id),
    ];
    this.set('learnerGroups', learnerGroupModels);
    this.set('sortBy', 'title');
    await render(hbs`<LearnerGroups::List
      @learnerGroups={{this.learnerGroups}}
      @sortBy={{this.sortBy}}
      @setSortBy={{set this.sortBy}}
    />`);

    assert.strictEqual(component.items.length, 3);
    assert.ok(component.header.title.isSortedAscending);
    assert.ok(component.header.users.isNotSorted);
    assert.ok(component.header.children.isNotSorted);
    assert.strictEqual(component.items[0].title, 'learner group 0');
    assert.strictEqual(component.items[0].users, '5');
    assert.strictEqual(component.items[0].children, '2');
    assert.strictEqual(component.items[1].title, 'learner group 1');
    assert.strictEqual(component.items[1].users, '3');
    assert.strictEqual(component.items[1].children, '5');
    assert.strictEqual(component.items[2].title, 'learner group 2');
    assert.strictEqual(component.items[2].users, '4');
    assert.strictEqual(component.items[2].children, '4');

    await component.header.title.click();
    assert.ok(component.header.title.isSortedDescending);
    assert.ok(component.header.users.isNotSorted);
    assert.ok(component.header.children.isNotSorted);
    assert.strictEqual(component.items[0].title, 'learner group 2');
    assert.strictEqual(component.items[1].title, 'learner group 1');
    assert.strictEqual(component.items[2].title, 'learner group 0');

    await component.header.users.click();
    assert.ok(component.header.title.isNotSorted);
    assert.ok(component.header.users.isSortedAscending);
    assert.ok(component.header.children.isNotSorted);
    assert.strictEqual(component.items[0].users, '3');
    assert.strictEqual(component.items[1].users, '4');
    assert.strictEqual(component.items[2].users, '5');

    await component.header.users.click();
    assert.ok(component.header.title.isNotSorted);
    assert.ok(component.header.users.isSortedDescending);
    assert.ok(component.header.children.isNotSorted);
    assert.strictEqual(component.items[0].users, '5');
    assert.strictEqual(component.items[1].users, '4');
    assert.strictEqual(component.items[2].users, '3');

    await component.header.children.click();
    assert.ok(component.header.title.isNotSorted);
    assert.ok(component.header.users.isNotSorted);
    assert.ok(component.header.children.isSortedAscending);
    assert.strictEqual(component.items[0].children, '2');
    assert.strictEqual(component.items[1].children, '4');
    assert.strictEqual(component.items[2].children, '5');

    await component.header.children.click();
    assert.ok(component.header.title.isNotSorted);
    assert.ok(component.header.users.isNotSorted);
    assert.ok(component.header.children.isSortedDescending);
    assert.strictEqual(component.items[0].children, '5');
    assert.strictEqual(component.items[1].children, '4');
    assert.strictEqual(component.items[2].children, '2');
  });

  test('remove', async function (assert) {
    this.server.createList('learner-group', 3, { cohort: this.cohort });
    const learnerGroupModels = await this.owner.lookup('service:store').findAll('learner-group');
    this.set('learnerGroups', learnerGroupModels);
    await render(hbs`<LearnerGroups::List
      @learnerGroups={{this.learnerGroups}}
      @sortBy="title"
      @setSortBy={{(noop)}}
    />`);
    assert.strictEqual(this.server.db.learnerGroups.length, 3);
    assert.strictEqual(component.items.length, 3);
    assert.strictEqual(component.items[0].title, 'learner group 0');
    await component.items[0].remove();
    await component.confirmRemoval.confirm();
    assert.strictEqual(this.server.db.learnerGroups.length, 2);
    assert.strictEqual(component.items.length, 2);
    assert.strictEqual(component.items[0].title, 'learner group 1');
  });

  test('cancel remove', async function (assert) {
    this.server.createList('learner-group', 3, { cohort: this.cohort });
    const learnerGroupModels = await this.owner.lookup('service:store').findAll('learner-group');
    this.set('learnerGroups', learnerGroupModels);
    await render(hbs`<LearnerGroups::List
      @learnerGroups={{this.learnerGroups}}
      @sortBy="title"
      @setSortBy={{(noop)}}
    />`);
    assert.strictEqual(this.server.db.learnerGroups.length, 3);
    assert.strictEqual(component.items.length, 3);
    assert.strictEqual(component.items[0].title, 'learner group 0');
    await component.items[0].remove();
    await component.confirmRemoval.cancel();
    assert.strictEqual(this.server.db.learnerGroups.length, 3);
    assert.strictEqual(component.items.length, 3);
    assert.strictEqual(component.items[0].title, 'learner group 0');
  });

  test('copy with learners', async function (assert) {
    assert.expect(3);
    this.server.createList('learner-group', 1, { cohort: this.cohort });
    const learnerGroupModels = await this.owner.lookup('service:store').findAll('learner-group');
    this.set('learnerGroups', learnerGroupModels);
    this.set('copyGroup', (withLearners, group) => {
      assert.ok(withLearners);
      assert.strictEqual(parseInt(group.id, 10), 1);
    });
    await render(hbs`<LearnerGroups::List
      @learnerGroups={{this.learnerGroups}}
      @canCopyWithLearners={{true}}
      @copyGroup={{this.copyGroup}}
      @sortBy="title"
      @setSortBy={{(noop)}}
    />`);
    await component.items[0].copy();
    assert.ok(component.confirmCopy.canCopyWithLearners);
    await component.confirmCopy.copyWithLearners();
  });

  test('copy without learners when with learners is enabled', async function (assert) {
    assert.expect(3);
    this.server.createList('learner-group', 1, { cohort: this.cohort });
    const learnerGroupModels = await this.owner.lookup('service:store').findAll('learner-group');
    this.set('learnerGroups', learnerGroupModels);
    this.set('copyGroup', (withLearners, group) => {
      assert.notOk(withLearners);
      assert.strictEqual(parseInt(group.id, 10), 1);
    });
    await render(hbs`<LearnerGroups::List
      @learnerGroups={{this.learnerGroups}}
      @canCopyWithLearners={{true}}
      @copyGroup={{this.copyGroup}}
      @sortBy="title"
      @setSortBy={{(noop)}}
    />`);
    await component.items[0].copy();
    assert.ok(component.confirmCopy.canCopyWithLearners);
    await component.confirmCopy.copyWithoutLearners();
  });

  test('copy without learners', async function (assert) {
    assert.expect(3);
    this.server.createList('learner-group', 1, { cohort: this.cohort });
    const learnerGroupModels = await this.owner.lookup('service:store').findAll('learner-group');
    this.set('learnerGroups', learnerGroupModels);
    this.set('copyGroup', (withLearners, group) => {
      assert.notOk(withLearners);
      assert.strictEqual(parseInt(group.id, 10), 1);
    });
    await render(hbs`<LearnerGroups::List
      @learnerGroups={{this.learnerGroups}}
      @canCopyWithLearners={{false}}
      @copyGroup={{this.copyGroup}}
      @sortBy="title"
      @setSortBy={{(noop)}}
    />`);
    await component.items[0].copy();
    assert.notOk(component.confirmCopy.canCopyWithLearners);
    await component.confirmCopy.copyWithoutLearners();
  });

  test('cancel copy with learners enabled', async function (assert) {
    assert.expect(3);
    this.server.createList('learner-group', 1, { cohort: this.cohort });
    const learnerGroupModels = await this.owner.lookup('service:store').findAll('learner-group');
    this.set('learnerGroups', learnerGroupModels);
    this.set('copyGroup', () => {
      assert.ok(false);
    });
    await render(hbs`<LearnerGroups::List
      @learnerGroups={{this.learnerGroups}}
      @canCopyWithLearners={{true}}
      @copyGroup={{this.copyGroup}}
      @sortBy="title"
      @setSortBy={{(noop)}}
    />`);
    await component.items[0].copy();
    assert.ok(component.confirmCopy.isPresent);
    assert.ok(component.confirmCopy.canCopyWithLearners);
    await component.confirmCopy.cancel();
    assert.notOk(component.confirmCopy.isPresent);
  });

  test('cancel copy with learners disabled', async function (assert) {
    assert.expect(3);
    this.server.createList('learner-group', 1, { cohort: this.cohort });
    const learnerGroupModels = await this.owner.lookup('service:store').findAll('learner-group');
    this.set('learnerGroups', learnerGroupModels);
    this.set('copyGroup', () => {
      assert.ok(false);
    });
    await render(hbs`<LearnerGroups::List
      @learnerGroups={{this.learnerGroups}}
      @canCopyWithLearners={{false}}
      @copyGroup={{this.copyGroup}}
      @sortBy="title"
      @setSortBy={{(noop)}}
    />`);
    await component.items[0].copy();
    assert.ok(component.confirmCopy.isPresent);
    assert.notOk(component.confirmCopy.canCopyWithLearners);
    await component.confirmCopy.cancel();
    assert.notOk(component.confirmCopy.isPresent);
  });
});


text:
package org.openqa.selenium.logging;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assume.assumeFalse;
import static org.junit.Assume.assumeTrue;
import static org.openqa.selenium.testing.Driver.HTMLUNIT;
import static org.openqa.selenium.testing.Driver.IE;
import static org.openqa.selenium.testing.Driver.MARIONETTE;
import static org.openqa.selenium.testing.Driver.PHANTOMJS;

import org.junit.After;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.testing.Ignore;
import org.openqa.selenium.testing.JUnit4TestBase;
import org.openqa.selenium.testing.NeedsLocalEnvironment;
import org.openqa.selenium.testing.TestUtilities;
import org.openqa.selenium.testing.drivers.WebDriverBuilder;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;

@Ignore({HTMLUNIT, IE, PHANTOMJS, MARIONETTE})
public class GetLogsTest extends JUnit4TestBase {

  private WebDriver localDriver;

  @After
  public void quitDriver() {
    if (localDriver != null) {
      localDriver.quit();
      localDriver = null;
    }
  }

  @Test
  public void logBufferShouldBeResetAfterEachGetLogCall() {
    assumeFalse(TestUtilities.isOldChromedriver(driver));  // Only chromedriver2 supports logging.
    Set<String> logTypes = driver.manage().logs().getAvailableLogTypes();
    for (String logType : logTypes) {
      driver.get(pages.simpleTestPage);
      LogEntries firstEntries = driver.manage().logs().get(logType);
      assumeTrue(firstEntries.getAll().size() > 0);
      LogEntries secondEntries = driver.manage().logs().get(logType);
      assertFalse(String.format("There should be no overlapping log entries in " +
          "consecutive get log calls for %s logs", logType),
          LogEntriesChecks.hasOverlappingLogEntries(firstEntries, secondEntries));
    }
  }

  @Test
  public void differentLogsShouldNotContainTheSameLogEntries() {
    assumeFalse(TestUtilities.isOldChromedriver(driver));  // Only chromedriver2 supports logging.
    driver.get(pages.simpleTestPage);
    Map<String, LogEntries> logTypeToEntriesMap = new HashMap<>();
    Set<String> logTypes = driver.manage().logs().getAvailableLogTypes();
    for (String logType : logTypes) {
      logTypeToEntriesMap.put(logType, driver.manage().logs().get(logType));
    }
    for (String firstLogType : logTypeToEntriesMap.keySet()) {
      for (String secondLogType : logTypeToEntriesMap.keySet()) {
        if (!firstLogType.equals(secondLogType)) {
          assertFalse(String.format("Two different log types (%s, %s) should not " +
              "contain the same log entries", firstLogType, secondLogType),
              LogEntriesChecks.hasOverlappingLogEntries(logTypeToEntriesMap.get(firstLogType),
                  logTypeToEntriesMap.get(secondLogType)));
        }
      }
    }
  }

  @Test
  @NeedsLocalEnvironment
  public void turningOffLogShouldMeanNoLogMessages() {
    assumeFalse(TestUtilities.isOldChromedriver(driver));  // Only chromedriver2 supports logging.
    Set<String> logTypes = driver.manage().logs().getAvailableLogTypes();
    for (String logType : logTypes) {
      createWebDriverWithLogging(logType, Level.OFF);
      LogEntries entries = localDriver.manage().logs().get(logType);
      assertEquals(String.format("There should be no log entries for " +
          "log type %s when logging is turned off.", logType),
          0, entries.getAll().size());
      quitDriver();
    }
  }

  private void createWebDriverWithLogging(String logType, Level logLevel) {
    LoggingPreferences loggingPrefs = new LoggingPreferences();
    loggingPrefs.enable(logType, logLevel);
    DesiredCapabilities caps = new DesiredCapabilities();
    caps.setCapability(CapabilityType.LOGGING_PREFS, loggingPrefs);
    //TODO: Set capabilities using required capabilities once these are supported
    // by the remote server.
    WebDriverBuilder builder = new WebDriverBuilder().setDesiredCapabilities(caps);
    localDriver = builder.get();
    localDriver.get(pages.simpleTestPage);
  }
}