text:
#include <sstream>
#include <typeinfo>

#include "../include/ppddl/mini-gpt/states.h"
#include "../include/ppddl/mini-gpt/problems.h"
#include "../include/ppddl/mini-gpt/domains.h"
#include "../include/ppddl/mini-gpt/states.h"
#include "../include/ppddl/mini-gpt/exceptions.h"

#include "../include/State.h"
#include "../include/ppddl/PPDDLProblem.h"
#include "../include/ppddl/PPDDLHeuristic.h"

#include "../include/solvers/Solver.h"
#include "../include/solvers/SoftFLARESSolver.h"
#include "../include/solvers/HMinHeuristic.h"
#include "../include/solvers/LRTDPSolver.h"
#include "../include/solvers/LAOStarSolver.h"
#include "../include/solvers/UCTSolver.h"

#include "../include/util/flags.h"

using namespace mdplib;
using namespace mlsolvers;
using namespace std;

extern int yyparse();
extern FILE* yyin;
string current_file;
int warning_level = 0;
int verbosity = 0;
bool using_soft_flares = false;

/* Parses the given file, and returns true on success. */
static bool read_file( const char* name )
{
    yyin = fopen( name, "r" );
    if( yyin == NULL ) {
        std::cerr << "parser:" << name <<
            ": " << strerror( errno ) << std::endl;
        return( false );
    }
    else {
        current_file = name;
        bool success;
        try {
            success = (yyparse() == 0);
        }
        catch( Exception exception ) {
            fclose( yyin );
            std::cerr << exception << std::endl;
            return( false );
        }
        fclose( yyin );
        return( success );
    }
}

bool mustReplan(Solver* solver,
                mlcore::State* current_state,
                mlcore::Action* current_action) {
    if (current_action == nullptr)
        return true;
    if (using_soft_flares) {
        return !static_cast<SoftFLARESSolver*>(solver)->
                    labeledSolved(current_state);
    }
}

int main(int argc, char *args[])
{
    std::string file;
    std::string prob;
    problem_t *problem = NULL;
    std::pair<state_t *,Rational> *initial = NULL;

    if (argc < 2) {
        std::cerr << "Usage: testPPDDL [file] [problem]\n";
        return -1;
    }

    file = args[1];
    prob = args[2];

    if( !read_file( file.c_str() ) ) {
        std::cerr <<
            "<main>: ERROR: couldn't read problem file `" << file << std::endl;
        return( -1 );
    }
    problem = (problem_t*) problem_t::find( prob.c_str() );
    if( !problem ) {
        std::cerr << "<main>: ERROR: problem `" << prob <<
            "' is not defined in file '" << file << "'" << std::endl;
        return( -1 );
    }

    /* Initializing problem */
    mlppddl::PPDDLProblem* MLProblem = new mlppddl::PPDDLProblem(problem);
    mlppddl::PPDDLHeuristic* heuristic =
        new mlppddl::PPDDLHeuristic(MLProblem, mlppddl::atomMin1Forward);
//        new mlppddl::PPDDLHeuristic(MLProblem, mlppddl::atomMinMForward);
//        new mlppddl::PPDDLHeuristic(MLProblem, mlppddl::FF);
    MLProblem->setHeuristic(heuristic);

    cerr << "HEURISTIC s0: " << MLProblem->initialState()->cost() << endl;

    int ntrials = 5000;
    if (argc > 3) {
        ntrials = atoi(args[3]);
    }

    cerr << "INITIAL: " << MLProblem->initialState() << " ";
    Solver* solver;
    register_flags(argc, args);
    if (flag_is_registered("algorithm") &&
            flag_value("algorithm") == "soft-flares") {
        using_soft_flares = true;
        double depth = 4;
        double alpha = 0.10;
        double tol = 1.0e-3;
        int trials = 1000;
        if (flag_is_registered_with_value("depth"))
            depth = stoi(flag_value("depth"));
        TransitionModifierFunction mod_func = kLogistic;
        DistanceFunction dist_func = kStepDist;
        HorizonFunction horizon_func = kFixed;
        if (flag_is_registered_with_value("alpha"))
            alpha = stof(flag_value("alpha"));
        // Distance functions
        if (flag_is_registered("dist")) {
            string dist_str = flag_value("dist");
            if (dist_str == "traj") {
                dist_func = kTrajProb;
            } else if (dist_str == "plaus") {
                dist_func = kPlaus;
            } else if (dist_str == "depth") {
                dist_func = kStepDist;
            } else {
                cerr << "Error: unknown distance function." << endl;
                exit(0);
            }
        }
        // Labeling functions
        if (flag_is_registered("labelf")) {
            string labelf_str = flag_value("labelf");
            if (labelf_str == "exp") {
                mod_func = kExponential;
            } else if (labelf_str == "step") {
                mod_func = kStep;
            } else if (labelf_str == "linear") {
                mod_func = kLinear;
            } else if (labelf_str == "logistic") {
                mod_func = kLogistic;
            } else {
                cerr << "Error: unknown labeling function." << endl;
                exit(0);
            }
        }
        // Labeling functions
        if (flag_is_registered("horf")) {
            string labelf_str = flag_value("horf");
            if (labelf_str == "exp") {
                horizon_func = kExponentialH;
            } else if (labelf_str == "fixed") {
                horizon_func = kFixed;
            } else if (labelf_str == "bern") {
                horizon_func = kBernoulli;
            } else {
                cerr << "Error: unknown labeling function." << endl;
                exit(0);
            }
        }
        solver = new SoftFLARESSolver(
            MLProblem, trials, tol, depth,
            mod_func, dist_func, horizon_func, alpha);
        static_cast<SoftFLARESSolver*>(solver)->maxPlanningTime(1000);
    } else {
        solver = new LRTDPSolver(MLProblem, ntrials, 0.0001);
    }

    mdplib_debug = true;
    solver->solve(MLProblem->initialState());

    cerr << MLProblem->initialState()->cost() << endl;

    int nsims = argc > 4 ? atoi(args[4]) : 1;
    int verbosity = argc > 5 ? atoi(args[5]) : 0;

    int totalSuccess = 0;
    double expectedCost = 0.0;
    for (int i = 0; i < nsims; i++) {
        mlcore::State* tmp = MLProblem->initialState();
        double cost = 0.0;
        while (true) {
            mlcore::Action* a = tmp->bestAction();

            if (verbosity > 100)
                cerr << tmp << " " << tmp->cost() << endl;

            if (MLProblem->goal(tmp)) {
                expectedCost += cost;
                totalSuccess++;
                if (verbosity > 1) {
                    cerr << "GOAL :-)"
                        << " Num. Successes " << totalSuccess << endl;
                }
                break;
            }
            if (mustReplan(solver, tmp, a)) {
                if (verbosity > 10)
                    cerr << "REPLANNING..." << endl;
                solver->solve(tmp);
                a = tmp->bestAction();
                if (tmp->deadEnd() || a == nullptr) {
                    if (verbosity > 1)
                      cerr << "DEAD END!! giving up :-( " << endl;
                    break;
                }
            }
            cost += MLProblem->cost(tmp, a);

            if (cost > mdplib::dead_end_cost
                    || tmp->cost() >= mdplib::dead_end_cost) {
                cerr << "Too long... giving up " << endl;
                break;
            }

            if (verbosity > 100)
                cerr << tmp->bestAction() << endl;
            tmp = mlsolvers::randomSuccessor(MLProblem, tmp, a);
        }
    }
    cerr << "Expected Cost: " << expectedCost / totalSuccess << endl;
    cerr << "Total Successes " << totalSuccess << "/" << nsims << endl;

    state_t::finalize();
    problem_t::unregister_use(problem);
    problem_t::clear();

    delete heuristic;
    delete solver;
}


text:
:global .video-js {
  display: block;
  vertical-align: top;
  box-sizing: border-box;
  color: #fff;
  position: relative;
  padding: 0;
  font-size: 10px;
  line-height: 1;
  font-weight: normal;
  font-style: normal;
  font-family: Arial, Helvetica, sans-serif;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none; }
  :global .video-js:-moz-full-screen {
    position: absolute; }
  :global .video-js:-webkit-full-screen {
    width: 100% !important;
    height: 100% !important; }

:global .video-js *,
:global .video-js *:before,
:global .video-js *:after {
  box-sizing: inherit; }

:global .video-js ul {
  font-family: inherit;
  font-size: inherit;
  line-height: inherit;
  list-style-position: outside;
  margin-left: 0;
  margin-right: 0;
  margin-top: 0;
  margin-bottom: 0; }

:global .video-js .vjs-tech {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%; }

:global body.vjs-full-window {
  padding: 0;
  margin: 0;
  height: 100%;
  overflow-y: auto; }

:global .vjs-full-window .video-js.vjs-fullscreen {
  position: fixed;
  overflow: hidden;
  z-index: 1000;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0; }

:global .video-js.vjs-fullscreen {
  width: 100% !important;
  height: 100% !important;
  padding-top: 0 !important; }

:global .video-js.vjs-fullscreen.vjs-user-inactive {
  cursor: none; }

:global .vjs-hidden {
  display: none !important; }

:global .vjs-disabled {
  opacity: 0.5;
  cursor: default; }

:global .video-js .vjs-offscreen {
  height: 1px;
  left: -9999px;
  position: absolute;
  top: 0;
  width: 1px; }

:global .vjs-lock-showing {
  display: block !important;
  opacity: 1;
  visibility: visible; }

:global .vjs-no-js {
  padding: 20px;
  color: #fff;
  background-color: #000;
  font-size: 18px;
  font-family: Arial, Helvetica, sans-serif;
  text-align: center;
  width: 300px;
  height: 150px;
  margin: 0px auto; }

