text:
import logging

import networkx

import claripy
import ailment

from ...block import Block, BlockNode
from .. import Analysis, register_analysis
from .region_identifier import RegionIdentifier, MultiNode, GraphRegion

l = logging.getLogger(name=__name__)

INDENT_DELTA = 2

class EmptyBlockNotice(Exception):
    pass

class SequenceNode:
    def __init__(self, nodes=None):
        self.nodes = nodes if nodes is not None else [ ]

    def __repr__(self):
        return "<SequenceNode %#x, %d nodes>" % (self.addr, len(self.nodes))

    @property
    def addr(self):
        if self.nodes:
            return self.nodes[0].addr
        else:
            return None

    def add_node(self, node):
        self.nodes.append(node)

    def insert_node(self, pos, node):
        self.nodes.insert(pos, node)

    def remove_node(self, node):
        self.nodes.remove(node)

    def node_position(self, node):
        return self.nodes.index(node)

    def remove_empty_node(self):

        new_nodes = [ ]

        for node in self.nodes:
            if type(node) is ConditionNode and self._test_empty_condition_node(node):
                continue
            if type(node) is CodeNode and self._test_empty_node(node.node):
                continue
            if self._test_empty_node(node):
                continue
            new_nodes.append(node)

        self.nodes = new_nodes

    def _test_empty_condition_node(self, cond_node):

        for node in [ cond_node.true_node, cond_node.false_node ]:
            if node is None:
                continue
            if type(node) is CodeNode and self._test_empty_node(node.node):
                continue
            if self._test_empty_node(node):
                continue
            return False

        return True

    def _test_empty_node(self, node):
        if type(node) is ailment.Block:
            if not node.statements:
                return True
            if len(node.statements) == 1 and type(node.statements[0]) is ailment.Stmt.ConditionalJump:
                # conditional jumps have been taken care of during reaching condition recovery
                return True
            else:
                # not empty
                return False
        # unsupported node type. probably not empty?
        return False

    def copy(self):
        return SequenceNode(nodes=self.nodes[::])

    def dbg_repr(self, indent=0):
        s = ""
        for node in self.nodes:
            s += (node.dbg_repr(indent=indent + INDENT_DELTA))
            s += "\n"

        return s

class CodeNode:
    def __init__(self, node, reaching_condition):
        self.node = node
        self.reaching_condition = reaching_condition

    def __repr__(self):
        if self.addr is not None:
            return "<CodeNode %#x>" % self.addr
        else:
            return "<CodeNode %s>" % repr(self.node)

    @property
    def addr(self):
        if hasattr(self.node, 'addr'):
            return self.node.addr
        else:
            return None

    def dbg_repr(self, indent=0):
        indent_str = indent * " "
        s = ""
        if self.reaching_condition is not None and not claripy.is_true(self.reaching_condition):
            s += (indent_str + "if (<block-missing>; %s)\n" +
                 indent_str + "{\n" +
                 indent_str + "  %s\n" +
                 indent_str + "}") % \
                              (self.reaching_condition, self.node)
        else:
            s += indent_str + str(self.node)

        return s

    def copy(self):
        return CodeNode(self.node, self.reaching_condition)

class ConditionNode:
    def __init__(self, addr, reaching_condition, condition, true_node, false_node=None):
        self.addr = addr
        self.reaching_condition = reaching_condition
        self.condition = condition
        self.true_node = true_node
        self.false_node = false_node

    def dbg_repr(self, indent=0):
        indent_str = indent * " "
        s = ""
        s += (indent_str + "if (<block-missing>; %s)\n" +
              indent_str + "{\n" +
              indent_str + "%s\n" +
              indent_str + "}\n") % (
            self.condition, self.true_node.dbg_repr(indent+2),
        )
        if self.false_node is not None:
            s += (indent_str + "else\n" +
              indent_str + "{\n" +
              indent_str + "%s\n" +
              indent_str + "}") % \
             self.false_node.dbg_repr(indent+2)

        return s

class LoopNode:
    def __init__(self, sort, condition, sequence_node, addr=None):
        self.sort = sort
        self.condition = condition
        self.sequence_node = sequence_node
        self._addr = addr

    @property
    def addr(self):
        if self._addr is None:
            return self.sequence_node.addr
        else:
            return self._addr

class BreakNode:
    def __init__(self, addr, target):
        self.addr = addr
        self.target = target

class ConditionalBreakNode(BreakNode):
    def __init__(self, addr, condition, target):
        super(ConditionalBreakNode, self).__init__(addr, target)
        self.condition = condition

    def __repr__(self):
        return "<ConditionalBreakNode %#x target:%#x>" % (self.addr, self.target)

class RecursiveStructurer(Analysis):
    """
    Recursively structure a region and all of its subregions.
    """
    def __init__(self, region):
        self._region = region

        self.result = None

        self._analyze()

    def _analyze(self):

        region = self._region.recursive_copy()

        # visit the region in post-order DFS
        parent_map = { }
        stack = [ region ]

        while stack:
            current_region = stack[-1]

            has_region = False
            for node in networkx.dfs_postorder_nodes(current_region.graph, current_region.head):
                if type(node) is GraphRegion:
                    stack.append(node)
                    parent_map[node] = current_region
                    has_region = True

            if not has_region:
                # pop this region from the stack
                stack.pop()

                # Get the parent region
                parent_region = parent_map.get(current_region, None)
                # structure this region
                st = self.project.analyses.Structurer(current_region, parent_map=parent_map)
                # replace this region with the resulting node in its parent region... if it's not an orphan
                if not parent_region:
                    # this is the top-level region. we are done!
                    self.result = st.result
                    break
                else:
                    self._replace_region(parent_region, current_region, st.result)

    @staticmethod
    def _replace_region(parent_region, sub_region, node):

        parent_region.replace_region(sub_region, node)

