com.twosigma.beakerx.jvm.object.SimpleEvaluationObject Java Examples

The following examples show how to use com.twosigma.beakerx.jvm.object.SimpleEvaluationObject. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ClasspathAddDynamicMagicCommand.java    From beakerx with Apache License 2.0 6 votes vote down vote up
@Override
public MagicCommandOutcomeItem execute(MagicCommandExecutionParam param) {
  String command = param.getCommand();
  String[] split = splitPath(command);
  if (split.length < 4) {
    return new MagicCommandOutput(MagicCommandOutput.Status.ERROR, WRONG_FORMAT_MSG + CLASSPATH_ADD_DYNAMIC);
  }

  String codeToExecute = command.substring(command.indexOf(DYNAMIC) + DYNAMIC.length()).trim();
  SimpleEvaluationObject seo = createSimpleEvaluationObject(codeToExecute, kernel, param.getCode().getMessage(), param.getExecutionCount());
  TryResult either = kernel.executeCode(codeToExecute, seo);
  if (either.isResult()) {
    try {
      return addJars(either.result());
    } catch (Exception e) {
      return new MagicCommandOutput(MagicCommandOutput.Status.ERROR, "There occurs problem during execution of " + CLASSPATH_ADD_DYNAMIC + " : " + e.getMessage());
    }
  } else {
    return new MagicCommandOutput(MagicCommandOutput.Status.ERROR, "There occurs problem during execution of " + CLASSPATH_ADD_DYNAMIC + " : " + either.error());
  }
}
 
Example #2
Source File: GroovyOutputContainerTest.java    From beakerx with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAddPlotToOutputContainerTest() throws Exception {
  //given
  String code =
          "import com.twosigma.beakerx.groovy.evaluator.ResourceLoaderTest;\n" +
                  "import com.twosigma.beakerx.jvm.object.OutputContainer;\n" +
                  "import com.twosigma.beakerx.chart.xychart.SimpleTimePlot;\n" +
                  "List<Map<?, ?>> rates = ResourceLoaderTest.readAsList(\"tableRowsTest.csv\");\n" +
                  "plot2 = new SimpleTimePlot(rates, [\"m3\", \"y1\"], showLegend:false, initWidth: 300, initHeight: 400)\n" +
                  "new OutputContainer() << plot2";

  //when
  SimpleEvaluationObject evaluationObject = PlainCode.createSimpleEvaluationObject(code, groovyKernel, HEADER_MESSAGE, 1);
  TryResult seo = evaluator.evaluate(evaluationObject, code);
  //then
  assertThat(seo.result()).isNotNull();
  verifyPlot(groovyKernel.getPublishedMessages());
}
 
Example #3
Source File: ScalaEvaluatorTest.java    From beakerx with Apache License 2.0 6 votes vote down vote up
@Test
public void javaImports_shouldBeAdjustedForScala() throws Exception {
  //given
  Map<String, Object> paramMap = new HashMap<>();
  // This import tests both "static" removal and "object" escaping.
  List<String> imports = Arrays.asList(
          "import static com.twosigma.beakerx.scala.evaluator.object.ImportTestHelper.staticMethod");
  paramMap.put(IMPORTS, imports);
  EvaluatorParameters kernelParameters = new EvaluatorParameters(paramMap);
  //when
  scalaEvaluator.updateEvaluatorParameters(kernelParameters);
  String code = "val x = staticMethod()";
  SimpleEvaluationObject seo = KernelTest.createSeo(code);
  TryResult evaluate = scalaEvaluator.evaluate(seo, code);
  //then
  assertThat(evaluate.result()).isNull();
}
 