:global .vjs-no-js a,
:global .vjs-no-js a:visited {
  color: #66A8CC; }

:global .vjs-poster {
  display: inline-block;
  vertical-align: middle;
  background-repeat: no-repeat;
  background-position: 50% 50%;
  background-size: contain;
  background-color: #000000;
  cursor: pointer;
  margin: 0;
  padding: 0;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  height: 100%; }

:global .vjs-poster img {
  display: block;
  vertical-align: middle;
  margin: 0 auto;
  max-height: 100%;
  padding: 0;
  width: 100%; }

:global .vjs-has-started .vjs-poster {
  display: none; }

:global .vjs-audio.vjs-has-started .vjs-poster {
  display: block; }

:global .vjs-using-native-controls .vjs-poster {
  display: none; }

:global .vjs-text-track-display {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  top: 0;
  pointer-events: none; }

:global .video-js .vjs-text-track {
  font-size: 17px;
  text-align: center;
  margin-bottom: 0.1em;
  background-color: #000;
  background-color: rgba(0, 0, 0, 0.5); }

:global .vjs-subtitles {
  color: #fff; }

:global .vjs-captions {
  color: #fc6; }

:global .vjs-tt-cue {
  display: block; }

@media print {
  :global .video-js > *:not(.vjs-tech):not(.vjs-poster) {
    visibility: hidden; } }

:global .vjs-resize-manager {
  border: none;
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Heystack\Core\DependencyInjection\CompilerPass;

use Heystack\Core\Services;
use Symfony\Component\DependencyInjection\Reference;

class EventDispatcherTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers \Heystack\Core\DependencyInjection\CompilerPass\EventDispatcher::process
     */
    public function testProcessHasDefinition()
    {
        $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerBuilder');
        $definition = $this->getMock('Symfony\Component\DependencyInjection\Definition');

        $definition
            ->expects($this->once())
            ->method('addMethodCall')
            ->with('addSubscriber', [new Reference('test')]);

        $container
            ->expects($this->once())
            ->method('hasDefinition')
            ->with(Services::EVENT_DISPATCHER)
            ->will($this->returnValue(true));

        $container
            ->expects($this->once())
            ->method('getDefinition')
            ->with(Services::EVENT_DISPATCHER)
            ->will($this->returnValue($definition));

        $container
            ->expects($this->once())
            ->method('findTaggedServiceIds')
            ->with(Services::EVENT_DISPATCHER.'.subscriber')
            ->will($this->returnValue([
                'test' => [true]
            ]));

        (new EventDispatcher())->process($container);
    }

    /**
     * @covers \Heystack\Core\DependencyInjection\CompilerPass\EventDispatcher::process
     */
    public function testProcessNoDefinition()
    {
        $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerBuilder');

        $container
            ->expects($this->once())
            ->method('hasDefinition')
            ->with(Services::EVENT_DISPATCHER)
            ->will($this->returnValue(false));

        $container
            ->expects($this->never())
            ->method('getDefinition');

        (new EventDispatcher())->process($container);
    }
}


text:
Python.LineParser
=================

LineParser


text:
package gov.nih.nci.ncicb.cadsr.common.persistence.dao.jdbc;

import gov.nih.nci.ncicb.cadsr.common.dto.InstructionTransferObject;
import gov.nih.nci.ncicb.cadsr.common.exception.DMLException;
import gov.nih.nci.ncicb.cadsr.common.persistence.dao.FormValidValueInstructionDAO;
import gov.nih.nci.ncicb.cadsr.common.resource.Instruction;

import java.util.List;

import javax.sql.DataSource;

public class JDBCFormValidValueInstructionDAOV2 extends JDBCInstructionDAOV2
  implements FormValidValueInstructionDAO {

	public JDBCFormValidValueInstructionDAOV2(DataSource dataSource) {
		super(dataSource);
	}

  /**
   * Creates a new form valid value instruction component (just the header info).
   *
   * @param valueInstr FormValidValueInstruction object
   *
   * @return int 1 - success, 0 - failure.
   *
   * @throws DMLException
   */

  public int createInstruction(Instruction vvInstr, String parentId)
    throws DMLException {
    return super.createInstruction(vvInstr,parentId,"VALUE_INSTR","VALUE_INSTRUCTION");
  }

  public List getInstructions(String vvID)
    throws DMLException {
    return super.getInstructions(vvID,"VALUE_INSTR");
  }

  /**
   * Test application
   */
  public static void main(String[] args) {
    //ServiceLocator locator = new SimpleServiceLocator();
    JDBCFormValidValueInstructionDAO test =
      new JDBCFormValidValueInstructionDAO(null);

    // test createValueInstructionComponent method.
    // for each test, change long name(preferred name generated from long name)
    try {
      Instruction formValidValueInstr =
        new InstructionTransferObject();

      formValidValueInstr.setVersion(new Float(2.31));
      formValidValueInstr.setLongName("Test Valid Value Instr Long Name 030204 1");
      formValidValueInstr.setPreferredDefinition("Test Valid Value Instr pref def");
      formValidValueInstr.setConteIdseq("99BA9DC8-2095-4E69-E034-080020C9C0E0");
      formValidValueInstr.setAslName("DRAFT NEW");
      formValidValueInstr.setCreatedBy("Hyun Kim");
      formValidValueInstr.setDisplayOrder(101);
      int res = test.createInstruction(formValidValueInstr,"D4AA6D94-3345-1C0E-E034-0003BA0B1A09");
      System.out.println("\n*****Create Valid Value Instruction Result 1: " + res);
    }
    catch (DMLException de) {
      de.printStackTrace();
    }
  }

}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Revis. gen. pl. (Leipzig) 2: 873 (1891)

#### Original name
Thozetia nivea Berk., 1881

### Remarks
null


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

          <title>Nonreflectable - omp4j - API reference - org.omp4j.tree.Nonreflectable</title>
          <meta name="description" content="Nonreflectable - omp4j - API reference - org.omp4j.tree.Nonreflectable" />
          <meta name="keywords" content="Nonreflectable omp4j API reference org.omp4j.tree.Nonreflectable" />
          <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

      <link href="../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" />
      <link href="../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" />

org.omp4j.tree

Nonreflectable

        trait

        Nonreflectable extends ClassTrait

The nonreflectable trait represents classes that can't be reflected.

          Linear Supertypes

ClassTrait, AnyRef, Any

          Known Subclasses

AnonymousClass, InnerInLocalClass, LocalClass

<input id="mbrsel-input" type="text" accesskey="/" />

              Ordering

Alphabetic

By inheritance

                Inherited

Nonreflectable

ClassTrait

AnyRef

Any

                Implicitly

by any2stringadd

by any2stringfmt

by any2ArrowAssoc

by any2Ensuring

Hide All

Show all

            Learn more about member selection

            Visibility

Public

All

Abstract Value Members

        abstract
        val

        THIS: OMPClass

Definition Classes

ClassTrait

        abstract
        val

        classBody: ClassBodyContext

Definition Classes

ClassTrait

        abstract
        val

        conf: Config

Definition Classes

ClassTrait

        abstract
        val

        ctx: ClassDeclarationContext

Definition Classes

ClassTrait

        abstract
        val

        cunit: CompilationUnitContext

Definition Classes

ClassTrait

        abstract
        val

        name: String

Definition Classes

ClassTrait

        abstract
        val

        ompFile: OMPFile

Definition Classes

ClassTrait

        abstract
        def

        packageNamePrefix(pt: ParserRuleContext = ctx): String

Definition Classes

ClassTrait

        abstract
        val

        parent: OMPClass

Definition Classes

ClassTrait

        abstract
        val

        parser: Java8Parser

Definition Classes

ClassTrait

Concrete Value Members

        final
        def

        !=(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        final
        def

        !=(arg0: Any): Boolean

Definition Classes

Any

        final
        def

        ##(): Int

Definition Classes

AnyRef → Any

        def

        +(other: String): String

Implicit information

            This member is added by an implicit conversion from Nonreflectable to
            StringAdd performed by method any2stringadd in scala.Predef.

Definition Classes

StringAdd

        def

        ->[B](y: B): (Nonreflectable, B)

Implicit information

            This member is added by an implicit conversion from Nonreflectable to
            ArrowAssoc[Nonreflectable] performed by method any2ArrowAssoc in scala.Predef.

Definition Classes

ArrowAssoc

Annotations

                @inline()

        final
        def

        ==(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        final
        def

        ==(arg0: Any): Boolean

Definition Classes

Any

        lazy val

        FQN: String

Placeholder for debug purposes

Placeholder for debug purposes

Definition Classes

Nonreflectable → ClassTrait

        final
        def

        asInstanceOf[T0]: T0

Definition Classes

Any

        def

        clone(): AnyRef

Attributes

protected[java.lang]

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

        def

        ensuring(cond: (Nonreflectable) ⇒ Boolean, msg: ⇒ Any): Nonreflectable

Implicit information

            This member is added by an implicit conversion from Nonreflectable to
            Ensuring[Nonreflectable] performed by method any2Ensuring in scala.Predef.

Definition Classes

Ensuring

        def

        ensuring(cond: (Nonreflectable) ⇒ Boolean): Nonreflectable

Implicit information

            This member is added by an implicit conversion from Nonreflectable to
            Ensuring[Nonreflectable] performed by method any2Ensuring in scala.Predef.

Definition Classes

Ensuring

        def

        ensuring(cond: Boolean, msg: ⇒ Any): Nonreflectable

Implicit information

            This member is added by an implicit conversion from Nonreflectable to
            Ensuring[Nonreflectable] performed by method any2Ensuring in scala.Predef.

Definition Classes

Ensuring

        def

        ensuring(cond: Boolean): Nonreflectable

Implicit information

            This member is added by an implicit conversion from Nonreflectable to
            Ensuring[Nonreflectable] performed by method any2Ensuring in scala.Predef.

Definition Classes

Ensuring

        final
        def

        eq(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        def

        equals(arg0: Any): Boolean

Definition Classes

AnyRef → Any

        def

        finalize(): Unit

Attributes

protected[java.lang]

Definition Classes

AnyRef

Annotations

                @throws(

      classOf[java.lang.Throwable]
    )

        def

        findAllFields: Array[OMPVariable]

Find all fields syntactically (use only for allFields initialization)

Find all fields syntactically (use only for allFields initialization)

returns

Array of OMPVariable

        def

        findAllFieldsRecursively(clazz: Class[_], firstRun: Boolean): Array[OMPVariable]

Recursively build array of class fields

Recursively build array of class fields

clazz

fields of this class are returned

firstRun

If set to True, private Fields will be included (but not parents ones)

returns

Array of Fields

Attributes

protected

Definition Classes

ClassTrait

        def

        findFieldsSyntactically: Array[OMPVariable]

Apply syntax analysis

        def

        findInheritedFields(superName: String): Array[OMPVariable]

Fetch all inherited fields.

Fetch all inherited fields.

Firstly by using variable, secondly seeking implemented classes (local, other) and finally via reflection API.

superName

superclass name

returns

array of fields

        def

        formatted(fmtstr: String): String

Implicit information

            This member is added by an implicit conversion from Nonreflectable to
            StringFormat performed by method any2stringfmt in scala.Predef.

Definition Classes

StringFormat

Annotations

                @inline()

        final
        def

        getClass(): Class[_]

Definition Classes

AnyRef → Any

        def

        hashCode(): Int

Definition Classes

AnyRef → Any

        val

        innerClasses: List[OMPClass]

Inner classes of type InnerInLocalClass

Inner classes of type InnerInLocalClass

Definition Classes

Nonreflectable → ClassTrait

        final
        def

        isInstanceOf[T0]: Boolean

Definition Classes

Any

        val

        localClasses: List[OMPClass]

List of local classes (first level only)

List of local classes (first level only)

Definition Classes

ClassTrait

        final
        def

        ne(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        final
        def

        notify(): Unit

Definition Classes

AnyRef

        final
        def

        notifyAll(): Unit

Definition Classes

AnyRef

        final
        def

        synchronized[T0](arg0: ⇒ T0): T0

Definition Classes

AnyRef

        def

        toString(): String

Definition Classes

AnyRef → Any

        final
        def

        wait(): Unit

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

        final
        def

        wait(arg0: Long, arg1: Int): Unit

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

        final
        def

        wait(arg0: Long): Unit

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

        def

        →[B](y: B): (Nonreflectable, B)

Implicit information

            This member is added by an implicit conversion from Nonreflectable to
            ArrowAssoc[Nonreflectable] performed by method any2ArrowAssoc in scala.Predef.

Definition Classes

ArrowAssoc

Shadowed Implicit Value Members

        val

        self: Any

Implicit information

            This member is added by an implicit conversion from Nonreflectable to
            StringAdd performed by method any2stringadd in scala.Predef.

Shadowing

This implicitly inherited member is ambiguous. One or more implicitly inherited members have similar signatures, so calling this member may produce an ambiguous implicit conversion compiler error.
To access this member you can use a type ascription:

(nonreflectable: StringAdd).self

Definition Classes

StringAdd

        val

        self: Any

Implicit information

            This member is added by an implicit conversion from Nonreflectable to
            StringFormat performed by method any2stringfmt in scala.Predef.

Shadowing

This implicitly inherited member is ambiguous. One or more implicitly inherited members have similar signatures, so calling this member may produce an ambiguous implicit conversion compiler error.
To access this member you can use a type ascription:

(nonreflectable: StringFormat).self

Definition Classes

StringFormat

Deprecated Value Members

        def

        x: Nonreflectable

Implicit information

            This member is added by an implicit conversion from Nonreflectable to
            ArrowAssoc[Nonreflectable] performed by method any2ArrowAssoc in scala.Predef.

Shadowing

This implicitly inherited member is ambiguous. One or more implicitly inherited members have similar signatures, so calling this member may produce an ambiguous implicit conversion compiler error.
To access this member you can use a type ascription:

(nonreflectable: ArrowAssoc[Nonreflectable]).x

Definition Classes

ArrowAssoc

Annotations

                @deprecated

Deprecated

(Since version 2.10.0) Use leftOfArrow instead

        def

        x: Nonreflectable

Implicit information

            This member is added by an implicit conversion from Nonreflectable to
            Ensuring[Nonreflectable] performed by method any2Ensuring in scala.Predef.

Shadowing

This implicitly inherited member is ambiguous. One or more implicitly inherited members have similar signatures, so calling this member may produce an ambiguous implicit conversion compiler error.
To access this member you can use a type ascription:

(nonreflectable: Ensuring[Nonreflectable]).x

Definition Classes

Ensuring

Annotations

                @deprecated

Deprecated

(Since version 2.10.0) Use resultOfEnsuring instead

Inherited from ClassTrait

Inherited from AnyRef

Inherited from Any

Inherited by implicit conversion any2stringadd from
                Nonreflectable to StringAdd

Inherited by implicit conversion any2stringfmt from
                Nonreflectable to StringFormat

Inherited by implicit conversion any2ArrowAssoc from
                Nonreflectable to ArrowAssoc[Nonreflectable]

Inherited by implicit conversion any2Ensuring from
                Nonreflectable to Ensuring[Nonreflectable]

Ungrouped


text:
<?xml version="1.0"?>
<!--

-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <update handle="multishipping_checkout"/>
    <body>
        <referenceBlock name="page.main.title">
            <action method="setPageTitle">
                <argument name="label" translate="true" xsi:type="string">Change Billing Address</argument>
            </action>
        </referenceBlock>
        <referenceContainer name="content">
            <block class="Magento\Multishipping\Block\Checkout\Address\Select" name="checkout_address_select" template="checkout/address/select.phtml" cacheable="false"/>
        </referenceContainer>
    </body>
</page>


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

    <groupId>org.runmyprocess.sec</groupId>
    <artifactId>rmp-sec-ftp</artifactId>
    <version>1.0</version>
    <packaging>jar</packaging>

    <properties>
        <!-- Explicitly declaring the source encoding eliminates the following message: -->
        <!-- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent! -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.runmyprocess</groupId>
            <artifactId>json</artifactId>
            <version>1.6.4</version>
        </dependency>
        <dependency>
            <groupId>org.runmyprocess.sec</groupId>
            <artifactId>rmp-sec-sdk</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.8</version>
        </dependency>
        <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>2.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.51</version>
        </dependency>
        <dependency>
            <groupId>commons-vfs</groupId>
            <artifactId>commons-vfs</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>org.runmyprocess</groupId>
            <artifactId>json</artifactId>
            <version>1.8.6</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <encoding>utf8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.3.1</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.1</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <artifactSet>
                                <excludes>
                                    <exclude>junit:junit</exclude>
                                </excludes>
                            </artifactSet>
                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>org.runmyprocess.sec.FTPHandler</mainClass>
                                    <manifestEntries>
                                        <Implementation-Title>FTPAdapter</Implementation-Title>
                                        <Implementation-Version>SDC 1.3-rc0 Built: 06-24-2010 02:44</Implementation-Version>
                                        <Implementation-Vendor>RunMyProcess</Implementation-Vendor>
                                    </manifestEntries>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <descriptors>
                        <descriptor>src/main/assembly/install.xml</descriptor>
                    </descriptors>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase> <!-- append to the packaging phase. -->
                        <goals>
                            <goal>attached</goal> <!-- goals == mojos -->
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


text:
angular.module('app.menu', ['app.modal'])

.controller('MenuController', function($scope, $rootScope, $timeout, $window, ModalService) {
  this.update = function() {
    var settings = $window.app.editor.settings;

    // UPDATE LABELS ON THE MENU
    $timeout(function() {
      $scope.$apply(function() {
        for (var k in settings._dict) {
          if (k.indexOf('key_') == 0) {
            var value = settings.get(k);
            $scope[k] = value;
          }
        }
      });
    }, 0, false);

    // UPDATE CALLBACKS
    $window.keyboard(settings.get('key_copy'), function(e) {$scope.onButtonCopy(e)});
    $window.keyboard(settings.get('key_cut'), function(e) {$scope.onButtonCut(e)});
    $window.keyboard(settings.get('key_paste'), function(e) {$scope.onButtonPaste(e)});
    $window.keyboard(settings.get('key_duplicate'), function(e) {$scope.onButtonDuplicate(e)});
    $window.keyboard(settings.get('key_remove'), function(e) {$scope.onButtonRemove(e)});
    $window.keyboard(settings.get('key_organize'), function(e) {$scope.onButtonAutoOrganize(e)});
    $window.keyboard(settings.get('key_zoom_in'), function(e) {$scope.onButtonZoomIn(e)});
    $window.keyboard(settings.get('key_zoom_out'), function(e) {$scope.onButtonZoomOut(e)});
    $window.keyboard(settings.get('key_select_all'), function(e) {$scope.onButtonSelectAll(e)});
    $window.keyboard(settings.get('key_deselect_all'), function(e) {$scope.onButtonDeselectAll(e)});
    $window.keyboard(settings.get('key_invert_selection'), function(e) {$scope.onButtonInvertSelection(e)});
    $window.keyboard(settings.get('key_new_project'), function(e) {$scope.onButtonNewProject(e)});
    $window.keyboard(settings.get('key_open_project'), function(e) {$scope.onButtonOpenProject(e)});
    $window.keyboard(settings.get('key_new_tree'), function(e) {$scope.onButtonNewTree(e)});
    $window.keyboard(settings.get('key_new_node'), function(e) {$scope.onButtonNewNode(e)});
    $window.keyboard(settings.get('key_open_tree'), function(e) {$scope.onButtonOpenTree(e)});
    $window.keyboard(settings.get('key_save_tree'), function(e) {$scope.onButtonSaveTree(e)});
    $window.keyboard(settings.get('key_save_as'), function(e) {$scope.onButtonSaveAs(e)});
  }
  this.update();
  $window.app.editor.on('shortcutsChanged', this.update, this);

  // CALLBACKS ----------------------------------------------------------------
  // this.onButtonNewProject = function(e) {}
  // ...
  $scope.onButtonNewTree = function(e) {
    if (e) e.preventDefault();
    $rootScope.$broadcast('onButtonNewTree');
    return false;
  }
  $scope.onButtonOpenTree = function(e) {
    if (e) e.preventDefault();

    dialog.showOpenDialog({
      title: "Open Behavior File",
      filters : [
        { name: "Behavior", extensions: ['behavior']},
        { name: "All files", extensions: ['*']}
      ]
    }, function(filenames) {
      if (filenames) {
        var filename = filenames[0];
        $window.app.editor.openTreeFile(filenames[0]);
      }
    });

    return false;
  }
  $scope.onButtonSaveTree = function(e) {
    if (e) e.preventDefault();

    $window.app.editor.saveTree();
    return false;
  }
  $scope.onButtonSaveAs = function(e) {
    if (e) e.preventDefault();

    $window.app.editor.tree.path = "";
    $window.app.editor.saveTree();
    return false;
  }
  $scope.onButtonImportNodes = function(e) {
    if (e) e.preventDefault();

    var editor = $window.app.editor;
    dialog.showOpenDialog({
      title: "Import nodes",
      filters : [
        { name: "JSON", extensions: ['json']},
        { name: "All files", extensions: ['*']}
      ]
    }, function(filenames) {
      if (filenames) {
        var filename = filenames[0];
        fs.readFile(filename, function(err, data){
          if (err) throw err;
          $window.app.editor.importNodes(data);

          editor.trigger('notification', name, {
            level: 'success',
            message: 'Imported Nodes'
          });
        });
      }
    });
    return false;
  }
  $scope.onButtonExportNodes = function(e) {
    if (e) e.preventDefault();
    var editor = $window.app.editor;
    var nodes = editor.exportNodes();
    if (editor.project == null) {
      editor.trigger('notification', name, {
        level: 'error',
        message: 'Cannot export nodes. No project loaded.'
      });
    }

    for (category in nodes) {
      fs.writeFileSync(path.join(editor.project.nodesPath, category + ".nodes"), nodes[category]);
    }
    return false;
  }

  $scope.onButtonNewProject = function(e) {
    if (e) e.preventDefault();
    dialog.showOpenDialog({
      title: "Select path for nodes",
      filters : [
      ],
      properties: [ "openDirectory" ]
    }, function(filenames) {
      if (filenames) {
        var project = new b3editor.Project();
        project.nodesPath = filenames[0];

        dialog.showSaveDialog({
          title: "Save project",
          filters : [
            { name: "Behavior project", extensions: ['.behavior-project']}
          ]
        }, function(filename) {
          project.fileName = filename;

          var editor = $window.app.editor;
          fs.writeFile(filename, project.save(), function(err){
            if (err) throw err;

            editor.loadProject(project);
          });
        });
      }
    });
    return false;
  }

  $scope.onButtonOpenProject = function(e) {
    if (e) e.preventDefault();

    var editor = $window.app.editor;
    dialog.showOpenDialog({
      title: "Open project",
      filters : [
        { name: "Behavior project", extensions: ['behavior-project']},
        { name: "All files", extensions: ['*']}
      ]
    }, function(filenames) {
      if (filenames) {
        var filename = filenames[0];
        fs.readFile(filename, function(err, data){
          if (err) throw err;
          var project = b3editor.Project.load(filename, data);
          editor.loadProject(project);
        });
      }
    });
    return false;
  }

  $scope.onButtonNewNode = function(e) {
    if (e) e.preventDefault();
    $rootScope.$broadcast('onButtonNewNode');
    return false;
  }
  $scope.onButtonCopy = function(e) {
    if (e) e.preventDefault();
    $window.app.editor.copy();
  }
  $scope.onButtonCut = function(e) {
    if (e) e.preventDefault();
    $window.app.editor.cut();
  }
  $scope.onButtonPaste = function(e) {
    if (e) e.preventDefault();
    $window.app.editor.paste();
  }
  $scope.onButtonDuplicate = function(e) {
    if (e) e.preventDefault();
    $window.app.editor.duplicate();
  }
  $scope.onButtonRemove = function(e) {
    if (e) e.preventDefault();
    $window.app.editor.remove();
  }
  $scope.onButtonRemoveAllConnections = function(e) {
    if (e) e.preventDefault();
    $window.app.editor.removeConnections();
  }
  $scope.onButtonRemoveInConnections = function(e) {
    if (e) e.preventDefault();
    $window.app.editor.removeInConnections();
  }
  $scope.onButtonRemoveOutConnections = function(e) {
    if (e) e.preventDefault();
    $window.app.editor.removeOutConnections();
  }
  $scope.onButtonAutoOrganize = function(e) {
    if (e) e.preventDefault();
    $window.app.editor.organize();
  }
  $scope.onButtonZoomIn = function(e) {
    if (e) e.preventDefault();
    $window.app.editor.zoomIn();
  }
  $scope.onButtonZoomOut = function(e) {
    if (e) e.preventDefault();
    $window.app.editor.zoomOut();
  }
  $scope.onButtonSelectAll = function(e) {
    if (e) e.preventDefault();
    $window.app.editor.selectAll();
  }
  $scope.onButtonDeselectAll = function(e) {
    if (e) e.preventDefault();
    $window.app.editor.deselectAll();
  }
  $scope.onButtonInvertSelection = function(e) {
    if (e) e.preventDefault();
    $window.app.editor.invertSelection();
  }
  // --------------------------------------------------------------------------

})

.directive('menu', function() {
  return {
    restrict: 'E',
    controller: 'MenuController',
    templateUrl: 'app/menu/menu.html'
  }
});


text:
<?php

namespace Alphatrader\ApiBundle\Model;

use JMS\Serializer\Annotation;

/**
 * Class BondTrait
 *
 * @package                            Alphatrader\ApiBundle\Model
 * @Annotation\ExclusionPolicy("none")
 */
trait BondTrait
{
    /**
     * @Annotation\Type("string")
     * @Annotation\SerializedName("id")
     */
    private $id;

    /**
     * @Annotation\Type("float")
     * @Annotation\SerializedName("faceValue")
     */
    private $faceValue;

    /**
     * @Annotation\Type("float")
     * @Annotation\SerializedName("interestRate")
     */
    private $interestRate;

    /**
     * @Annotation\Type("integer")
     * @Annotation\SerializedName("issueDate")
     */
    private $issueDate;

    /**
     * @Annotation\Type("integer")
     * @Annotation\SerializedName("maturityDate")
     */
    private $maturityDate;

    /**
     * @Annotation\Type("string")
     * @Annotation\SerializedName("name")
     */
    private $name;

    /**
     * @Annotation\Type("Alphatrader\ApiBundle\Model\Listing")
     * @Annotation\SerializedName("repurchaseListing")
     */
    private $repurchaseListing;

    /**
     * @Annotation\Type("Alphatrader\ApiBundle\Model\PriceSpread")
     * @Annotation\SerializedName("priceSpread")
     */
    private $priceSpread;

    /**
     * @Annotation\Type("Alphatrader\ApiBundle\Model\Listing")
     * @Annotation\SerializedName("listing")
     */
    private $listing;

    /**
     * @Annotation\Type("float")
     * @Annotation\SerializedName("volume")
     */
    private $volume;

    /**
     * @return mixed
     */
    public function getFaceValue()
    {
        return $this->faceValue;
    }

    /**
     * @param mixed $faceValue
     */
    public function setFaceValue($faceValue)
    {
        $this->faceValue = $faceValue;
    }

    /**
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param mixed $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * @return mixed
     */
    public function getInterestRate()
    {
        return $this->interestRate;
    }

    /**
     * @param mixed $interestRate
     */
    public function setInterestRate($interestRate)
    {
        $this->interestRate = $interestRate;
    }

    /**
     * @return mixed
     */
    public function getIssueDate()
    {
        return $this->issueDate;
    }

    /**
     * @param mixed $issueDate
     */
    public function setIssueDate($issueDate)
    {
        $this->issueDate = $issueDate;
    }

    /**
     * @return mixed
     */
    public function getMaturityDate()
    {
        return $this->maturityDate;
    }

    /**
     * @param mixed $maturityDate
     */
    public function setMaturityDate($maturityDate)
    {
        $this->maturityDate = $maturityDate;
    }

    /**
     * @return mixed
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param mixed $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }

    /**
     * @return Listing
     */
    public function getRepurchaseListing()
    {
        return $this->repurchaseListing;
    }

    /**
     * @param Listing $repurchaseListing
     */
    public function setRepurchaseListing($repurchaseListing)
    {
        $this->repurchaseListing = $repurchaseListing;
    }

    /**
     * @return mixed
     */
    public function getVolume()
    {
        return $this->volume;
    }

    /**
     * @param mixed $volume
     */
    public function setVolume($volume)
    {
        $this->volume = $volume;
    }

    /**
     * @return Listing
     */
    public function getListing()
    {
        return $this->listing;
    }

    /**
     * @param Listing $listing
     */
    public function setListing($listing)
    {
        $this->listing = $listing;
    }

    /**
     * @return PriceSpread
     */
    public function getPriceSpread()
    {
        return $this->priceSpread;
    }

    /**
     * @param PriceSpread $priceSpread
     */
    public function setPriceSpread($priceSpread)
    {
        $this->priceSpread = $priceSpread;
    }

    /**
     * @SuppressWarnings("unused")
     * @Annotation\PostDeserialize
     */
    private function afterDeserialization()
    {
        if ($this->issueDate !== null) {
            $startdate = substr($this->issueDate, 0, 10) . '.' . substr($this->issueDate, 10);
            $micro = sprintf("%06d", ($startdate - floor($startdate)) * 1000000);
            $date = new \DateTime(date('Y-m-d H:i:s.' . $micro, $startdate));
            $this->issueDate = $date;
        }

        if ($this->maturityDate !== null) {
            $enddate = substr($this->maturityDate, 0, 10) . '.' . substr($this->maturityDate, 10);
            $micro = sprintf("%06d", ($enddate - floor($enddate)) * 1000000);
            $date = new \DateTime(date('Y-m-d H:i:s.' . $micro, $enddate));
            $this->maturityDate = $date;
        }
    }
}


text:
package io.quantumdb.core.schema.operations;

import static com.google.common.base.Preconditions.checkArgument;

import com.google.common.base.Strings;
import io.quantumdb.core.schema.definitions.ForeignKey.Action;
import io.quantumdb.core.utils.RandomHasher;
import lombok.AccessLevel;
import lombok.Data;
import lombok.Setter;

@Data
@Setter(AccessLevel.NONE)
public class AddForeignKey implements SchemaOperation {

	private final String referringTableName;
	private final String[] referringColumnNames;

	private String name;
	private Action onDelete;
	private Action onUpdate;

	private String referencedTableName;
	private String[] referencedColumnNames;

	AddForeignKey(String table, String... columns) {
		checkArgument(!Strings.isNullOrEmpty(table), "You must specify a 'table'.");
		checkArgument(columns != null && columns.length > 0, "You must specify at least one 'column'.");

		this.name = "fk_" + RandomHasher.generateHash();
		this.onDelete = Action.NO_ACTION;
		this.onUpdate= Action.NO_ACTION;
		this.referringTableName = table;
		this.referringColumnNames = columns;
	}

	public AddForeignKey named(String name) {
		this.name = name;
		return this;
	}

	public AddForeignKey onDelete(Action action) {
		this.onDelete = action;
		return this;
	}

	public AddForeignKey onUpdate(Action action) {
		this.onUpdate = action;
		return this;
	}

	public AddForeignKey referencing(String table, String... columns) {
		checkArgument(!Strings.isNullOrEmpty(table), "You must specify a 'table'.");
		checkArgument(columns != null && columns.length > 0, "You must specify at least one 'column'.");
		checkArgument(columns.length == referringColumnNames.length, "The number of columns is mismatched.");

		this.referencedTableName = table;
		this.referencedColumnNames = columns;
		return this;
	}

}


text:
package io.compgen.ngsutils.cli.vcf;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

import io.compgen.cmdline.annotation.Command;
import io.compgen.cmdline.annotation.Exec;
import io.compgen.cmdline.annotation.Option;
import io.compgen.cmdline.annotation.UnnamedArg;
import io.compgen.cmdline.exceptions.CommandArgumentException;
import io.compgen.cmdline.impl.AbstractOutputCommand;
import io.compgen.common.IterUtils;
import io.compgen.common.SetBuilder;
import io.compgen.ngsutils.NGSUtils;
import io.compgen.ngsutils.vcf.VCFContigDef;
import io.compgen.ngsutils.vcf.VCFHeader;
import io.compgen.ngsutils.vcf.VCFReader;
import io.compgen.ngsutils.vcf.VCFRecord;
import io.compgen.ngsutils.vcf.VCFWriter;

@Command(name="vcf-chrfix", desc="Changes the reference (chrom) format (Ensembl/UCSC)", category="vcf")
public class VCFChrFix extends AbstractOutputCommand {
	private String filename = "-";
	private boolean ucsc = false;
    private boolean ensembl = false;
    private boolean primary = false;
    private Set<String> keepContigs = null;

    @Option(desc="UCSC references (chr1, chr2, etc...)", name="ucsc")
    public void setUCSC(boolean val) {
        this.ucsc = val;
    }

    @Option(desc="Ensembl references (1, 2, etc...)", name="ensembl")
    public void setEnsembl(boolean val) {
        this.ensembl = val;
    }

    @Option(desc="Only keep primary human contigs (1,2,3,...,22,X,Y,M)", name="primary-human")
    public void setPrimary(boolean val) {
        this.primary = val;
    }

    @Option(desc="Only keep these contigs/chrom (comma separated list)", name="contigs")
    public void setContigs(String val) {
        this.keepContigs = new HashSet<String>();
        for (String v: val.split(",")) {
            this.keepContigs.add(v.trim());
        }
    }

    @UnnamedArg(name = "input.vcf", required=true)
    public void setFilename(String filename) throws CommandArgumentException {
    	this.filename = filename;
    }

	@Exec
	public void exec() throws Exception {
		if (!ucsc && !ensembl && !primary && keepContigs == null) {
    		throw new CommandArgumentException("No changers specified");
		}

		if (ucsc && ensembl) {
    		throw new CommandArgumentException("You must set either --ucsc or --ensembl, not both.");
		}

		VCFReader reader;
		if (filename.equals("-")) {
			reader = new VCFReader(System.in);
		} else {
			reader = new VCFReader(filename);
		}

		VCFHeader header = reader.getHeader();

		if (ucsc) {
    		for (String contig: new ArrayList<String>(header.getContigNames())) {
                if (!contig.startsWith("chr")) {
                    String newid;
                    if (contig.equals("MT")) {
                        newid = "chrM";
                    } else {
                        newid = "chr"+contig;
                    }

                    long len = header.getContigLength(contig);
                    header.removeContig(contig);
                    header.addContig(VCFContigDef.build(newid, len));
                }
    		}
		}

		if (ensembl) {
            for (String contig: new ArrayList<String>(header.getContigNames())) {
                if (contig.startsWith("chr")) {
                    String newid;
                    if (contig.equals("chrM")) {
                        newid = "MT";
                    } else {
                        newid = contig.substring(3);
                    }

                    long len = header.getContigLength(contig);
                    header.removeContig(contig);
                    header.addContig(VCFContigDef.build(newid, len));
                }
    		}
   		}

		if (primary || keepContigs!= null) {
		      for (String contig: new ArrayList<String>(header.getContigNames())) {
                if (!keepChrom(contig)) {
                    header.removeContig(contig);
                    continue;
                }
		      }
		}

		header.addLine("##ngsutilsj_vcf_chrfixCommand="+NGSUtils.getArgs());
		if (!header.contains("##ngsutilsj_vcf_chrfixVersion="+NGSUtils.getVersion())) {
		    header.addLine("##ngsutilsj_vcf_chrfixVersion="+NGSUtils.getVersion());
		}

		VCFWriter writer = new VCFWriter(out, header);
//		VCFWriter writer;
//		if (out.equals("-")) {
//			writer = new VCFWriter(System.out, header);
//		} else {
//			writer = new VCFWriter(out, header);
//		}

		for (VCFRecord rec: IterUtils.wrap(reader.iterator())) {
			if (ucsc && !rec.getChrom().startsWith("chr")) {
				if (rec.getChrom().equals("MT")) {
	                rec.setChrom("chrM");
				} else {
	                rec.setChrom("chr"+rec.getChrom());
				}

			} else if (ensembl && rec.getChrom().startsWith("chr")) {
                if (rec.getChrom().equals("chrM")) {
                    rec.setChrom("MT");
                } else {
                    rec.setChrom(rec.getChrom().substring(3));
                }
			}

			if (keepChrom(rec.getChrom())) {
			    writer.write(rec);
			}
		}
		reader.close();
		writer.close();
	}

	Set<String> humanContigs = new SetBuilder<String>()
	        .add("1")
	        .add("2")
	        .add("3")
	        .add("4")
	        .add("5")
	        .add("6")
	        .add("7")
	        .add("8")
	        .add("9")
	        .add("10")
            .add("11")
            .add("12")
            .add("13")
            .add("14")
            .add("15")
            .add("16")
            .add("17")
            .add("18")
            .add("19")
            .add("20")
            .add("21")
            .add("22")
            .add("X")
            .add("Y")
            .add("M")
            .add("MT")
            .build();

    private boolean keepChrom(String chrom) {
        if (!primary && keepContigs == null) {
            return true;
        }

        if (keepContigs != null) {
            return keepContigs.contains(chrom);
        }

        String sub;
        if (chrom.startsWith("chr")) {
            sub = chrom.substring(3);
        } else {
            sub = chrom;
        }

        return humanContigs.contains(sub);
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="cmov.stock.stock_portfolio"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="18" />

    <uses-permission android:name="android.permission.INTERNET" />

    <uses-feature
        android:glEsVersion="0x00010000"
        android:required="true" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="cmov.stock_portfolio.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="cmov.stock_portfolio.TickEditActivity"></activity>
    </application>

</manifest>


text:
using System.Composition;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;

namespace Microsoft.QualityGuidelines.Analyzers
{
    /// <summary>
    /// CA2000: Dispose Objects Before Losing Scope
    /// </summary>
    [ExportCodeFixProvider(LanguageNames.CSharp), Shared]
    public sealed class CSharpDisposeObjectsBeforeLosingScopeFixer : DisposeObjectsBeforeLosingScopeFixer
    {
    }
}


text:
namespace gloperate_text
{

glm::vec2 labelOrigin(RelativeLabelPosition position, const glm::vec2 & origin, const glm::vec2 & extent)
{
    switch (position)
    {
    case RelativeLabelPosition::UpperRight: return origin;
    case RelativeLabelPosition::UpperLeft:  return origin - glm::vec2(extent.x, 0.f);
    case RelativeLabelPosition::LowerLeft:  return origin - extent;
    case RelativeLabelPosition::LowerRight: return origin - glm::vec2(0.f, extent.y);
    case RelativeLabelPosition::Hidden:     return origin;
    default: assert(false);
    }
}

RelativeLabelPosition relativeLabelPosition(const glm::vec2 & offset, const glm::vec2 & extent)
{
    const auto midpointOffset = offset + extent / 2.f;
    if (midpointOffset.x > 0 && midpointOffset.y > 0) return RelativeLabelPosition::UpperRight;
    if (midpointOffset.x < 0 && midpointOffset.y > 0) return RelativeLabelPosition::UpperLeft;
    if (midpointOffset.x < 0 && midpointOffset.y < 0) return RelativeLabelPosition::LowerLeft;
    if (midpointOffset.x > 0 && midpointOffset.y < 0) return RelativeLabelPosition::LowerRight;
    assert(false);
}

} // namespace gloperate_text


text:
package org.sharedhealth.datasense.model.fhir;

import org.hl7.fhir.dstu3.model.Reference;
import org.sharedhealth.datasense.model.Encounter;

public class EncounterReference {
    private Encounter value;
    private Reference encounterReference;
    private org.hl7.fhir.dstu3.model.Encounter resource;

    public EncounterReference(Reference encounterReference,
                              org.hl7.fhir.dstu3.model.Encounter encounter) {
        this.encounterReference = encounterReference;
        this.resource = encounter;
    }

    public void setValue(Encounter value) {
        this.value = value;
    }

    public Encounter getValue() {
        return value;
    }

    public String getEncounterId() {
        return this.getValue().getEncounterId();
    }

    public org.hl7.fhir.dstu3.model.Encounter getResource() {
        return resource;
    }
}


text:
@interface WETouchableView()

@property (nonatomic, strong) WEBlockingGestureRecognizer *blockingGestureRecognizer;

@end

@interface WETouchableView(Private)

- (BOOL)isPassthroughView:(UIView *)v;

@end

@implementation WETouchableView {
    BOOL _testHits;
    BOOL _gestureBlockingEnabled;
}

- (id)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {
        WEBlockingGestureRecognizer *gr = [[WEBlockingGestureRecognizer alloc] init];
        [self addGestureRecognizer:gr];
        gr.enabled = YES;
        self.blockingGestureRecognizer = gr;
        self.backgroundColor = [UIColor clearColor];

        self.fillView = [[UIView alloc] init];
        self.fillView.backgroundColor = [UIColor clearColor];
        [self addSubview:self.fillView];

        _gestureBlockingEnabled = YES;
    }
    return self;
}

- (void)setGestureBlockingEnabled:(BOOL)gestureBlockingEnabled {
    if (_gestureBlockingEnabled != gestureBlockingEnabled) {
        _gestureBlockingEnabled = gestureBlockingEnabled;
        self.blockingGestureRecognizer.enabled = gestureBlockingEnabled;
    }
}

- (BOOL)gestureBlockingEnabled {
    return _gestureBlockingEnabled;
}

- (void)setFillView:(UIView *)fillView {
    if (_fillView != fillView) {
        [_fillView removeFromSuperview];
        _fillView = fillView;
        if (_fillView != nil) {
            [self addSubview:_fillView];
            [self setNeedsLayout];
        }
    }
}

- (void)setFillColor:(UIColor *)fillColor {
    self.fillView.backgroundColor = fillColor;
}

- (void)layoutSubviews {
    [super layoutSubviews];

    CGRect fillRect = self.bounds;
    if ([self.delegate respondsToSelector:@selector(fillRectForView:)]) {
        fillRect = [self.delegate fillRectForView:self];
    }
    self.fillView.frame = fillRect;
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    if (_testHits) {
        return nil;
    } else if (_touchForwardingDisabled) {
        return self;
    } else {
        UIView *hitView = [super hitTest:point withEvent:event];

        if (hitView == self || hitView == self.fillView) {
            //Test whether any of the passthrough views would handle this touch
            _testHits = YES;
            UIView *superHitView = [self.superview hitTest:point withEvent:event];
            _testHits = NO;

            if ([self isPassthroughView:superHitView]) {
                hitView = superHitView;
            }
        }

        return hitView;
    }
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    if ([self.delegate respondsToSelector:@selector(viewWasTouched:)]) {
        [self.delegate viewWasTouched:self];
    }
}

@end

@implementation WETouchableView(Private)

- (BOOL)isPassthroughView:(UIView *)v {

    if (v == nil) {
        return NO;
    }

    if ([_passthroughViews containsObject:v]) {
        return YES;
    }

    return [self isPassthroughView:v.superview];
}

@end


text:
'''
Test Steps:
    1. disconnect slave mn host network 10s and recover.
    2. check vip has not been changed.
    3. create vm to validate everything goes on well.

@author: SyZhao
'''

import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_state as test_state
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.operations.node_operations as node_ops
import zstackwoodpecker.zstack_test.zstack_test_vm as test_vm_header
import test_stub
import time
import os

vm = None
non_vip_s_vm_cfg_lst = None

def test():
    global vm
    global non_vip_s_vm_cfg_lst

    vip_s_vm_cfg_lst = test_stub.get_s_vm_cfg_lst_vip_bind(test_lib.all_scenario_config, test_lib.scenario_file)
    if len(vip_s_vm_cfg_lst) != 1:
        test_util.test_fail('vip has been running on %d host(s)' % len(vip_s_vm_cfg_lst))

    non_vip_s_vm_cfg_lst = test_stub.get_s_vm_cfg_lst_vip_not_bind(test_lib.all_scenario_config, test_lib.scenario_file)
    if len(non_vip_s_vm_cfg_lst) != 1:
        test_util.test_fail('find %d non vip mn hosts.' % len(non_vip_s_vm_cfg_lst))

    test_util.test_logger("disconnect host [%s]" % (vip_s_vm_cfg_lst[0].ip_))
    test_stub.down_host_network(non_vip_s_vm_cfg_lst[0].ip_, test_lib.all_scenario_config)
    time.sleep(10)
    test_stub.up_host_network(non_vip_s_vm_cfg_lst[0].ip_, test_lib.all_scenario_config)

    expected_vip_s_vm_cfg_lst_ip = vip_s_vm_cfg_lst[0].ip_
    if not test_stub.check_if_vip_is_on_host(test_lib.all_scenario_config, test_lib.scenario_file, expected_vip_s_vm_cfg_lst_ip):
        test_util.test_fail("find vip should drift on ip %s, but is not on it." %(expected_vip_s_vm_cfg_lst_ip))

    vip_s_vm_cfg_lst_new = test_stub.get_s_vm_cfg_lst_vip_bind(test_lib.all_scenario_config, test_lib.scenario_file)
    if len(vip_s_vm_cfg_lst_new) != 1:
        test_util.test_fail('vip has been running on %d host(s)' % len(vip_s_vm_cfg_lst_new))

    test_stub.wrapper_of_wait_for_management_server_start(600)

    test_stub.ensure_hosts_connected(exclude_host=[non_vip_s_vm_cfg_lst[0]])
    test_stub.ensure_bss_connected()
    test_stub.ensure_pss_connected()

    vm = test_stub.create_basic_vm()
    vm.check()
    vm.destroy()

    test_util.test_pass('Create VM Test Success')

#Will be called what ever test result is
def env_recover():
    global non_vip_s_vm_cfg_lst
    test_util.test_logger("recover host: %s" % (non_vip_s_vm_cfg_lst[0].ip_))
    test_stub.up_host_network(non_vip_s_vm_cfg_lst[0].ip_, test_lib.all_scenario_config)
    test_stub.exec_zsha2_version(vip_s_vm_cfg_lst[0].ip_, "root", "password")

#Will be called only if exception happens in test().
def error_cleanup():
    global vm
    if vm:
        try:
            vm.destroy()
        except:
            pass


text:
require_dependency "blorgh/application_controller"

module Blorgh
  class CommentsController < ApplicationController
    def create
      @post = Post.find(params[:post_id])
      @comment = @post.comments.create(comment_params)
      flash[:notice] = "Comment has been created!"
      redirect_to posts_path
    end

    private
      def comment_params
        params.require(:comment).permit(:text)
      end
  end
end


text:
using System.Web.Mvc;

using Moq;

namespace AspNetMvcSeo.Tests
{
    public static class HtmlHelperTestFactory
    {
        public static HtmlHelper Create(ViewContext viewContext = null)
        {
            viewContext = viewContext ?? ViewContextTestFactory.Create();

            var viewDataContainer = new Mock<IViewDataContainer>();
            viewDataContainer.Setup(x => x.ViewData).Returns(viewContext.ViewData);

            var htmlHelper = new HtmlHelper(viewContext, viewDataContainer.Object);
            return htmlHelper;
        }
    }
}


text:
---
layout: post
title: Mengenal Null Safety Pada Kotlin
modified:
categories:
description: Mengenal Null Safety Pada Kotlin
tags: [Kotlin, Jetbrains, IntelliJ IDEA, Gradle, Null Safety, Collection, Elvis]
image:
  background: abstract-2.png
comments: true
share: true
date: 2017-06-12T20:15:28+07:00
---

Pada artikel [sebelumnya](https://rizkimufrizal.github.io/setup-project-kotlin/), penulis telah membahas mengenai setup project kotlin dengan menggunakan gradle. Nah pada artikel ini, penulis akan membahas sedikit mengenai null safety pada kotlin.

## Apa Itu Null Safety

Sebagai developer java, anda pasti sering menemui yang namanya NullPointerException atau disingkat dengan NPE. Terkadang kita akan mengecek seluruh object apakah terdapat potensi NPE atau tidak dan NPE ini sangat sering terjadi terutama jika anda adalah android developer. Pada kotlin, anda dapat membedakan antara variabel yang boleh null dan yang tidak boleh null. Supaya lebih memahami, silahkan buka project yang dulu pernah anda buat, lalu buatlah sebuah file kotlin di dalam package `org.rizki.mufrizal.belajarKotlin` dengan nama `NullSafety`. Kemudian isikan codingan seperti berikut.

{% highlight kotlin %}
package org.rizki.mufrizal.belajarKotlin

/**
 * Created by rizkimufrizal on 6/12/17.
 */

class NullSafety {
    companion object {
        @JvmStatic
        fun main(args: Array<String>) {
            var nama = "rizki"
            nama = null //error
            print("hello $nama")
        }
    }
}
{% endhighlight %}

Dari codingan diatas, maka secara otomatis codingan anda akan error seperti berikut.

![Screen Shot 2017-06-12 at 9.57.17 AM.png](../images/Screen Shot 2017-06-12 at 9.57.17 AM.png)

Error ini disebabkan karena secara default variabel pada kotlin tidak boleh diisi dengan null, sehingga dengan error ini developer lebih dapat mengatasi NPE. Agar variabel diatas dapat diisi dengan null maka silahkan ubah codingan nya menjadi seperti berikut.

{% highlight kotlin %}
package org.rizki.mufrizal.belajarKotlin

/**
 * Created by rizkimufrizal on 6/12/17.
 */

class NullSafety {
    companion object {
        @JvmStatic
        fun main(args: Array<String>) {
            var nama: String? = "rizki"
            nama = null
            print("hello $nama")
        }
    }
}
{% endhighlight %}

Tanda dari `?` berfungsi agar variabel tersebut dapat diisi dengan null. Oke langkah selanjutnya adalah ketika anda ingin mengetahui panjang dari suatu string, biasanya kita akan menggunakan function dari `length`, Jika anda menggunakan tanda `?` maka setiap mengakses function `length` maka anda wajib juga menyertakan tanda `?`, di IntelliJ IDEA, ketika anda mencoba mengakses function `length` tanpa tanda `?` maka warna nya akan gelap pertanda bahwa anda diwajibkan menggunakan tanda `?` seperti berikut.

![Screen Shot 2017-06-12 at 10.08.52 AM.png](../images/Screen Shot 2017-06-12 at 10.08.52 AM.png)

Jika anda tidak menggunakan tanda `?` maka akan compiler akan memberitahukan error karena variabel memiliki nilai null. Untuk mengatasi hal demikian, silahkan ubah codingan menjadi seperti berikut.

{% highlight kotlin %}
package org.rizki.mufrizal.belajarKotlin

/**
 * Created by rizkimufrizal on 6/12/17.
 */

class NullSafety {
    companion object {
        @JvmStatic
        fun main(args: Array<String>) {
            var nama: String? = "rizki"
            nama = null
            print("hello $nama dengan panjang nama : ${nama?.length}")
        }
    }
}
{% endhighlight %}

Untuk mempermudah melakukan test, silahkan ubah codingan diatas menjadi seperti berikut.

{% highlight kotlin %}
package org.rizki.mufrizal.belajarKotlin

/**
 * Created by rizkimufrizal on 6/12/17.
 */

class NullSafety {

    fun nullOrNot(text: String?) = "hello $text dengan panjang text : ${text?.length}"

    companion object {
        @JvmStatic
        fun main(args: Array<String>) {
            println(NullSafety().nullOrNot(text = "rizki"))
            println(NullSafety().nullOrNot(text = null))
        }
    }
}
{% endhighlight %}

Jika pada codingan sebelumnya kita langsung melakukan print, maka pada codingan ini kita mendeklarasikan sebuah function dengan mengembalikan type data string. Pada function nullOrNot terdapat 1 parameter yaitu `text` dimana parameter ini dapat diisi dengan null dikarenakan menggunakan tanda `?`. Untuk mengembalikan data dalam bentuk string, kita dapat langsung melakukan return jika codingan hanya sebaris seperti codingan diatas dan tanpa perlu menggunakan keyword `return`.

Langkah selanjutnya, kita akan membuat test nya, silahkan buat sebuah kotlin file dengan nama `NullSafetyTest` di dalam package test, kemudian isikan codingan seperti berikut.

{% highlight kotlin %}
package org.rizki.mufrizal.belajarKotlin

import com.winterbe.expekt.should
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.on

/**
 * Created by rizkimufrizal on 6/12/17.
 */
class NullSafetyTest : Spek({
    given("a class NullSafety") {
        val nullSafety = NullSafety()
        on("set text to not null") {
            val textNotNull = nullSafety.nullOrNot(text = "rizki")
            it("should return not null") {
                textNotNull.should.equal("hello rizki dengan panjang text : 5")
            }
        }
        on("set text to null") {
            val textNull = nullSafety.nullOrNot(text = null)
            it("should return null") {
                textNull.should.equal("hello null dengan panjang text : null")
            }
        }
    }
})
{% endhighlight %}

## Memeriksa Null

Jika kita menggunakan tanda `?` maka jika anda mengakses suatu function contohnya `length` maka kita akan mendapatkan output null, terkadang kita ingin mengambalikan value yang lain. Alaternatif lain adalah dengan menggunakan fungsi `if`. Silahkan edit source code yang ada pada class `NullSafety` seperti berikut.

{% highlight kotlin %}
package org.rizki.mufrizal.belajarKotlin

/**
 * Created by rizkimufrizal on 6/12/17.
 */

class NullSafety {

    fun nullOrNot(text: String?) = "hello $text dengan panjang text : ${text?.length}"

    fun nullOrNotIf(text: String?) = if (text != null) "hello $text dengan panjang text : ${text.length}" else "Kosong / Isinya null"

    companion object {
        @JvmStatic
        fun main(args: Array<String>) {
            println(NullSafety().nullOrNot(text = "rizki"))
            println(NullSafety().nullOrNot(text = null))
            println(NullSafety().nullOrNotIf(text = "mufrizal"))
            println(NullSafety().nullOrNotIf(text = null))
        }
    }
}
{% endhighlight %}

Pada kodingan diatas kita ada penambahan 1 function yaitu `nullOrNotIf` dimana sebenarnya function ini juga sama dengan function `nullOrNot`, bedanya yaitu pada function ini kita melakukan pengecekan null terhadap variabel `text` sehingga pada saat kita mengakses function `length` dari variabel `text`, kita tidak perlu lagi menggunakan tanda `?`. Jika kita memasukkan null, maka nantinya akan dicetak `Kosong / Isinya null` sedangkan jika tidak null maka akan dicetak kalimat `hello mufrizal dengan panjang text : 8`.

Selain menggunakan `if else`, untuk mengecek null, kita juga dapat menggunakan `elvis`, silahkan ubah codingan seperti berikut.

{% highlight kotlin %}
package org.rizki.mufrizal.belajarKotlin

/**
 * Created by rizkimufrizal on 6/12/17.
 */

class NullSafety {

    fun nullOrNot(text: String?) = "hello $text dengan panjang text : ${text?.length}"

    fun nullOrNotIf(text: String?) = if (text != null) "hello $text dengan panjang text : ${text.length}" else "Kosong / Isinya null"

    fun nullOrNotElvis(text: String?): String {
        val length = text?.length ?: 0
        return if (length != 0) "hello $text dengan panjang text : $length" else "Kosong / Isinya null"
    }

    companion object {
        @JvmStatic
        fun main(args: Array<String>) {
            println(NullSafety().nullOrNot(text = "rizki"))
            println(NullSafety().nullOrNot(text = null))
            println(NullSafety().nullOrNotIf(text = "mufrizal"))
            println(NullSafety().nullOrNotIf(text = null))
            println(NullSafety().nullOrNotElvis(text = "rizki mufrizal"))
            println(NullSafety().nullOrNotElvis(text = null))
        }
    }
}
{% endhighlight %}

Dengan menggunakan elvis, kita hanya perlu menggunakan operator `?:`, sintak ini mirip dengan ternary operator. Jika `text?.length` tidak null maka akan dikembalikan nilai `text?.length`, sedangkan jika null maka akan dikembalikan nilai 0.

Dan yang terakhir adalah adanya operator `!!`, biasanya operator ini berfungsi untuk mengembalikan data yang benar - benar tidak null, jika null maka akan menghasilkan error, berikut adalah contoh penggunaan `!!`, silahkan ubah source code seperti berikut.

{% highlight kotlin %}
package org.rizki.mufrizal.belajarKotlin

/**
 * Created by rizkimufrizal on 6/12/17.
 */

class NullSafety {

    fun nullOrNot(text: String?) = "hello $text dengan panjang text : ${text?.length}"

    fun nullOrNotIf(text: String?) = if (text != null) "hello $text dengan panjang text : ${text.length}" else "Kosong / Isinya null"

    fun nullOrNotElvis(text: String?): String {
        val length = text?.length ?: 0
        return if (length != 0) "hello $text dengan panjang text : $length" else "Kosong / Isinya null"
    }

    fun nullOrNotNew(text: String?) = "hello $text dengan panjang text : ${text!!.length}"

    companion object {
        @JvmStatic
        fun main(args: Array<String>) {
            println(NullSafety().nullOrNot(text = "rizki"))
            println(NullSafety().nullOrNot(text = null))
            println(NullSafety().nullOrNotIf(text = "mufrizal"))
            println(NullSafety().nullOrNotIf(text = null))
            println(NullSafety().nullOrNotElvis(text = "rizki mufrizal"))
            println(NullSafety().nullOrNotElvis(text = null))
            println(NullSafety().nullOrNotNew(text = "mufrizal rizki"))
        }
    }
}
{% endhighlight %}

oke langkah selanjutnya kita akan membuat test nya, silahkan ubah source code yang ada di dalam file `NullSafetyTest` seperti berikut.

{% highlight kotlin %}
package org.rizki.mufrizal.belajarKotlin

import com.winterbe.expekt.should
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.on

/**
 * Created by rizkimufrizal on 6/12/17.
 */
class NullSafetyTest : Spek({
    given("a class NullSafety") {
        val nullSafety = NullSafety()
        on("set text to not null") {
            val textNotNull = nullSafety.nullOrNot(text = "rizki")
            it("should return not null") {
                textNotNull.should.equal("hello rizki dengan panjang text : 5")
            }
        }
        on("set text to null") {
            val textNull = nullSafety.nullOrNot(text = null)
            it("should return null") {
                textNull.should.equal("hello null dengan panjang text : null")
            }
        }
        on("set text to not null if") {
            val textNull = nullSafety.nullOrNotIf(text = "mufrizal")
            it("should return null") {
                textNull.should.equal("hello mufrizal dengan panjang text : 8")
            }
        }
        on("set text to null if") {
            val textNull = nullSafety.nullOrNotIf(text = null)
            it("should return null") {
                textNull.should.equal("Kosong / Isinya null")
            }
        }
        on("set text to not null elvis") {
            val textNull = nullSafety.nullOrNotElvis(text = "rizki mufrizal")
            it("should return null") {
                textNull.should.equal("hello rizki mufrizal dengan panjang text : 14")
            }
        }
        on("set text to null elvis") {
            val textNull = nullSafety.nullOrNotElvis(text = null)
            it("should return null") {
                textNull.should.equal("Kosong / Isinya null")
            }
        }
        on("set text to not null !!") {
            val textNull = nullSafety.nullOrNotNew(text = "mufrizal rizki")
            it("should return null") {
                textNull.should.equal("hello mufrizal rizki dengan panjang text : 14")
            }
        }
    }
})
{% endhighlight %}

## Memeriksa Null Pada Collections

Terkadang ketika memasukkan suatu nilai ke sebuah collection, nilai tersebut dapat berupa null. Jika menggunakan kotlin, terdapat function `filterNotNull` yang berfungsi untuk menghilangkan value null yang terdapat di dalam collection. Silahkan ubah codingan nya menjadi seperti berikut.

{% highlight kotlin %}
package org.rizki.mufrizal.belajarKotlin

/**
 * Created by rizkimufrizal on 6/12/17.
 */

class NullSafety {

    fun nullOrNot(text: String?) = "hello $text dengan panjang text : ${text?.length}"

    fun nullOrNotIf(text: String?) = if (text != null) "hello $text dengan panjang text : ${text.length}" else "Kosong / Isinya null"

    fun nullOrNotElvis(text: String?): String {
        val length = text?.length ?: 0
        return if (length != 0) "hello $text dengan panjang text : $length" else "Kosong / Isinya null"
    }

    fun nullOrNotNew(text: String?) = "hello $text dengan panjang text : ${text!!.length}"

    fun filterCollection(list: List<*>) = list.filterNotNull()

    companion object {
        @JvmStatic
        fun main(args: Array<String>) {
            println(NullSafety().nullOrNot(text = "rizki"))
            println(NullSafety().nullOrNot(text = null))
            println(NullSafety().nullOrNotIf(text = "mufrizal"))
            println(NullSafety().nullOrNotIf(text = null))
            println(NullSafety().nullOrNotElvis(text = "rizki mufrizal"))
            println(NullSafety().nullOrNotElvis(text = null))
            println(NullSafety().nullOrNotNew(text = "mufrizal rizki"))

            val list = mutableListOf<String?>()
            list.add("rizki")
            list.add("mufrizal")
            list.add(null)

            val listNotNull = NullSafety().filterCollection(list)
            listNotNull.forEach { println("Nama Saya $it") }
        }
    }
}
{% endhighlight %}

Pada codingan diatas terdapat tambahan yaitu tambahan function `filterCollection`, dimana didalam function tersebut dilakukan filter terhadap list dengan type data bebas, mengapa bebas ? ini dikarenakan kita menggunakan tanda `*` atau sama juga dengan generic. Untuk melakukan perulangan terhadap variabel `listNotNull` maka dapat menggunakan function `forEach`. Disini saya menggunakan variabel `it`, variabel `it` sebenarnya variabel yang mengembalikan nilai dari perulangan variabel `listNotNull`. Jadi variabel `it` tergantung dari type data yang ada di dalam list tersebut.

Tahap selanjutnya kita membuat test nya, silahkan ubah codingan `NullSafetyTest` seperti berikut.

{% highlight kotlin %}
package org.rizki.mufrizal.belajarKotlin

import com.winterbe.expekt.should
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.on

/**
 * Created by rizkimufrizal on 6/12/17.
 */
class NullSafetyTest : Spek({
    given("a class NullSafety") {
        val nullSafety = NullSafety()
        on("set text to not null") {
            val textNotNull = nullSafety.nullOrNot(text = "rizki")
            it("should return not null") {
                textNotNull.should.equal("hello rizki dengan panjang text : 5")
            }
        }
        on("set text to null") {
            val textNull = nullSafety.nullOrNot(text = null)
            it("should return null") {
                textNull.should.equal("hello null dengan panjang text : null")
            }
        }
        on("set text to not null if") {
            val textNull = nullSafety.nullOrNotIf(text = "mufrizal")
            it("should return null") {
                textNull.should.equal("hello mufrizal dengan panjang text : 8")
            }
        }
        on("set text to null if") {
            val textNull = nullSafety.nullOrNotIf(text = null)
            it("should return null") {
                textNull.should.equal("Kosong / Isinya null")
            }
        }
        on("set text to not null elvis") {
            val textNull = nullSafety.nullOrNotElvis(text = "rizki mufrizal")
            it("should return null") {
                textNull.should.equal("hello rizki mufrizal dengan panjang text : 14")
            }
        }
        on("set text to null elvis") {
            val textNull = nullSafety.nullOrNotElvis(text = null)
            it("should return null") {
                textNull.should.equal("Kosong / Isinya null")
            }
        }
        on("set text to not null !!") {
            val textNull = nullSafety.nullOrNotNew(text = "mufrizal rizki")
            it("should return null") {
                textNull.should.equal("hello mufrizal rizki dengan panjang text : 14")
            }
        }
        on("set collection filter") {
            val list = mutableListOf<String?>()
            list.add("rizki")
            list.add("mufrizal")
            list.add(null)
            val collectionNotNull = nullSafety.filterCollection(list)
            it("should return collection not null") {
                collectionNotNull.should.not.`null`
                collectionNotNull.should.any.elements("rizki", "mufrizal")
                collectionNotNull.should.have.all.elements("rizki", "mufrizal")
                collectionNotNull.should.have.size.equal(2)
                collectionNotNull.should.have.size.above(1)
            }
        }
    }
})
{% endhighlight %}

Untuk melakukan test diatas, silahkan jalankan perintah berikut.

{% highlight bash %}
gradle test
{% endhighlight %}

dan berikut hasilnya.

{% highlight bash %}
:compileKotlin
Using kotlin incremental compilation
:compileJava NO-SOURCE
:copyMainKotlinClasses
:processResources NO-SOURCE
:classes UP-TO-DATE
:compileTestKotlin
Using kotlin incremental compilation
:compileTestJava NO-SOURCE
:copyTestKotlinClasses
:processTestResources NO-SOURCE
:testClasses UP-TO-DATE
:junitPlatformTest

Test run finished after 5131 ms
[        14 containers found      ]
[         0 containers skipped    ]
[        14 containers started    ]
[         0 containers aborted    ]
[        14 containers successful ]
[         0 containers failed     ]
[         9 tests found           ]
[         0 tests skipped         ]
[         9 tests started         ]
[         0 tests aborted         ]
[         9 tests successful      ]
[         0 tests failed          ]

:test SKIPPED

BUILD SUCCESSFUL

Total time: 13.815 secs
{% endhighlight %}

Sekian artikel mengenai mengenal null safety pada kotlin, jika ada saran dan komentar silahkan isi dibawah dan terima kasih :)


text:
package org.osanchezhuerta.hr.employees.soa.services.impl;

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

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;

import org.osanchezhuerta.hr.employees.soa.commons.to.SalaryTO;
import org.osanchezhuerta.hr.employees.soa.model.Salary;
import org.osanchezhuerta.hr.employees.soa.persistence.dao.SalariesDAO;
import org.osanchezhuerta.hr.employees.soa.services.SalaryService;
import org.osanchezhuerta.hr.employees.soa.services.transformer.SalaryTransformer;

@Stateless(name  = "salaryService", mappedName = "salaryService")
@TransactionManagement(TransactionManagementType.CONTAINER)
public class SalaryServiceImpl implements SalaryService {

	@EJB
	private SalariesDAO salariesDAO;

	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public List<SalaryTO> consultarSalariesPorRango(List<Integer> lstEmpNo, int pageNumber, int pageSize) {
		List<SalaryTO> lstSalaryTO = new ArrayList<SalaryTO>(0);
		List<Salary> lstSalary = salariesDAO.consultarSalariesPorRango(lstEmpNo, pageNumber, pageSize);
		for(Salary salary:lstSalary){
			lstSalaryTO.add(SalaryTransformer.toTransferObject(salary));
		}
		return lstSalaryTO;
	}

	public SalariesDAO getSalariesDAO() {
		return salariesDAO;
	}

	public void setSalariesDAO(SalariesDAO salariesDAO) {
		this.salariesDAO = salariesDAO;
	}

}


text:
var config = {
	host_url: "https://YOUR_NAME.herokuapp.com",		// mounted on this url
	base: "/",								// add a base url path. e.g: "/auth"
	base_api: "/api",						// api base path
	port: process.env.PORT || 80,
	//bind: "127.0.0.1",					// bind to an ip

	debug: true,							// add stack trace & infos in errors

	staticsalt: 'i m a random string, change me.',
	publicsalt: 'i m another random string, change me.',

	// see https://github.com/pmstss/heroku-oauthd/blob/master/README.md to fill this block
	redis: {
		port: 9019,	// YOUR_REDIS_PORT
		host: 'YOUR_REDIS_HOST',
		password: 'YOUR_REDIS_PASSWORD'
		// database: ...0~15...
		// options: {...other options...}
	},

	plugins: [

	]
};

try {
	if (__dirname != process.cwd()) {
		var instance_config = require(process.cwd() + '/config.js');
		for (var k in instance_config) {
			config[k] = instance_config[k];
		}
	}
} catch (e) {
	console.log(e);
	console.log('No config file found, using defaults');
}

try {
	if (__dirname != process.cwd()) {
		var instance_config = require(process.cwd() + '/config.local.js');
		for (var k in instance_config) {
			config[k] = instance_config[k];
		}
	}
} catch (e) {
}

console.log('using config: %s', JSON.stringify(config));

module.exports = config;


text:
// Copyright (c) .NET Core Community. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using DotNetCore.CAP.Internal;
using DotNetCore.CAP.Persistence;

namespace DotNetCore.CAP.Transport
{
    public interface IDispatcher : IProcessingServer
    {
        void EnqueueToPublish(MediumMessage message);

        void EnqueueToExecute(MediumMessage message, ConsumerExecutorDescriptor descriptor);
    }
}


text:
(function() {
    "use strict";

    angular
        .module('jdRoll.sidebar.character', [])
        .service('CharacterService', CharacterService)
        .controller('SidebarCharacterController', SidebarCharacterController)
        .directive('jdCharacterLink', CharacterLink);

    function SidebarCharacterController($scope, CharacterService) {
        $scope.refreshCharacters = function(search) {
            CharacterService.get(search).then(function(data) {
                $scope.characters = data;
            });
        };

        $scope.openModalCharacter = function(character) {
            persoModalService.openPerso(character.campagneId, character.id);
        };
    }

    function CharacterService($http) {
        this.get = get;

        function get(text) {
            return $http({
                url : '/apiv2/character/' + window.CAMPAGNE_ID,
                params: {
                    text: text
                }
            }).then(function(ret) {
                return ret.data;
            });
        }
    }

    function CharacterLink() {
        return {
            restrict: 'A',
            templateUrl: 'js/angular/sidebar/character-link.html',
        }
    }

})();


text:
<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">

    <solid
        android:color="@color/grey_700"/>

    <size
        android:width="72dp"
        android:height="72dp"/>
</shape>


text:
package bgames.trie;

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

public class Trie<T> {
  private final T value;
  private final HashMap<Character, Trie<T>> table;

  public Trie(T value, HashMap<Character, Trie<T>> table) {
    this.value = value;
    this.table = table;
  }
  public Trie() {
    this(null, new HashMap<>());
  }

  public boolean isEmpty() {
    return table.isEmpty();
  }

  public T getValue() {
    return value;
  }
  public boolean hasNext(Character ch) {
    return table.containsKey(ch);
  }
  public Trie<T> next(Character ch) {
    return table.get(ch);
  }
  public Iterator<Character> keyIterator() {
    return table.keySet().iterator();
  }

  public Trie<T> setValue(T value) {
    if (value == this.value) {
      return this;
    }
    return new Trie<T>(value, this.table);
  }
  public Trie<T> setChild(Character ch, Trie<T> child) {
    if (child == next(ch)) {
      return this;
    }
    HashMap<Character, Trie<T>> table = new HashMap<Character, Trie<T>>(this.table);
    table.put(ch, child);
    return new Trie<T>(this.value, table);
  }

  public static Stack<Character> strToStack(String str) {
    Stack<Character> stack = new Stack<>();
    for (int i = str.length() - 1; i >= 0; i--) {
      stack.push(str.charAt(i));
    }
    return stack;
  }
  private T get(Stack<Character> stack) {
    if (stack.empty()) {
      return value;
    }
    Character ch = stack.pop();
    if (!hasNext(ch)) {
      return null;
    }
    return next(ch).get(stack);
  }
  public T get(String name) {
    return get(strToStack(name));
  }

  private void collect(StringBuilder location, ArrayList<String> result) {
    if (value != null) {
      result.add(location.toString());
    }
    Iterator<Character> subs = keyIterator();
    while (subs.hasNext()) {
      Character ch = subs.next();
      location.append(ch);
      next(ch).collect(location, result);
      location.deleteCharAt(location.length() - 1);
    }
  }
  public ArrayList<String> collect() {
    ArrayList<String> result = new ArrayList<>();
    StringBuilder builder = new StringBuilder();
    collect(builder, result);
    return result;
  }

  @Override
  public String toString() {
    StringBuilder builder = new StringBuilder();
    ArrayList<String> list = collect();
    for (int i = 0; i < list.size(); i++) {
      T value = get(list.get(i));
      builder.append(value.toString());
      builder.append("\n");
    }
    return builder.toString();
  }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NugetCracker.Data;
using NugetCracker.Interfaces;
using NugetCracker.Persistence;

namespace NugetCracker.Commands
{
	public class ExcludeDirectoryCommand : ICommand
	{
		public bool Matches(string commandPattern)
		{
			commandPattern = commandPattern.Trim().ToLowerInvariant();
			return "excludedirectory".StartsWith(commandPattern) && commandPattern.Length > 1;
		}

		public string HelpLine { get { return "ExcludeDirectory Add directory to exclusion list"; } }

		public string Help
		{
			get
			{
				return @"Ex[cludeDirectory] [options] relativePath

	Add directory to exclusion list, found by relativePath.

	Options
	-f[orce]
		Don't ask confirmation for matched paths to exclude.
";
			}
		}

		public bool Process(ILogger logger, IEnumerable<string> args, MetaProjectPersistence metaProject, ComponentsList components, string packagesOutputDirectory)
		{
			var relativePath = string.Join(" ", args.Where(s => !s.StartsWith("-")));
			if (string.IsNullOrWhiteSpace(relativePath)) {
				logger.Error("No relativePath provided");
				return true;
			}
			bool force = args.Any(s => s.Length > 1 && "-force".StartsWith(s.ToLowerInvariant()));
			var path = metaProject.ToAbsolutePath(relativePath);
			if (!Directory.Exists(path)) {
				logger.Error("The path '{0}' doesn't exist", path);
				return true;
			}
			if (!force) {
				Console.Write("Exclude directory '{0}' and all subfolders from scanning?  [y/N]", path);
				var answer = Console.ReadLine().Trim().ToLowerInvariant();
				if (answer != "y")
					return true;
			}
			metaProject.AddExcludedDirectory(path);
			components.Prune(path);
			logger.Info("Directory '{0}' excluded from scanning", relativePath);
			return true;
		}
	}
}


text:
import React from 'react';
import './assets/scss';
import './assets/images';

const Error = ({ header, paragraph }) => {
  const setClass = () => {
    const itemImageClass = ['errorMessage', 'class'];
    return itemImageClass;
  };

  return (

{header}

{paragraph}

  );
};

export default Error;


text:
package org.hisp.dhis.importexport.action.util;

import org.hisp.dhis.dxf2.common.ImportOptions;
import org.hisp.dhis.dxf2.gml.GmlImportService;
import org.hisp.dhis.importexport.ImportStrategy;
import org.hisp.dhis.scheduling.TaskId;

import java.io.InputStream;

/**
 * @author Halvdan Hoem Grelland
 */
public class ImportMetaDataGmlTask
    implements Runnable
{
    private TaskId taskId;

    private String userUid;

    // -------------------------------------------------------------------------
    // Dependencies
    // -------------------------------------------------------------------------

    private GmlImportService gmlImportService;

    private ImportOptions importOptions;

    private InputStream inputStream;

    // -------------------------------------------------------------------------
    // Constructors
    // -------------------------------------------------------------------------

    public ImportMetaDataGmlTask( String userUid, GmlImportService gmlImportService,
        ImportOptions importOptions, InputStream inputStream, TaskId taskId )
    {
        this.userUid = userUid;
        this.gmlImportService = gmlImportService;
        this.importOptions = importOptions;
        this.inputStream = inputStream;
        this.taskId = taskId;
    }

    // -------------------------------------------------------------------------
    // Runnable implementation
    // -------------------------------------------------------------------------

    @Override
    public void run()
    {
        importOptions.setImportStrategy( ImportStrategy.UPDATE.name() );
        gmlImportService.importGml( inputStream, userUid, importOptions, taskId );
    }
}


text:
require 'formula'
require 'cmd/config'
require 'net/http'
require 'net/https'
require 'stringio'

module Homebrew
  def gistify_logs f
    files = load_logs(f.name)

    s = StringIO.new
    Homebrew.dump_verbose_config(s)
    files["config.out"] = { :content => s.string }
    files["doctor.out"] = { :content => `brew doctor 2>&1` }

    url = create_gist(files)

    if ARGV.include?('--new-issue') || ARGV.switch?('n')
      auth = :AUTH_TOKEN

      unless HOMEBREW_GITHUB_API_TOKEN
        puts 'You can create an API token: https://github.com/settings/applications'
        puts 'and then set HOMEBREW_GITHUB_API_TOKEN as authentication method.'
        puts

        auth = :AUTH_BASIC
      end

      url = new_issue(f.tap, "#{f.name} failed to build on #{MACOS_FULL_VERSION}", url, auth)
    end

    puts url if url
  end

  #Hack for ruby < 1.9.3
  def noecho_gets
    system 'stty -echo'
    result = $stdin.gets
    system 'stty echo'
    puts
    result
  end

  def login request
    print 'GitHub User: '
    user = $stdin.gets.chomp
    print 'Password: '
    password = noecho_gets.chomp
    puts
    request.basic_auth(user, password)
  end

  def load_logs name
    logs = {}
    dir = HOMEBREW_LOGS/name
    dir.children.sort.each do |file|
      contents = file.size? ? file.read : "empty log"
      logs[file.basename.to_s] = { :content => contents }
    end if dir.exist?
    raise 'No logs.' if logs.empty?
    logs
  end

  def create_gist files
    post("/gists", { "public" => true, "files" => files })["html_url"]
  end

  def new_issue repo, title, body, auth
    post("/repos/#{repo}/issues", { "title" => title, "body" => body }, auth)["html_url"]
  end

  def http
    @http ||= begin
      uri = URI.parse('https://api.github.com')
      p = ENV['http_proxy'] ? URI.parse(ENV['http_proxy']) : nil
      if p.class == URI::HTTP or p.class == URI::HTTPS
        @http = Net::HTTP.new(uri.host, uri.port, p.host, p.port, p.user, p.password)
      else
        @http = Net::HTTP.new(uri.host, uri.port)
      end
      @http.use_ssl = true
      @http
    end
  end

  def make_request(path, data, auth)
    headers = {
      "User-Agent"   => HOMEBREW_USER_AGENT,
      "Accept"       => "application/vnd.github.v3+json",
      "Content-Type" => "application/json",
    }

    if auth == :AUTH_TOKEN || (auth == nil && HOMEBREW_GITHUB_API_TOKEN)
      headers["Authorization"] = "token #{HOMEBREW_GITHUB_API_TOKEN}"
    end

    request = Net::HTTP::Post.new(path, headers)

    login(request) if auth == :AUTH_BASIC

    request.body = Utils::JSON.dump(data)
    request
  end

  def post(path, data, auth = nil)
    request = make_request(path, data, auth)

    case response = http.request(request)
    when Net::HTTPCreated
      Utils::JSON.load get_body(response)
    else
      raise "HTTP #{response.code} #{response.message} (expected 201)"
    end
  end

  def get_body(response)
    if !response.body.respond_to?(:force_encoding)
      response.body
    elsif response["Content-Type"].downcase == "application/json; charset=utf-8"
      response.body.dup.force_encoding(Encoding::UTF_8)
    else
      response.body.encode(Encoding::UTF_8, :undef => :replace)
    end
  end

  def gist_logs
    if ARGV.formulae.length != 1
      puts "usage: brew gist-logs [--new-issue|-n] <formula>"
      Homebrew.failed = true
      return
    end

    gistify_logs(ARGV.formulae[0])
  end
end