class Structurer(Analysis):
    """
    Structure a region.
    """
    def __init__(self, region, parent_map=None):

        self._region = region
        self._parent_map = parent_map

        self._reaching_conditions = None
        self._predicate_mapping = None
        self._edge_conditions = None
        self._condition_mapping = {}

        self.result = None

        self._analyze()

    def _analyze(self):

        if self._has_cycle():
            self._analyze_cyclic()
        else:
            self._analyze_acyclic()

    def _analyze_cyclic(self):

        # TODO: transform to a single-entry region

        loop_head = self._region.head

        # determine loop nodes and successors
        loop_subgraph, successors = self._find_loop_nodes_and_successors()

        # refine loop successors
        # TODO: transform to a single-successor region
        self._refine_loop_successors(loop_subgraph, successors)

        assert len(successors) <= 1

        loop_node = self._make_endless_loop(loop_head, loop_subgraph, successors)

        loop_node = self._refine_loop(loop_node)

        self.result = SequenceNode(nodes=[ loop_node ] + [ succ for succ in successors if succ in loop_subgraph ])

    def _analyze_acyclic(self):

        # let's generate conditions first
        self._recover_reaching_conditions()

        # make the sequence node
        seq = self._make_sequence()

        self._make_ites(seq)

        seq = self._merge_conditional_breaks(seq)

        seq = self._remove_claripy_bool_asts(seq)

        self.result = seq

    def _has_cycle(self):
        """
        Test if the region contains a cycle.

        :return: True if the region contains a cycle, False otherwise.
        :rtype: bool
        """

        return not networkx.is_directed_acyclic_graph(self._region.graph)

    def _find_loop_nodes_and_successors(self):

        graph = self._region.graph
        head = self._region.head

        # find latching nodes

        latching_nodes = set()

        queue = [ head ]
        traversed = set()
        while queue:
            node = queue.pop()
            successors = graph.successors(node)
            traversed.add(node)

            for dst in successors:
                if dst in traversed:
                    latching_nodes.add(node)
                else:
                    queue.append(dst)

        # find loop nodes and successors
        loop_subgraph = RegionIdentifier.slice_graph(graph, head, latching_nodes, include_frontier=True)
        loop_node_addrs = set( node.addr for node in loop_subgraph )

        # Case A: The loop successor is inside the current region (does it happen at all?)
        loop_successors = set()

        for node, successors in networkx.bfs_successors(graph, head):
            if node.addr in loop_node_addrs:
                for suc in successors:
                    if suc not in loop_subgraph:
                        loop_successors.add(suc)

        # Case B: The loop successor is the successor to this region in the parent graph
        if not loop_successors:
            current_region = self._region
            parent_region = self._parent_map.get(current_region, None)
            while parent_region and not loop_successors:
                parent_graph = parent_region.graph
                for node, successors in networkx.bfs_successors(parent_graph, current_region):
                    if node.addr == current_region.addr:
                        for suc in successors:
                            if suc not in loop_subgraph:
                                loop_successors.add(suc)
                current_region = parent_region
                parent_region = self._parent_map.get(current_region, None)

        return loop_subgraph, loop_successors

    def _refine_loop_successors(self, loop_subgraph, loop_successors):  # pylint:disable=unused-argument,no-self-use

        l.warning('_refine_loop_successors() is not implemented yet.')

    def _make_endless_loop(self, loop_head, loop_subgraph, loop_successors):

        loop_body = self._to_loop_body_sequence(loop_head, loop_subgraph, loop_successors)

        # create a while(true) loop with sequence node being the loop body
        loop_node = LoopNode('while', None, loop_body, addr=loop_head.addr)

        return loop_node

    def _refine_loop(self, loop_node):

        while True:
            # while
            r, loop_node = self._refine_loop_while(loop_node)
            if r: continue

            # do-while
            r, loop_node = self._refine_loop_dowhile(loop_node)
            if r: continue

            # no more changes
            break

        return loop_node

    @staticmethod
    def _refine_loop_while(loop_node):

        if loop_node.sort == 'while' and loop_node.condition is None:
            # it's an endless loop
            first_node = loop_node.sequence_node.nodes[0]
            if type(first_node) is CodeNode:
                first_node = first_node.node
            if type(first_node) is ConditionalBreakNode:
                while_cond = Structurer._negate_cond(first_node.condition)
                new_seq = loop_node.sequence_node.copy()
                new_seq.nodes = new_seq.nodes[1:]
                new_loop_node = LoopNode('while', while_cond, new_seq, addr=loop_node.addr)

                return True, new_loop_node

        return False, loop_node

    @staticmethod
    def _refine_loop_dowhile(loop_node):

        if loop_node.sort == 'while' and loop_node.condition is None:
            # it's an endless loop
            last_node = loop_node.sequence_node.nodes[-1]
            if type(last_node) is ConditionalBreakNode:
                while_cond = Structurer._negate_cond(last_node.condition)
                new_seq = loop_node.sequence_node.copy()
                new_seq.nodes = new_seq.nodes[:-1]
                new_loop_node = LoopNode('do-while', while_cond, new_seq)

                return True, new_loop_node

        return False, loop_node

    def _to_loop_body_sequence(self, loop_head, loop_subgraph, loop_successors):

        graph = self._region.graph
        loop_nodes = set(s.addr for s in graph.nodes)
        loop_region_graph = networkx.DiGraph()

        # TODO: Make sure the loop body has been structured

        queue = [ loop_head ]
        traversed = set()
        loop_successors = set(s.addr for s in loop_successors)
        replaced_nodes = {}

        while queue:
            node = queue[0]
            queue = queue[1:]

            loop_region_graph.add_node(node)

            traversed.add(node)

            successors = list(graph.successors(node))  # successors are all inside the current region

            last_stmt = self._get_last_statement(node)
            real_successor_addrs = self._extract_jump_targets(last_stmt)

            if any(succ_addr in loop_successors for succ_addr in real_successor_addrs):
                # This node has an exit to the outside of the loop
                # add a break or a conditional break node
                new_node = None
                if type(last_stmt) is ailment.Stmt.Jump:
                    # shrink the block to remove the last statement
                    self._remove_last_statement(node)
                    # add a break
                    new_node = BreakNode(last_stmt.ins_addr, last_stmt.target.value)
                elif type(last_stmt) is ailment.Stmt.ConditionalJump:
                    # add a conditional break
                    if last_stmt.true_target.value in loop_successors and \
                                last_stmt.false_target.value in loop_nodes:
                        cond = last_stmt.condition
                        target = last_stmt.true_target.value
                    elif last_stmt.false_target.value in loop_successors and \
                                last_stmt.true_target.value in loop_nodes:
                        cond = ailment.Expr.UnaryOp(last_stmt.condition.idx, 'Not', (last_stmt.condition))
                        target = last_stmt.false_target.value
                    else:
                        l.warning("I'm not sure which branch is jumping out of the loop...")
                        raise Exception()
                    # remove the last statement from the node
                    self._remove_last_statement(node)
                    new_node = ConditionalBreakNode(last_stmt.ins_addr, cond, target)

                if new_node is not None:
                    # special checks if node goes empty
                    if isinstance(node, ailment.Block) and not node.statements:
                        replaced_nodes[node] = new_node
                        preds = list(loop_region_graph.predecessors(node))
                        loop_region_graph.remove_node(node)
                        for pred in preds:
                            loop_region_graph.add_edge(pred, new_node)
                    else:
                        loop_region_graph.add_edge(node, new_node)
                    # update node
                    node = new_node

            for dst in successors:
                # sanity check
                if dst not in loop_subgraph:
                    # what's this node?
                    l.error("Found a node that belongs to neither loop body nor loop successors. Something is wrong.")
                    raise Exception()
                if dst is not loop_head:
                    loop_region_graph.add_edge(node, replaced_nodes.get(dst, dst))
                if dst in traversed:
                    continue
                queue.append(dst)

        # Create a graph region and structure it
        region = GraphRegion(loop_head, loop_region_graph)
        structurer = self.project.analyses.Structurer(region)
        seq = structurer.result

        last_stmt = self._get_last_statement(seq)
        if type(last_stmt) is ailment.Stmt.Jump:
            target = last_stmt.target
            if target.value != loop_head.addr:
                l.error('The last Goto in the loop body does not jump to the loop head. Why?')
                raise Exception()
            # we want to remove this Jump as it is not necessary anymore
            self._remove_last_statement(seq)

        seq.remove_empty_node()

        return seq

    def _recover_reaching_conditions(self):

        edge_conditions = { }
        predicate_mapping = { }
        # traverse the graph to recover the condition for each edge
        for src in self._region.graph.nodes():
            nodes = self._region.graph[src]
            if len(nodes) >= 1:
                for dst in nodes:
                    edge = src, dst
                    predicate = self._extract_predicate(src, dst)
                    edge_conditions[edge] = predicate
                    predicate_mapping[predicate] = dst

        reaching_conditions = { }
        # recover the reaching condition for each node
        for node in networkx.topological_sort(self._region.graph):
            preds = self._region.graph.predecessors(node)
            reaching_condition = None
            for pred in preds:
                edge = (pred, node)
                pred_condition = reaching_conditions.get(pred, claripy.true)
                edge_condition = edge_conditions.get(edge, claripy.true)

                if reaching_condition is None:
                    reaching_condition = claripy.And(pred_condition, edge_condition)
                else:
                    reaching_condition = claripy.Or(claripy.And(pred_condition, edge_condition), reaching_condition)

            if reaching_condition is not None:
                reaching_conditions[node] = self._simplify_condition(reaching_condition)

        self._reaching_conditions = reaching_conditions
        self._predicate_mapping = predicate_mapping
        self._edge_conditions = edge_conditions

    def _convert_claripy_bool_ast(self, cond):
        """
        Convert recovered reaching conditions from claripy ASTs to ailment Expressions

        :return: None
        """

        if isinstance(cond, ailment.Expr.Expression):
            return cond

        if cond.op == "BoolS" and claripy.is_true(cond):
            return cond
        if cond in self._condition_mapping:
            return self._condition_mapping[cond]

        _mapping = {
            'Not': lambda cond_: ailment.Expr.UnaryOp(None, 'Not', self._convert_claripy_bool_ast(cond_.args[0])),
            'And': lambda cond_: ailment.Expr.BinaryOp(None, 'LogicalAnd', (
                self._convert_claripy_bool_ast(cond_.args[0]),
                self._convert_claripy_bool_ast(cond_.args[1]),
            )),
            'Or': lambda cond_: ailment.Expr.BinaryOp(None, 'LogicalOr', (
                self._convert_claripy_bool_ast(cond_.args[0]),
                self._convert_claripy_bool_ast(cond_.args[1]),
            )),
            'ULE': lambda cond_: ailment.Expr.BinaryOp(None, 'CmpULE',
                                                          tuple(map(self._convert_claripy_bool_ast, cond_.args)),
                                                          ),
            '__le__': lambda cond_: ailment.Expr.BinaryOp(None, 'CmpLE',
                                                          tuple(map(self._convert_claripy_bool_ast, cond_.args)),
                                                          ),
            '__lt__': lambda cond_: ailment.Expr.BinaryOp(None, 'CmpLT',
                                                          tuple(map(self._convert_claripy_bool_ast, cond_.args)),
                                                          ),
            'UGT': lambda cond_: ailment.Expr.BinaryOp(None, 'CmpUGT',
                                                          tuple(map(self._convert_claripy_bool_ast, cond_.args)),
                                                          ),
            '__gt__': lambda cond_: ailment.Expr.BinaryOp(None, 'CmpGT',
                                                          tuple(map(self._convert_claripy_bool_ast, cond_.args)),
                                                          ),
            '__eq__': lambda cond_: ailment.Expr.BinaryOp(None, 'CmpEQ',
                                                          tuple(map(self._convert_claripy_bool_ast, cond_.args)),
                                                          ),
            '__ne__': lambda cond_: ailment.Expr.BinaryOp(None, 'CmpNE',
                                                          tuple(map(self._convert_claripy_bool_ast, cond_.args)),
                                                          ),
            '__xor__': lambda cond_: ailment.Expr.BinaryOp(None, 'Xor',
                                                          tuple(map(self._convert_claripy_bool_ast, cond_.args)),
                                                          ),
            '__and__': lambda cond_: ailment.Expr.BinaryOp(None, 'And',
                                                           tuple(map(self._convert_claripy_bool_ast, cond_.args)),
                                                           ),
            'LShR': lambda cond_: ailment.Expr.BinaryOp(None, 'Shr',
                                                        tuple(map(self._convert_claripy_bool_ast, cond_.args)),
                                                        ),
            'BVV': lambda cond_: ailment.Expr.Const(None, None, cond_.args[0], cond_.size()),
            'BoolV': lambda cond_: ailment.Expr.Const(None, None, True, 1) if cond_.args[0] is True
                                                                        else ailment.Expr.Const(None, None, False, 1),
        }

        if cond.op in _mapping:
            return _mapping[cond.op](cond)
        raise NotImplementedError(("Condition variable %s has an unsupported operator %s. "
                                   "Consider implementing.") % (cond, cond.op))

    def _make_sequence(self):

        seq = SequenceNode()

        for node in networkx.topological_sort(self._region.graph):
            seq.add_node(CodeNode(node, self._reaching_conditions.get(node, None)))

        return seq

    def _make_ites(self, seq):

        # search for a == ^a pairs

        while True:
            for node_0 in seq.nodes:
                if not type(node_0) is CodeNode:
                    continue
                rcond_0 = node_0.reaching_condition
                if rcond_0 is None:
                    continue
                for node_1 in seq.nodes:
                    if not type(node_1) is CodeNode:
                        continue
                    if node_0 is node_1:
                        continue
                    rcond_1 = node_1.reaching_condition
                    if rcond_1 is None:
                        continue
                    cond_ = claripy.simplify(claripy.Not(rcond_0) == rcond_1)
                    if claripy.is_true(cond_):
                        # node_0 and node_1 should be structured using an if-then-else
                        self._make_ite(seq, node_0, node_1)
                        break
            else:
                break

        # make all conditionally-reachable nodes ConditionNodes
        for i in range(len(seq.nodes)):
            node = seq.nodes[i]
            if node.reaching_condition is not None and not claripy.is_true(node.reaching_condition):
                if isinstance(node.node, ConditionalBreakNode):
                    # Put conditions together and simplify them
                    cond = claripy.And(node.reaching_condition, self._bool_variable_from_ail_condition(node.node.condition))
                    new_node = CodeNode(ConditionalBreakNode(node.node.addr, cond, node.node.target), None)
                else:
                    new_node = ConditionNode(node.addr, None, node.reaching_condition, node,
                                             None)
                seq.nodes[i] = new_node

    def _make_ite(self, seq, node_0, node_1):

        pos = max(seq.node_position(node_0), seq.node_position(node_1))

        node_0_, node_1_ = node_0.copy(), node_1.copy()
        # clear their reaching conditions
        node_0_.reaching_condition = None
        node_1_.reaching_condition = None

        seq.insert_node(pos, ConditionNode(0, None, node_0.reaching_condition, node_0_,
                                           node_1_))

        seq.remove_node(node_0)
        seq.remove_node(node_1)

    def _merge_conditional_breaks(self, seq):

        # Find consecutive ConditionalBreakNodes and merge their conditions

        new_nodes = [ ]
        i = 0
        while i < len(seq.nodes):
            node = seq.nodes[i]

            if type(node) is CodeNode:
                node = node.node

            if isinstance(node, SequenceNode):
                node = self._merge_conditional_breaks(node)
            elif isinstance(node, ConditionalBreakNode) and i > 0:
                prev_node = seq.nodes[i-1]
                if type(prev_node) is CodeNode:
                    prev_node = prev_node.node
                if isinstance(prev_node, ConditionalBreakNode):
                    # found them!

                    # pop the previously added node
                    if new_nodes:
                        new_nodes = new_nodes[:-1]

                    merged_condition = self._simplify_condition(claripy.Or(node.condition, prev_node.condition))
                    new_node = ConditionalBreakNode(node.addr,
                                                    merged_condition,
                                                    node.target
                                                    )
                    node = new_node

            new_nodes.append(node)
            i += 1

        return SequenceNode(new_nodes)

    def _remove_claripy_bool_asts(self, node):

        # Convert claripy Bool ASTs to AIL expressions

        if isinstance(node, SequenceNode):
            new_nodes = [ ]
            for n in node.nodes:
                new_node = self._remove_claripy_bool_asts(n)
                new_nodes.append(new_node)
            new_seq_node = SequenceNode(new_nodes)
            return new_seq_node

        elif isinstance(node, CodeNode):
            node = CodeNode(self._remove_claripy_bool_asts(node.node),
                            None if node.reaching_condition is None
                            else self._convert_claripy_bool_ast(node.reaching_condition))
            return node

        elif isinstance(node, ConditionalBreakNode):

            return ConditionalBreakNode(node.addr,
                                        self._convert_claripy_bool_ast(node.condition),
                                        node.target,
                                        )

        elif isinstance(node, ConditionNode):

            return ConditionNode(node.addr,
                                 None if node.reaching_condition is None else
                                    self._convert_claripy_bool_ast(node.reaching_condition),
                                 self._convert_claripy_bool_ast(node.condition),
                                 self._remove_claripy_bool_asts(node.true_node),
                                 self._remove_claripy_bool_asts(node.false_node),
                                 )

        elif isinstance(node, LoopNode):

            return LoopNode(node.sort,
                            node.condition,
                            self._remove_claripy_bool_asts(node.sequence_node),
                            addr=node.addr,
                            )

        else:
            return node

    def _get_last_statement(self, block):
        if type(block) is SequenceNode:
            if block.nodes:
                return self._get_last_statement(block.nodes[-1])
        elif type(block) is CodeNode:
            return self._get_last_statement(block.node)
        elif type(block) is ailment.Block:
            if not block.statements:
                raise EmptyBlockNotice()
            return block.statements[-1]
        elif type(block) is Block:
            return block.vex.statements[-1]
        elif type(block) is BlockNode:
            b = self.project.factory.block(block.addr, size=block.size)
            return b.vex.statements[-1]
        elif type(block) is MultiNode:
            # get the last node
            for the_block in reversed(block.nodes):
                try:
                    last_stmt = self._get_last_statement(the_block)
                    return last_stmt
                except EmptyBlockNotice:
                    continue
        elif type(block) is LoopNode:
            return self._get_last_statement(block.sequence_node)
        elif type(block) is ConditionalBreakNode:
            return None
        elif type(block) is ConditionNode:
            return None
        else:
            raise NotImplementedError()

        return None

    def _remove_last_statement(self, node):

        stmt = None

        if type(node) is CodeNode:
            stmt = self._remove_last_statement(node.node)
        elif type(node) is ailment.Block:
            stmt = node.statements[-1]
            node.statements = node.statements[:-1]
        elif type(node) is MultiNode:
            if node.nodes:
                stmt = self._remove_last_statement(node.nodes[-1])
        elif type(node) is SequenceNode:
            if node.nodes:
                stmt = self._remove_last_statement(node.nodes[-1])
        else:
            raise NotImplementedError()

        return stmt

    def _extract_predicate(self, src_block, dst_block):

        if type(src_block) is ConditionalBreakNode:
            # bool_var = self._bool_variable_from_ail_condition(src_block.condition)
            # if src_block.target == dst_block.addr:
            #     return bool_var
            # else:
            #     return claripy.Not(bool_var)
            if src_block.target == dst_block.addr:
                return claripy.false
            else:
                return claripy.true

        if type(src_block) is GraphRegion:
            return claripy.true

        last_stmt = self._get_last_statement(src_block)

        if last_stmt is None:
            return claripy.true
        if type(last_stmt) is ailment.Stmt.Jump:
            return claripy.true
        if type(last_stmt) is ailment.Stmt.ConditionalJump:
            bool_var = self._bool_variable_from_ail_condition(last_stmt.condition)
            if last_stmt.true_target.value == dst_block.addr:
                return bool_var
            else:
                return claripy.Not(bool_var)

        return claripy.true

    @staticmethod
    def _extract_jump_targets(stmt):
        """
        Extract goto targets from a Jump or a ConditionalJump statement.

        :param stmt:    The statement to analyze.
        :return:        A list of known concrete jump targets.
        :rtype:         list
        """

        targets = [ ]

        # FIXME: We are assuming all jump targets are concrete targets. They may not be.

        if isinstance(stmt, ailment.Stmt.Jump):
            targets.append(stmt.target.value)
        elif isinstance(stmt, ailment.Stmt.ConditionalJump):
            targets.append(stmt.true_target.value)
            targets.append(stmt.false_target.value)

        return targets

    def _bool_variable_from_ail_condition(self, condition):

        # Unpack a condition all the way to the leaves

        _mapping = {
            'LogicalAnd': lambda expr, conv: claripy.And(conv(expr.operands[0]), conv(expr.operands[1])),
            'LogicalOr': lambda expr, conv: claripy.Or(conv(expr.operands[0]), conv(expr.operands[1])),
            'CmpEQ': lambda expr, conv: conv(expr.operands[0]) == conv(expr.operands[1]),
            'CmpLE': lambda expr, conv: conv(expr.operands[0]) <= conv(expr.operands[1]),
            'CmpLT': lambda expr, conv: conv(expr.operands[0]) < conv(expr.operands[1]),
            'Not': lambda expr, conv: claripy.Not(conv(expr.operand)),
            'Xor': lambda expr, conv: conv(expr.operands[0]) ^ conv(expr.operands[1]),
            'And': lambda expr, conv: conv(expr.operands[0]) & conv(expr.operands[1]),
            'Shr': lambda expr, conv: claripy.LShR(conv(expr.operands[0]), expr.operands[1])
        }

        if isinstance(condition, (ailment.Expr.Load, ailment.Expr.Register, ailment.Expr.DirtyExpression)):
            var = claripy.BVS('ailexpr_%s' % repr(condition), condition.bits, explicit_name=True)
            self._condition_mapping[var] = condition
            return var
        elif isinstance(condition, ailment.Expr.Convert):
            # convert is special. if it generates a 1-bit variable, it should be treated as a BVS
            if condition.to_bits == 1:
                var = claripy.BoolS('ailcond_%s' % repr(condition), explicit_name=True)
            else:
                var = claripy.BVS('ailexpr_%s' % repr(condition), condition.to_bits, explicit_name=True)
            self._condition_mapping[var] = condition
            return var
        elif isinstance(condition, ailment.Expr.Const):
            var = claripy.BVV(condition.value, condition.bits)
            return var
        elif isinstance(condition, ailment.Expr.Tmp):
            l.warning("Left-over ailment.Tmp variable %s.", condition)
            var = claripy.BVS('ailtmp_%d' % condition.tmp_idx, condition.bits)
            self._condition_mapping[var] = condition
            return var

        lambda_expr = _mapping.get(condition.op, None)
        if lambda_expr is None:
            raise NotImplementedError("Unsupported AIL expression operation %s. Consider implementing." % condition.op)
        return lambda_expr(condition, self._bool_variable_from_ail_condition)

    @staticmethod
    def _negate_cond(cond):
        if isinstance(cond, ailment.Expr.UnaryOp) and cond.op == 'Not':
            # Unpacck it
            return cond.operand
        return ailment.Expr.UnaryOp(0, 'Not', cond)

    def _simplify_condition(self, cond):

        claripy_simplified = claripy.simplify(cond)
        if not claripy_simplified.symbolic:
            return claripy_simplified
        simplified = self._revert_short_circuit_conditions(cond)
        cond = simplified if simplified is not None else cond
        return cond

    def _revert_short_circuit_conditions(self, cond):

        # revert short-circuit conditions
        # !A||(A&&!B) ==> !(A&&B)

        if cond.op != "Or":
            return cond

        or_arg0, or_arg1 = cond.args[:2]
        if or_arg1.op == 'And':
            pass
        elif or_arg0.op == 'And':
            or_arg0, or_arg1 = or_arg1, or_arg0
        else:
            return cond

        not_a = or_arg0
        solver = claripy.SolverCacheless()

        if not_a.variables == or_arg1.args[0].variables:
            solver.add(not_a == or_arg1.args[0])
            not_b = or_arg1.args[1]
        elif not_a.variables == or_arg1.args[1].variables:
            solver.add(not_a == or_arg1.args[1])
            not_b = or_arg1.args[0]
        else:
            return cond

        if not solver.satisfiable():
            # found it!
            b = claripy.Not(not_b)
            a = claripy.Not(not_a)
            if len(cond.args) <= 2:
                return claripy.Not(claripy.And(a, b))
            else:
                return claripy.Or(claripy.Not(claripy.And(a, b)), *cond.args[2:])
        else:
            return cond