Example #4
Source File: KotlinEvaluatorTest.java    From beakerx with Apache License 2.0 6 votes vote down vote up
@Test
public void javaImports_shouldBeAdjustedForKotlin() throws Exception {
  //given
  Map<String, Object> paramMap = new HashMap<>();
  // This import tests both "static" removal and "object" escaping.
  List<String> imports = asList(
          "import static com.twosigma.beakerx.kotlin.evaluator.object.ImportTestHelper.staticMethod");
  paramMap.put(IMPORTS, imports);
  EvaluatorParameters kernelParameters = new EvaluatorParameters(paramMap);
  //when
  evaluator.updateEvaluatorParameters(kernelParameters);
  String code = "val x = staticMethod()";
  SimpleEvaluationObject seo = KernelTest.createSeo(code);
  TryResult evaluate = evaluator.evaluate(seo, code);
  //then
  assertThat(evaluate.result()).isNull();
}
 
Example #5
Source File: KotlinEvaluatorTest.java    From beakerx with Apache License 2.0 6 votes vote down vote up
@Test
public void returnFromFunction() throws Exception {
  //given
  String code = "" +
          "val a = 2.2\n" +
          "val b = 14\n" +
          "\n" +
          "val f = {x: Double -> a*x + b}\n" +
          "\n" +
          "println(f(2.0))\n" +
          "f(2.0)";
  SimpleEvaluationObject seo = KernelTest.createSeo(code);
  //when
  TryResult evaluate = evaluator.evaluate(seo, code);
  //then
  assertThat((Double) evaluate.result()).isEqualTo(18.4);
}
 
Example #6
Source File: CompiledCodeRunner.java    From beakerx with Apache License 2.0 6 votes vote down vote up
static void runCommEvent(Message message, CommActions action, Widget.ActionPerformed handlerAction) {
  if (message.getContent() != null) {
    Serializable data = message.getContent().get("data");
    if (data != null && data instanceof LinkedHashMap) {
      Object contentObject = ((LinkedHashMap) data).get("content");
      if (contentObject instanceof LinkedHashMap) {
        HashMap content = (LinkedHashMap) contentObject;
        if (handlerAction != null) {
          final SimpleEvaluationObject seo = initOutput(message);
          handlerAction.executeAction(content, message);
          seo.clrOutputHandler();
        }
      }
    }
  }
}
 
Example #7
Source File: CompiledCodeRunner.java    From beakerx with Apache License 2.0 5 votes vote down vote up
private static void printError(Message message, SimpleEvaluationObject seo, Exception e) {
  if (message != null) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    e.printStackTrace(pw);
    seo.error(sw.toString());
  } else {
    logger.info("Execution result ERROR: \n" + e);
  }
}
 
Example #8
Source File: MessageCreator.java    From beakerx with Apache License 2.0 5 votes vote down vote up
private static List<MessageHolder> createConsoleResult(SimpleEvaluationObject seo, Message message) {
  List<MessageHolder> result = new ArrayList<>();
  while (!seo.getConsoleOutput().isEmpty()) {
    ConsoleOutput co = seo.getConsoleOutput().poll(); //FIFO : peek to see, poll -- removes the data
    result.add(new MessageHolder(SocketEnum.IOPUB_SOCKET, buildOutputMessage(message, co.getText(), co.isError())));
  }
  return result;
}
 
Example #9
Source File: InternalVariable.java    From beakerx with Apache License 2.0 5 votes vote down vote up
public static Message getParentHeader() {
  SimpleEvaluationObject simpleEvaluationObject = getSimpleEvaluationObject();
  if (simpleEvaluationObject != null && simpleEvaluationObject.getJupyterMessage() != null) {
    return simpleEvaluationObject.getJupyterMessage();
  }
  return null;
}
 
Example #10
Source File: KotlinEvaluatorTest.java    From beakerx with Apache License 2.0 5 votes vote down vote up
@Test
public void executePlot() throws Exception {
  //given
  String code = "" +
          "import com.twosigma.beakerx.chart.xychart.*\n" +
          "val plot = Plot()";
  SimpleEvaluationObject seo = KernelTest.createSeo(code);
  //when
  TryResult evaluate = evaluator.evaluate(seo, code);
  //then
  assertThat(evaluate.result()).isNull();
}
 
