text:
#### find_bb_for_statement(top_number::Int64,  bl::CompilerTools.CFGs.CFG) [¶](#method__find_bb_for_statement.1)
Find the basic block that contains a given statement number.
Returns the basic block label of the basic block that contains the given statement number or "nothing" if the statement number is not found.

*source:*
[CompilerTools/src/CFGs.jl:718](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### from_exprs(ast::Array{Any, 1},  depth,  state,  callback,  cbdata) [¶](#method__from_exprs.1)
Process an array of expressions.
We know that the first array of expressions we will find is for the lambda body.
top_level_number starts out 0 and if we find it to be 0 then we know that we're processing the array of expr for the body
and so we keep track of the index into body so that we can number the statements in the basic blocks by this top level number.
Recursively process each element of the array of expressions.

*source:*
[CompilerTools/src/CFGs.jl:841](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### show(io::IO,  bb::CompilerTools.CFGs.BasicBlock) [¶](#method__show.1)
Overload of Base.show to pretty-print a CFGS.BasicBlock object.

*source:*
[CompilerTools/src/CFGs.jl:124](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### show(io::IO,  bl::CompilerTools.CFGs.CFG) [¶](#method__show.2)
Overload of Base.show to pretty-print a CFG object.

*source:*
[CompilerTools/src/CFGs.jl:204](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### show(io::IO,  tls::CompilerTools.CFGs.TopLevelStatement) [¶](#method__show.3)
Overload of Base.show to pretty-print a TopLevelStatement.

*source:*
[CompilerTools/src/CFGs.jl:63](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

## Internal

---

#### TypedExpr(typ,  rest...) [¶](#method__typedexpr.1)
Creates a typed Expr AST node.
Convenence function that takes a type as first argument and the varargs thereafter.
The varargs are used to form an Expr AST node and the type parameter is used to fill in the "typ" field of the Expr.

*source:*
[CompilerTools/src/CFGs.jl:43](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### addStatement(top_level,  state,  ast::ANY) [¶](#method__addstatement.1)
Adds a top-level statement just encountered during a partial walk of the AST.
First argument indicates if this statement is a top-level statement.
Second argument is a object collecting information about the CFG as we go along.
Third argument is some sub-tree of the AST.

*source:*
[CompilerTools/src/CFGs.jl:107](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### addStatementToEndOfBlock(bl::CompilerTools.CFGs.CFG,  block,  stmt) [¶](#method__addstatementtoendofblock.1)
Given a CFG "bl" and a basic "block", add statement "stmt" to the end of that block.

*source:*
[CompilerTools/src/CFGs.jl:622](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### changeEndingLabel(bb,  after::CompilerTools.CFGs.BasicBlock,  new_bb::CompilerTools.CFGs.BasicBlock) [¶](#method__changeendinglabel.1)
BasicBlock bb currently is known to contain a jump to the BasicBlock after.
This function changes bb so that it no longer jumps to after but to "new_bb" instead.
The jump has to be in the last statement of the BasicBlock.
AstWalk on the last statement of the BasicBlock is used with the update_label callback function.

*source:*
[CompilerTools/src/CFGs.jl:310](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### compute_dfn(basic_blocks) [¶](#method__compute_dfn.1)
Computes the depth first numbering of the basic block graph.

*source:*
[CompilerTools/src/CFGs.jl:757](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### compute_dfn_internal(basic_blocks,  cur_bb,  cur_dfn,  visited,  bbs_df_order) [¶](#method__compute_dfn_internal.1)
The recursive heart of depth first numbering.

*source:*
[CompilerTools/src/CFGs.jl:736](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### compute_dominators(bl::CompilerTools.CFGs.CFG) [¶](#method__compute_dominators.1)
Compute the dominators of the CFG.

*source:*
[CompilerTools/src/CFGs.jl:1182](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### compute_inverse_dominators(bl::CompilerTools.CFGs.CFG) [¶](#method__compute_inverse_dominators.1)
Compute the inverse dominators of the CFG.

*source:*
[CompilerTools/src/CFGs.jl:1246](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### connect(from,  to,  fallthrough) [¶](#method__connect.1)
Connect the "from" input argument basic block to the "to" input argument basic block.
If the third argument "fallthrough" is true then the "to" block is also set as the "from" basic block's fallthrough successor.

*source:*
[CompilerTools/src/CFGs.jl:153](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### connect_finish(state) [¶](#method__connect_finish.1)
Connect the current basic block as a fallthrough to the final invisible basic block (-2).

*source:*
[CompilerTools/src/CFGs.jl:775](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### createFunctionBody(bl::CompilerTools.CFGs.CFG) [¶](#method__createfunctionbody.1)
Create the array of statements that go in a :body Expr given a CFG "bl".

*source:*
[CompilerTools/src/CFGs.jl:667](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### dump_bb(bl::CompilerTools.CFGs.CFG) [¶](#method__dump_bb.1)
Prints a CFG "bl" with varying degrees of verbosity from debug level 2 up to 4.
Additionally, at debug level 4 and graphviz bbs.dot file is generated that can be used to visualize the basic block structure of the function.

*source:*
[CompilerTools/src/CFGs.jl:784](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### findReachable(reachable,  cur::Int64,  bbs::Dict{Int64, CompilerTools.CFGs.BasicBlock}) [¶](#method__findreachable.1)
Process a basic block and add its successors to the set of reachable blocks
if it isn't already there.  If it is freshly added then recurse to adds its successors.

*source:*
[CompilerTools/src/CFGs.jl:877](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### find_top_number(top_number::Int64,  bl::CompilerTools.CFGs.CFG) [¶](#method__find_top_number.1)
Search for a statement with the given number in the CFG "bl".
Returns the statement corresponding to the given number or "nothing" if the statement number is not found.

*source:*
[CompilerTools/src/CFGs.jl:700](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### from_ast(ast) [¶](#method__from_ast.1)
The main entry point to construct a control-flow graph.
Typically you would pass in a :lambda Expr here.

*source:*
[CompilerTools/src/CFGs.jl:1004](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### from_expr(ast,  callback,  cbdata) [¶](#method__from_expr.1)
Another entry point to construct a control-flow graph but one that allows you to pass a callback and some opaque object
so that non-standard node types can be processed.

*source:*
[CompilerTools/src/CFGs.jl:1013](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### from_expr(ast::LambdaStaticData,  depth,  state,  top_level,  callback,  cbdata) [¶](#method__from_expr.2)
The main routine that switches on all the various AST node types.
The internal nodes of the AST are of type Expr with various different Expr.head field values such as :lambda, :body, :block, etc.
The leaf nodes of the AST all have different types.

*source:*
[CompilerTools/src/CFGs.jl:1123](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### from_goto(label,  state,  callback,  cbdata) [¶](#method__from_goto.1)
Process a GotoNode for CFG construction.

*source:*
[CompilerTools/src/CFGs.jl:1052](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### from_if(args,  depth,  state,  callback,  cbdata) [¶](#method__from_if.1)
Process a :gotoifnot Expr not for CFG construction.

*source:*
[CompilerTools/src/CFGs.jl:1082](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### from_label(label,  state,  callback,  cbdata) [¶](#method__from_label.1)
Process LabelNode for CFG construction.

*source:*
[CompilerTools/src/CFGs.jl:1036](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### from_lambda(ast::Array{Any, 1},  depth,  state,  callback,  cbdata) [¶](#method__from_lambda.1)
To help construct the CFG given a lambda, we recursively process the body of the lambda.

*source:*
[CompilerTools/src/CFGs.jl:820](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### from_return(args,  depth,  state,  callback,  cbdata) [¶](#method__from_return.1)
Process a :return Expr for CFG construction.

*source:*
[CompilerTools/src/CFGs.jl:1069](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### getBbBodyOrder(bl::CompilerTools.CFGs.CFG) [¶](#method__getbbbodyorder.1)
Determine a valid and reasonable order of basic blocks in which to reconstruct a :body Expr.
Also useful for printing in a reasonable order.

*source:*
[CompilerTools/src/CFGs.jl:639](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### getDistinctStatementNum(bl::CompilerTools.CFGs.CFG) [¶](#method__getdistinctstatementnum.1)
Get a possible new statement number by finding the maximum statement value in any BasicBlock in the given CFG and adding 1.

*source:*
[CompilerTools/src/CFGs.jl:407](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### getMaxBB(bl::CompilerTools.CFGs.CFG) [¶](#method__getmaxbb.1)
Returns the maximum basic block label for the given CFG.

*source:*
[CompilerTools/src/CFGs.jl:217](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### getMaxStatementNum(bb::CompilerTools.CFGs.BasicBlock) [¶](#method__getmaxstatementnum.1)
Get the maximum statement index for a given BasicBlock.

*source:*
[CompilerTools/src/CFGs.jl:394](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### getMinBB(bl::CompilerTools.CFGs.CFG) [¶](#method__getminbb.1)
Returns the minimum basic block label for the given CFG.

*source:*
[CompilerTools/src/CFGs.jl:225](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### insertBefore(bl::CompilerTools.CFGs.CFG,  after::Int64) [¶](#method__insertbefore.1)
Given a CFG in input parameter "bl" and a basic block label "after" in that CFG,
insert a new basic block into the CFG before block "after".
Returns a tuple of the new basic block created and if needed a GotoNode AST node to be inserted at the end of the new
basic block so that it will jump to the "after" basic block.  The user of this function is expected to insert
at the end of the new basic block once they are done inserting their other code.
If "after" is the head of a loop, you can stop the basic block containing the loop's back edge from being added to
the new basic block by setting excludeBackEdge to true and setting back_edge to the loop's basic block containing
the back edge.

*source:*
[CompilerTools/src/CFGs.jl:332](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### insertBefore(bl::CompilerTools.CFGs.CFG,  after::Int64,  excludeBackEdge::Bool) [¶](#method__insertbefore.2)
Given a CFG in input parameter "bl" and a basic block label "after" in that CFG,
insert a new basic block into the CFG before block "after".
Returns a tuple of the new basic block created and if needed a GotoNode AST node to be inserted at the end of the new
basic block so that it will jump to the "after" basic block.  The user of this function is expected to insert
at the end of the new basic block once they are done inserting their other code.
If "after" is the head of a loop, you can stop the basic block containing the loop's back edge from being added to
the new basic block by setting excludeBackEdge to true and setting back_edge to the loop's basic block containing
the back edge.

*source:*
[CompilerTools/src/CFGs.jl:332](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### insertBefore(bl::CompilerTools.CFGs.CFG,  after::Int64,  excludeBackEdge::Bool,  back_edge) [¶](#method__insertbefore.3)
Given a CFG in input parameter "bl" and a basic block label "after" in that CFG,
insert a new basic block into the CFG before block "after".
Returns a tuple of the new basic block created and if needed a GotoNode AST node to be inserted at the end of the new
basic block so that it will jump to the "after" basic block.  The user of this function is expected to insert
at the end of the new basic block once they are done inserting their other code.
If "after" is the head of a loop, you can stop the basic block containing the loop's back edge from being added to
the new basic block by setting excludeBackEdge to true and setting back_edge to the loop's basic block containing
the back edge.

*source:*
[CompilerTools/src/CFGs.jl:332](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### insertBetween(bl::CompilerTools.CFGs.CFG,  before::Int64,  after::Int64) [¶](#method__insertbetween.1)
Insert a new basic block into the CFG "bl" between the basic blocks whose labels are "before" and "after".
Returns a tuple of the new basic block created and if needed a GotoNode AST node to be inserted at the end of the new
basic block so that it will jump to the "after" basic block.  The user of this function is expected to insert
at the end of the new basic block once they are done inserting their other code.

*source:*
[CompilerTools/src/CFGs.jl:515](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### insertStatementAfter(bl::CompilerTools.CFGs.CFG,  block,  stmt_idx,  new_stmt) [¶](#method__insertstatementafter.1)
For a given CFG "bl" and a "block" in that CFG, add a new statement "new_stmt" to the basic block
after statement index "stmt_idx".

*source:*
[CompilerTools/src/CFGs.jl:580](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### insertStatementBefore(bl::CompilerTools.CFGs.CFG,  block,  stmt_idx,  new_stmt) [¶](#method__insertstatementbefore.1)
For a given CFG "bl" and a "block" in that CFG, add a new statement "new_stmt" to the basic block
before statement index "stmt_idx".

*source:*
[CompilerTools/src/CFGs.jl:588](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### insertat!(a,  value,  idx) [¶](#method__insertat.1)
Insert into an array "a" with a given "value" at the specified index "idx".

*source:*
[CompilerTools/src/CFGs.jl:571](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### not_handled(a,  b) [¶](#method__not_handled.1)
A default callback that handles no extra AST node types.

*source:*
[CompilerTools/src/CFGs.jl:995](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### removeUselessBlocks(bbs::Dict{Int64, CompilerTools.CFGs.BasicBlock}) [¶](#method__removeuselessblocks.1)
This function simplifies the dict of basic blocks "bbs".
One such simplification that is necessary for depth first numbering not to fail is the removal of dead blocks.
Other simplifications can be seen commented out below and while they may make the graph nicer to look at they
don't really add anything in terms of functionality.

*source:*
[CompilerTools/src/CFGs.jl:896](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### replaceSucc(cur_bb::CompilerTools.CFGs.BasicBlock,  orig_succ::CompilerTools.CFGs.BasicBlock,  new_succ::CompilerTools.CFGs.BasicBlock) [¶](#method__replacesucc.1)
For a given basic block "cur_bb", replace one of its successors "orig_succ" with a different successor "new_succ".

*source:*
[CompilerTools/src/CFGs.jl:858](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### uncompressed_ast(l::LambdaStaticData) [¶](#method__uncompressed_ast.1)
Convert a compressed LambdaStaticData format into the uncompressed AST format.

*source:*
[CompilerTools/src/CFGs.jl:814](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### update_label(x::Expr,  state::CompilerTools.CFGs.UpdateLabelState,  top_level_number,  is_top_level,  read) [¶](#method__update_label.1)
An AstWalk callback that pattern matches GotoNode's and :gotoifnot Expr nodes and determines if the
label specified in this nodes is equal to the "old_label" in the UpdateLabelState and if so replaces
the "old_label" with "new_label" and sets the "changed" flag to true to indicate that update_label
was successful.

*source:*
[CompilerTools/src/CFGs.jl:255](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### wrapInConditional(bl::CompilerTools.CFGs.CFG,  cond_gotoifnot::Expr,  first::Int64,  merge::Int64) [¶](#method__wrapinconditional.1)
Modifies the CFG to create a conditional (i.e., if statement) that wraps a certain region of the CFG whose entry block is
"first" and whose last block is "last".
Takes a parameters:
1) bl - the CFG to modify
2) cond_gotoifnot - a :gotoifnot Expr whose label is equal to "first"
3) first - the existing starting block of the code to be included in the conditional
4) merge - the existing block to be executed after the conditional
To be eligible for wrapping, first and merge must be in the same scope of source code.
This restriction is validated by confirming that "first" dominates "merge" and that "merge" inverse dominates "first".

*source:*
[CompilerTools/src/CFGs.jl:436](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### wrapInConditional(bl::CompilerTools.CFGs.CFG,  cond_gotoifnot::Expr,  first::Int64,  merge::Int64,  back_edge::Union{CompilerTools.CFGs.BasicBlock, Void}) [¶](#method__wrapinconditional.2)
Modifies the CFG to create a conditional (i.e., if statement) that wraps a certain region of the CFG whose entry block is
"first" and whose last block is "last".
Takes a parameters:
1) bl - the CFG to modify
2) cond_gotoifnot - a :gotoifnot Expr whose label is equal to "first"
3) first - the existing starting block of the code to be included in the conditional
4) merge - the existing block to be executed after the conditional
To be eligible for wrapping, first and merge must be in the same scope of source code.
This restriction is validated by confirming that "first" dominates "merge" and that "merge" inverse dominates "first".

*source:*
[CompilerTools/src/CFGs.jl:436](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### CompilerTools.CFGs.BasicBlock [¶](#type__basicblock.1)
Data structure to hold information about one basic block in the control-flow graph.
This structure contains the following fields:
1) label - an Int.  If positive, this basic block corresponds to a basic block declared in the AST through a label node.
                    The special label value -1 corresponds to the starting basic blocks.  The special value -2
                    corresponds to the final basic block (to which everything must flow).  Negative values correspond to
                    implicit basic blocks following gotoifnot nodes.  There nodes may goto some (positive) label but if
                    that branch is not taken they fall-through into an unlabelled basic (in the AST at least) but we
                    give such blocks negative labels.
2) preds - a set of basic blocks from which control may reach the current basic block
3) succs - a set of basic blocks to which control may flow from the current basic block
4) fallthrough_succ - if not "nothing", this indicates which of the basic block successors is reached via falling through from
                    the current basic block rather than a jump (goto or gotoifnot)
5) depth_first_number - a depth first numbering of the basic block graph is performed and this basic block's number is stored here
6) statements - an array of the statements in this basic block.

*source:*
[CompilerTools/src/CFGs.jl:100](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### CompilerTools.CFGs.CFG [¶](#type__cfg.1)
The main data structure to hold information about the control flow graph.
The basic_blocks field is a dictionary from basic block label to BasicBlock object.
The depth_first_numbering is an array of length the number of basic blocks.
   Entry N in this array is the label of the basic block with depth-first numbering N.

*source:*
[CompilerTools/src/CFGs.jl:195](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### CompilerTools.CFGs.TopLevelStatement [¶](#type__toplevelstatement.1)
Data structure to hold the index (relative to the beginning of the body of the function) of a top-level statement
and the top-level statement itself.

*source:*
[CompilerTools/src/CFGs.jl:54](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### CompilerTools.CFGs.UpdateLabelState [¶](#type__updatelabelstate.1)
The opaque callback data type for the update_label callback.
It holds the old_label that should be changed to the new_label.
It also holds a "changed" field that starts as false and gets set to true when the callback actually
finds the old label and replaces it with the new one.

*source:*
[CompilerTools/src/CFGs.jl:239](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)

---

#### CompilerTools.CFGs.expr_state [¶](#type__expr_state.1)
Collects information about the CFG as it is being constructed.
Contains a dictionary of the currently known basic blocks that maps the label to a BasicBlock object.
cur_bb is the currently active BasicBlock to which the next statement encountered should be added.
next_if contains the next negative label number to be used for the next needed implicit basic block label.
top_level_number is the last top-level statement added.

*source:*
[CompilerTools/src/CFGs.jl:173](file:///home/etotoni/.julia/v0.4/CompilerTools/src/CFGs.jl)


text:
<?php

use yii\bootstrap\ActiveForm;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\helpers\Url;
use yii\jui\AutoComplete;
use yii\web\JsExpression;
use app\models\User;

/* @var $this yii\web\View */
/* @var $form yii\bootstrap\ActiveForm */
/* @var $model app\models\ContactForm */

$this->title = Yii::t('app', 'User Merging');

$users = ArrayHelper::map(User::find()->all(), 'id', 'username');
$user_names = ArrayHelper::getColumn($users, 'username');
?>

        <?php $form = ActiveForm::begin(); ?>

        <?= $form->field($model, 'users')->inline(true)->checkBoxList(
            $users
        ); ?>

            <?= Html::submitButton('Create', ['class' => 'btn btn-primary']) ?>

        <?php $form->end(); ?>

            <?php foreach($documents as $document): ?>

                <?= Html::a(
                    $document->name,
                    ['/document/view', 'id' => $document->id]
                ) ?>

                <?= $document->interpret->name ?>
                <?= $document->type->name ?>

            <?php endforeach; ?>

<?php $this->registerJsFile(
    Yii::$app->request->baseUrl.'/js/autocomplete.js',
    ['depends' => [\yii\web\JqueryAsset::className()]]
);

redpajama_set_name: RedPajamaGithub


text:
title: "Searching For An Item In A Binary Search Tree"
excerpt: "In this post we are going to talk about searching for items in a binary search tree"
header:
  overlay_image: /images/code.jpeg
date: 2022-01-09
tags: [Data Structures, Binary Search Tree]
---

In the [previous post]({{ site.baseurl}}/binary-search-tree-intro) we introduced a binary search tree and implemented a basic binary search tree. We also spoke about how to insert an item into a binary search tree. In this post we are going to talk about how we can search for items in a binary search tree. This, like all the other posts, is going to be a very short read.

## Searching For Items

To search for an item in a binary search tree we recursively go through the tree, moving left if the value we are looking for is less than the current node or right if it's greater. We continue doing this until we have found what we are looking for or have reached a leaf node. The average time complexity for this algorithm is $$ O(\log(n)) $$ if the tree is fairly balance. Here is the code:

```csharp
public TreeNode<T> Search(T value)
{
    return FindNode(_root, value);
}

private TreeNode<T> FindNode(TreeNode<T> node, T value)
{
    if (node is null)
    {
        return null;
    }

    if (value.CompareTo(node.Value) == 0)
    {
        return node;
    }

    if (value.CompareTo(node.Value)< 0)
    {
        return FindNode(node.Left, value);
    }

    return FindNode(node.Right, value);
}
```

In this post we spoke about how we can search for items in a binary search tree. All the code is available on [GitHub](https://github.com/vince-nyanga/data-structures). In the next post we are going to talk about how traverse a binary search tree.


text:
package obrien.processing;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.EvictingQueue;
import obrien.Util.DefaultValues;
import obrien.entity.TradeMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.Currency;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static obrien.Util.DefaultValues.*;

/**
 * Track overall metrics for trades.
 *
Doesn't do much yet.

 */
public class Trends {

    // This could be something much more interesting, but I am low on time
    private static final Map<Currency, EvictingQueue<BigDecimal>> trends = new ConcurrentHashMap<>();

    /**
     * Submit a trade message for metrics extraction.
     * @param tradeMessage a single trade.
     */
    public static void submitTrade(TradeMessage tradeMessage) {
        // For the currency sold, update the last recent trades
        Currency soldCurrency = tradeMessage.getCurrencyFrom();
        EvictingQueue<BigDecimal> soldRecents = trends.getOrDefault(
                soldCurrency, EvictingQueue.create(LAST_N_TRADES));
        soldRecents.add(tradeMessage.getAmountSell().negate()); // a critical difference, .negate()
        trends.put(soldCurrency, soldRecents);

        // For the currency bought, update the last recent trades
        Currency boughtCurrency = tradeMessage.getCurrencyTo();
        EvictingQueue<BigDecimal> boughtRecents = trends.getOrDefault(
                boughtCurrency, EvictingQueue.create(LAST_N_TRADES));
        boughtRecents.add(tradeMessage.getAmountBuy());
        trends.put(boughtCurrency, boughtRecents);
    }

    /**
     * What are the totals bought - sold for the currencies?
     * @return map of totals for the currencies.
     */
    public static Map<Currency, BigDecimal> calculateTotals() {
        HashMap<Currency, BigDecimal> output = new HashMap<>();

        trends.keySet().forEach((key) -> {
            BigDecimal total = trends.get(key).stream().reduce((a, b) -> a.add(b)).get();
            output.put(key, total);
        });
        return output;
    }
}


text:
/**
 * Script used to start the local web site used for the unit tests.
 * This is mainly a static web site containing pages with the different use cases to tests
 */

var express     = require('express');
var serveStatic = require('serve-static');

var TEST_SITE_FOLDER = "./test/website/www";
var site = express();

var countNotFound = 0;

site.get('/redirect', function(req, res) {
  res.redirect(301, '/page2.html');
});

site.get('/redirect1', function(req, res) {
  res.redirect(301, '/redirect2');
});

site.get('/redirect2', function(req, res) {
  res.redirect(302, '/redirect3');
});

site.get('/redirect3', function(req, res) {
  res.redirect(301, '/index.html');
});

site.get('/internal-error', function(req, res) {
  res.status(500).json({ error: 'Internal Server Error' });
});

site.get('/timeout', function(req, res) {
  setTimeout(function(){
    res.status(200).json({ message: 'This is a long process' });
  }, 1500);
});

site.get('/timeout2', function(req, res) {
  setTimeout(function(){
    res.status(200).json({ message: 'This is a long process' });
  }, 1500);
});

site.get('/timeout3', function(req, res) {
  setTimeout(function(){
    res.status(200).json({ message: 'This is a long process' });
  }, 1500);
});

site.get('/timeout4', function(req, res) {
  setTimeout(function(){
    res.status(200).json({ message: 'This is a long process' });
  }, 500);
});

site.get('/notfound', function(req, res) {
  if (countNotFound < 2) {
      countNotFound++;
      res.status(404).json({ error: 'Not Found' });
  }
  else {
    res.status(200).json({ message: 'Hello world' });
  }

});

site.get('/notfound-2', function(req, res) {
  res.status(404).json({ error: 'Not Found' });

});

site.get('/buffer', function(req, res) {
  res.send (new Buffer(600));

});

site.use(serveStatic(TEST_SITE_FOLDER));
site.listen(9999);

//console.log("Website used for the tests is starting from : " + TEST_SITE_FOLDER);
exports.site = site;


text:
    State
    <input type="text"
        role="combobox"
        aria-labelledby="state_label"
        aria-autocomplete="list"
        aria-owns="state_list"
        aria-readonly="true"
        aria-activedescendant="state2"/>

Alabama

Alaska


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>geomesa-fs-storage_2.11</artifactId>
        <groupId>org.locationtech.geomesa</groupId>
        <version>2.4.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>geomesa-fs-storage-parquet_2.11</artifactId>
    <name>GeoMesa FileSystem Storage Parquet</name>

    <dependencies>
        <dependency>
            <groupId>org.apache.parquet</groupId>
            <artifactId>parquet-column</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.parquet</groupId>
            <artifactId>parquet-hadoop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-common</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-mapreduce-client-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.scala-lang</groupId>
            <artifactId>scala-reflect</artifactId>
        </dependency>
        <dependency>
            <groupId>org.parboiled</groupId>
            <artifactId>parboiled-scala_${scala.binary.version}</artifactId>
        </dependency>
        <dependency>
            <groupId>org.locationtech.geomesa</groupId>
            <artifactId>geomesa-feature-common_${scala.binary.version}</artifactId>
        </dependency>
        <dependency>
            <groupId>org.locationtech.geomesa</groupId>
            <artifactId>geomesa-fs-storage-api_${scala.binary.version}</artifactId>
        </dependency>
        <dependency>
            <groupId>org.locationtech.geomesa</groupId>
            <artifactId>geomesa-fs-storage-common_${scala.binary.version}</artifactId>
        </dependency>
        <dependency>
            <groupId>org.locationtech.geomesa</groupId>
            <artifactId>geomesa-index-api_${scala.binary.version}</artifactId>
        </dependency>

        <!-- Test dependencies -->
        <dependency>
            <groupId>org.specs2</groupId>
            <artifactId>specs2-core_${scala.binary.version}</artifactId>
        </dependency>
        <dependency>
            <groupId>org.specs2</groupId>
            <artifactId>specs2-junit_${scala.binary.version}</artifactId>
        </dependency>
    </dependencies>

</project>


text:
require 'pdfkit/source'
require 'pdfkit/pdfkit'
require 'pdfkit/middleware'
require 'pdfkit/html_preprocessor'
require 'pdfkit/os'
require 'pdfkit/configuration'
require 'pdfkit/wkhtmltopdf'
require 'pdfkit/version'


text:
/*
 * Decompiled with CFR 0_119.
 */
package systemCalls.image;

import java.awt.image.BufferedImage;
import script.InternalScriptError;
import script.Script;
import script.dataObjects.DataObject;
import script.dataObjects.IntObject;
import script.systemCalls.Trap;

public class Trap_GetPixelB
extends Trap {
    public Trap_GetPixelB(Script s) {
        super(s, "getPixelB");
    }

    @Override
    public DataObject apply() throws InternalScriptError {
        Object o = this.getObjParam(0, true);
        int x = this.getIntParam(1, true);
        int y = this.getIntParam(2, true);
        if (!(o instanceof BufferedImage)) {
            throw new InternalScriptError("Trap error: The first parameter handed to rescaleImage is no valid image!");
        }
        BufferedImage in = (BufferedImage)o;
        return new IntObject(in.getRGB(x, y) & 255);
    }
}


text:
using Aragas.Network.IO;

namespace PokeD.Core.Packets.SCON.Chat
{
    public class ChatReceivePacket : SCONPacket
    {
        public bool Enabled { get; set; }

        public override void Deserialize(ProtobufDeserialiser deserialiser)
        {
            Enabled = deserialiser.Read(Enabled);
        }
        public override void Serialize(ProtobufSerializer serializer)
        {
            serializer.Write(Enabled);
        }
    }
}


text:
"""
Selects the appropreate core for the environment you are running in
"""
Core = None

# initialize the ui system for the environment we are running in
try:
	from maya.core import MayaCore as Core
except:
	pass

try:
	from studiomax.core import StudioMaxCore as Core
except:
	pass

try:
	from motionbuilder.core import MotionBuilderCore as Core
except:
	pass

if Core is None:
	from external import Core

Core = Core.instance()


text:
package com.bingzer.android;

import java.util.LinkedList;
import java.util.List;

/**
 * HTML Utils
 */
public final class WebColor {
    private static List<Integer> list = null;

    private WebColor(){
        // nothing
    }

    //////////////////////////////////////////////////////////////////////

    public static final int WHITE       = android.graphics.Color.WHITE;
    // public static final int WHITE_SMOKE = 0xFFF5F5F5;
    public static final int RED         = android.graphics.Color.RED;
    public static final int PINK        = 0xFFFFC0CB;
    public static final int MAGENTA     = android.graphics.Color.MAGENTA;
    public static final int ORANGE      = 0xFFFF7F00;
    public static final int MAROON      = 0xFF800000;
    public static final int YELLOW      = android.graphics.Color.YELLOW;
    public static final int GREEN       = android.graphics.Color.GREEN;
    public static final int LIME        = 0xFFBFFF00;
    public static final int OLIVE       = 0xFF808000;
    public static final int BLUE        = android.graphics.Color.BLUE;
    public static final int AQUA        = android.graphics.Color.CYAN;
    public static final int TEAL        = 0xFF008080;
    public static final int NAVY_BLUE   = 0xFF000080;
    public static final int PURPLE      = 0xFF800080;
    public static final int BLACK       = android.graphics.Color.BLACK;
    public static final int BROWN       = 0xFF964B00;
    public static final int SILVER      = android.graphics.Color.LTGRAY;
    public static final int GRAY        = android.graphics.Color.GRAY;
    public static final int DARK_GRAY   = android.graphics.Color.DKGRAY;

    /////////////////////////////////////////////////////////////////

    public static List<Integer> all(){
        if(list == null){
            list = new LinkedList<Integer>();
            list.add(WHITE);
            list.add(RED);
            list.add(PINK);
            list.add(MAGENTA);
            list.add(ORANGE);
            list.add(MAROON);
            list.add(YELLOW);
            list.add(GREEN);
            list.add(LIME);
            list.add(OLIVE);
            list.add(BLUE);
            list.add(AQUA);
            list.add(TEAL);
            list.add(NAVY_BLUE);
            list.add(PURPLE);
            list.add(BLACK);
            list.add(BROWN);
            list.add(SILVER);
            list.add(GRAY);
            list.add(DARK_GRAY);
        }

        return list;
    }

	/**
	 * Returns html color 6 digit (ex: #ffffff for white, #000000 for black etc...)
	 */
	public static String getHexColorCode(int color){
    	return String.format("#%06X", (0xFFFFFF & color));
	}

}


text:
import struct
import select
import math
import sys
import signal

import common.debug as debug
import common.messaging as messaging
import tree.common.coordinator_message_type as message_type
import tree.common.protocol.client_configuration_pb2 as client_config_protocol
import tree.common.protocol.server_configuration_pb2 as server_config_protocol

from tree.common.config import BRANCHING_FACTOR
from tree.common.server import Server

class ClientHandler(object):
    def __init__(self, coordinator, peer):
        self.coordinator = coordinator
        self.peer = peer
        self.fileno = peer.get_socket().fileno()

        msg = client_config_protocol.AssignClientId()
        msg.identifier = self.coordinator.next_client_id
        self.coordinator.next_client_id += 1

        self.peer.send(message_type.client.assign_client_id, msg.SerializeToString())

        self.send_config_to_client(self.coordinator.root)
        debug.log("Sent config to client")

    def close(self):
        self.peer.close()
        self.coordinator.client_acceptor.client.remove(self)

    def update(self):
        while True:
            msgtype, msg = self.peer.receive()

            if msgtype is None:
                if not self.peer.is_connected():
                    print("Client disconnected from coordinator")
                    self.peer.close()
                    self.coordinator.poll_set.unregister(self.fileno)
                    del self.coordinator.sockets[self.fileno]
                    self.coordinator.client_acceptor.clients.remove(self)
            else:
                print(msg)

            if not self.peer.has_messages():
                return

    def server_to_message(self, server):
        server_msg = client_config_protocol.Server()
        server_msg.ip = server.get_network_peer().get_ip()
        assert server.client_port > 0
        server_msg.port = server.client_port

        server_msg.content_position = server.get_content_position() if server.is_leaf() else -1

        if server.left_child and server.left_child.client_port >= 0:
            server_msg.left_child.CopyFrom(self.server_to_message(server.left_child))
        if server.right_child and server.right_child.client_port >= 0:
            server_msg.right_child.CopyFrom(self.server_to_message(server.right_child))

        return server_msg

    def send_config_to_client(self, root):
        assert root

        config_message = client_config_protocol.UpdateServerConfiguration()
        config_message.root.CopyFrom(self.server_to_message(root))
        config_message.num_partitions = self.coordinator.num_partitions

        self.peer.send(message_type.client.update_config, config_message.SerializeToString())

class ServerHandler:
    def __init__(self, coordinator, peer):
        self.coordinator = coordinator
        self.peer = peer

    def close(self):
        self.peer.close()
        self.coordinator.server_acceptor.servers.remove(self)

    def send_server_configuration(self, server):
        if not server.get_network_peer():
            return

        msg = server_config_protocol.AssignSubtree()
        msg.is_root = server.is_root()
        msg.center = round(server.get_extend().center())

        msg.num_partitions = self.coordinator.num_partitions

        if server.left_child and server.left_child.client_port > 0:
            msg.left_child.ip = server.left_child.get_network_peer().get_ip()
            msg.left_child.port = server.left_child.client_port

            for p in server.left_child.get_partitions():
               msg.left_partitions.append(p)

        if server.right_child and server.right_child.client_port > 0:
            msg.right_child.ip = server.right_child.get_network_peer().get_ip()
            msg.right_child.port = server.right_child.client_port

            for p in server.right_child.get_partitions():
               msg.right_partitions.append(p)

        msg.is_leaf = server.is_leaf()
        msg.content_position = server.get_content_position() if server.is_leaf() else -1

        server.get_network_peer().send(message_type.server.assign_subtree, msg.SerializeToString())

    def update(self):
        while True:
            msgtype, msgstr = self.peer.receive()

            if msgtype is None:
                assert not self.peer.is_connected()
                print("Lost connection to server")
                self.peer.close()
                raise RuntimeError("FIXME")

            elif msgtype is message_type.server.set_config:
                msg = server_config_protocol.SetConfig()
                msg.ParseFromString(msgstr)

                assert self.coordinator.root
                server = self.coordinator.get_server(self.coordinator.root, msg.level, msg.position)

                assert server
                if server.get_network_peer():
                     raise RuntimeError("Same server tried to connect twice!")

                server.set_peer(self.peer)

                self.server = server
                self.send_server_configuration(server)
                self.server.client_port = msg.client_port

                if not self.server.is_root():
                    # notify parent
                    self.send_server_configuration(self.server.parent)

                self.coordinator.client_acceptor.send_config(self.coordinator.root)

            else:
                raise RuntimeError("Received unknonw message from content server")

            if not self.peer.has_messages():
                return

class ServerAcceptor:
    def __init__(self, coordinator, internal_port):
        self.coordinator = coordinator
        self.socket = messaging.Socket()
        self.socket.listen(self.coordinator.address, internal_port)
        self.servers = []

    def update(self):
        p = self.socket.accept()

        if p:
            print('Got server connection from' + str(p.address))
            handler = ServerHandler(self.coordinator, p)

            self.coordinator.poll_set.register(p.get_socket().fileno(), self.coordinator.epoll_flags)
            self.coordinator.sockets[p.get_socket().fileno()] = handler

            self.servers.append(handler)

    def close(self):
        self.socket.close()

        for server in self.servers:
            server.close()

class ClientAcceptor:
    def __init__(self, coordinator, external_port):
        self.clients = []
        self.coordinator = coordinator
        self.socket = messaging.Socket()
        self.socket.listen(self.coordinator.address, external_port)

    def update(self):
        # Poll all incoming connections
        while True:
            c = self.socket.accept()

            if c:
                debug.log('Got client connection from' + str(c.address))
                handler = ClientHandler(self.coordinator, c)

                self.coordinator.poll_set.register(c.get_socket().fileno(), self.coordinator.epoll_flags)
                self.coordinator.sockets[c.get_socket().fileno()] = handler

                self.clients.append(handler)
            else:
                return

    def send_config(self, root):
        for client in self.clients:
            client.send_config_to_client(root)

    def close(self):
        self.socket.close()

        for client in self.clients:
            client.close()

class Coordinator:
    epoll_flags = (select.EPOLLIN | select.EPOLLERR | select.EPOLLHUP)

    def __init__(self, address, num_partitions, external_port, internal_port):
        self.num_partitions = num_partitions

        self.address = address
        self.running = True
        self.sockets = {}
        self.root = None
        self.next_client_id = 1

        # Sort transactions by starting time
        self.transactions = []

        self.poll_set = select.epoll()

        self.server_acceptor = ServerAcceptor(self, internal_port)

        self.poll_set.register(self.server_acceptor.socket.get_socket().fileno(), self.epoll_flags)
        self.sockets[self.server_acceptor.socket.get_socket().fileno()] = self.server_acceptor

        self.client_acceptor = ClientAcceptor(self, external_port)

        self.poll_set.register(self.client_acceptor.socket.get_socket().fileno(), self.epoll_flags)
        self.sockets[self.client_acceptor.socket.get_socket().fileno()] = self.client_acceptor

        # Create the empty tree
        # launch content server processes
        level = 0

        while level <= Server.get_tree_height(self.num_partitions):
            amount = Server.get_level_size(level, self.num_partitions)

            for i in range(0, amount):
                parent = None
                parent_pos = -1

                if level > 0:
                    parent_pos = int(math.floor(i / BRANCHING_FACTOR))
                    parent = self.get_server(self.root, level-1, parent_pos)

                s = Server(parent, self.num_partitions)

                if not parent:
                    assert level == 0
                    self.root = s
                else:
                    assert parent.get_level_position() == parent_pos

                    if i <= parent_pos * BRANCHING_FACTOR:
                        assert not parent.left_child
                        parent.left_child = s
                    else:
                        assert not parent.right_child
                        parent.right_child = s

            level += 1

        print("Coordinator set up. Ready to accept connections.")

    def get_server(self, root, level, position):
        if level == 0:
            assert position == 0
            return root
        else:
            parent_pos = int(math.floor(position / BRANCHING_FACTOR))
            parent = self.get_server(self.root, level-1, parent_pos)

            if position <= parent_pos * BRANCHING_FACTOR:
                return parent.left_child
            else:
                return parent.right_child

    def update(self):
        events = []

        try:
            events = self.poll_set.poll(0.1)
        except IOError as e:
            debug.log(e.strerror)
            self.close()

        for socket, event in events:
            obj = self.sockets.get(socket)
            assert obj
            if event & (select.EPOLLIN | select.EPOLLHUP | select.EPOLLERR):
                obj.update()

    def close(self):
        self.running = False
        self.server_acceptor.close()
        self.client_acceptor.close()


text:
<?php

namespace Sylius\Behat\MultiContainerExtension;

use Behat\Behat\EventDispatcher\Event\ExampleTested;
use Behat\Behat\EventDispatcher\Event\ScenarioTested;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * @author Kamil Kokot <kamil.kokot@lakion.com>
 */
final class ScopeManipulator implements EventSubscriberInterface
{
    /**
     * @var ContainerInterface
     */
    private $container;

    /**
     * @param ContainerInterface $container
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        return [
            ScenarioTested::BEFORE => ['enterScope', 128],
            ExampleTested::BEFORE => ['enterScope', 128],
            ScenarioTested::AFTER => ['leaveScope', -128],
            ExampleTested::AFTER => ['leaveScope', -128],
        ];
    }

    public function enterScope()
    {
        if (!$this->container->isScopeActive('scenario')) {
            $this->container->enterScope('scenario');
        }
    }

    public function leaveScope()
    {
        if ($this->container->isScopeActive('scenario')) {
            $this->container->leaveScope('scenario');
        }
    }
}


text:
jQuery(document).ready(function ($) { // wait until the document is ready
	$('#send').click(function(){ // when the button is clicked the code executes
		$('.error').fadeOut('slow'); // reset the error messages (hides them)

		var error = false; // we will set this true if the form isn't valid

		var name = $('input#name').val(); // get the value of the input field
		if(name == "" || name == " ") {
			$('#err-name').fadeIn('slow'); // show the error message
			error = true; // change the error state to true
		}

		var email_compare = /^([a-z0-9_.-]+)@([da-z.-]+).([a-z.]{2,6})$/; // Syntax to compare against input
		var email = $('input#email').val(); // get the value of the input field
		if (email == "" || email == " ") { // check if the field is empty
			$('#err-email').fadeIn('slow'); // error - empty
			error = true;
		}else if (!email_compare.test(email)) { // if it's not empty check the format against our email_compare variable
			$('#err-emailvld').fadeIn('slow'); // error - not right format
			error = true;
		}

		if(error == true) {
			$('#err-form').slideDown('slow');
			return false;
		}

		var data_string = $('#ajax-form').serialize(); // Collect data from form

		$.ajax({
			type: "POST",
			url: $('#ajax-form').attr('action'),
			data: data_string,
			timeout: 6000,
			error: function(request,error) {
				if (error == "timeout") {
					$('#err-timedout').slideDown('slow');
				}
				else {
					$('#err-state').slideDown('slow');
					$("#err-state").html('An error occurred: ' + error + '');
				}
			},
			success: function() {
				$('#ajax-form').slideUp('slow');
				$('#ajaxsuccess').slideDown('slow');
			}
		});

		return false; // stops user browser being directed to the php file
	}); // end click function
});


text:
package org.elasticsearch.search.aggregations.bucket.significant.heuristics;

import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.search.internal.SearchContext;

import java.io.IOException;

public interface SignificanceHeuristicParser {

    SignificanceHeuristic parse(XContentParser parser, ParseFieldMatcher parseFieldMatcher, SearchContext context) throws IOException,
            ParsingException;

    String[] getNames();
}


text:
/**
 * WordPress dependencies
 */
import { useEffect, useRef } from '@wordpress/element';

/**
 * Internal dependencies
 */
import Data from 'googlesitekit-data';
import { MODULES_TAGMANAGER } from '../datastore/constants';
const { useSelect, useDispatch } = Data;

export default function useExistingTagEffect() {
	const existingTag = useSelect( ( select ) =>
		select( MODULES_TAGMANAGER ).getExistingTag()
	);
	const containerID = useSelect( ( select ) =>
		select( MODULES_TAGMANAGER ).getPrimaryContainerID()
	);

	const skipEffect = useRef( true );

	const { setUseSnippet } = useDispatch( MODULES_TAGMANAGER );

	useEffect( () => {
		if ( existingTag && containerID !== undefined ) {
			if ( containerID === '' || skipEffect.current ) {
				skipEffect.current = false;
				return;
			}
			if ( existingTag === containerID ) {
				setUseSnippet( false );
			} else {
				setUseSnippet( true );
			}
		}
	}, [ containerID, existingTag, setUseSnippet ] );
}


text:
require 'spec_helper'

module Untied
  module Publisher
    describe Doorkeeper do
      before do
        class ::Doorkeeper
          include Untied::Publisher::Doorkeeper
        end

        module SomeRepresenter; end
      end
      let(:doorkeeper) { ::Doorkeeper.new }

      context "#watch" do
        it "should add observed classes to observed list" do
          doorkeeper.watch(User, :after_create)
          doorkeeper.observed.should == [[User, [:after_create], {}]]
        end

        it "should accept a constant" do
          opts = { :represent_with => SomeRepresenter }
          doorkeeper.watch(User, :after_create, opts)
          doorkeeper.observed.should == [[User, [:after_create], opts]]
        end
      end

      context "#define_callbacks" do
        before do
          doorkeeper.watch(User, :after_create)
        end

        it "should add methods to observable" do
          doorkeeper.define_callbacks
          User.new.should \
            respond_to(:_notify_untied__publisher__observer_for_after_create)
        end

        it "should accept multiple classes" do
          doorkeeper.watch(Post, :after_create)
          doorkeeper.define_callbacks

          User.new.should \
            respond_to(:_notify_untied__publisher__observer_for_after_create)
          Post.new.should \
            respond_to(:_notify_untied__publisher__observer_for_after_create)
        end

        it "should accept multiple callbacks" do
          doorkeeper.watch(Post, :after_create, :after_update)
          doorkeeper.define_callbacks

          Post.new.should \
            respond_to(:_notify_untied__publisher__observer_for_after_update)
          Post.new.should \
            respond_to(:_notify_untied__publisher__observer_for_after_create)
        end

        context "with :represent_with option" do
          let(:observer) do
            observer = double('Untied::Publisher::Observer')
            observer.stub(:name).and_return("Untied::Publisher::Observer")
            observer.stub(:after_create)
            observer
          end
          before do
            Observer.stub(:instance).and_return(observer)
            doorkeeper.watch(Post, :after_create, :represent_with => SomeRepresenter)
            doorkeeper.define_callbacks
          end

          it "should extend the entity with the constant" do
            observer.should_receive(:after_create).
              with(an_instance_of(Post), { :represent_with => SomeRepresenter })
            Post.create
          end
        end
      end

      context "Observed#_notify_untied__publisher__observer_for_[callback]" do
        let(:observer) do
          observer = double('Untied::Publisher::Observer')
          observer.stub(:name).and_return("Untied::Publisher::Observer")
        end
        before do
          doorkeeper.watch(User, :after_create)
          Observer.stub(:instance).and_return(observer)
        end

        it "should invoke observer method" do
          observer.should_receive(:after_create)
          doorkeeper.define_callbacks
          User.new.send(:_notify_untied__publisher__observer_for_after_create)
        end
      end

      context "#observed_classes" do
        it "should return a list of observed classes" do
          doorkeeper.watch(Post, :after_create)
          doorkeeper.watch(Post, :after_update)
          doorkeeper.watch(User, :after_update)

          doorkeeper.observed_classes.should == [Post, User]
        end
      end
    end
  end
end


text:
package intdataplane

import (
	. "github.com/onsi/gomega"
	log "github.com/sirupsen/logrus"

	"github.com/projectcalico/felix/iptables"
)

type mockTable struct {
	Table          string
	currentChains  map[string]*iptables.Chain
	expectedChains map[string]*iptables.Chain
	UpdateCalled   bool
}

func newMockTable(table string) *mockTable {
	return &mockTable{
		Table:          table,
		currentChains:  map[string]*iptables.Chain{},
		expectedChains: map[string]*iptables.Chain{},
	}
}

func logChains(message string, chains []*iptables.Chain) {
	if chains == nil {
		log.Debug(message, " with nil chains")
	} else {
		log.WithField("chains", chains).Debug(message)
		for _, chain := range chains {
			log.WithField("chain", *chain).Debug("")
		}
	}
}

func (t *mockTable) UpdateChain(chain *iptables.Chain) {
	t.UpdateChains([]*iptables.Chain{chain})
}

func (t *mockTable) UpdateChains(chains []*iptables.Chain) {
	t.UpdateCalled = true
	logChains("UpdateChains", chains)
	for _, chain := range chains {
		t.currentChains[chain.Name] = chain
	}
}

func (t *mockTable) RemoveChains(chains []*iptables.Chain) {
	logChains("RemoveChains", chains)
	for _, chain := range chains {
		t.RemoveChainByName(chain.Name)
		delete(t.currentChains, chain.Name)
	}
}

func (t *mockTable) RemoveChainByName(name string) {
	delete(t.currentChains, name)
}

func (t *mockTable) checkChains(expecteds [][]*iptables.Chain) {
	t.expectedChains = map[string]*iptables.Chain{}
	for _, expected := range expecteds {
		for _, chain := range expected {
			t.expectedChains[chain.Name] = chain
		}
	}
	t.checkChainsSameAsBefore()
}

func (t *mockTable) checkChainsSameAsBefore() {
	log.Debug("Expected chains")
	for _, chain := range t.expectedChains {
		log.WithField("chain", *chain).Debug("")
	}
	Expect(t.currentChains).To(Equal(t.expectedChains), t.Table+" chains incorrect")
}


text:
import _ from 'lodash'
import { API } from '../../../store/api'

// ------------------------------------
// Constants
// ------------------------------------
export const GOTO_ENTITY_ADD_PAGE = 'GOTO_ENTITY_ADD_PAGE'
export const SEARCH_ENTITY = 'SEARCH_ENTITY'

// ------------------------------------
// Actions
// ------------------------------------
export function switchToEntityAddPage () {
  window.connectify_browserHistory.push('entity/add', { type: 'new' })
  return {
    type: GOTO_ENTITY_ADD_PAGE
  }
}

/**
 * search entity
 * @param  {String} query
 * @param  {Boolean} jump  whether to jump to search result page
 * @return {Function}
 */
export function searchEntity (query, jump = true) {
  return (dispatch) => {
    API.searchEntity(query).then((response) => {
      return response.json()
    }).then((response) => {
      dispatch({
        type: SEARCH_ENTITY,
        searchResults: preprocessResponse(response.data)
      })
      jump && window.connectify_browserHistory.push('search/' + encodeURIComponent(query))
    })
  }
}

export const actions = {
  switchToEntityAddPage
}

const preprocessResponse = (data) => {
  return _.map(data, entity => {
    _.forEach(entity.relations, r => { r.id = _.uniqueId('relationId_') })
    return entity
  })
}

// ------------------------------------
// Action Handlers
// ------------------------------------
const ACTION_HANDLERS = {
  [GOTO_ENTITY_ADD_PAGE]: (state, action) => {
    return state
  },
  [SEARCH_ENTITY]: (state, action) => {
    return _.cloneDeep(action.searchResults)
  }
}

// ------------------------------------
// Reducer
// ------------------------------------
const initialState = []
export default function entityReducer (state = initialState, action) {
  const handler = ACTION_HANDLERS[action.type]
  return handler ? handler(state, action) : state
}


text:
package ch.qos.logback.core.rolling;

import ch.qos.logback.core.rolling.aws.AmazonS3ClientImpl;
import ch.qos.logback.core.rolling.shutdown.RollingPolicyShutdownListener;
import ch.qos.logback.core.rolling.shutdown.ShutdownHookType;
import ch.qos.logback.core.rolling.shutdown.ShutdownHookUtil;
import java.util.Date;

public class S3FixedWindowRollingPolicy extends FixedWindowRollingPolicy implements RollingPolicyShutdownListener {

    private String           awsAccessKey;
    private String           awsSecretKey;
    private String           s3BucketName;
    private String           s3FolderName;
    private ShutdownHookType shutdownHookType;
    private boolean          rolloverOnExit;
    private boolean          prefixTimestamp;
    private boolean          prefixIdentifier;

    private AmazonS3ClientImpl s3Client;

    public S3FixedWindowRollingPolicy() {

        super();

        rolloverOnExit = false;
        shutdownHookType = ShutdownHookType.NONE;
        prefixTimestamp = false;
        prefixIdentifier = false;
    }

    @Override
    public void start() {

        super.start();

        //Init S3 client
        s3Client = new AmazonS3ClientImpl( getAwsAccessKey(), getAwsSecretKey(), getS3BucketName(), getS3FolderName(), isPrefixTimestamp(),
                isPrefixIdentifier() );

        if (isPrefixIdentifier()) {

            addInfo( "Using identifier prefix \"" + s3Client.getIdentifier() + "\"" );
        }

        //Register shutdown hook so the log gets uploaded on shutdown, if needed
        ShutdownHookUtil.registerShutdownHook( this, getShutdownHookType() );
    }

    @Override
    public void rollover()
            throws RolloverFailure {

        super.rollover();

        //Upload the current log file into S3
        s3Client.uploadFileToS3Async( fileNamePattern.convertInt( getMinIndex() ), new Date() );
    }

    /**
     * Shutdown hook that gets called when exiting the application.
     */
    @Override
    public void doShutdown() {

        if (isRolloverOnExit()) {

            //Do rolling and upload the rolled file on exit
            rollover();
        } else {

            //Upload the active log file without rolling
            s3Client.uploadFileToS3Async( getActiveFileName(), new Date(), true );
        }

        //Wait until finishing the upload
        s3Client.doShutdown();
    }

    public String getAwsAccessKey() {

        return awsAccessKey;
    }

    public void setAwsAccessKey(String awsAccessKey) {

        this.awsAccessKey = awsAccessKey;
    }

    public String getAwsSecretKey() {

        return awsSecretKey;
    }

    public void setAwsSecretKey(String awsSecretKey) {

        this.awsSecretKey = awsSecretKey;
    }

    public String getS3BucketName() {

        return s3BucketName;
    }

    public void setS3BucketName(String s3BucketName) {

        this.s3BucketName = s3BucketName;
    }

    public String getS3FolderName() {

        return s3FolderName;
    }

    public void setS3FolderName(String s3FolderName) {

        this.s3FolderName = s3FolderName;
    }

    public boolean isRolloverOnExit() {

        return rolloverOnExit;
    }

    public void setRolloverOnExit(boolean rolloverOnExit) {

        this.rolloverOnExit = rolloverOnExit;
    }

    public ShutdownHookType getShutdownHookType() {

        return shutdownHookType;
    }

    public void setShutdownHookType(ShutdownHookType shutdownHookType) {

        this.shutdownHookType = shutdownHookType;
    }

    public boolean isPrefixTimestamp() {

        return prefixTimestamp;
    }

    public void setPrefixTimestamp(boolean prefixTimestamp) {

        this.prefixTimestamp = prefixTimestamp;
    }

    public boolean isPrefixIdentifier() {

        return prefixIdentifier;
    }

    public void setPrefixIdentifier(boolean prefixIdentifier) {

        this.prefixIdentifier = prefixIdentifier;
    }
}


text:
package io.spine.server.event.model;

import io.spine.model.contexts.projects.rejection.ProjectRejections.SigCannotCreateProject;
import io.spine.server.event.model.given.subscriber.RejectionSubscriber;
import io.spine.server.type.EventClass;
import io.spine.testing.UtilityClassTest;
import io.spine.testing.server.model.ModelTests;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;

@DisplayName("`RejectionDispatchKeys` should")
final class RejectionDispatchKeysTest extends UtilityClassTest<RejectionDispatchKeys> {

    RejectionDispatchKeysTest() {
        super(RejectionDispatchKeys.class);
    }

    @Test
    @DisplayName("create a valid key")
    @SuppressWarnings("ResultOfMethodCallIgnored")
    void createValidKey() {
        assertDoesNotThrow(() -> {
            var method = ModelTests.getMethod(RejectionSubscriber.class, "rejectionWithCommand");
            RejectionDispatchKeys.of(EventClass.from(SigCannotCreateProject.class), method);
        });
        assertDoesNotThrow(() -> {
            var method = ModelTests.getMethod(RejectionSubscriber.class,
                                              "rejectionWithCommandAndCtx");
            RejectionDispatchKeys.of(EventClass.from(SigCannotCreateProject.class), method);
        });
    }

    @Test
    @DisplayName("not create keys for rejections without a cause")
    @SuppressWarnings("ResultOfMethodCallIgnored")
    void notCreateKeyForRejectionsWithoutCause() {
        assertThrows(IllegalArgumentException.class, () -> {
            var method = ModelTests.getMethod(RejectionSubscriber.class,
                                              "rejectionWithoutCommand");
            RejectionDispatchKeys.of(EventClass.from(SigCannotCreateProject.class), method);
        });
        assertThrows(IllegalArgumentException.class, () -> {
            var method = ModelTests.getMethod(RejectionSubscriber.class, "rejectionWithCtx");
            RejectionDispatchKeys.of(EventClass.from(SigCannotCreateProject.class), method);
        });
    }
}


text:
package dtable

import (
	"fmt"
	"github.com/fastfn/dendrite"
	"github.com/golang/protobuf/proto"
	zmq "github.com/pebbe/zmq4"
	"time"
)

// Client Request: Get value for a key from remote host
func (dt *DTable) remoteGet(remote *dendrite.Vnode, reqItem *kvItem) (*kvItem, bool, error) {
	error_c := make(chan error, 1)
	resp_c := make(chan *kvItem, 1)
	notfound_c := make(chan bool, 1)
	zmq_transport := dt.transport.(*dendrite.ZMQTransport)
	go func() {

		req_sock, err := zmq_transport.ZMQContext.NewSocket(zmq.REQ)
		if err != nil {
			error_c <- fmt.Errorf("ZMQ:DTable:remoteGet - newsocket error - %s", err)
			return
		}
		req_sock.SetRcvtimeo(2 * time.Second)
		req_sock.SetSndtimeo(2 * time.Second)

		defer req_sock.Close()
		err = req_sock.Connect("tcp://" + remote.Host)
		if err != nil {
			error_c <- fmt.Errorf("ZMQ:DTable:remoteGet - connect error - %s", err)
			return
		}
		// Build request protobuf
		req := &PBDTableGetItem{
			Dest:    remote.ToProtobuf(),
			KeyHash: reqItem.keyHash,
		}

		reqData, _ := proto.Marshal(req)
		encoded := dt.transport.Encode(PbDtableGetItem, reqData)
		_, err = req_sock.SendBytes(encoded, 0)
		if err != nil {
			error_c <- fmt.Errorf("ZMQ:DTable:remoteGet - error while sending request - %s", err)
			return
		}

		// read response and decode it
		resp, err := req_sock.RecvBytes(0)
		if err != nil {
			error_c <- fmt.Errorf("ZMQ:DTable:remoteGet - error while reading response - %s", err)
			return
		}
		decoded, err := dt.transport.Decode(resp)
		if err != nil {
			error_c <- fmt.Errorf("ZMQ:DTable:remoteGet - error while decoding response - %s", err)
			return
		}

		switch decoded.Type {
		case dendrite.PbErr:
			pbMsg := decoded.TransportMsg.(dendrite.PBProtoErr)
			error_c <- fmt.Errorf("ZMQ:DTable:remoteGet - got error response - %s", pbMsg.GetError())
		case PbDtableItem:
			pbMsg := decoded.TransportMsg.(PBDTableItem)
			if found := pbMsg.GetFound(); !found {
				notfound_c <- true
				return
			}
			item := new(kvItem)
			copy(item.Key, reqItem.Key)
			copy(item.keyHash, reqItem.keyHash)
			item.Val = pbMsg.GetVal()
			resp_c <- item
			return
		default:
			// unexpected response
			error_c <- fmt.Errorf("ZMQ:DTable:remoteGet - unexpected response")
			return
		}
	}()

	select {
	case <-time.After(zmq_transport.ClientTimeout):
		return nil, false, fmt.Errorf("ZMQ:DTable:remoteGet - command timed out!")
	case err := <-error_c:
		return nil, false, err
	case _ = <-notfound_c:
		return nil, false, nil
	case item := <-resp_c:
		return item, true, nil
	}
}

// Client Request: set value for a key to remote host
func (dt *DTable) remoteSet(origin, remote *dendrite.Vnode, reqItem *kvItem, minAcks int, demoting bool, done chan error) {
	//fmt.Printf("REMOTESET CALLED from %s to %s for key %s\n", origin.String(), remote.String(), reqItem.keyHashString())
	error_c := make(chan error, 1)
	resp_c := make(chan bool, 1)
	zmq_transport := dt.transport.(*dendrite.ZMQTransport)

	go func() {
		req_sock, err := zmq_transport.ZMQContext.NewSocket(zmq.REQ)
		if err != nil {
			error_c <- fmt.Errorf("ZMQ:DTable:remoteSet - newsocket error - %s", err)
			return
		}
		req_sock.SetRcvtimeo(5 * time.Second)
		req_sock.SetSndtimeo(5 * time.Second)

		defer req_sock.Close()
		err = req_sock.Connect("tcp://" + remote.Host)
		if err != nil {
			error_c <- fmt.Errorf("ZMQ:DTable:remoteSet - connect error - %s", err)
			return
		}
		// Build request protobuf
		req := &PBDTableSetItem{
			Origin:   origin.ToProtobuf(),
			Dest:     remote.ToProtobuf(),
			Item:     reqItem.to_protobuf(),
			MinAcks:  proto.Int32(int32(minAcks)),
			Demoting: proto.Bool(demoting),
		}

		reqData, _ := proto.Marshal(req)
		encoded := dt.transport.Encode(PbDtableSetItem, reqData)
		_, err = req_sock.SendBytes(encoded, 0)
		if err != nil {
			error_c <- fmt.Errorf("ZMQ:DTable:remoteSet - error while sending request - %s", err)
			return
		}

		// read response and decode it
		resp, err := req_sock.RecvBytes(0)
		if err != nil {
			error_c <- fmt.Errorf("ZMQ:DTable:remoteSet - error while reading response - %s", err)
			return
		}
		decoded, err := dt.transport.Decode(resp)
		if err != nil {
			error_c <- fmt.Errorf("ZMQ:DTable:remoteSet - error while decoding response - %s", err)
			return
		}

		switch decoded.Type {
		case dendrite.PbErr:
			pbMsg := decoded.TransportMsg.(dendrite.PBProtoErr)
			error_c <- fmt.Errorf("ZMQ:DTable:remoteSet - got error response - %s", pbMsg.GetError())
		case PbDtableResponse:
			pbMsg := decoded.TransportMsg.(PBDTableResponse)
			success := pbMsg.GetOk()
			if success {
				resp_c <- true
				return
			}
			error_c <- fmt.Errorf("ZMQ:DTable:remoteSet - write error - %s", pbMsg.GetError())
			return
		default:
			// unexpected response
			error_c <- fmt.Errorf("ZMQ:DTable:remoteSet - unexpected response")
			return
		}
	}()

	select {
	case <-time.After(zmq_transport.ClientTimeout):
		done <- fmt.Errorf("ZMQ:DTable:remoteSet - command timed out!")
	case err := <-error_c:
		done <- err
	case _ = <-resp_c:
		done <- nil
	}
}

// Client Request: set replicaInfo for replicated item to remote host
func (dt *DTable) remoteSetReplicaInfo(remote *dendrite.Vnode, reqItem *kvItem) error {
	error_c := make(chan error, 1)
	resp_c := make(chan bool, 1)
	zmq_transport := dt.transport.(*dendrite.ZMQTransport)

	go func() {
		req_sock, err := zmq_transport.ZMQContext.NewSocket(zmq.REQ)
		if err != nil {
			error_c <- fmt.Errorf("ZMQ:DTable:remoteSetReplicaInfo - newsocket error - %s", err)
			return
		}
		req_sock.SetRcvtimeo(5 * time.Second)
		req_sock.SetSndtimeo(5 * time.Second)

		defer req_sock.Close()
		err = req_sock.Connect("tcp://" + remote.Host)
		if err != nil {
			error_c <- fmt.Errorf("ZMQ:DTable:remoteSetReplicaInfo - connect error - %s", err)
			return
		}
		// Build request protobuf
		req := &PBDTableSetReplicaInfo{
			Dest:        remote.ToProtobuf(),
			KeyHash:     reqItem.keyHash,
			ReplicaInfo: reqItem.replicaInfo.to_protobuf(),
		}

		reqData, _ := proto.Marshal(req)
		encoded := dt.transport.Encode(PbDtableSetReplicaInfo, reqData)
		_, err = req_sock.SendBytes(encoded, 0)
		if err != nil {
			error_c <- fmt.Errorf("ZMQ:DTable:remoteSetReplicaInfo - error while sending request - %s", err)
			return
		}

		// read response and decode it
		resp, err := req_sock.RecvBytes(0)
		if err != nil {
			error_c <- fmt.Errorf("ZMQ:DTable:remoteSetReplicaInfo - error while reading response - %s", err)
			return
		}
		decoded, err := dt.transport.Decode(resp)
		if err != nil {
			error_c <- fmt.Errorf("ZMQ:DTable:remoteSetReplicaInfo - error while decoding response - %s", err)
			return
		}

		switch decoded.Type {
		case dendrite.PbErr:
			pbMsg := decoded.TransportMsg.(dendrite.PBProtoErr)
			error_c <- fmt.Errorf("ZMQ:DTable:remoteSetReplicaInfo - got error response - %s", pbMsg.GetError())
		case PbDtableResponse:
			pbMsg := decoded.TransportMsg.(PBDTableResponse)
			success := pbMsg.GetOk()
			if success {
				resp_c <- true
				return
			}
			error_c <- fmt.Errorf("ZMQ:DTable:remoteSetReplicaInfo - write error - %s", pbMsg.GetError())
			return
		default:
			// unexpected response
			error_c <- fmt.Errorf("ZMQ:DTable:remoteSetReplicaInfo - unexpected response")
			return
		}
	}()

	select {
	case <-time.After(zmq_transport.ClientTimeout):
		return fmt.Errorf("ZMQ:DTable:remoteSetReplicaInfo - command timed out!")
	case err := <-error_c:
		return err
	case _ = <-resp_c:
		return nil
	}
}

// Client Request: remove replica
func (dt *DTable) remoteClearReplica(remote *dendrite.Vnode, reqItem *kvItem, demoted bool) error {
	error_c := make(chan error, 1)
	resp_c := make(chan bool, 1)
	zmq_transport := dt.transport.(*dendrite.ZMQTransport)

	go func() {
		req_sock, err := zmq_transport.ZMQContext.NewSocket(zmq.REQ)
		if err != nil {
			error_c <- fmt.Errorf("ZMQ:DTable:remoteClearReplica - newsocket error - %s", err)
			return
		}
		req_sock.SetRcvtimeo(5 * time.Second)
		req_sock.SetSndtimeo(5 * time.Second)

		defer req_sock.Close()
		err = req_sock.Connect("tcp://" + remote.Host)
		if err != nil {
			error_c <- fmt.Errorf("ZMQ:DTable:remoteClearReplica - connect error - %s", err)
			return
		}
		// Build request protobuf
		req := &PBDTableClearReplica{
			Dest:    remote.ToProtobuf(),
			KeyHash: reqItem.keyHash,
			Demoted: proto.Bool(demoted),
		}

		reqData, _ := proto.Marshal(req)
		encoded := dt.transport.Encode(PbDtableClearReplica, reqData)
		_, err = req_sock.SendBytes(encoded, 0)
		if err != nil {
			error_c <- fmt.Errorf("ZMQ:DTable:remoteClearReplica - error while sending request - %s", err)
			return
		}

		// read response and decode it
		resp, err := req_sock.RecvBytes(0)
		if err != nil {
			error_c <- fmt.Errorf("ZMQ:DTable:remoteClearReplica - error while reading response - %s", err)
			return
		}
		decoded, err := dt.transport.Decode(resp)
		if err != nil {
			error_c <- fmt.Errorf("ZMQ:DTable:remoteClearReplica - error while decoding response - %s", err)
			return
		}

		switch decoded.Type {
		case dendrite.PbErr:
			pbMsg := decoded.TransportMsg.(dendrite.PBProtoErr)
			error_c <- fmt.Errorf("ZMQ:DTable:remoteClearReplica - got error response - %s", pbMsg.GetError())
		case PbDtableResponse:
			pbMsg := decoded.TransportMsg.(PBDTableResponse)
			success := pbMsg.GetOk()
			if success {
				resp_c <- true
				return
			}
			error_c <- fmt.Errorf("ZMQ:DTable:remoteClearReplica - error - %s", pbMsg.GetError())
			return
		default:
			// unexpected response
			error_c <- fmt.Errorf("ZMQ:DTable:remoteClearReplica - unexpected response")
			return
		}
	}()

	select {
	case <-time.After(zmq_transport.ClientTimeout):
		return fmt.Errorf("ZMQ:DTable:remoteClearReplica - command timed out!")
	case err := <-error_c:
		return err
	case _ = <-resp_c:
		return nil
	}
}

// Client Request: take a rvalue and write replica to another host
func (dt *DTable) remoteWriteReplica(origin, remote *dendrite.Vnode, reqItem *kvItem) error {
	error_c := make(chan error, 1)
	resp_c := make(chan bool, 1)
	zmq_transport := dt.transport.(*dendrite.ZMQTransport)

	go func() {
		req_sock, err := zmq_transport.ZMQContext.NewSocket(zmq.REQ)
		if err != nil {
			error_c <- fmt.Errorf("ZMQ:DTable:remoteWriteReplica - newsocket error - %s", err)
			return
		}
		req_sock.SetRcvtimeo(5 * time.Second)
		req_sock.SetSndtimeo(5 * time.Second)

		defer req_sock.Close()
		err = req_sock.Connect("tcp://" + remote.Host)
		if err != nil {
			error_c <- fmt.Errorf("ZMQ:DTable:remoteWriteReplica - connect error - %s", err)
			return
		}
		// Build request protobuf
		req := &PBDTableSetItem{
			Origin: origin.ToProtobuf(),
			Dest:   remote.ToProtobuf(),
			Item:   reqItem.to_protobuf(),
		}

		reqData, _ := proto.Marshal(req)
		encoded := dt.transport.Encode(PbDtableSetReplica, reqData)
		_, err = req_sock.SendBytes(encoded, 0)
		if err != nil {
			error_c <- fmt.Errorf("ZMQ:DTable:remoteWriteReplica - error while sending request - %s", err)
			return
		}

		// read response and decode it
		resp, err := req_sock.RecvBytes(0)
		if err != nil {
			error_c <- fmt.Errorf("ZMQ:DTable:remoteWriteReplica - error while reading response - %s", err)
			return
		}
		decoded, err := dt.transport.Decode(resp)
		if err != nil {
			error_c <- fmt.Errorf("ZMQ:DTable:remoteWriteReplica - error while decoding response - %s", err)
			return
		}

		switch decoded.Type {
		case dendrite.PbErr:
			pbMsg := decoded.TransportMsg.(dendrite.PBProtoErr)
			error_c <- fmt.Errorf("ZMQ:DTable:remoteWriteReplica - got error response - %s", pbMsg.GetError())
		case PbDtableResponse:
			pbMsg := decoded.TransportMsg.(PBDTableResponse)
			success := pbMsg.GetOk()
			if success {
				resp_c <- true
				return
			}
			error_c <- fmt.Errorf("ZMQ:DTable:remoteWriteReplica - write error - %s", pbMsg.GetError())
			return
		default:
			// unexpected response
			error_c <- fmt.Errorf("ZMQ:DTable:remoteWriteReplica - unexpected response")
			return
		}
	}()

	select {
	case <-time.After(zmq_transport.ClientTimeout):
		return fmt.Errorf("ZMQ:DTable:remoteWriteReplica - command timed out!")
	case err := <-error_c:
		return err
	case _ = <-resp_c:
		return nil
	}
}

// Client Request: get dtable status of remote vnode
func (dt *DTable) remoteStatus(remote *dendrite.Vnode) error {
	error_c := make(chan error, 1)
	resp_c := make(chan bool, 1)
	zmq_transport := dt.transport.(*dendrite.ZMQTransport)

	go func() {
		req_sock, err := zmq_transport.ZMQContext.NewSocket(zmq.REQ)
		if err != nil {
			error_c <- fmt.Errorf("ZMQ:DTable:remoteStatus - newsocket error - %s", err)
			return
		}
		req_sock.SetRcvtimeo(5 * time.Second)
		req_sock.SetSndtimeo(5 * time.Second)

		defer req_sock.Close()
		err = req_sock.Connect("tcp://" + remote.Host)
		if err != nil {
			error_c <- fmt.Errorf("ZMQ:DTable:remoteStatus - connect error - %s", err)
			return
		}
		// Build request protobuf
		req := &PBDTableStatus{
			Dest: remote.ToProtobuf(),
		}

		reqData, _ := proto.Marshal(req)
		encoded := dt.transport.Encode(PbDtableStatus, reqData)
		_, err = req_sock.SendBytes(encoded, 0)
		if err != nil {
			error_c <- fmt.Errorf("ZMQ:DTable:remoteStatus - error while sending request - %s", err)
			return
		}

		// read response and decode it
		resp, err := req_sock.RecvBytes(0)
		if err != nil {
			error_c <- fmt.Errorf("ZMQ:DTable:remoteStatus - error while reading response - %s", err)
			return
		}
		decoded, err := dt.transport.Decode(resp)
		if err != nil {
			error_c <- fmt.Errorf("ZMQ:DTable:remoteStatus - error while decoding response - %s", err)
			return
		}

		switch decoded.Type {
		case dendrite.PbErr:
			pbMsg := decoded.TransportMsg.(dendrite.PBProtoErr)
			error_c <- fmt.Errorf("ZMQ:DTable:remoteStatus - got error response - %s", pbMsg.GetError())
		case PbDtableResponse:
			pbMsg := decoded.TransportMsg.(PBDTableResponse)
			success := pbMsg.GetOk()
			if success {
				resp_c <- true
				return
			}
			error_c <- fmt.Errorf("ZMQ:DTable:remoteStatus - error - %s", pbMsg.GetError())
			return
		default:
			// unexpected response
			error_c <- fmt.Errorf("ZMQ:DTable:remoteStatus - unexpected response")
			return
		}
	}()

	select {
	case <-time.After(zmq_transport.ClientTimeout):
		return fmt.Errorf("ZMQ:DTable:remoteStatus - command timed out!")
	case err := <-error_c:
		return err
	case _ = <-resp_c:
		return nil
	}
}

// Client Request: promote remote vnode for a key
func (dt *DTable) remotePromoteKey(origin, remote *dendrite.Vnode, reqItem *kvItem) error {
	error_c := make(chan error, 1)
	resp_c := make(chan bool, 1)
	zmq_transport := dt.transport.(*dendrite.ZMQTransport)

	go func() {
		req_sock, err := zmq_transport.ZMQContext.NewSocket(zmq.REQ)
		if err != nil {
			error_c <- fmt.Errorf("ZMQ:DTable:remotePromoteKey - newsocket error - %s", err)
			return
		}
		req_sock.SetRcvtimeo(5 * time.Second)
		req_sock.SetSndtimeo(5 * time.Second)

		defer req_sock.Close()
		err = req_sock.Connect("tcp://" + remote.Host)
		if err != nil {
			error_c <- fmt.Errorf("ZMQ:DTable:remotePromoteKey - connect error - %s", err)
			return
		}

		// Build request protobuf
		req := &PBDTablePromoteKey{
			Dest:   remote.ToProtobuf(),
			Origin: origin.ToProtobuf(),
			Item:   reqItem.to_protobuf(),
		}

		reqData, _ := proto.Marshal(req)
		encoded := dt.transport.Encode(PbDtablePromoteKey, reqData)
		_, err = req_sock.SendBytes(encoded, 0)
		if err != nil {
			error_c <- fmt.Errorf("ZMQ:DTable:remotePromoteKey - error while sending request - %s", err)
			return
		}

		// read response and decode it
		resp, err := req_sock.RecvBytes(0)
		if err != nil {
			error_c <- fmt.Errorf("ZMQ:DTable:remotePromoteKey - error while reading response - %s", err)
			return
		}
		decoded, err := dt.transport.Decode(resp)
		if err != nil {
			error_c <- fmt.Errorf("ZMQ:DTable:remotePromoteKey - error while decoding response - %s", err)
			return
		}

		switch decoded.Type {
		case dendrite.PbErr:
			pbMsg := decoded.TransportMsg.(dendrite.PBProtoErr)
			error_c <- fmt.Errorf("ZMQ:DTable:remotePromoteKey - got error response - %s", pbMsg.GetError())
		case PbDtableResponse:
			pbMsg := decoded.TransportMsg.(PBDTableResponse)
			success := pbMsg.GetOk()
			if success {
				resp_c <- true
				return
			}
			error_c <- fmt.Errorf("ZMQ:DTable:remotePromoteKey - error - %s", pbMsg.GetError())
			return
		default:
			// unexpected response
			error_c <- fmt.Errorf("ZMQ:DTable:remotePromoteKey - unexpected response")
			return
		}
	}()

	select {
	case <-time.After(zmq_transport.ClientTimeout):
		return fmt.Errorf("ZMQ:DTable:remotePromoteKey - command timed out!")
	case err := <-error_c:
		return err
	case _ = <-resp_c:
		return nil
	}
}


text:
This gem allows you to easily manage ActiveRecord objects that are pseudo destroyed a.k.a. removed.

## Installation

Add this line to your application's Gemfile:

    gem 'acts_as_removable'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install acts_as_removable

## Usage

```ruby
# a column removed_at of type timestamp is required
class MyModel < ActiveRecord::Base
  acts_as_removable
end

record = MyModel.create
record.removed? # => false
record.remove
record.removed? # => true
```

You can also specify the column to use:
```ruby
class MyModel < ActiveRecord::Base
  acts_as_removable column_name: :some_column
end
```

And you can use callbacks:
```ruby
class MyModel < ActiveRecord::Base
  acts_as_removable

  before_remove do |r|
    puts "Before removing record"
  end

  after_remove :after_remove_method
  def after_remove_method
    puts "After removing record"
  end

  before_unremove do |r|
    puts "Before unremoving record"
  end

  after_unremove :after_unremove_method
  def after_unremove_method
    puts "After unremoving record"
  end
end
```

## Code Status

* [![Build Status](https://api.travis-ci.org/SICSoftwareGmbH/acts_as_removable.png)](https://travis-ci.org/SICSoftwareGmbH/acts_as_removable)
* [![Dependencies](https://gemnasium.com/SICSoftwareGmbH/acts_as_removable.png?travis)](https://gemnasium.com/SICSoftwareGmbH/acts_as_removable)
* [![Code Climate](https://codeclimate.com/github/SICSoftwareGmbH/acts_as_removable.png)](https://codeclimate.com/github/SICSoftwareGmbH/acts_as_removable)

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
import os
import docker
import subprocess
from f1.a.user.session import Session
from twisted.internet.defer import inlineCallbacks

class DockerRunner:
    def __init__(self, docker_briefing, session_id):
        self.briefing = docker_briefing
        self.session_id = session_id
        self.docker_network = self.briefing['network_name']
        self.docker = docker.from_env()
        self.containers = {}

    @inlineCallbacks
    def run(self, image, component, path=None, ip=None, port=None, *args):
        # TODO
        run = 'docker run -itd'
        net = '--network={}'.format(self.docker_network)

        if ip is not None:
            ip = '--ip={}'.format(ip)
        if port is not None:
            port = '-p {}:{}'.format(port, port)
        # port_local = '-p localhost:{}:{}'.format(port, port)
        # volume_docker_sock = '-v /var/run/docker.sock:/var/run/docker.sock'

        volume_config = None
        volume_device = None

        if Session.architecture.startswith('arm'):
            if path:
                volume_device = '--device={}:{}'.format(path, path)
            # volume_config = '--volumes-from zeroclient'

            # TODO mount to f1/s/docker/

            volume_config = '-v /home/pirate/zeroclient/f1/s/docker/:/zeroclient/f1/s/docker/ ' \
                            '-v /home/pirate/config/:/zeroclient/config/ ' \
                            '-v /home/pirate/zeroclient/docker_starter.py:/zeroclient/docker_starter.py'

        elif Session.architecture.startswith('x86'):  # TODO absolute path w/o whitespace
            volume_config = '-v ""'
            # volume_config = '--volumes-from zeroclient'
            # volume_config = '-v /config/:/zeroclient/config/'
        else:
            print('docker.run: architecture unknown: ', Session.architecture)

        component_option = '--component {}'.format(component)
        # cmd = 'cd zeroclient && python3 -m'
        cmd = 'python3'
        # cmd = 'ls -la'

        # TODO put files for device docker image into f1/s/docker/
        # path = '/zeroclient'
        path = '/zeroclient/docker_starter.py'
        # path = 'f1.s.docker.starter'
        # path = '/zeroclient/f1/s/docker/starter.py'
        option = '--options'
        name_container = ''
        name_options = ''
        args_string = ''
        # print(args)

        # concatenate name for container TODO ' '.join(str(arg)) oder append
        try:
            args_string = ''
            for arg in args:
                arg = ' {}'.format(str(arg))
                args_string += str(arg)
            # args_string = (' '.join(str(arg)) for arg in args)
            args_containername = ''
            for arg in args:
                arg = '_{}'.format(str(arg))
                args_containername += str(arg)
            name_container = '{}{}'.format(component, args_containername)
            name_options = '--name={}'.format(name_container)
        except Exception as exc:
            print(exc.args)
            return exc

        platform = '--platform {}'.format(Session.platform)
        architecture = '--architecture {}'.format(Session.architecture)
        session_id = '--session_id {}'.format(self.session_id)

        # docker options
        #   run, net, name_container, volume, ip, port, image,

        if component == 'light':
            if port is not None:
                docker_options = '{} {} {} {} {} {}'.format(run, net, port, volume_config, name_options, image)
            else:
                docker_options = '{} {} {} {} {}'.format(run, net, volume_config, name_options, image)

        elif component in ('mockupreader', 'rfidreader', 'honeywellrfidreader'):
            if port is not None:
                docker_options = '{} {} {} {} {} {}'.format(run, net, port, volume_config, name_options, image)
            else:
                docker_options = '{} {} {} {} {}'.format(run, net, volume_config, name_options, image)

        elif component == 'usbqrcodereader':
            if port is not None:
                docker_options = '{} {} {} {} {} {} {}' \
                    .format(run, net, port, volume_config, volume_device, name_options, image)
            else:
                docker_options = '{} {} {} {} {} {}' \
                    .format(run, net, volume_config, volume_device, name_options, image)

        elif component == 'logiturn':
            if port is not None:
                docker_options = '{} {} {} {} {} {}'.format(run, net, port, volume_config, name_options, image)
            else:
                docker_options = '{} {} {} {} {}'.format(run, net, volume_config, name_options, image)

        else:
            return 'docker.run component value unknown {}'.format(component)

        # image options for starter.py
        #   cmd, path, option, args_string, component_option, board_version?

        if component == 'light':
            starter_options = '{} {} {}{} {}'.format(cmd, path, option, args_string, component_option)

        elif component in ('usbqrcodereader', 'mockupreader', 'rfidreader', 'honeywellrfidreader'):
            starter_options = '{} {} {}{} {}'.format(cmd, path, option, args_string, component_option)

        elif component == 'logiturn':
            starter_options = '{} {} {}{} {}'.format(cmd, path, option, args_string, component_option)

        else:
            starter_options = None

        # container options (python) for inside started container
        #   id, direction, platform, architecture

        inside_options = '{} {} {}'.format(platform, architecture, session_id)

        try:
            if len(self.docker.containers.list(all=True, filters={'name': name_container})) > 0:
                # if name_container in (self.docker.containers.list(all=True, filters={'name': name_container})):

                try:
                    print('remove container ', self.docker.containers.list(all=True, filters={'name': name_container}))
                    os.system('docker stop {} && docker rm {}'.format(name_container, name_container))

                except Exception as x:
                    print(x)
                    return x

            print('{} {} {}'.format(docker_options, starter_options, inside_options))
            container = yield os.system('{} {} {}'.format(docker_options, starter_options, inside_options))  # TODO

            self.containers[name_container] = container
            return True

        except Exception as exception:
            print('docker exception')
            print(exception)
            return exception


text:
package de.seven.fate.event;

import java.io.Serializable;

public abstract class PersonRelatedEventData<T extends Serializable> implements Serializable {

    private final String ldapId;
    private final T data;

    public PersonRelatedEventData(String ldapId, T data) {
        this.ldapId = ldapId;
        this.data = data;
    }

    public String getLdapId() {
        return ldapId;
    }

    public T getData() {
        return data;
    }

    @Override
    public String toString() {
        return "UserRelatedEventData{" + "ldapId='" + ldapId + '\'' + ", data=" + data + '}';
    }
}


text:
/*
 * routes/api/index.js
 */

var BASE_PATH = '../../lib/';

var _ = require('underscore')
  , crypto = require('crypto')
  , check = require('validator').check
  , Step = require('step')
  , humane = require(BASE_PATH + 'humane')
  , email = require(BASE_PATH + 'email')
  , logging = require(BASE_PATH + 'logging')
  , InviteCode = require(BASE_PATH + 'models').InviteCode

module.exports = {
  config: require('./config'),
  require_param: require_param,
  invite_new: invite_new
}

/*
 * Require a request parameter is present or return a 400 response.
 */
function require_param(key, req, res) {
  var val = req.param(key);
  if (val === undefined) {
    res.statusCode = 400;
    var r = {
      status: "error",
      errors: ["you must supply parameter " + key]
    };
    return res.end(JSON.stringify(r), null, '\t');
  }
  return val;
}

/*
 * POST /api/invite/new
 *
 * Create & email a new Strider invite. Only core@beyondfog.com may use this.
 *
 * <invite_code> - Invite token string to set.
 * <email> - Email to send to.
 *
 */

function invite_new(req, res) {
  var invite_code, email_addr;
  invite_code = require_param("invite_code", req, res);
  email_addr = require_param("email", req, res);
  if (invite_code === undefined ||
      email_addr === undefined) {
    return;
  }

  var invite = new InviteCode();
  invite.code = invite_code;
  invite.created_timestamp = new Date();
  invite.emailed_to = email_addr;

  invite.save(function(err, invite) {
    email.send_invite(invite.code, email_addr)
    res.redirect('/admin/invites')
  });
}


text:
FROM ubuntu:14.04

RUN echo "deb mirror://mirrors.ubuntu.com/mirrors.txt utopic main restricted universe multiverse \n\
deb mirror://mirrors.ubuntu.com/mirrors.txt utopic-updates main restricted universe multiverse \n\
deb mirror://mirrors.ubuntu.com/mirrors.txt utopic-backports main restricted universe multiverse \n\
deb mirror://mirrors.ubuntu.com/mirrors.txt utopic-security main restricted universe multiverse" > /etc/apt/sources.list.d/all-mirrors.list

RUN apt-get update && \
    apt-get install -y mongodb pwgen && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

RUN mkdir -p /data/db
VOLUME /data/db

ENV AUTH yes

# Add run scripts
ADD run.sh /run.sh
RUN chmod 755 ./*.sh

EXPOSE 27017

CMD ["/run.sh"]


text:
import logging
import time
import numpy as np
import sys
import copy

from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
from experiments.config import setup_lcsts
from emolga.utils.generic_utils import *
from emolga.models.covc_encdec import NRM
from emolga.models.encdec import NRM as NRM0
from emolga.dataset.build_dataset import deserialize_from_file
from collections import OrderedDict
from fuel import datasets
from fuel import transformers
from fuel import schemes

setup = setup_lcsts

def init_logging(logfile):
    formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(module)s: %(message)s',
                                  datefmt='%m/%d/%Y %H:%M:%S'   )
    fh = logging.FileHandler(logfile)
    # ch = logging.StreamHandler()

    fh.setFormatter(formatter)
    # ch.setFormatter(formatter)
    # fh.setLevel(logging.INFO)
    # ch.setLevel(logging.INFO)
    # logging.getLogger().addHandler(ch)
    logging.getLogger().addHandler(fh)
    logging.getLogger().setLevel(logging.INFO)
    return logging

# prepare logging.
tmark   = time.strftime('%Y%m%d-%H%M%S', time.localtime(time.time()))
config  = setup()   # load settings.
for w in config:
    print '{0}={1}'.format(w, config[w])

logger  = init_logging(config['path_log'] + '/experiments.CopyLCSTS.id={}.log'.format(tmark))
n_rng   = np.random.RandomState(config['seed'])
np.random.seed(config['seed'])
rng     = RandomStreams(n_rng.randint(2 ** 30))
logger.info('Start!')

train_set, test_set, idx2word, word2idx = deserialize_from_file(config['dataset'])
if config['voc_size'] == -1:   # not use unk
    config['enc_voc_size'] = max(zip(*word2idx.items())[1]) + 1
    config['dec_voc_size'] = config['enc_voc_size']
else:
    config['enc_voc_size'] = config['voc_size']
    config['dec_voc_size'] = config['enc_voc_size']

samples = len(train_set['source'])

logger.info('build dataset done. ' +
            'dataset size: {} ||'.format(samples) +
            'vocabulary size = {0}/ batch size = {1}'.format(
        config['dec_voc_size'], config['batch_size']))

def unk_filter(data):
    if config['voc_size'] == -1:
        return copy.copy(data)
    else:
        mask = (np.less(data, config['voc_size'])).astype(dtype='int32')
        data = copy.copy(data * mask + (1 - mask))
        return data

source = '临近 岁末 , 新 基金 发行 步入 旺季 , 11 月份 以来 单周 新基 ' +  \
         '发行 数 始终保持 35 只 以上 的 高位 , 仅 11 月 25 日 一天 , ' + \
         '就 有 12 只 基金 同时 发售 。 国内 首只 公募 对冲 混合型 基金 — 嘉实 绝对 收益 策略 ' + \
         '定期 混合 基金 自 发行 首日 便 备受 各界 青睐 , 每日 认购 均 能 达到 上 亿'
target = '首只 公募 对冲 基金 每日 吸金 上 亿'

test_s = [word2idx[w.decode('utf-8')] for w in source.split()]
test_t = [word2idx[w.decode('utf-8')] for w in target.split()]

logger.info('load the data ok.')

logger.info('Evaluate CopyNet')
echo              = 9
tmark             = '20160226-164053'  # '20160221-025049'  # copy-net model [no unk]
config['copynet'] = True
agent  = NRM(config, n_rng, rng, mode=config['mode'],
                  use_attention=True, copynet=config['copynet'], identity=config['identity'])
agent.build_()
agent.compile_('display')
agent.load(config['path_h5'] + '/experiments.CopyLCSTS.id={0}.epoch={1}.pkl'.format(tmark, echo))
logger.info('generating [testing set] samples')

v      = agent.evaluate_(np.asarray(test_s, dtype='int32'),
                         np.asarray(test_t, dtype='int32'),
                         idx2word, np.asarray(unk_filter(test_s), dtype='int32'))
logger.info('Complete!')


text: export { CoursesListComponent } from './courses-list.component';


text:
package com.vimeo.stag;

import com.google.gson.annotations.SerializedName;

import org.jetbrains.annotations.NotNull;

import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

/**
 * Use this annotation to tell Stag that all the member variables
 * of the class should be processed.
 * <p>
 * If the class is annotated, Stag will generate a TypeAdapter for
 * that class. Stag does not generate TypeAdapters for abstract classes.
 * </p>
 */
@Target({ElementType.TYPE})
public @interface UseStag {

    enum FieldOption {
        /**
         * Will serialize/de-serialize all member variables
         * which are not static or transient.
         */
        ALL,
        /**
         * Will skip serialization and deserialization
         * for all member variables. Only inherited members
         * will be included.
         */
        NONE,
        /**
         * Will Serialize or Deserialize Fields only which are
         * annotated with {@link SerializedName}.
         */
        SERIALIZED_NAME
    }

    /**
     * The chosen field option.
     *
     * @return the field option specified, or the default
     * if none is specified.
     */
    @NotNull FieldOption value() default FieldOption.ALL;
}