register_analysis(RecursiveStructurer, 'RecursiveStructurer')
register_analysis(Structurer, 'Structurer')


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

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>Simple Test</title>

  <link rel="stylesheet" type="text/css" href="../jquery.jqplot.css" />
  <link rel="stylesheet" type="text/css" href="examples.css" />

<?php include "nav.inc"; ?>

Waterfall chart using default bar colors.

Waterfall chart using custom colors and "useNegativeColors" set to "false".

redpajama_set_name: RedPajamaGithub


text:
<META http-equiv="content-type" content="text/html;charset=iso-8859-9"/><meta name="viewport" content="width=device-width, initial-scale=1"><title>ac</title> <link rel="stylesheet"  href="css/jquery.mobile-1.2.0.css" />

ALÝ RIZA

Geri

On iki imâmýn sekizincisi. Muhammed Cevâd Tâkî'nin babasýdýr. Nesebi, Ali Rýzâ bin Mûsâ
Kâzým bin Câfer-i Sâdýk bin Muhammed Bâkýr bin Ali Zeynel Âbidîn bin Hüseyin bin Ali
bin Ebî Tâlib'dir (r.anhüm).

Künyesi, babasýnýn künyesi gibi Ebü'l-Hasan'dýr. Mûsâ Kâzým hazretleri ona kendi künyemi
baðýþladým buyurmuþlardýr. Lakabý Rýzâ'dýr. Babasýna dediler ki: "Halîfe Me'mûn ondan râzý
olduðu için mi oðlun Ali'yi, Rýzâ diye çaðýrýyorsun?" Cevâbýnda; "Hayýr, Allahü teâlâ ve
Resûlü râzý olduklarý içindir." buyurdu. Ona uyanlar ve muhâlifleri ondan râzýydý.

Rýzâ lakabýndan baþka her biri onun üstünlüðünü ifâde etmek için söylenmiþ, Sâbir, Zekî,
Velî gibi baþka lakaplarý da vardýr. 770 (H.153)de Medîne'de doðdu. 818 (H.203)
senesiRamazân-ý
þerîfin yirmi birinci Perþembe günü elli yaþýnda Tûs (Meþhed)de vefât etti.

Namazýný halîfe Me'mûn kýldýrdý. Me'mûn, Ýmâm-ý Ali Rýzâ hazretlerini çok sever ve sayardý.
Kýzýný nikâh edip, Ýmâmý kendine dâmâd yaptý. Yerine halîfe olmasýný emir ve îlân edip,
paralara ismini yazdýrdý. Fakat, Ýmâm önce vefât etti. Bâyezîd-i Bistâmî ve Ma'rûf-i Kerhî
hazretleri Ýmâmýn sohbeti ile þereflenip kemâle gelip, yüksek derecelere ulaþtýlar.

Ýmâmlýðý, tasavvufta rehberliði yâni Kur'ân-ý kerîmin mânevî hükümlerine kavuþturma
vazîfesi, bunu kalplere yerleþtirmek, tasavvuf hâllerine ve derecelerine ulaþtýrma vazîfesi
vefâtýna kadar sürdü.

Ýmâm-ý Ali Rýzâ'nýn babasý
Ýmâm-ý Mûsâ Kâzým'ýn üstün talebelerinden biri þöyle anlattý:
"Bir gün Ýmâm-ý Mûsâ Kâzým; "Maðrib (Fas) tüccarlarýndan gelen oldu mu?" diye