Example #11
Source File: MagicCommand.java    From beakerx with Apache License 2.0 5 votes vote down vote up
@Override
public void executeFrame(Code code, KernelFunctionality kernel, Message message, int executionCount) {
  MagicCommandOutcomeItem execute = execute(code, executionCount, false);
  execute.sendMagicCommandOutcome(kernel, message, executionCount);
  TryResult result = execute.getResult();
  SimpleEvaluationObject seo = execute.getSimpleEvaluationObject();
  handleResult(seo, result);
}
 
Example #12
Source File: SQLEvaluatorTest.java    From beakerx with Apache License 2.0 5 votes vote down vote up
@Test
public void insertsShouldReturnOutputCellHIDDEN() throws Exception {
  //given
  SimpleEvaluationObject seo = KernelTest.createSeo(SQLForColorTable.CREATE);
  //when
  TryResult evaluate = sqlEvaluator.evaluate(seo, seo.getExpression());
  //then
  verifyInsertResult(evaluate);
}
 
Example #13
Source File: ScalaReprTest.java    From beakerx with Apache License 2.0 5 votes vote down vote up
@Test
public void unitObjectShouldBeRepresentedAsHIDDEN() {
  //given
  String code = "()";
  SimpleEvaluationObject seo = KernelTest.createSeo(code);
  //when
  TryResult evaluate = scalaEvaluator.evaluate(seo, code);
  //then
  assertThat(((MIMEContainer) evaluate.result())).isEqualTo(MIMEContainer.HIDDEN);
}
 
Example #14
Source File: TimeMagicCommand.java    From beakerx with Apache License 2.0 5 votes vote down vote up
private int getBestNumber(String codeToExecute, boolean showResult, Message message) {
  for (int value = 0; value < 10; ) {
    Double numberOfExecution = Math.pow(10, value);
    CompletableFuture<Boolean> keepLooking = new CompletableFuture<>();

    Long startTime = System.nanoTime();
    IntStream.range(0, numberOfExecution.intValue()).forEach(indexOfExecution -> {
      SimpleEvaluationObject simpleEvaluationObject = createSimpleEvaluationObject(
              codeToExecute, kernel, new Message(new Header(message.type(), message.getHeader().getSession())), 0);
      if (!showResult) {
        simpleEvaluationObject.noResult();
      }

      kernel.executeCode(codeToExecute, simpleEvaluationObject);
      if (numberOfExecution.intValue() - 1 == indexOfExecution) {
        if (TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime) > 0.2) {
          keepLooking.complete(false);
        } else {
          keepLooking.complete(true);
        }
      }
    });

    try {
      if (keepLooking.get()) {
        value++;
      } else {
        return numberOfExecution.intValue();
      }
    } catch (ExecutionException | InterruptedException e) {
      throw new IllegalStateException("Cannot create best number of execution.");
    }
  }

  throw new IllegalStateException("Cannot create best number of execution.");
}
 
Example #15
Source File: ExecutionResultSender.java    From beakerx with Apache License 2.0 5 votes vote down vote up
@Override
public void update(SimpleEvaluationObject seo ) {
  if (seo != null) {
    List<MessageHolder> message = MessageCreator.createMessage(seo);
    message.forEach(job -> {
      if (SocketEnum.IOPUB_SOCKET.equals(job.getSocketType())) {
        kernel.publish(singletonList(job.getMessage()));
      } else if (SocketEnum.SHELL_SOCKET.equals(job.getSocketType())) {
        kernel.send(job.getMessage());
      }
    });
  }
}
 
Example #16
Source File: CompiledCodeRunner.java    From beakerx with Apache License 2.0 5 votes vote down vote up
public static void runCompiledCodeAndPublish(Message message, ExecuteCompiledCode handler, Object... params) {
  final SimpleEvaluationObject seo = initOutput(message);
  InternalVariable.setValue(seo);
  KernelManager.get().publish(singletonList(MessageCreator.buildClearOutput(message, true)));
  try {
    Object result = handler.executeCode(params);
    if (result != null) {
      List<MIMEContainer> resultString = MIMEContainerFactory.createMIMEContainers(result);
      KernelManager.get().publish(singletonList(MessageCreator.buildDisplayData(message, resultString)));
    }
  } catch (Exception e) {
    printError(message, seo, e);
  }
  seo.clrOutputHandler();
}
 