sordu."Bilmiyoruz." dedik. O da; "Gelmiþtir." buyurdu. Atlara binip gittik. Orada câriye
satan bir Maðribli vardý. Bize yedi câriye gösterdi. Ýmâm hazretleri hiçbirini kabûl etmedi.
Bir daha bulunduðunu fakat hasta olduðundan göstermediklerini öðrendik. Hazret-i Ýmâm
bana; "Yarýn gel. Ne kadar ücret isterse kabûl edip o câriyeyi al!" buyurdu. Ertesi gün
Maðriblinin yanýna vardým. "Dün isteyip de hasta olduðu için göremediðimiz câriyeyi
istiyorum." dedim. Yüksek bir fiat söyleyip; "Daha aþaðý olmaz." dedi. Ben de; "O fiyata
kabûl ettim." dedim. Bana; "Bunu kimin için alýyorsun?" diye sorunca; "Dünkü berâber
geldiðimiz zât için." dedim. Tüccar; "O kimlerdendir?" dedi. "Benî Hâþim'dendir." deyince,
Magribli tüccar, bu câriye hakkýnda þöyle anlattý: "Ben, bu câriyeyi Magrib'in en uzak
beldesinden aldým. Bir kadýn bana; "Bu câriyeyi kimin için aldýn?" dedi. Ben de; "Kendim
için aldým." diye söyleyince, o kadýn; "Hayýr! Bu senin olacak bir câriye deðildir! Bu câriye,
yeryüzünün en kýymetli zâtýnýndýr! Bunlarýn bir çocuðu olur. O büyüyüp yetiþince,
yeryüzünün en âlimi olacaktýr." dedi. Daha sonra câriyeyi Mûsâ Kâzým'a getirdim. Bu
câriyeden Ýmâm-ý Ali Rýzâ dünyâya geldi.

Mûsâ Kâzým hazretlerinin annesi Hamîde Hâtun, Peygamber efendimizi rüyâsýnda gördü.
Ona buyurdu ki: "Yakýn zamanda, zamânýn insanlarýnýn en üstünü olan bir torunun olacaktýr."

Ali Rýzâ'nýn annesi anlatýr; "Hâmile olduðum zaman hiçbir aðýrlýk duymazdým. Geceleri
uykuda karnýmda tesbih, Sübhânallah ve tehlil, Lâ ilâhe illallah sesleri iþitir, korkardým.
Uyandýðým zaman hiç ses duymazdým. Oðlum doðduðu zaman ellerini yere koyup, bir söz
söyleyen veya münâcaat eden bir kimse gibi dudaklarýný oynattý."

Huzâa kabîlesinden Da'bel bin Ali ismindeki zât zamânýnýn en meþhûr þâirlerinden ve güzel
söz söyleyenlerindendi. Þâir þöyle anlattý: "Ehl-i beyte muhabbeti anlatan Medâris-i Âyât
isimli kasîdeyi yazýp, Ýmâm-ý Ali Rýzâ'ya arzettim. Çok beðendiler ve; "Benden izinsiz hiç
kimseye okuma!" buyurdular. Ben; "Peki!" deyip ayrýldým. Halife Me'mûn, bu kasîdeyi
yazdýðýmý duyup beni çaðýrdý. Hâl hatýr sorduktan sonra, yeni yazdýðým kasîdeyi okumamý
istedi. Ben özür dileyip hazret-i Ýmâm'ýn emrini bildirdim. Halîfe, hazret-i Ýmâm'ý çaðýrýp,
kendisinden izin alýnca, ben de kasîdeyi okudum. Halîfe çok memnun olup bana elli bin akçe
hediye etti. Ýmâm-ý Ali Rýzâ da o kadar ihsânda bulundu. Ben de; "Efendim! Ben giydiðiniz
elbiselerinizden istirhâm ediyorum. Bereketlenmek için yanýmda bulundururum. Öldüðüm
zaman kefenim olur." dedim. Ýhsân edip, giydiklerinden bir gömlek ve çok güzel bir havlu
verip; "Ýnþâallah bunlarý saklarsýn ve bunlarla belâlardan emin olursun." buyurdular. Bir
zaman Irak'a gidiyordum. Yolda eþkýyâ yolumuzu kesip, neyimiz varsa hepsini almaya
baþladýlar. Eþyâlarýn alýndýðýna deðil de, Ýmâm hazretlerinin hediyesi olan gömlek ve
havlunun da alýnacaðýndan çok korktum. Bir taraftan da hazret-i Ýmâm'ýn; "Belâlardan emin
olursun." sözlerini düþünüyordum. Bu sýrada haydutlardan birinin, benim atýma bindiðini ve
benim yazdýðým kasîdeyi okuyup aðladýðýný gördüm. Haydudun Ehl-i beyte olan
muhabbetine hayret ettim ve dedim ki: "O kasîdeyi kim yazdý?" Eþkýyâ; "Bu kasîdeyi yazan,
Ýmâm-ý Ali Rýzâ'nýn þâiri, meþhûr Da'bel bin Ali'dir. Fakat sen onu tanýmazsýn." deyince;
"Da'bel bin Ali benim!" dedim, inanmadý. Kâfilede bulunanlar tasdik edince, eþkýyâ kâfileden
aldýðý bütün mallarý sâhiplerine iâde etti. Bize de kýlavuzluk edip tehlikeli yerlerden
selâmetle geçmemize vesîle oldu. Hazret-i Ýmâm'ýn hediyelerinin bereketiyle bütün kâfile
belâdan kurtulduk."

Bir gün Ýmâm hazretleri, bir kimseye bakýp, "Hiç kimsenin elinden kurtulamayacaðý iþe
hazýrlýk yap, vasiyyetini yaz!" buyurdu. Üç gün sonra o kimse vefât etti.

Bir kimse þöyle anlattý: Hacca gitmeye niyet etmiþtim. Evdekiler, ihrâm olarak Sevb-i
Mülcem denen, sert ve âdî dokunmuþ kumaþ elbise hazýrlamýþlardý. "Bunlarla ihrâm câiz
midir, deðil midir?" diye þübhe edip, ihtiyât olarak baþka bir ihrâm aldým. Mekke-i
mükerremeye varýnca, Ýmâm-ý Ali Rýzâ'ya bir mektup yazdým. Ama asýl sormak istediðim,
Sevb-i Mülcem ile ihrâmýn câiz olup olmadýðý suâlini yazmayý unutmuþtum. Bir müddet

sonra, Hazret-i Ýmâm mektubuma cevap gönderdiler. Mektubun sonunda "Sevb-i Mülcem ile
ihrâm câizdir." yazýsýný okudum.

Ebû Ýsmâil Sindî isminde bir zât anlatýyor: Bir zaman Ýmâm-ý Ali Rýzâ'nýn huzûruna gittim.
Arabî lisânýndan hiçbir þey bilmediðim için, Sind (Hindistan'ýn kuzey batýsýnda bir eyâlet)
lisâný ile selâm verdim. Selâmýma benim lisâným ile cevap verdiler. Yine Sind lisâný ile bâzý
suâller sordum, Sind lisâný ile gâyet açýk cevap verdiler. Ben; "Efendim! Arabî lisânýný hiç
bilmiyorum. Fakat öðrenmeyi çok arzu ediyorum." diye sorunca, mübârek elini dudaklarýma
sürdü. O anda Arabî konuþmaya baþladým. Allahü teâlâ, hazret-i Ýmâm hürmetine bunu bana
ihsân etti."

Ýmâm-ý Ali Rýzâ hazretleri Niþâbur'a gelince, yirmi binden fazla âlim ve talebe, kendisini
karþýladý. Dedelerinden gelen bir hadîs-i þerîf okumasý için yalvardýlar. Ýmâm hazretleri;
"Ben, babam Mûsâ Kâzým'dan, o da babasý Câfer-i Sâdýk'tan, o da babasý Muhammed
Bâkýr'dan, o, babasý Ali Zeynel Âbidîn'den, o, babasý hazret-i Hüseyin'den, o, babasý hazret-i
Ali'den, o, Peygamber efendimizden, o, Cebrâil aleyhisselâmdan, o da Allahü teâlâdan. Bu
hadîs-i kudsîyi okudu. "Lâ ilâhe illallah kal'amdýr. Bunu okuyan, kal'ama girmiþ olur.
Kal'ama giren de azâbýmdan kurtulur." Ýmâm-ý Ahmed ibni Hanbel hazretleri, bu hadîs-i
kudsînin râvileri ile berâber okunduðunda bütün hastalýklara iyi geleceðini bildirmiþtir.

Bir tanýdýðý anlatýr: Hanýmým yüklü idi. Ýmâm-ý Ali Rýzâ hazretlerinin huzûruna varýp, "Duâ
buyurun da bir oðlumuz olsun." dedim. Bunun üzerine; "Hanýmýn iki çocuða hâmiledir."
buyurdu.

Huzûrlarýndan çýkýp giderken çocuklarýn adýný Muhammed ve Ali koysam diye hatýrýmdan
geçirdim. Beni yoldan çaðýrtýp: "Çocuklarýn birine Ali, diðerine Ümm-i Amr adýný koy!"
buyurdu. Çocuklar doðdu, biri kýz diðeri de oðlandý. Adlarýný dedikleri gibi koydum. Anneme
Ümm-i Amr adýný sorduðumda; "O isim annemin adý idi." dedi.

Sâlih bir müslüman, Ýmâm-ý Ali Rýzâ ile ilgili menkýbesini þöyle anlatýr:

Peygamber efendimizi rüyâmda gördüm. Hacýlarýn konduklarý mescidde oturuyorlardý.
Huzûrlarýna vardým. Selâm verdim. Önlerinde hurma yapraðýndan örülmüþ bir tabakta
Seyhânî hurmalarý vardý. Bana bir avuç hurma verdi. Saydým on yedi tâne idi. Kendi kendime
on yedi yýl ömrüm kalmýþ diye tâbir ettim.

On beþ yirmi gün sonra Ýmâm-ý Ali Rýzâ hazretlerinin bu mescidde konakladýklarýný duydum.
Hemen yanlarýna koþtum. Rüyâmda gördüðüm gibi Resûlullah'ýn oturduðu yerde oturmuþtu.
Önlerinde de bir tabak hurma vardý. Beni yanýna çaðýrarak bir avuç hurma verdi. Saydým tam
on yedi tâne idi. Biraz daha hurma istediðimde; "Resûlullah'tan daha fazla verilir mi?"
buyurdu.

Tüccarýn biri dil tutukluðundan dolayý güçlükle konuþurdu. Kendi kendine; "Ýmâm-ý Ali Rýzâ
hazretleri Peygamber efendimizin evlâtlarýndandýr. Huzûruna varayým da benim dilime bir
ilâç tavsiye etsin." diye düþündü. O gece rüyâsýnda Ýmâm-ý Ali Rýzâ hazretlerini gördü.
Kendisine, "Kimyon, sa'ter ve tuzu, su ile karýþtýr, iki üç kere aðzýnda çalkala þifâ bulursun."
buyurdu. Sabahleyin uyandýðýnda rüyâsýný hâtýrladý; fakat rüyâ deyip fazla ehemmiyet
vermedi. Hazret-i Ýmâmýn huzûruna gidip, hâlini arz ettiðinde: "Senin dilinin ilâcýný rüyâda
söylemediler mi?" buyurdu. Tüccar, târif ettikleri ilâcý kullanýnca, konuþmasý hemen düzeldi.

Birisi bir mektup yazarak bâzý suâllerini hazret-i Ýmâm-ý Ali Rýzâ'ya arz etmek istedi.
Evlerinin önüne vardýðýnda çok kimsenin orada beklediðini ve kendileri ile görüþmek
istediðini gördü. Bu kalabalýkta mektubunu veremeyeceðini düþünerek, üzüldü. Tam geri
döneceði sýrada bir hizmetçi dýþarý çýkarak o þahsý ismiyle çaðýrarak; "Bu kâðýdý
Ýmâm
hazretleri gönderdi." dedi. O þahýs kâðýdý aldý. Baktýðýnda elindeki suâllerinin cevâbý
olduðunu hayret içinde gördü.

Sâlih bir zât anlatýr: "Bir gün Ýmâm-ý Ali Rýzâ hazretleri ile bir evin duvarýnýn dibinde
duruyorduk. Biraz sohbet ettik. O sýrada bir kuþ geldi. Ýmâm hazretlerinin önünde yere
kondu. Ötmeðe baþladý. Dertli olduðu belliydi. Ýmâm hazretleri bana sordu. "Biliyor musunuz
bu kuþ ne diyor?" Ben de dedim ki: "Ehl-i beytten olan Peygamber efendimizin evlâtlarý daha
iyi bilirler." Hazret-i Ýmâm; "Bu kuþ, þu evde bir yýlan olduðunu ve yavrularýný yiyeceðini
söylüyor. Kalk eve gir ve o yýlaný öldür!" buyurdu. Ýmâm hazretlerinin buyurduðu gibi eve
girdim, gerçekten içeride bir yýlan dolaþýyordu. Hemen bir sopa ile yýlaný öldürdüm."

Hüseyin bin Mûsa þöyle anlatýyor: "Biz Hâþimoðullarý'ndan bir grup genç, Ýmâm-ý Ali
Rýzâ'nýn yanýnda oturuyorduk. Biraz sonra akrabâmýzdan Câfer bin Ömer, kýlýk kýyâfeti
periþan bir vaziyette geçti. Biz hâline acýyarak ve üzülerek bakýnca, buyurdu ki: "Ey gençler!
Bu zâtýn hâline acýyorsunuz deðil mi?" buyurunca; "Evet efendim!" dedik."Kýsa bir zaman
sonra yanýnýzdan, kýymetli elbiseler ve etrâfýnda hizmetçiler ile geçerse hiç þaþmayýn."
buyurdu. Aradan bir ay geçti. Bu zât, halîfe tarafýndan Medîne'ye vâli tâyin edildi. Bir zaman
sonra, biz gene ayný yerde otururken o zâtý gördük. Kýymetli elbiseleri ve etrâfýnda
hizmetçileri vardý. Biz, hazret-i Ýmâm'ýn bu durumu daha önceden haber verdiðini hatýrlayýp,
Ýmâm'ýn kerâmeti olduðunu anladýk.

Halîfe Me'mûn, Ýmâm-ý Ali Rýzâ hazretlerini çok sever, sýk sýk onunla görüþürdü. Saraya
geliþinde saray görevlileri onu karþýlar, hürmet gösterirlerdi. Fakat bu hürmetleri
mecbûriyetten idi. Çünkü Ýmâm hazretlerini sevmiyorlardý. Bir araya gelerek, hazret-i
Ýmâm'ýn geldiðinde sarayýn perdesini kaldýrmamaya ve onu karþýlamamaða karar verdiler.
Fakat hazret-i Ýmâm'ýn her geliþinde ellerinde olmadan kalkýp, karþýlayýp perdeyi de
kaldýrýyorlardý. Bir gün hazret-i Ýmâm'ýn geldiðinde yine ayaða kalktýlar; fakat perdeyi
kaldýrmakta biraz durakladýlar. O anda bir rüzgâr peyda oldu ve perde kalktý. Çýkýþýnda da
yine rüzgâr gelip perdeyi kaldýrdý.

Bunu gören saray görevlileri; "Allahü teâlânýn azîz ettiði kimseyi kimse küçültemez!"
diyerek eski âdetlerine devâm ettiler.

Ýbrâhim ibni Abbâs diyor ki: "Ýmâm-ý Ali Rýzâ öyle büyük âlim idi ki, hangi ilimden olursa
olsun, sorulan her meseleye çok güzel cevaplar verirdi. Halîfe Me'mûn, kendisine çok suâl
sorar, verdiði cevaplara hayrân kalýrdý. Hazret-i Ýmâm, az uyur, çok namaz kýlar ve çok oruç
tutardý. Muhtaçlarý arayýp bulur, onlara yardým ederdi. Bir hasýr üzerinde oturur, yatacaðý
zaman da o hasýr üzerinde yatardý. Her iþinde Allahü teâlâya karþý tam bir teslimiyet ve
tevekkül üzere idi. Yüzüðünün taþýnda; "Hasbiyallah=Allahü teâlâ bana kâfidir." yazýlý idi.

MÜSLÜMANA HÝZMET
Ýmâm-ý Ali Rýzâ bir gün hamama gitti. Oturup yýkanýrken bir asker geldi ve ona; "Baþýma su dök de
yýkanayým." dedi. O da, "Peki." deyip askerin baþýna su dökmeye baþladý. Biraz sonra Ýmâmý
tanýyanlardan biri gelip, bu hâli görünce çok üzüldü ve askere; "Ey asker! Senin, kendine hizmet
ettirdiðin bu zât, hazret-i Aliyyül Mürtezâ'nýn ve hazret-i Fâtýmat-üz-Zehrâ'nýn torunu Ýmâm-ý Ali
Rýzâ hazretleridir. Sen ne yaptýðýnýn farkýnda mýsýn?" dedi. Asker bunlarý duyunca, yaptýðýna piþman
olup, Ali Rýzâ hazretlerinin ayaklarýna kapandý ve; "Aman efendim, niye bana kendinizi tanýtmadýnýz!
Niçin bana hizmet ettiniz! Kusûrumuzu affediniz!" diye özür dileyip aðladý. Özrünü kabûl edip;
"Müslümana hizmet etmek sevâb olduðu için senin isteðini kabûl ettim." buyurdu.

1) El-A'lâm; c.5, s.26

2) Vefeyât-ül-A'yân; c.1, s.321, c.3, s.269

3) Târih-i Taberî; c.10, s.251

4) El-Kâmil fi't-Târih; c.6, s.119

5) Nuzhet-ül-Celîs; c.2, s.65

6) El-Ýber; c.1, s.340

7) Nûr-ül-Ebsâr; s.152

8) Tam Ýlmihâl Seâdet-i Ebediyye; s.1059

9) Câmiu Kerâmâti'l-Evliyâ; c.2, s.156

10) Sefînet-ül-Evliyâ (Fârisî); s.26

11) Þezerât-üz-Zeheb; c.2, s.2, 6

12) Hadâik-ül-Verdiyye; s.41

13) Eshâb-ý Kirâm; s.158

14) Ýslâm Âlimleri Ansiklopedisi; c.3, s.98

15) Supleman; c.2, s.573


text:
'use strict';

var _ = require('lodash');

module.exports = Compare;

/**
 * Compare models using previous migration model snapshots.
 * @returns {function}
 * @constructor
 */
function Compare () {

    var self = this;

    function compare (current, previous) {

        // all up/down properties are arrays of string.
        var build = {
                up: {
                    createTable: [],
                    dropTable: [],
                    dropTables: [],
                    addColumn: [],
                    changeColumn: [],
                    removeColumn: []
                    //renameTable: [],  // TODO future feature.
                    //renameColumn: [], // TODO future feature.
                    //addIndex: [],     // TODO future feature.
                    //removeIndex: []   // TODO future feature.
                },
                down: {
                    createTable: [],
                    dropTable: [],
                    dropTables: [],
                    addColumn: [],
                    changeColumn: [],
                    removeColumn: []
                    //renameTable: [],  // TODO future feature.
                    //renameColumn: [], // TODO future feature.
                    //addIndex: [],     // TODO future feature.
                    //removeIndex: []   // TODO future feature.
                },
                options: []
            },
            validAttrs = self.migConf.validAttributes,
            excludeAttrs = self.migConf.excludeAttributes,
            typeVariable = self.migConf.typeVariable || 'types',
            modelName = current.name,
            baseTabs = 2;

        function getTabs(int, addBase) {
            var tabs = '';
            if(addBase)
                int += baseTabs;
            while(int){
                tabs += '\t';
                --int;
            }
            return tabs;
        }

        function isValid(attr) {
            return validAttrs.indexOf(attr) !== -1;
        }

        function qwrap(str) {
            return "'" + str + "'";
        }

        function getActions(type) {
            var actions = [];
            _.forEach(type, function (v) {
                if(v.length) actions.push(v);
            });
            return actions;
        }

        function filterAttributes(obj) {
            var clone = _.clone(obj);
            _.forEach(clone, function (v,k) {
                if(!isValid(k))
                delete clone[k];
            });
            return clone;
        }

        function arrayToString(arr, def) {
            var val = '[';
            def = def || undefined;
            if(!arr || !arr.length)
                return def;
            if(!_.isString(arr[0])){
                val += arr.join(',');
            }else {
                _.forEach(arr, function (v) {
                    val += qwrap(v) + ',';
                });
                val = val.slice(0, val.length -1);
            }
            val += ']';
           return val;
        }

        function funcToString(func, level) {
            var split = func.split('\n'),
                tmp = [];
            _.forEach(split, function (v, k) {
                v = v.replace(/^\s+/, '').replace('\r', '');
                if(k +1 === split.length)
                    tmp.push(getTabs(level + 1, true) + v);
                else if(k > 0)
                    tmp.push(getTabs(level + 2, true) + v);
                else tmp.push(v);
            });
            return tmp.join('\n');
        }

        /**
         * Concats all up migration events to string.
         * @private
         * @memberof Compare
         * @returns {string}
         */
        function upToString() {
            var upStr = '',
                ctr = 0,
                items = getActions(build.up),
                tab,
                suffix;
            // build the output string for up.
            _.forEach(items, function (v,k) {
                _.forEach(v, function(item, key){
                    suffix = (ctr < v.length -1) || (k+1 < items.length) ? '\n' : '';
                    tab = ctr > 0 ? getTabs(0, true) : '';
                    upStr += (tab + item + suffix);
                    ctr += 1;
                });
            });
            return upStr;
        }

        /**
         * Concats all down migration events to string.
         * @private
         * @memberof Compare
         * @returns {string}
         */
        function downToString() {
            var dwnStr = '',
                ctr = 0,
                items = getActions(build.down),
                tab,
                suffix;
            // build the output string for down.
            _.forEach(items, function (v,k) {
                _.forEach(v, function(item, key){
                    suffix = (ctr < v.length -1) || (k+1 < items.length) ? '\n' : '';
                    tab = ctr > 0 ? getTabs(0, true) : '';
                    dwnStr += (tab + item + suffix);
                    ctr += 1;
                });
            });
            return dwnStr;
        }

        /**
         * Recurse child options concat to string.
         * @private
         * @memberof Compare
         * @param {object} obj - the child object.
         * @returns {string}
         */
        function recurseChildOptions(obj, level){
            var child = '',
                len = Object.keys(obj).length,
                ctr = 0,
                prefix;
            level = level || 1;
            for(var prop in obj) {
                if(obj.hasOwnProperty(prop)){
                    var tab = getTabs(level +1, true),
                        val;
                    prefix = ctr > 0 ? ',\n' : '';
                    if(_.isPlainObject(obj[prop])){
                        if(!_.isEmpty(obj[prop])){
                            var subChild = recurseChildOptions(obj[prop], level + 1);
                            if(subChild && subChild.length)
                                child += (tab + prop + ': { \n' + subChild + '\n' + tab + '}');
                        }
                    } else {
                        if(_.isArray(obj[prop])){
                            val = arrayToString(obj[prop]);
                            if(val){
                                tab = ctr === 0 ? getTabs(level) : getTabs(level +1, true);
                                child += (prefix + tab + prop + ': ' + arrayToString(obj[prop]));
                            }
                        } else {
                            var isFunc;
                            val = obj[prop];
                            isFunc = _.isFunction(val);
                            if(_.isString(val)){
                                val = "'" + val.toString() + "'";
                            } else {
                                val = val.toString();
                                if(isFunc)
                                    val = funcToString(val, level);
                            }
                            child += (prefix + tab + prop + ': ' + val);
                        }
                    }
                    ctr +=1;
                }
            }
            return child;
        }

        /**
         * Parse options for create model migrations.
         * @private
         * @memberof Compare
         * @param {object} obj - the object of options.
         */
        function parseOptions(obj) {
            var ctr = 0,
                tab = getTabs(1, true);
            for(var prop in obj) {
                if(obj.hasOwnProperty(prop)){
                    if(_.isPlainObject(obj[prop])){
                        if(!_.isEmpty(obj[prop])){
                            var child = recurseChildOptions(obj[prop]);
                            if(child && child.length)
                                build.options.push(tab + prop + ': { \n' + child + ' \n' + tab + '}');
                        }
                    } else {
                        if(_.isArray(obj[prop])){
                            build.options.push(tab + prop + ': ' + arrayToString(obj[prop]));
                        } else {
                            var val = obj[prop];
                            if(_.isString(val))
                                val = qwrap(val);
                            else
                                val = val.toString();
                            build.options.push(tab + prop + ': ' + val);
                        }
                    }
                }
                ctr +=1;
            }

        }

        /**
         * Converts a property's atttributes to string.
         * @private
         * @memberof Compare
         * @param {object} obj - the object of attributes.
         * @param {object} prevObj - the previous object of attributes from last snapshot.
         * @returns {string}
         */
        function attributesToString(obj, prevObj, level) {
            var attrs = '',
                prefix,
                tab;
            level = level || 1;
            tab = getTabs(level, true);
            _.forEach(obj, function (v, k) {
                if(excludeAttrs.indexOf(k) === -1){
                    var prev = prevObj && prevObj[k] !== undefined ? prevObj[k] : undefined;
                    prefix = attrs.length ? ',\n' : '';
                    if(_.isPlainObject(v)){
                        var subAttr = attributesToString(v, prev, level +1);
                        if(subAttr && subAttr.length)
                            attrs += (prefix + tab + k + ': {\n' + subAttr + '\n' + tab + '}');
                    } else {
                        if(prev !== v){
                            var val = k === 'type' ? 'types.' + v : v;
                            if(_.isArray(val))
                                val = arrayToString(val);
                            if(_.isFunction(val)){
                                val = funcToString(val.toString(), 2);
                            }
                            attrs += (prefix + tab + k + ': ' + val);
                        }
                    }
                }
            });

            return attrs;
        }

        /**
         * Iterate table/model properties and compare or create new.
         * @private
         * @memberof Compare
         */
        function compareMigration(){

            var tab

            // the model/table already exists.
            if(previous){

                tab = getTabs(0, true),

                // compare to previous table checking for
                // any dropped columns.
                _.forEach(previous.attributes, function (v,k) {
                    if (v._modelAttribute) {
                        var curCol = current && current.attributes ? current.attributes[k] : undefined,
                            removeAttrs;
                        // if curCol is undefined it was removed.
                        if(!curCol){
                            removeAttrs = attributesToString(filterAttributes(v));
                            if(removeAttrs) {
                                build.up.removeColumn.push(
                                        'migration.removeColumn(' + qwrap(modelName) + ', ' + qwrap(k) + ');'
                                );
                                build.down.addColumn.push(
                                        'migration.addColumn(' + qwrap(modelName) + ', ' + qwrap(k) + ',\n' +
                                        tab + '{\n'+ removeAttrs + '\n' + tab + '});'
                                );
                            }
                        }
                    }

                });

                // iterate current defined attrs
                // looking for adds & changes.
                _.forEach(current.attributes, function (v,k) {

                    if(v._modelAttribute){
                        // check if is new column or existing.
                        var prevCol = previous.attributes ? previous.attributes[k] : undefined,
                            prevAttrs, curAttrs;

                        if(prevCol){

                            curAttrs = attributesToString(filterAttributes(v), filterAttributes(prevCol));
                            prevAttrs = attributesToString(filterAttributes(prevCol), filterAttributes(v));

                            if(curAttrs) {
                                build.up.changeColumn.push(
                                        'migration.changeColumn(' + qwrap(modelName) + ', ' + qwrap(k) + ',\n' +
                                        tab + '{\n' + curAttrs + '\n' + tab + '});'
                                );
                            }

                            if(prevAttrs) {
                                build.down.changeColumn.push(
                                        'migration.changeColumn(' + qwrap(modelName) + ', ' + qwrap(k) + ',\n' +
                                        tab + '{\n' +  prevAttrs + '\n' + tab +'});'
                                );
                            }

                        } else {

                            curAttrs = attributesToString(filterAttributes(v));
                            // column needs to be added.

                            if(curAttrs) {
                                build.up.addColumn.push(
                                        'migration.addColumn(' + qwrap(modelName) + ', ' + qwrap(k) + ',\n' +
                                        '{\n' + curAttrs + '\n' + tab + '});'
                                );
                                build.down.removeColumn.push(
                                        'migration.removeColumn(' + qwrap(modelName) + ', ' + qwrap(k) + ');'
                                );
                            }

                        }
                    }

                    ctr += 1;

                });

            }

            // this is a new model/table.
            else {

                // this is a new table so we need to parse options.
                var newAttrs = [],
                    ctr = 0,
                    attrTab = getTabs(1, true),
                    newOpts;

                tab = getTabs(0, true);

                parseOptions(current.options);
                newOpts = build.options.join(',\n')

                _.forEach(current.attributes, function (v,k) {

                    //if (v._modelAttribute) {
                        var attrs = attributesToString(filterAttributes(v), null, 2);
                        if(attrs) newAttrs.push(attrTab + k + ': {\n' + attrs + '\n' + attrTab + '}');
                    //}
                    ctr +=1;
                });

                build.up.createTable.push(
                        'migration.createTable(' + qwrap(modelName) + ',\n' +
                        tab + '{\n' + newAttrs.join(',\n') + '\n' + tab + '},\n' +
                        tab + '{\n' + newOpts + '\n' + tab + '});'
                );
                build.down.dropTable.push('migration.dropTable(' + qwrap(modelName) + ');');

            }

            build.up.toString = upToString;
            build.down.toString = downToString;
        }

        // parse properties attributes & options.
        compareMigration();

        return build;

    };

    return compare;

};