Example #17
Source File: ScalaEvaluatorTest.java    From beakerx with Apache License 2.0 5 votes vote down vote up
@Test
public void evaluatePlot_shouldCreatePlotObject() throws Exception {
  //given
  String code = "import com.twosigma.beakerx.chart.xychart.Plot;\n" +
          "val plot = new Plot();\n" +
          "plot.setTitle(\"test title\");";
  SimpleEvaluationObject seo = KernelTest.createSeo(code);
  //when
  TryResult evaluate = scalaEvaluator.evaluate(seo, code);
  //then
  assertThat(evaluate.result() instanceof Plot).isTrue();
  assertThat(((Plot) evaluate.result()).getTitle()).isEqualTo("test title");
}
 
Example #18
Source File: EvaluatorBaseTest.java    From beakerx with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldDivide16By2() throws Exception {
  //given
  String code = codeForDivide16By2();
  SimpleEvaluationObject seo = KernelTest.createSeo(code);
  //when
  TryResult result = evaluator().evaluate(seo, code);
  //then
  assertThat(result.result().toString()).isEqualTo("8");
}
 
Example #19
Source File: EvaluatorBaseTest.java    From beakerx with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCreateErrorResultWithArithmeticExceptionWhenDivisionByZero() throws Exception {
  //given
  String code = codeForDivisionByZero();
  SimpleEvaluationObject seo = KernelTest.createSeo(code);
  //when
  TryResult either = evaluator().evaluate(seo, code);
  //then
  assertThat(either.error()).contains(textAssertionForDivisionByZero());
}
 
Example #20
Source File: EvaluatorBaseTest.java    From beakerx with Apache License 2.0 5 votes vote down vote up
@Test
public void returnPrintln() throws Exception {
  //given
  String code = codeForPrintln();
  SimpleEvaluationObject seo = KernelTest.createSeo(code);
  //when
  TryResult result = evaluator().evaluate(seo, code);
  //then
  verifyReturnPrintlnStatement(result);
}
 
Example #21
Source File: GroovyEvaluatorStackTraceTest.java    From beakerx with Apache License 2.0 5 votes vote down vote up
@Test
public void unableToResolveClass() throws Exception {
  String code = "new IntSlider()";
  SimpleEvaluationObject seo = KernelTest.createSeo(code);
  //when
  TryResult evaluate = groovyEvaluator.evaluate(seo, code);
  //then
  assertThat(evaluate.isError()).isTrue();
  System.out.println(evaluate.error());
  assertThat(evaluate.error()).contains("unable to resolve class IntSlider");
}
 
Example #22
Source File: KernelTest.java    From beakerx with Apache License 2.0 5 votes vote down vote up
public KernelTest(String id, CommRepository commRepository) {
  this.id = id;
  this.commRepository = commRepository;
  this.beakerXJson = new BeakerXJsonMock();
  initMagicCommands();
  SimpleEvaluationObject value = new SimpleEvaluationObject("ok", new SeoConfigurationFactoryMock(this, commMsg()));
  InternalVariable.setValue(value);
  KernelManager.register(this);

}
 
Example #23
Source File: KernelTest.java    From beakerx with Apache License 2.0 5 votes vote down vote up
public KernelTest(String id, Evaluator evaluator) {
  this.id = id;
  this.evaluator = evaluator;
  this.commRepository = new BeakerXCommRepositoryMock();
  this.beakerXJson = new BeakerXJsonMock();
  initMagicCommands();
  SimpleEvaluationObject value = new SimpleEvaluationObject("ok", new SeoConfigurationFactoryMock(this, commMsg()));
  InternalVariable.setValue(value);
  KernelManager.register(this);
  this.magicKernels = new HashMap<>();
}
 