text:
// @flow

import mongoose, { Schema } from "mongoose";

export const AdminSchema = new Schema(
  {
    _id: String,
    email: {
      type: String,
      set: (v: string) => v.toLowerCase().trim(),
      required: true
    },
    token: {
      type: String,
      required: true
    },
    name: String
  },
  {
    timestamps: true,
    collection: "admin"
  }
);

AdminSchema.index({ email: 1 }, { background: true });

AdminSchema.pre("save", function(next) {
  this._id = this.email;
  next();
});

export class AdminDoc /*:: extends Mongoose$Document */ {
  email: string;
  token: string;
  name: ?string;

  // internal properties
  _plainPassword: ?string;

  static test(ok: number): string {
    return ok.toString();
  }

  // NOT SUPPORTED in flow-typed tests
  // But will work with your code if you add in your .flowconfig
  //   [options]
  //   unsafe.enable_getters_and_setters=true
  //
  // get password(): ?string {
  //   return this._plainPassword;
  // }
  //
  // set password(password: string): void {
  //   this._plainPassword = password;
  //   this.token = this.encryptPassword(password);
  // }
  //
  // get fullname(): string {
  //   const fullname = [];
  //   if (this.lastname) fullname.push(this.lastname);
  //   if (this.name) fullname.push(this.name);
  //   if (this.middlename) fullname.push(this.middlename);
  //   return fullname.join(' ');
  // }

  encryptPassword(password: string): string {
    return "bcrypt.hashSync(password, 13)";
  }

  checkPassword(password: string): boolean {
    return !!"bcrypt.compareSync(password, this.token)";
  }
}

AdminSchema.loadClass(AdminDoc);

AdminSchema.post("save", (doc, next) => {
  doc.name = "Abc";
  // $FlowExpectedError
  doc.name = 123;
  next();
});

export const Admin = mongoose.model("Admin", AdminSchema);

Admin.findById(1).then(d => {
  if (d) {
    // $FlowExpectedError
    d.checkPassword(123);
  }
});

Admin.test(123);
// $FlowExpectedError
Admin.test("123");

const a = Admin.findOne({})
  .exec()
  .then(ddd => {
    if (ddd) {
      ddd.checkPassword("123");
      // $FlowExpectedError
      ddd.checkPassword(123);
    }
  });

const a1 = new Admin({ email: "123", token: "www" });
// $FlowExpectedError
const a2 = new Admin({ email: 123, token: "www" });

Admin.aggregate([ { $project : { email : 1 } } ]).allowDiskUse(true).exec()

//
export const UserSchema = new Schema(
  {
    email: {
      type: String,
      match: /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/,
      set: (v: string) => v.toLowerCase().trim(),
      required: true
    },
    name: String
  },
  {
    timestamps: {
      createdAt: "created_at",
      updatedAt: "updated_at"
    },
    collection: "admin"
  }
);

mongoose.disconnect(err => console.log("err"));

mongoose.disconnect().then(data => console.log(data));


text:
wchar_t *_aswprintf(const wchar_t *fmt, ...)
{
    va_list va_args;
    va_start(va_args, fmt);
    int size = _vscwprintf(fmt, va_args) + 1;
    wchar_t *dst = malloc(size * 2);
    vsnwprintf(dst, size, fmt, va_args);
    va_end(va_args);
    return dst;
}

int winver = WIN_UNSUPPORTED;

// Wine function
char *(CDECL *wine_get_unix_file_name)(LPCWSTR dosW) = NULL;

// DLL hinstance
HINSTANCE dll_hInstance = NULL;

// RPG game window
HWND window = NULL;

// LAUNCHER VARIABLES
LPWSTR szDataPath = NULL;
LPWSTR szFuncCmd = NULL;
LPWSTR szRcPath = NULL;
LPWSTR szReturnPath = NULL;
LPWSTR szEndingPath = NULL;
LPWSTR szSavePath = NULL;
WCHAR szBatPath[MAX_PATH + 11];
#ifdef FONT_EMBED
LPWSTR szFontPath = NULL;
#endif

LPWSTR szDocumentPath = NULL;
LPWSTR szDesktopPath = NULL;

// How do we start out the game?
int ending = ENDING_BEGINNING;

// The array of game variables
int *variables = NULL;

// The array of switches
char *switches = NULL;

// Username that we choose for the player, gets overwritten by the real name
char username[256];
DWORD usernameSize = sizeof(username);

// TRUE if the game started. For the deja vu "ending".
BOOL gameStarted = FALSE;

// TRUE if we're in the game
BOOL isInGame = FALSE;

// TRUE if the oneshot function was called. If the game is exited while this is true, the kitty dies.
BOOL oneshot = FALSE;

BOOL isWindowDestroyed = FALSE;

FILE *saveFile = NULL;

BOOL forceEnding = FALSE;

BOOL closeEnabled = TRUE;


text:
import { CALL_API } from 'redux-api-middleware'

import log from '../../utils/log'

const authlog = log.child({childName: 'redux/auth'})

/* Action types
 * ------------
 */

const GET = 'crcd-web/auth/GET'
const GET_SUCCESS = 'crcd-web/auth/GET_SUCCESS'
const GET_FAIL = 'crcd-web/auth/GET_FAIL'

const LOGIN = 'crcd-web/auth/LOGIN'
const LOGIN_SUCCESS = 'crcd-web/auth/LOGIN_SUCCESS'
const LOGIN_FAIL = 'crcd-web/auth/LOGIN_FAIL'

const LOGOUT = 'crcd-web/auth/LOGOUT'
const LOGOUT_SUCCESS = 'crcd-web/auth/LOGOUT_SUCCESS'
const LOGOUT_FAIL = 'crcd-web/auth/LOGOUT_FAIL'

/* Action creators
 * ---------------
 */

export function fetchData () {
  return {
    [CALL_API]: {
      types: [GET, GET_SUCCESS, GET_FAIL],
      endpoint: '/',
      method: 'GET'
    }
  }
}

export function fetchDataIfNeeded () {
  return (dispatch, getState) => {
    if (getState().auth.user != null) return
    return dispatch(fetchData())
  }
}

export function login (username, password) {
  return {
    [CALL_API]: {
      types: [LOGIN, LOGIN_SUCCESS, LOGIN_FAIL],
      endpoint: '/login',
      method: 'POST',
      body: {
        username,
        password
      }
    }
  }
}

export function logout () {
  return {
    [CALL_API]: {
      types: [LOGOUT, LOGOUT_SUCCESS, LOGOUT_FAIL],
      endpoint: '/logout',
      method: 'GET'
    }
  }
}

/* Reducer
 * ------
 */

export default function reducer (state = {
  ...window.__data.auth,
  loginSent: false,
  loginFailed: false
}, action) {
  switch (action.type) {
    case GET:
      authlog.debug('User get sent')
      return state
    case GET_SUCCESS:
      authlog.debug('User get successful', action.payload)
      return {
        ...state,
        user: action.payload.data.user
      }
    case GET_FAIL:
      authlog.debug('User get failed', action.payload)
      return state
    case LOGIN:
      authlog.debug('Login sent')
      return {
        ...state,
        loginSent: true,
        loginFailed: false
      }
    case LOGIN_SUCCESS:
      let { redirectTo, user } = action.payload.data
      authlog.info('Login successful, user:', user.username)
      if (redirectTo) authlog.debug('Redirecting:', redirectTo)
      return {
        ...state,
        user,
        redirectTo,
        loginSent: false
      }
    case LOGIN_FAIL:
      authlog.error('Login failed.', action.payload)
      return {
        ...state,
        loginFailed: true,
        loginSent: false
      }
    case LOGOUT:
      authlog.debug('Logout sent.')
      return state
    case LOGOUT_SUCCESS:
      authlog.info('Logout successful.')
      delete state['user']
      return {
        ...state,
        redirectTo: '/login'
      }
    case LOGOUT_FAIL:
      authlog.error('Logout failed.', action.payload)
      return state
    default:
      return state
  }
}


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

      <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
      <meta name="keywords" content="W3C SVG 1.1 2nd Edition Test Suite"/>
      <meta name="description" content="W3C SVG 1.1 2nd Edition SVGWeb Test Suite"/>
      <title>
SVG 1.1 2nd Edition Test (svgweb): masking-path-11-b.svg
      </title>

      <link rel="prev" href="masking-path-10-b.html" />
      <link rel="index" href="index.html" />
      <link rel="next" href="masking-path-12-f.html" />

Specification link: 14.3 Clipping paths

    masking-path-10-b ←
    index
    → masking-path-12-f

    Tests that contain the draft-watermark are under development and may be incorrectly testing a feature.

masking-path-11-b.svg

            SVG Image

            PNG Image

              <object data="../../svg/masking-path-11-b.svg" width="480" height="360" type="image/svg+xml">
FAIL

              </object>

      Operator Script

        Run the test. No interaction required.

    Pass Criteria

        The test is passed if the letters 'ABC' are visible inside a blue
        circle, and the letters are transparent, showing the checkered
        background image.

    Test Description

        Test the mask element with child elements with white and black fills,
        to create a mask that clips out some text in the middle.

    masking-path-10-b ←
    index
    → masking-path-12-f


text:
package com.andrewreitz.onthisday.data.api.archive.model;

import java.util.Map;
import java.util.Set;
import rx.Observable;

import static java.util.Map.Entry;

public final class Archive {
  private final String server;
  private final String dir;
  private final Metadata metadata;
  private final Map<String, FileData> files;
  private final Map<String, String> misc;

  private Archive(String server, String dir, Metadata metadata, Map<String, FileData> files,
      Map<String, String> misc) {
    this.server = server;
    this.dir = dir;
    this.metadata = metadata;
    this.files = files;
    this.misc = misc;
  }

  public String getServer() {
    return server;
  }

  public String getDir() {
    return dir;
  }

  public Metadata getMetadata() {
    return metadata;
  }

  public Map<String, FileData> getFileMap() {
    return files;
  }

  public Observable<FileData> getFileData() {
    return Observable.from(files.values());
  }

  public Observable<Entry<String, FileData>> getFiles() {
    return Observable.from(files.entrySet());
  }

  public Map<String, String> getMisc() {
    return misc;
  }
}


text:
package mpg.biochem.de.interbase.task;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import mpg.biochem.de.interbase.batch.FlatFileItemIoFactory;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.FlatFileItemWriter;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

/**
 * Tasklet sorts the contents of the specified input file and writes the sorted
 * records into a designated output file. The sort algorithm performs an out-of
 * -core sort, allowing very large files to be processed without exceeding the
 * JVM's allocated quantity of memory, provided that the max number of rows
 * specified can be held in main memory.
 *
 * @author Rob Upcraft
 *
 * @param <T>
 *            Type of bean represented by file records.
 */
public class FlatFileSortTasklet<T> implements Tasklet {

    private FileSystemResource inputResource;
    private FileSystemResource outputResource;
    private FlatFileItemIoFactory<T> inputIoFactory;
    private FlatFileItemIoFactory<T> outputIoFactory;
    private FileSystemResource tmpDirectory;
    private Comparator<T> comparator;
    private static final int DEFAULT_MAX_ROWS_READ = 100000;
    private int maxRecords;
    private static final Log logger = LogFactory
	    .getLog(FlatFileSortTasklet.class);

    public FlatFileSortTasklet() {
		inputResource = null;
		outputResource = null;
		inputIoFactory = null;
		outputIoFactory = null;
		tmpDirectory = null;
		comparator = null;
		maxRecords = DEFAULT_MAX_ROWS_READ;
    }

    /**
     * Specifies how many records may be loaded into main memory without being
     * written out to the destination file. If OutOfMemory errors manifest
     * themselves, this value should be decreased.
     *
     * @param maxLoadedRecords
     *            Maximum number of loaded records.
     */
    public void setMaxLoadedRecords(int maxLoadedRecords) {
		if (maxLoadedRecords < 1)
	    	throw new IllegalArgumentException(
		    	"max loaded records must be greater than 0");
		this.maxRecords = maxLoadedRecords;
    }

    @Override
    public RepeatStatus execute(StepContribution stepContrib,
	    ChunkContext chunkContext) throws Exception {

		// Check tasklet's state
		if (comparator == null)
			throw new IllegalStateException("no comparator specified");
		if (inputResource == null)
			throw new IllegalStateException("no input resource specified");
		if (outputResource == null)
			throw new IllegalStateException("no output resource specified");
		if (inputIoFactory == null)
			throw new IllegalStateException("no input I/O factory defined");
		if (outputIoFactory == null)
			throw new IllegalStateException("no output I/O factory defined");
		if (this.tmpDirectory == null)
			throw new IllegalStateException(
				"no temporary working directory specified");

		// Get output and input files
		File inputFile = inputResource.getFile();
		File outputFile = outputResource.getFile();

		// Execution context
		ExecutionContext context = new ExecutionContext();

		// Prepare reader and writer
		FlatFileItemReader<T> reader = inputIoFactory.getReader(inputResource);
		reader.open(context);
		logger.info("input file, '" + inputFile.getAbsolutePath()
			+ "' opened for reading");
		FlatFileItemWriter<T> writer = inputIoFactory.getWriter(outputResource);
		writer.setTransactional(false);

		// Prepare sorting variables
		T record = null;
		List<T> records = new ArrayList<T>();
		List<FileSystemResource> tmpFiles = new ArrayList<FileSystemResource>();

		// Load first rows into memory
		logger.info("loading records into memory");
		try {
			for (int i = 0; i < maxRecords; i++) {
			record = reader.read();
			if (record == null)
				break;
			records.add(record);
			}
		} catch (Exception e) {
			reader.close();
			throw e;
		}

		if (record == null) {
			// Temporary files were not necessary, just sort in memory
			// and write to output file
			logger.info("complete input file fits in memory, no temporary files required");
			try {
			reader.close();
			if (outputFile.exists())
				outputFile.delete(); // Remove file if it already exists
			writer.open(context);
			logger.info("output file, '" + outputFile.getAbsolutePath()
				+ "' opened for writing");
			Collections.sort(records, comparator);
			writer.write(records);
			logger.info("output file written successfully");
			writer.close();
			logger.info("output file closed successfully");
			} catch (Exception e) {
			logger.error("an exception occurred while writing the output file: "
				+ e.getMessage());
			logger.info("attempting to remove '"
				+ outputFile.getAbsoluteFile()
				+ "' from the filesystem...");
			writer.close();
			if (outputFile.exists()) {
				if (outputFile.delete())
				logger.info("file deleted successfully");
				else
				logger.warn("file could not be deleted");
			}
			throw e;
			}
		} else {
			logger.info("full file doesn't fit in main memory, using out-of-core resources");
			File tmpDirectory = this.tmpDirectory.getFile();
			if (!tmpDirectory.isDirectory())
			throw new IllegalStateException("temporary space resource '"
				+ tmpDirectory.getAbsolutePath()
				+ "' is not a directory");

			// Remove existing output file
			if (outputFile.exists() && !outputFile.delete()) {
			logger.warn("couldn't remove existing output file, '"
				+ outputFile.getAbsolutePath() + "' from disk");
			}

			// Temporary files will be needed
			do {
			// Sort records currently in memory
			Collections.sort(records, comparator);

			// Prepare a temporary file and add it to the merge list
			FileSystemResource tmp = new FileSystemResource(new File(
				tmpDirectory.getAbsolutePath() + "/"
					+ outputFile.getName() + tmpFiles.size()));
			tmpFiles.add(tmp);

			// Write records to temporary file
			writeTmpFile(tmp, records, tmpFiles, context);

			// Read in next set of records
			records = new ArrayList<T>();
			for (int i = 0; i < maxRecords; i++) {
				record = reader.read();
				if (record == null)
				break;
				records.add(record);
			}
			} while (records.size() > 0);

			// Merge temporary files into output
			logger.info("merging temporary files into: '"
				+ outputFile.getAbsolutePath() + "'...");
			FlatFileMergeTasklet<T> merger = new FlatFileMergeTasklet<T>();
			merger.setWriter(writer);

			List<FlatFileItemReader<T>> readers = new ArrayList<FlatFileItemReader<T>>();
			for (FileSystemResource r : tmpFiles) {
			FlatFileItemReader<T> t = outputIoFactory.getReader(r);
			t.setResource(r);
			readers.add(t);
			}
			merger.setReaders(readers);

			merger.setComparator(comparator);
			try {
			merger.execute(null, null);
			logger.info("merge complete");
			cleanupTemporaryFiles(tmpFiles);
			} catch (Exception e) {
			logger.error("merge operation failed");
			cleanupTemporaryFiles(tmpFiles);
			throw e;
			}
		}

		return RepeatStatus.FINISHED;
    }

    /**
     * Cleans up temporary files used during out-of-core sort.
     *
     * @param tmpFiles
     *            List of temporary files.
     * @throws IOException
     *             Thrown if an I/O error occurs.
     */
    private void cleanupTemporaryFiles(List<FileSystemResource> tmpFiles)
	    throws IOException {
	logger.info("cleaning up temporary files...");
	for (Resource r : tmpFiles) {
	    if (!r.getFile().delete()) {
		logger.warn("couldn't delete temporary file: '"
			+ r.getFile().getAbsolutePath()
			+ "', additional cleanup may be required");
	    }
	}
	logger.info("done cleaning up temporary files");
    }