Example #24
Source File: ScalaReprTest.java    From beakerx with Apache License 2.0 5 votes vote down vote up
@Test
public void emptyStringShouldBeRepresentedAsEmptyString() {
  //given
  String code = "\"\"";
  SimpleEvaluationObject seo = KernelTest.createSeo(code);
  //when
  TryResult evaluate = scalaEvaluator.evaluate(seo, code);
  //then
  assertThat(evaluate.result()).isEqualTo("");
}
 
Example #25
Source File: ScalaEvaluatorTest.java    From beakerx with Apache License 2.0 5 votes vote down vote up
@Test
public void displayTable() throws Exception {
  //given
  String code = "val table = new TableDisplay(new CSV().readFile(\"src/test/resources/tableRowsTest.csv\"))\n" +
          "table";
  SimpleEvaluationObject seo = KernelTest.createSeo(code);
  //when
  TryResult evaluate = scalaEvaluator.evaluate(seo, code);
  //then
  assertThat(evaluate.result() instanceof DisplayableWidget).isTrue();
}
 
Example #26
Source File: NamespaceClientShowProgressReportingTest.java    From beakerx with Apache License 2.0 5 votes vote down vote up
@Test
public void updateProgressReporting() throws Exception {
  //given
  SimpleEvaluationObject code = new SimpleEvaluationObject("code", new KernelTest.SeoConfigurationFactoryMock(kernel, commMsg()));
  InternalVariable.setValue(code);
  //when
  namespaceClient.showProgressUpdate("msg1", 20);
  namespaceClient.showProgressUpdate("msg2", 40);
  //then
  assertThat(kernel.getPublishedMessages()).isNotEmpty();
}
 
Example #27
Source File: MessageCreatorNoResultTest.java    From beakerx with Apache License 2.0 5 votes vote down vote up
@Test
public void noResult() throws Exception {
  //given
  SimpleEvaluationObject seo = new SimpleEvaluationObject("code", new KernelTest.SeoConfigurationFactoryMock(kernel, MessageFactorTest.commMsg()));
  seo.finished(OutputCell.HIDDEN);
  //when
  List<MessageHolder> messages = MessageCreator.createMessage(seo);
  //then
  messages.forEach(m -> assertThat(JupyterMessages.EXECUTE_RESULT).isNotEqualTo(m.getMessage().type()));
}
 
Example #28
Source File: KotlinEvaluatorTest.java    From beakerx with Apache License 2.0 5 votes vote down vote up
@Test
public void handleErrors() throws Exception {
  //given
  String code = "val plot = UndefinedPlot()";
  SimpleEvaluationObject seo = KernelTest.createSeo(code);
  //when
  TryResult evaluate = evaluator.evaluate(seo, code);
  //then
  assertThat(evaluate.error()).contains("unresolved reference: UndefinedPlot");
}
 
Example #29
Source File: ScalaEvaluatorTest.java    From beakerx with Apache License 2.0 5 votes vote down vote up
@Test
public void inputIncomplete() {
  //given
  String code =
                  "/*\n" +
                  "*";
  SimpleEvaluationObject seo = KernelTest.createSeo(code);
  //when
  TryResult evaluate = scalaEvaluator.evaluate(seo, code);
  //then
  assertThat(evaluate.error()).isEqualTo(ScalaEvaluatorGlue.INPUT_IS_INCOMPLETE());
}
 
Example #30
Source File: JavaEvaluatorTest.java    From beakerx with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultipleLines() throws Exception {
  //given
  String code = "import java.util.ArrayList;\n" +
          "var a = new ArrayList();\n" +
          "a.add(1);\n" +
          "a;";
  SimpleEvaluationObject seo = createSeo(code);
  //when
  TryResult evaluate = javaEvaluator.evaluate(seo, code);
  //then
  assertThat(evaluate.result()).isEqualTo(Arrays.asList(1));
}