    /**
     * Write records to a temporary file.
     *
     * @param tmp
     *            File resource handle.
     * @param records
     *            Records to write. Will be written in the given order.
     * @param tmpFiles
     *            List of current temporary files. These will be deleted if a
     *            backout occurs.
     * @throws Exception
     *             Thrown in the event of an I/O error.
     */
    private void writeTmpFile(FileSystemResource tmp, List<T> records,
	    List<FileSystemResource> tmpFiles, ExecutionContext context) throws Exception {

		String path = tmp.getFile().getAbsolutePath();
		logger.info("writing records to temporary file: '" + path + "'");
		if (tmp.getFile().exists())
			logger.warn("temporary file, '"
				+ path
				+ "' already exists, did a previous cleanup operation fail?");
		FlatFileItemWriter<T> tmpWriter = outputIoFactory.getWriter(tmp);
		tmpWriter.setTransactional(false);
		tmpWriter.open(context);

		try {
			// Write records
			tmpWriter.write(records);
			tmpWriter.close();
		} catch (Exception e) {
			tmpWriter.close();
			logger.info("removing temporary files...");
			for (FileSystemResource r : tmpFiles) {
				if (!r.getFile().delete()) {
					logger.warn("failed to delete temporary file: '"
						+ r.getFile().getAbsolutePath()
						+ "', additional cleanup may be required");
				}
			}
			logger.info("done removing temporary files");
			throw e;
		}
    }

    public void setInputResource(FileSystemResource r) {
	this.inputResource = r;
    }

    public void setOutputResource(FileSystemResource r) {
	this.outputResource = r;
    }

    public void setInputIoFactory(FlatFileItemIoFactory<T> input) {
	this.inputIoFactory = input;
    }

    public void setOutputIoFactory(FlatFileItemIoFactory<T> output) {
	this.outputIoFactory = output;
    }

    public void setTmpDirectory(FileSystemResource tmpDirectory) {
	this.tmpDirectory = tmpDirectory;
    }

    public void setComparator(Comparator<T> c) {
	this.comparator = c;
    }
}


text:
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');

if (!is_admin($GLOBALS['current_user'])) {
    sugar_die($GLOBALS['app_strings']['ERR_NOT_ADMIN']);
}

if (empty($_FILES)) {
	echo $mod_strings['LBL_IMPORT_CUSTOM_FIELDS_DESC'];
	echo <<<EOQ

<form enctype="multipart/form-data" action="index.php" method="POST">
   	<input type='hidden' name='module' value='Administration'>
   	<input type='hidden' name='action' value='ImportCustomFieldStructure'>
   {$mod_strings['LBL_IMPORT_CUSTOM_FIELDS_STRUCT']}: <input name="sugfile" type="file" />
    <input type="submit" value="{$mod_strings['LBL_ICF_IMPORT_S']}" class='button'/>
</form>
EOQ;
} else {
    $fmd = BeanFactory::getBean('EditCustomFields');

    echo $mod_strings['LBL_ICF_DROPPING'] . '
';
    $lines = file($_FILES['sugfile']['tmp_name']);
    $cur = array();
    foreach ($lines as $line) {
        if (trim($line) == 'DONE') {
            $fmd->new_with_id = true;
            echo $mod_strings['LBL_IMPORT_CUSTOM_FIELDS_ADDING'] . ':' . $fmd->custom_module . '-' .
                 $fmd->name . '
';
            $fmd->db->query("DELETE FROM $fmd->table_name WHERE id=".$fmd->db->quoted($fmd->id));
            $fmd->save(false);
            $fmd = BeanFactory::getBean('EditCustomFields');
        } else {

            $ln = explode(':::', $line, 2);
            if (sizeof($ln) == 2) {
                $KEY = trim($ln[0]);
                if ($KEY === 'table_name') {
                    continue;
                }
                $fmd->$KEY = trim($ln[1]);
            }
        }
    }
	$_REQUEST['run'] = true;
	$result = $fmd->db->query("SELECT count(*) field_count FROM $fmd->table_name");
	$row = $fmd->db->fetchByAssoc($result);
	echo 'Total Custom Fields :' . $row['field_count'] . '
';
	include('modules/Administration/UpgradeFields.php');
}


text:
package org.eigenbase.sql;

import java.util.*;

import org.eigenbase.sql.parser.*;
import org.eigenbase.sql.util.*;
import org.eigenbase.sql.validate.*;
import org.eigenbase.util.Util;

import com.google.common.collect.ImmutableList;

/**
 * A SqlIdentifier is an identifier, possibly compound.
 */
public class SqlIdentifier extends SqlNode {
  //~ Instance fields --------------------------------------------------------

  /**
   * Array of the components of this compound identifier.
   *
   *
It's convenient to have this member public, and it's convenient to
   * have this member not-final, but it's a shame it's public and not-final.
   * If you assign to this member, please use
   * {@link #setNames(java.util.List, java.util.List)}.
   * And yes, we'd like to make identifiers immutable one day.
   */
  public ImmutableList<String> names;

  /**
   * This identifier's collation (if any).
   */
  final SqlCollation collation;

  /**
   * A list of the positions of the components of compound identifiers.
   */
  private ImmutableList<SqlParserPos> componentPositions;

  //~ Constructors -----------------------------------------------------------

  /**
   * Creates a compound identifier, for example foo.bar.
   *
   * @param names Parts of the identifier, length ≥ 1
   */
  public SqlIdentifier(
      List<String> names,
      SqlCollation collation,
      SqlParserPos pos,
      List<SqlParserPos> componentPositions) {
    super(pos);
    this.names = ImmutableList.copyOf(names);
    this.collation = collation;
    this.componentPositions = componentPositions == null ? null
        : ImmutableList.copyOf(componentPositions);
    for (String name : names) {
      assert name != null;
    }
  }

  public SqlIdentifier(List<String> names, SqlParserPos pos) {
    this(names, null, pos, null);
  }

  /**
   * Creates a simple identifier, for example foo, with a
   * collation.
   */
  public SqlIdentifier(
      String name,
      SqlCollation collation,
      SqlParserPos pos) {
    this(ImmutableList.of(name), collation, pos, null);
  }

  /**
   * Creates a simple identifier, for example foo.
   */
  public SqlIdentifier(
      String name,
      SqlParserPos pos) {
    this(ImmutableList.of(name), null, pos, null);
  }

  //~ Methods ----------------------------------------------------------------

  public SqlKind getKind() {
    return SqlKind.IDENTIFIER;
  }

  public SqlNode clone(SqlParserPos pos) {
    return new SqlIdentifier(names, collation, pos, componentPositions);
  }

  public String toString() {
    return Util.sepList(names, ".");
  }

  /**
   * Modifies the components of this identifier and their positions.
   *
   * @param names Names of components
   * @param poses Positions of components
   */
  public void setNames(List<String> names, List<SqlParserPos> poses) {
    this.names = ImmutableList.copyOf(names);
    this.componentPositions = poses == null ? null
        : ImmutableList.copyOf(poses);
  }

  /**
   * Returns the position of the ith component of a compound
   * identifier, or the position of the whole identifier if that information
   * is not present.
   *
   * @param i Ordinal of component.
   * @return Position of i'th component
   */
  public SqlParserPos getComponentParserPosition(int i) {
    assert (i >= 0) && (i < names.size());
    return (componentPositions == null) ? getParserPosition()
        : componentPositions.get(i);
  }

  /**
   * Copies names and components from another identifier. Does not modify the
   * cross-component parser position.
   *
   * @param other identifier from which to copy
   */
  public void assignNamesFrom(SqlIdentifier other) {
    setNames(other.names, other.componentPositions);
  }

  /**
   * Creates an identifier which contains only the ordinalth
   * component of this compound identifier. It will have the correct {@link
   * SqlParserPos}, provided that detailed position information is available.
   */
  public SqlIdentifier getComponent(int ordinal) {
    return new SqlIdentifier(names.get(ordinal),
        getComponentParserPosition(ordinal));
  }

  public void unparse(
      SqlWriter writer,
      int leftPrec,
      int rightPrec) {
    final SqlWriter.Frame frame =
        writer.startList(SqlWriter.FrameTypeEnum.IDENTIFIER);
    for (String name : names) {
      writer.sep(".");
      if (name.equals("*")) {
        writer.print(name);
      } else {
        writer.identifier(name);
      }
    }

    if (null != collation) {
      collation.unparse(writer, leftPrec, rightPrec);
    }
    writer.endList(frame);
  }

  public void validate(SqlValidator validator, SqlValidatorScope scope) {
    validator.validateIdentifier(this, scope);
  }

  public void validateExpr(SqlValidator validator, SqlValidatorScope scope) {
    // First check for builtin functions which don't have parentheses,
    // like "LOCALTIME".
    SqlCall call =
        SqlUtil.makeCall(
            validator.getOperatorTable(),
            this);
    if (call != null) {
      validator.validateCall(call, scope);
      return;
    }

    validator.validateIdentifier(this, scope);
  }

  public boolean equalsDeep(SqlNode node, boolean fail) {
    if (!(node instanceof SqlIdentifier)) {
      assert !fail : this + "!=" + node;
      return false;
    }
    SqlIdentifier that = (SqlIdentifier) node;
    if (this.names.size() != that.names.size()) {
      assert !fail : this + "!=" + node;
      return false;
    }
    for (int i = 0; i < names.size(); i++) {
      if (!this.names.get(i).equals(that.names.get(i))) {
        assert !fail : this + "!=" + node;
        return false;
      }
    }
    return true;
  }

  public <R> R accept(SqlVisitor<R> visitor) {
    return visitor.visit(this);
  }

  public SqlCollation getCollation() {
    return collation;
  }

  public String getSimple() {
    assert names.size() == 1;
    return names.get(0);
  }

  /**
   * Returns whether this identifier is a star, such as "*" or "foo.bar.*".
   */
  public boolean isStar() {
    return Util.last(names).equals("*");
  }

  /**
   * Returns whether this is a simple identifier. "FOO" is simple; "*",
   * "FOO.*" and "FOO.BAR" are not.
   */
  public boolean isSimple() {
    return (names.size() == 1) && !names.get(0).equals("*");
  }

  public SqlMonotonicity getMonotonicity(SqlValidatorScope scope) {
    // First check for builtin functions which don't have parentheses,
    // like "LOCALTIME".
    final SqlValidator validator = scope.getValidator();
    SqlCall call =
        SqlUtil.makeCall(
            validator.getOperatorTable(),
            this);
    if (call != null) {
      return call.getMonotonicity(scope);
    }
    final SqlIdentifier fqId = scope.fullyQualify(this);
    final SqlValidatorNamespace ns =
        SqlValidatorUtil.lookup(scope, Util.skipLast(fqId.names));
    return ns.resolve().getMonotonicity(Util.last(fqId.names));
  }
}

// End SqlIdentifier.java


text:
var gulp = require('gulp'),
    // all gulp plugins installed by npm
    gp = require('gulp-load-plugins')({lazy: true}),
    // utils methods
    utils = require('./utils'),
    // task arguments
    args = require('yargs').argv;

/**
 * Config params:
 * - src: path to files that needs to be validated by jshint
 * @param config
 */
module.exports = function (taskName, config, depTasks) {

    gulp.task(taskName, depTasks, function () {
        utils.log('Linting: '+config.src);

        return gulp
            .src(config.src)
            .pipe(gp.if(args.verbose, gp.print()))
            .pipe(gp.jshint())
            .pipe(gp.jshint.reporter('jshint-stylish', {verbose: true}))
            .pipe(gp.jshint.reporter('fail'));
    });
};