text:
package com.cloudera.flume.handlers.exec;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.Pipe;
import java.nio.channels.ReadableByteChannel;
import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cloudera.flume.conf.FlumeConfiguration;
import com.cloudera.flume.conf.FlumeSpecException;
import com.cloudera.flume.core.Event;
import com.cloudera.flume.core.EventSource;
import com.cloudera.util.Clock;
import com.cloudera.util.FileUtil;

/**
 * Tests for the shell-based process exec event source.
 */
public class TestExecNioSource {
  private static final Logger LOG = LoggerFactory
      .getLogger(TestExecNioSource.class);

  /**
   * Test builders
   */
  @Test
  public void testStreamBuilder() throws IOException, FlumeSpecException {
    ExecNioSource e = (ExecNioSource) ExecNioSource.buildStream().build(
        "ps -aux");
    assertEquals(e.inAggregateMode, false);
    assertEquals(e.command, "ps -aux");
    assertEquals(e.restart, false);
    assertEquals(e.period, 0);
  }

  @Test
  public void testExecBuilder() throws IOException, FlumeSpecException {
    ExecNioSource e = (ExecNioSource) ExecNioSource.builder().build("ps -aux",
        "true", "true", "1000");
    assertEquals(e.inAggregateMode, true);
    assertEquals(e.command, "ps -aux");
    assertEquals(e.restart, true);
    assertEquals(e.period, 1000);
  }

  @Test
  public void testPeriodicBuilder() throws IOException, FlumeSpecException {
    ExecNioSource e = (ExecNioSource) ExecNioSource.buildPeriodic().build(
        "ps -aux", "1000");
    assertEquals(e.inAggregateMode, true);
    assertEquals(e.command, "ps -aux");
    assertEquals(e.restart, true);
    assertEquals(e.period, 1000);
  }

  /**
   * Test the extract lines function.
   *
   * @throws InterruptedException
   */
  @Test
  public void testExtractLines() throws InterruptedException {
    LinkedBlockingQueue<Event> q = new LinkedBlockingQueue<Event>();
    long maxSz = FlumeConfiguration.get().getEventMaxSizeBytes();
    ByteBuffer buf = ByteBuffer.allocate((int) maxSz * 4);

    // Empty Case
    boolean ret = ExecNioSource.extractLines(buf, "cmd", "tag", q);
    assertFalse(ret);
    assertEquals(0, q.size());

    // Overflow Case
    // this should fill the buffer and but progress should be made.
    for (int i = 0; i < maxSz; i++) {
      buf.put((byte) 'a');
    }

    ret = ExecNioSource.extractLines(buf, "cmd", "tag", q);
    assertFalse(ret);
    assertEquals(maxSz, buf.position()); // should have buffer cleared
    assertEquals(0, q.size());

    buf.put((byte) '\n');
    ret = ExecNioSource.extractLines(buf, "cmd", "tag", q);
    assertTrue(ret);
    assertEquals(0, buf.position()); // should have buffer cleared
    assertEquals(1, q.size());
    Event e = q.poll();
    assertEquals(maxSz, e.getBody().length);

    // Normal Case
    for (int i = 0; i < maxSz; i++) {
      if (i % 1024 == 1023) {
        buf.put((byte) '\n');
      } else {
        buf.put((byte) 'b');
      }
    }
    ret = ExecNioSource.extractLines(buf, "cmd", "tag", q);
    assertTrue(ret);
    assertEquals(0, buf.position()); // should have buffer cleared
    assertEquals(32, q.size());
    for (int i = 0; i < 32; i++) {
      e = q.poll();
      assertEquals(1023, e.getBody().length);
    }
  }

  /**
   * Test the dropUntilNewLineFunction
   */
  @Test
  public void testDropUntilNewLine() {
    long maxSz = FlumeConfiguration.get().getEventMaxSizeBytes();
    ByteBuffer buf = ByteBuffer.allocate((int) maxSz * 4);

    // Empty Case
    boolean ret = ExecNioSource.dropUntilNewLine(buf);
    assertTrue(ret); // not new line yet
    assertEquals(0, buf.position());

    // Overflow Case
    // this should fill the buffer and but progress should be made.
    for (int i = 0; i < maxSz; i++) {
      buf.put((byte) 'a');
    }

    ret = ExecNioSource.dropUntilNewLine(buf);
    assertTrue(ret);
    assertEquals(0, buf.position()); // should have buffer cleared

    buf.put((byte) '\n');
    buf.put((byte) 'd');
    ret = ExecNioSource.dropUntilNewLine(buf);
    assertFalse(ret);
    assertEquals(1, buf.position()); // should have buffer cleared

    buf.clear();

    // Normal Case
    for (int i = 0; i < maxSz; i++) {
      if (i % 1024 == 1023) {
        buf.put((byte) '\n');
      } else {
        buf.put((byte) 'b');
      }
    }
    ret = ExecNioSource.dropUntilNewLine(buf);
    assertFalse(ret);
    // cleared until first '\n' then and leaves remaining data
    assertEquals(maxSz - 1024, buf.position());

  }

  /**
   * Test that a too-large event is truncated, warns, and continues happily
   *
   * @throws FlumeSpecException
   * @throws IOException
   */
  @Test
  public void testLineModeLargeEvents() throws IOException, FlumeSpecException {
    testLineModeLargeEventOverflow(0);
    testLineModeLargeEventOverflow(1);
    testLineModeLargeEventOverflow(5);
  }

  public void testLineModeLargeEventOverflow(int overflow) throws IOException,
      FlumeSpecException {
    int max = (int) FlumeConfiguration.get().getEventMaxSizeBytes();
    File tmpdir = FileUtil.mktempdir();
    File tmp = new File(tmpdir, "flume-tmp");
    StringBuilder tooLarge = new StringBuilder();
    for (int i = 0; i < max + overflow; ++i) {
      tooLarge.append("X");
    }
    tooLarge.append("\n");

    FileOutputStream f = new FileOutputStream(tmp);
    f.write(tooLarge.toString().getBytes());
    f.close();
    EventSource source = new ExecNioSource.Builder().build("cat "
        + tmp.getCanonicalPath());
    source.open();
    Event e = source.next();
    assertNotNull(e);
    assertEquals(max, e.getBody().length); // check that event was truncated.
    source.close();
    FileUtil.rmr(tmpdir);
    // Check that the stdout reader closed correctly
    assertTrue(((ExecNioSource) source).readOut.signalDone.get());
  }

  /**
   * Test that a too-large event is truncated, warns, and continues happily
   *
   * @throws FlumeSpecException
   * @throws IOException
   */
  @Test
  public void testAggModeLargeEventOverflow() throws IOException,
      FlumeSpecException {
    int overflow = 5;
    int max = (int) FlumeConfiguration.get().getEventMaxSizeBytes();
    File tmpdir = FileUtil.mktempdir();
    File tmp = new File(tmpdir, "flume-tmp");
    StringBuilder tooLarge = new StringBuilder();
    for (int i = 0; i < max + overflow; ++i) {
      tooLarge.append("X");
    }
    tooLarge.append("\n");

    FileOutputStream f = new FileOutputStream(tmp);
    f.write(tooLarge.toString().getBytes());
    f.close();
    EventSource source = new ExecNioSource.Builder().build("cat "
        + tmp.getCanonicalPath(), "true");
    source.open();
    Event e = source.next();
    assertNotNull(e);
    assertEquals(max, e.getBody().length); // check that event was truncated.
    source.close();
    FileUtil.rmr(tmpdir);
    // Check that the stdout reader closed correctly
    assertTrue(((ExecNioSource) source).readOut.signalDone.get());
  }

  /**
   * Test that an event that gets written slowly gets fully read.
   *
   * @throws FlumeSpecException
   * @throws IOException
   */
  @Test
  public void testAggModeMultiWrite() throws IOException, FlumeSpecException {

    File temp = File.createTempFile("slowwrite", ".sh");
    temp.deleteOnExit();
    BufferedWriter out = new BufferedWriter(new FileWriter(temp));
    // echo, sleep 1s, echo
    out.write("#!/bin/bash\necho \"Hello world!\" >&2 \n"
        + "sleep 1s \necho \"Hello world!\" >&2 \n");
    out.close();
    String cmd = temp.getAbsolutePath();

    EventSource source = new ExecNioSource.Builder().build("/bin/bash " + cmd,
        "true");

    source.open();
    Event e = source.next();
    assertNotNull(e);
    assertEquals(26, e.getBody().length); // check that we read both lines
    source.close();

    // Check that the stdout reader closed correctly
    assertTrue(((ExecNioSource) source).readOut.signalDone.get());
  }

  /**
   * Test process creation and reading from stdout; assumes 'yes' is available.
   */
  public void testSimpleExec() throws IOException {
    try {
      EventSource source = new ExecNioSource.Builder().build("yes");
      source.open();
      Event e = source.next();
      String body = new String(e.getBody());
      assertEquals("Expected event body to be 'y', but got " + body, body, "y");
      source.close();
    } catch (Exception e) {
      LOG.error(e.getMessage(), e);
      fail(e.getMessage());
    }
  }

  /**
   * Test that an empty command throws an exception
   */
  @Test
  public void testEmptyCommand() throws IOException {
    Exception e = null;
    try {
      EventSource source = new ExecNioSource.Builder().build("");
      source.open();
      source.close();
    } catch (IllegalArgumentException i) {
      e = i;
    }
    assertNotNull("testEmptyCommand expected IllegalArgumentException", e);
  }

  /**
   * Test that we get some output from stderr
   */
  @Test
  public void testReadStdErr() throws IOException {
    File temp = File.createTempFile("flmtst", null);
    temp.deleteOnExit();

    BufferedWriter out = new BufferedWriter(new FileWriter(temp));
    out.write("#!/bin/bash\necho \"Hello world!\" >&2 \n");
    out.close();
    String cmd = temp.getAbsolutePath();

    EventSource source = new ExecNioSource.Builder().build("/bin/bash " + cmd);
    source.open();
    Event e = source.next();
    String body = new String(e.getBody());
    String src = new String(e.get(ExecNioSource.A_PROC_SOURCE));
    source.close();
    assertEquals("Expected event body to be 'Hello World!', but got '" + body
        + "'", body, "Hello world!");
    assertEquals("Expected to receive event from STDERR, but got " + src, src,
        "STDERR");
  }

  /**
   * Test that closing the source stops the reader threads
   */
  @Test
  public void testClose() throws IOException, InterruptedException {
    File temp = File.createTempFile("flmtst", null);
    temp.deleteOnExit();

    BufferedWriter out = new BufferedWriter(new FileWriter(temp));
    out.write("#!/bin/bash\n while true; do sleep 1; done; >&2 \n");
    out.close();
    String cmd = temp.getAbsolutePath();

    final EventSource source = new ExecNioSource.Builder().build("/bin/bash "
        + cmd);
    final CountDownLatch started = new CountDownLatch(1);
    final CountDownLatch latch = new CountDownLatch(1);
    Thread t = new Thread() {
      public void run() {
        try {
          source.open();
          started.countDown();
          source.next();
          latch.countDown();
        } catch (Exception e) {
          LOG.warn("Event consumption thread caught exception, test will fail",
              e);
        }
      }
    };
    t.start();
    started.await(1000, TimeUnit.MILLISECONDS);
    Clock.sleep(100); // give next a chance to start.
    source.close();
    assertTrue("source.next did not exit after close within 5 seconds", latch
        .await(5000, TimeUnit.MILLISECONDS));
  }

  @Ignore
  @Test(timeout = 1000)
  public void testNewChannelBlockingSemantics() throws IOException {
    ReadableByteChannel ch = Channels.newChannel(System.in);

    ByteBuffer buf = ByteBuffer.allocate(10);
    int rdSz = ch.read(buf); // this operation blocks!
    assertTrue(rdSz < 0);
  }

  @Ignore
  @Test
  public void testNewChannelBlockingCloseSemantics() throws IOException,
      InterruptedException {

    final ReadableByteChannel ch = Channels.newChannel(System.in);
    final CountDownLatch done = new CountDownLatch(1);

    new Thread() {
      public void run() {
        ByteBuffer buf = ByteBuffer.allocate(10);
        try {
          ch.read(buf);
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } finally {
          // this operation blocks!
          done.countDown();
        }
      }
    }.start();
    Clock.sleep(250); // get read got blocked
    ch.close();
    System.in.close();

    assertTrue("Timeout becuase channel read blocked", done.await(5000,
        TimeUnit.MILLISECONDS));
  }

  @Test
  public void testNewPipeBlockingSemantics() throws IOException {
    Pipe pipe = Pipe.open();
    ByteBuffer buf = ByteBuffer.allocate(10);
    assertTrue(pipe.source().isBlocking());
    pipe.source().configureBlocking(false);
    assertTrue(!pipe.source().isBlocking());
    int rdSz = pipe.source().read(buf); // this operation blocks!
    assertTrue(rdSz <= 0);
  }

  @Test
  public void testNewPipePartialReadSemantics() throws IOException {
    Pipe pipe = Pipe.open();
    int sz = 10;
    ByteBuffer buf = ByteBuffer.allocate(sz);
    pipe.sink().write(ByteBuffer.wrap("small".getBytes()));
    int rdSz = pipe.source().read(buf); // this operation blocks!
    assertTrue(rdSz <= sz);
  }

  /**
   * Test that aggregation works correctly - wait until file handle is closed
   * before returning the entire output
   *
   * @throws InterruptedException
   */
  @Test
  public void testAggregate() throws IOException, InterruptedException {
    File temp = File.createTempFile("flmtst", null);
    temp.deleteOnExit();

    BufferedWriter out = new BufferedWriter(new FileWriter(temp));
    out.write("#!/bin/bash\n echo \"Hello\"\necho \"World!\"\n");
    out.close();
    String cmd = temp.getAbsolutePath();
    ExecNioSource.Builder builder = new ExecNioSource.Builder();
    EventSource source = builder.build("/bin/bash " + cmd, "true");
    source.open();

    Clock.sleep(250); // need to sleep to let things percolate through threads.
    Event e = source.next();
    source.close();
    String output = new String(e.getBody());
    assertEquals("Expected aggregate exec output to be 'Hello\nWorld!', "
        + "but got '" + output + "'", output, "Hello\nWorld!\n");

  }

  /**
   * Test that restarting an exec after a pause works correctly. Requires
   * GNU-compatible 'date' to work correctly.
   */
  @Test
  public void testRestart() throws IOException, InterruptedException {
    File temp = File.createTempFile("flmtst", null);
    temp.deleteOnExit();

    BufferedWriter out = new BufferedWriter(new FileWriter(temp));
    out.write("#!/bin/bash\n date +%s");
    out.close();
    String cmd = temp.getAbsolutePath();
    ExecNioSource.Builder builder = new ExecNioSource.Builder();
    // aggregate = false, restart=true, restart after 1000ms
    EventSource source = builder.build("/bin/bash " + cmd, "false", "true",
        "1000");
    source.open();
    Event e1 = source.next();
    Event e2 = source.next();
    source.close();
    String t1 = new String(e1.getBody());
    String t2 = new String(e2.getBody());
    long time1 = Long.parseLong(t1);
    long time2 = Long.parseLong(t2);
    assertTrue("Time difference with repeated exec should be >= 1s", time2
        - time1 >= 1);
  }

  /**
   * Test that opening and closing a large number of times works correctly. In
   * order to hit file leak problems deterministically we need to know ulimit -n
   * on the local machine, but an assumption of 1024 is workable for now. So
   * this test can give false successes, but no false failures.
   */
  @Test
  public void testRepeatedOpenClose() {
    ExecNioSource.Builder builder = new ExecNioSource.Builder();
    EventSource source = builder.build("date");
    for (int i = 0; i < 1024; ++i) {
      try {
        source = builder.build("date");
        source.open();
        source.close();
      } catch (Exception e) {
        assertTrue("Exec open / close failed on iteration " + i
            + " with failure " + e, false);
      }
    }
  }

  @Test
  public void testNoRandomPrepend() throws IOException {
    File f = File.createTempFile("prepend", "bar");
    f.deleteOnExit();
    FileWriter fw = new FileWriter(f);

    ExecNioSource.Builder builder = new ExecNioSource.Builder();
    EventSource source = builder.build("tail -F " + f.getAbsolutePath());
    source.open();

    fw.write("foo\n");
    fw.flush();
    Event e = source.next();
    assertTrue(Arrays.equals("foo".getBytes(), e.getBody()));

    fw.write("bar\n");
    fw.flush();
    e = source.next();
    assertTrue(Arrays.equals("bar".getBytes(), e.getBody()));

    fw.write("baz\n");
    fw.flush();
    e = source.next();
    assertTrue(Arrays.equals("baz".getBytes(), e.getBody()));

    source.close();
  }

  @Test
  public void testTruncateLine() throws IOException {
    File f = File.createTempFile("truncate", ".bar");
    f.deleteOnExit();
    FileWriter fw = new FileWriter(f);

    ExecNioSource.Builder builder = new ExecNioSource.Builder();
    EventSource source = builder.build("tail -F " + f.getAbsolutePath());
    source.open();

    fw.write("foo\n");
    fw.flush();
    Event e = source.next();
    assertTrue(Arrays.equals("foo".getBytes(), e.getBody()));

    // this case inserts an extremely long line.
    int max = (int) FlumeConfiguration.get().getEventMaxSizeBytes();
    int tooBig = max * 10;
    byte[] data = new byte[tooBig];
    for (int i = 0; i < data.length; i++) {
      data[i] = 'a';
    }
    fw.write(new String(data) + "\n");
    fw.flush();
    e = source.next();
    assertEquals(max, e.getBody().length);

    // back to previous test
    fw.write("baz\n");
    fw.flush();
    e = source.next();
    assertTrue(Arrays.equals("baz".getBytes(), e.getBody()));

    source.close();
  }

}


text:
package io.gravitee.rest.api.service;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;

import io.gravitee.repository.exceptions.TechnicalException;
import io.gravitee.repository.management.api.GroupRepository;
import io.gravitee.repository.management.model.Group;
import io.gravitee.rest.api.model.*;
import io.gravitee.rest.api.model.api.ApiEntity;
import io.gravitee.rest.api.model.permissions.RoleScope;
import io.gravitee.rest.api.service.GroupService;
import io.gravitee.rest.api.service.MembershipService;
import io.gravitee.rest.api.service.impl.GroupServiceImpl;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

/**
 * @author Nicolas GERAUD (nicolas.geraud at graviteesource.com)
 * @author GraviteeSource Team
 */
@RunWith(MockitoJUnitRunner.class)
public class GroupService_IsUserAuthorizedToAccessTest {

    @InjectMocks
    private GroupService groupService = new GroupServiceImpl();

    @Mock
    private MembershipService membershipService;

    @Mock
    private GroupRepository groupRepository;

    @Mock
    private ApiEntity api;

    @Test
    public void shouldBeAuthorizedForAnonymousAndPublicApiWithoutRestrictions() throws TechnicalException {
        when(api.getVisibility()).thenReturn(Visibility.PUBLIC);

        boolean userAuthorizedToAccess = groupService.isUserAuthorizedToAccessApiData(api, Collections.emptyList(), null);

        assertTrue(userAuthorizedToAccess);
        verify(membershipService, never()).getRoles(any(), any(), any(), any());
        verify(groupRepository, never()).findAllByEnvironment("DEFAULT");
    }

    @Test
    public void shouldNotBeAuthorizedForAnonymousAndPrivateApiWithoutRestrictions() throws TechnicalException {
        when(api.getVisibility()).thenReturn(Visibility.PRIVATE);

        boolean userAuthorizedToAccess = groupService.isUserAuthorizedToAccessApiData(api, Collections.emptyList(), null);

        assertFalse(userAuthorizedToAccess);
        verify(membershipService, never()).getRoles(any(), any(), any(), any());
        verify(groupRepository, never()).findAllByEnvironment("DEFAULT");
    }

    @Test
    public void shouldBeAuthorizedForPublicApiWithoutRestriction() throws TechnicalException {
        boolean userAuthorizedToAccess = groupService.isUserAuthorizedToAccessApiData(api, Collections.emptyList(), "user");

        assertTrue(userAuthorizedToAccess);
        verify(membershipService, never()).getRoles(any(), any(), any(), any());
        verify(groupRepository, never()).findAllByEnvironment("DEFAULT");
    }

    @Test
    public void shouldBeAuthorizedForPrivateApiWithoutGroups() throws TechnicalException {
        when(api.getVisibility()).thenReturn(Visibility.PRIVATE);
        when(api.getGroups()).thenReturn(null);
        when(membershipService.getRoles(any(), any(), any(), any())).thenReturn(Collections.emptySet());
        boolean userAuthorizedToAccess = groupService.isUserAuthorizedToAccessApiData(api, Collections.singletonList("grp1"), "user");

        assertFalse(userAuthorizedToAccess);
        verify(membershipService, times(1)).getRoles(any(), any(), any(), any());
        verify(groupRepository, never()).findAllByEnvironment("DEFAULT");
    }

    @Test
    public void shouldBeAuthorizedForPrivateApiWithoutExcludedGroups() throws TechnicalException {
        boolean userAuthorizedToAccess = groupService.isUserAuthorizedToAccessApiData(api, null, "user");

        assertTrue(userAuthorizedToAccess);
        verify(membershipService, never()).getRoles(any(), any(), any(), any());
        verify(groupRepository, never()).findAllByEnvironment("DEFAULT");
    }

    @Test
    public void shouldBeAuthorizedForPrivateApiWithDirectMember() throws TechnicalException {
        when(api.getId()).thenReturn("apiId");
        when(membershipService.getRoles(MembershipReferenceType.API, api.getId(), MembershipMemberType.USER, "user"))
            .thenReturn(new HashSet<>(Arrays.asList(new RoleEntity())));

        boolean userAuthorizedToAccess = groupService.isUserAuthorizedToAccessApiData(api, Collections.singletonList("grp1"), "user");

        assertTrue(userAuthorizedToAccess);
        verify(membershipService, times(1)).getRoles(any(), any(), any(), any());
        verify(api, never()).getGroups();
        verify(groupRepository, never()).findAllByEnvironment("DEFAULT");
    }

    @Test
    public void shouldBeAuthorizedForPrivateApiIfMemberOfAuthorizedGroups() throws TechnicalException {
        when(api.getVisibility()).thenReturn(Visibility.PRIVATE);
        when(api.getId()).thenReturn("apiId");
        when(api.getGroups()).thenReturn(new HashSet<>(Arrays.asList("grp1", "grp2")));
        when(membershipService.getRoles(MembershipReferenceType.API, api.getId(), MembershipMemberType.USER, "user"))
            .thenReturn(Collections.emptySet());
        RoleEntity apiRoleEntity = new RoleEntity();
        apiRoleEntity.setScope(RoleScope.API);
        when(membershipService.getRoles(MembershipReferenceType.GROUP, "grp2", MembershipMemberType.USER, "user"))
            .thenReturn(new HashSet<>(Arrays.asList(apiRoleEntity)));

        boolean userAuthorizedToAccess = groupService.isUserAuthorizedToAccessApiData(api, Collections.singletonList("grp1"), "user");

        assertTrue(userAuthorizedToAccess);
        verify(membershipService, times(2)).getRoles(any(), any(), any(), any());
        verify(membershipService, times(1)).getRoles(MembershipReferenceType.API, api.getId(), MembershipMemberType.USER, "user");
        verify(membershipService, times(1)).getRoles(MembershipReferenceType.GROUP, "grp2", MembershipMemberType.USER, "user");
        verify(api, atLeast(2)).getGroups();
        verify(groupRepository, never()).findAllByEnvironment("DEFAULT");
    }

    @Test
    public void shouldNotBeAuthorizedForPrivateApiIfMemberOfUnauthorizedGroups() throws TechnicalException {
        when(api.getVisibility()).thenReturn(Visibility.PRIVATE);
        when(api.getId()).thenReturn("apiId");
        when(api.getGroups()).thenReturn(new HashSet<>(Arrays.asList("grp1", "grp2")));
        when(membershipService.getRoles(MembershipReferenceType.API, api.getId(), MembershipMemberType.USER, "user"))
            .thenReturn(Collections.emptySet());
        when(membershipService.getRoles(MembershipReferenceType.GROUP, "grp2", MembershipMemberType.USER, "user"))
            .thenReturn(Collections.emptySet());

        boolean userAuthorizedToAccess = groupService.isUserAuthorizedToAccessApiData(api, Collections.singletonList("grp1"), "user");

        assertFalse(userAuthorizedToAccess);
        verify(membershipService, times(2)).getRoles(any(), any(), any(), any());
        verify(membershipService, times(1)).getRoles(MembershipReferenceType.API, api.getId(), MembershipMemberType.USER, "user");
        verify(membershipService, times(1)).getRoles(MembershipReferenceType.GROUP, "grp2", MembershipMemberType.USER, "user");
        verify(api, atLeast(2)).getGroups();
        verify(groupRepository, never()).findAllByEnvironment("DEFAULT");
    }

    @Test
    public void shouldNotBeAuthorizedForPublicApiIfMemberOfUnauthorizedGroups() throws TechnicalException {
        when(api.getVisibility()).thenReturn(Visibility.PUBLIC);
        when(api.getId()).thenReturn("apiId");
        Group excludedGroup = new Group();
        excludedGroup.setId("excludedGroup");
        RoleEntity apiRole = new RoleEntity();
        apiRole.setScope(RoleScope.API);
        when(membershipService.getRoles(MembershipReferenceType.API, api.getId(), MembershipMemberType.USER, "user"))
            .thenReturn(Collections.emptySet());
        when(membershipService.getRoles(MembershipReferenceType.GROUP, "excludedGroup", MembershipMemberType.USER, "user"))
            .thenReturn(Collections.singleton(apiRole));

        boolean userAuthorizedToAccess = groupService.isUserAuthorizedToAccessApiData(
            api,
            Collections.singletonList("excludedGroup"),
            "user"
        );

        assertFalse(userAuthorizedToAccess);
        verify(membershipService, times(2)).getRoles(any(), any(), any(), any());
        verify(membershipService, times(1)).getRoles(MembershipReferenceType.API, api.getId(), MembershipMemberType.USER, "user");
        verify(membershipService, times(1)).getRoles(MembershipReferenceType.GROUP, "excludedGroup", MembershipMemberType.USER, "user");
        verify(api, never()).getGroups();
    }
}

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

# Test if the configs in rails_app/config/initializers/warden_github_rails.rb
# are actually being set and used by warden.
describe 'request to custom configured scope' do
  def test_redirect(url, args)
    request = get url
    params = Addressable::URI.parse(request.location).query_values

    expect(request).to be_github_oauth_redirect
    expect(params.fetch('client_id')).to eq(args.fetch(:client_id))
    expect(params.fetch('redirect_uri')).to match(args.fetch(:redirect_uri))
    expect(params.fetch('scope')).to eq(args.fetch(:scope))
  end

  context 'user' do
    it 'passes the correct configs to the oauth flow' do
      test_redirect('/protected',
                    client_id: 'foo',
                    redirect_uri: /\/protected$/,
                    scope: 'user')
    end
  end

  context 'admin' do
    it 'passes the correct configs to the oauth flow' do
      test_redirect('/admin/protected',
                    client_id: 'abc',
                    redirect_uri: /\/admin\/login\/callback$/,
                    scope: 'repo')
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<resources>
	<string name="home">ホーム</string>
	<string name="settings">設定</string>
	<string name="openWindow">新しいウインドを開く</string>
	<string name="newWindow">新しいウインド</string>
</resources>


text:
<?php
error_reporting(1);

require 'vendor/autoload.php';

try{
	$qr = new QuoteRoller\QuoteRoller();

}catch (Exception $e){
	echo $e->getMessgae();
}


text:
package net.bytebuddy.implementation;

import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.test.utility.MockitoRule;
import net.bytebuddy.test.utility.ObjectPropertyAssertion;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.mockito.Mock;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

public class FieldAccessorFieldNameExtractorForFixedValueTest {

    private static final String FOO = "foo", FOO_CAPITAL = "Foo";

    @Rule
    public TestRule mockitoRule = new MockitoRule(this);

    @Mock
    private MethodDescription methodDescription;

    @Test
    public void testGetterMethod() throws Exception {
        assertThat(new FieldAccessor.FieldNameExtractor.ForFixedValue(FOO).resolve(methodDescription), is(FOO));
    }

    @Test
    public void testObjectProperties() throws Exception {
        ObjectPropertyAssertion.of(FieldAccessor.FieldNameExtractor.ForFixedValue.class).apply();
    }
}


text:
class TestModelsController < ApplicationController
  before_action :set_test_model, only: [:show, :edit, :update, :destroy]

  # GET /test_models
  def index
    @test_models = TestModel.all
  end

  # GET /test_models/1
  def show
  end

  # GET /test_models/new
  def new
    @test_model = TestModel.new
  end

  # GET /test_models/1/edit
  def edit
  end

  # POST /test_models
  def create
    @test_model = TestModel.new(test_model_params)

    if @test_model.save
      redirect_to @test_model, notice: 'Test model was successfully created.'
    else
      render :new
    end
  end

  # PATCH/PUT /test_models/1
  def update
    if @test_model.update(test_model_params)
      redirect_to @test_model, notice: 'Test model was successfully updated.'
    else
      render :edit
    end
  end

  # DELETE /test_models/1
  def destroy
    @test_model.destroy
    redirect_to test_models_url, notice: 'Test model was successfully destroyed.'
  end

  private

  # Use callbacks to share common setup or constraints between actions.
  def set_test_model
    @test_model = TestModel.find(params[:id])
  end

  # Only allow a trusted parameter "white list" through.
  def test_model_params
    params.require(:test_model).permit(:title, :body, :user_id)
  end
end


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
var autoAdjustOverflow = {
  adjustX: 1,
  adjustY: 1
};

var targetOffset = [0, 0];

var placements = {
  bottomLeft: {
    points: ['tl', 'tl'],
    overflow: autoAdjustOverflow,
    offset: [0, -3],
    targetOffset: targetOffset
  },
  bottomRight: {
    points: ['tr', 'tr'],
    overflow: autoAdjustOverflow,
    offset: [0, -3],
    targetOffset: targetOffset
  },
  topRight: {
    points: ['br', 'br'],
    overflow: autoAdjustOverflow,
    offset: [0, 3],
    targetOffset: targetOffset
  },
  topLeft: {
    points: ['bl', 'bl'],
    overflow: autoAdjustOverflow,
    offset: [0, 3],
    targetOffset: targetOffset
  }
};

exports["default"] = placements;
module.exports = exports['default'];


text:
#pragma once
#include <aws/comprehend/Comprehend_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace Comprehend
{
namespace Model
{
  enum class PartOfSpeechTagType
  {
    NOT_SET,
    ADJ,
    ADP,
    ADV,
    AUX,
    CONJ,
    DET,
    INTJ,
    NOUN,
    NUM,
    O,
    PART,
    PRON,
    PROPN,
    PUNCT,
    SCONJ,
    SYM,
    VERB
  };

namespace PartOfSpeechTagTypeMapper
{
AWS_COMPREHEND_API PartOfSpeechTagType GetPartOfSpeechTagTypeForName(const Aws::String& name);

AWS_COMPREHEND_API Aws::String GetNameForPartOfSpeechTagType(PartOfSpeechTagType value);
} // namespace PartOfSpeechTagTypeMapper
} // namespace Model
} // namespace Comprehend
} // namespace Aws


text:
package com.rhomobile.nfc;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcManager;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.MifareUltralight;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.nfc.tech.NfcA;
import android.nfc.tech.NfcB;
import android.nfc.tech.NfcF;
import android.nfc.tech.NfcV;
import android.nfc.tech.TagTechnology;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;

import com.rhomobile.rhodes.RhodesActivity;
import com.rhomobile.rhodes.RhodesActivityListener;
import com.rhomobile.rhodes.RhodesService;
import com.rhomobile.rhodes.util.Utils;
import com.rhomobile.rhodes.util.PerformOnUiThread;

public class Nfc implements RhodesActivityListener {

	private static final String TAG = Nfc.class.getSimpleName();

	private static boolean ourIsEnable = false;
	private static String ourCallback = null;
	private static String ourTechCallback = null;

	private static NdefMessage ourP2PNdefMessage = null;

	private static Nfc ourInstance = null;

	private static native void callCallback(String callback_url, NfcMessagePack msgpack);
	private static native void callTechCallback(String callback_url, String tech_event);

	private static Tag ourTag = null;

	private MifareClassic mMifareClassic = null;
	private MifareUltralight mMifareUltralight = null;
	private Ndef mNdef = null;
	private NfcA mNfcA = null;
	private IsoDep mIsoDep = null;
	private NdefFormatable mNdefFormatable = null;
	private NfcB mNfcB = null;
	private NfcF mNfcF = null;
	private NfcV mNfcV = null;
	private ArrayList<String> mTechList = null;
	private Hashtable<String,TagTechnology> mTechs = null;

	private static final boolean isLogging = false;

	private static native void logNative(String msg);

	private static NdefMessage[] ourApplicationStartupMessages = null;
	private static Tag ourApplicationStartupTag = null;

	public static void setApplicationStartupIntent(Intent intent) {
		getInstance().onNewIntent(null, intent, true);
	}

	public static void performOpenApplicationTag() {
		PerformOnUiThread.exec(new Runnable() {
			public void run() {
				if (ourApplicationStartupMessages != null) {
					getInstance().onReceiveMessages(ourApplicationStartupMessages);
					ourApplicationStartupMessages = null;
				}
				else {
					log("ourApplicationStartupMessages is NULL !");
				}
				if (ourApplicationStartupTag != null) {
					getInstance().onReceiveTag(ourApplicationStartupTag);
					ourApplicationStartupTag = null;
				}
				else {
					log("ourApplicationStartupTag is NULL !");
				}
			}
		}, 100);
	}

	public static void log(String msg) {
		//logNative(msg);
		if (isLogging) {
			Utils.platformLog(TAG, msg);
		}
	}

	public static void loge(String msg) {
		Utils.platformLog(TAG, msg);
	}

	public static Nfc getInstance() {
		if (ourInstance == null) {
			ourInstance = new Nfc();
		}
		return ourInstance;
	}

	public static NfcAdapter getDefaultAdapter(Context ctx) {
		Context context = ctx;
		if (ctx == null) {
			context = RhodesActivity.getContext();
		}
		NfcAdapter da = null;
		try {
			int sdkVersion = Build.VERSION.SDK_INT;
			if (sdkVersion >= Build.VERSION_CODES.GINGERBREAD_MR1) {
				da = NfcAdapter.getDefaultAdapter(RhodesActivity.getContext());
			}
			else if (sdkVersion >= Build.VERSION_CODES.GINGERBREAD) {
				da = NfcAdapter.getDefaultAdapter();
			}
		}
		catch (Exception e) {
			// nothing
			Utils.platformLog(TAG, "Exception during get NFCAdapter");
			e.printStackTrace();
		}
		return da;
	}

	public static int isSupported() {
		NfcAdapter da = getDefaultAdapter(null);
		if (da == null) {
			return 0;
		}
		int res = 0;
		if (da.isEnabled()) {
			res = 1;
		}
		return res;
	}

	public static int isEnabled() {
		int res = 0;
		if (ourIsEnable) {
			res = 1;
		}
		return res;
	}

	public static void setEnable(int enable) {
		log(" $$$$$$$$$ setEnable() START() ");
		boolean oldEnable = ourIsEnable;
		ourIsEnable = (enable != 0);
		if ((oldEnable == false) && (ourIsEnable == true)) {
			//RhodesActivity.safeGetInstance().addRhodesActivityListener(getInstance());
			PerformOnUiThread.exec( new Runnable() {
				public void run() {
					if (RhodesActivity.safeGetInstance().isForegroundNow()) {
						getInstance().onResume(RhodesActivity.safeGetInstance());
					}
				}
			});
		}
		if ((oldEnable == true) && (ourIsEnable == false)) {
			//RhodesActivity.safeGetInstance().removeRhodesActivityListener(getInstance());
			PerformOnUiThread.exec( new Runnable() {
				public void run() {
					if (RhodesActivity.safeGetInstance().isForegroundNow()) {
						getInstance().onPause(RhodesActivity.safeGetInstance());
					}
				}
			});
		}
		log(" $$$$$$$$$ setEnable() FINISH() ");
	}

	public void onCreate(RhodesActivity activity, Intent intent) {
		getInstance().onNewIntent(activity, intent, true);
	}

	public void onRhodesActivityStartup(RhodesActivity activity) {
		activity.addRhodesActivityListener(getInstance());
	}

	public void onPause(RhodesActivity activity) {
		log(" $$$$$$$$$ onPause() ");
		NfcAdapter nfcAdapter = getDefaultAdapter(RhodesActivity.getContext());
		if (nfcAdapter != null) {
			nfcAdapter.disableForegroundDispatch(activity);
			nfcAdapter.disableForegroundNdefPush(activity);
		}
	}

	public void onResume(RhodesActivity activity) {
		log(" $$$$$$$$$ onResume() ");
		NfcAdapter nfcAdapter = getDefaultAdapter(RhodesActivity.getContext());
		if ((nfcAdapter != null) && (ourIsEnable)) {
			IntentFilter[] filters = new IntentFilter[1];
			filters[0] = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);

			PendingIntent intent =
	            PendingIntent.getActivity(activity, 0,
	              new Intent(activity, activity.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),
	              0);

			nfcAdapter.enableForegroundDispatch(activity, intent, null, null);
			if (ourP2PNdefMessage != null) {
				nfcAdapter.enableForegroundNdefPush(activity, ourP2PNdefMessage);
			}
		}
	}

	public void onNewIntent(RhodesActivity activity, Intent intent, boolean postpone) {
		String action = intent.getAction();

		Utils.platformLog("Nfc", "onNewIntent !!! Action = "+action+"     postpone="+String.valueOf(postpone));

		if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
			log("ACTION_TAG_DISCOVERED !");
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            NdefMessage[] msgs;
            if (rawMsgs != null) {
    			log(" Found rawMessages from Intent !");
                msgs = new NdefMessage[rawMsgs.length];
                for (int i = 0; i < rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];
                }
            } else {
                // Unknown tag type
    			log(" Intent not have any Messages !");
                byte[] empty = new byte[] {};
                NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, empty, empty);
                NdefMessage msg = new NdefMessage(new NdefRecord[] {record});
                msgs = new NdefMessage[] {msg};
            }
            if (postpone) {
            	ourApplicationStartupMessages = msgs;
            }
            else {
            	getInstance().onReceiveMessages(msgs);
            }
            Tag tag = (Tag)intent.getExtras().get(NfcAdapter.EXTRA_TAG);
			if (tag != null) {
				log("     Tag found in extars ! ");
	            if (postpone) {
	            	ourApplicationStartupTag = tag;
	            }
	            else {
	            	getInstance().onReceiveTag(tag);
	            }
			}
			else {
				log("     Tag not found in extars ! ");
			}
        }
		if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
			log("ACTION_NDEF_DISCOVERED !");
			Uri u = intent.getData();

			if (u != null) {
				log("     Data = "+u.toString());
			}
			else {
				log("     Data = NULL");
			}
			String t = intent.getType();
			if (t != null) {
				log("     Type = "+t);
			}
			else {
				log("     Type is NULL= ");
			}

			Tag tag = (Tag)intent.getExtras().get(NfcAdapter.EXTRA_TAG);
			if (tag != null) {
				log("     Tag found in extars ! ");
			}
			else {
				log("     Tag not found in extars ! ");
			}

            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            NdefMessage[] msgs;
            if (rawMsgs != null) {
                msgs = new NdefMessage[rawMsgs.length];
                for (int i = 0; i < rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];
                }
            } else {
                // Unknown tag type
    			log("     Unknown Tag type !!!");
                byte[] empty = new byte[] {};
                NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, empty, empty);
                NdefMessage msg = new NdefMessage(new NdefRecord[] {record});
                msgs = new NdefMessage[] {msg};
            }
            if (postpone) {
            	ourApplicationStartupMessages = msgs;
            }
            else {
            	getInstance().onReceiveMessages(msgs);
            }

            if (tag != null) {
	            if (postpone) {
	            	ourApplicationStartupTag = tag;
	            }
	            else {
	            	getInstance().onReceiveTag(tag);
	            }
            }
        }
		if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) {
			log("ACTION_TECH_DISCOVERED !");
			Tag tag = (Tag)intent.getExtras().get(NfcAdapter.EXTRA_TAG);
			if (tag != null) {
	            if (postpone) {
	            	ourApplicationStartupTag = tag;
	            }
	            else {
	            	getInstance().onReceiveTag(tag);
	            }
			}
        }
	}

	public void onNewIntent(RhodesActivity activity, Intent intent) {
		if (activity.isInsideStartStop()) {
			onNewIntent(activity, intent, false);
		}
		else {
			onNewIntent(activity, intent, true);
		}
	}

	public static void setCallback(String callback) {
		ourCallback = callback;
	}

	public static void setTechCallback(String callback) {
		ourTechCallback = callback;
	}

	//@Override
	//public void onReceive(Context context, Intent intent) {

	private static boolean isRhodesApplicationRun() {
		return RhodesService.getInstance()!=null;
	}

	public void onReceiveTag(Tag tag) {
		//if (!ourIsEnable) {
		//	return;
		//}

		log("onReceiveTag()");
		if (tag == null) {
			return;
		}

		ourTag = tag;

		mTechs = new Hashtable<String,TagTechnology>();
		mTechList = new ArrayList<String>();

		mMifareClassic = MifareClassic.get(tag);
		mMifareUltralight = MifareUltralight.get(tag);
		mNdef = Ndef.get(tag);
		mNfcA = NfcA.get(tag);
		mIsoDep = IsoDep.get(tag);
		mNdefFormatable = NdefFormatable.get(tag);
		mNfcB = NfcB.get(tag);
		mNfcF = NfcF.get(tag);
		mNfcV = NfcV.get(tag);

		if (mMifareClassic != null) {
			mTechs.put("MifareClassic", mMifareClassic);
			if (isLogging) {
				log("     MifareClassic found !");
				log("     MifareClassic.block_count() = "+String.valueOf(mMifareClassic.getBlockCount()));
				log("     MifareClassic.sector_count() = "+String.valueOf(mMifareClassic.getSectorCount()));
				log("     MifareClassic.size() = "+String.valueOf(mMifareClassic.getSize()));
			}
		}
		if (mMifareUltralight != null) {
			mTechs.put("MifareUltralight", mMifareUltralight);
		}
		if (mNdef != null) {
			mTechs.put("Ndef", mNdef);
		}
		if (mNfcA != null) {
			mTechs.put("NfcA", mNfcA);
		}
		if (mIsoDep != null) {
			mTechs.put("IsoDep", mIsoDep);
		}
		if (mNdefFormatable != null) {
			mTechs.put("NdefFormatable", mNdefFormatable);
		}
		if (mNfcB != null) {
			mTechs.put("NfcB", mNfcB);
		}
		if (mNfcF != null) {
			mTechs.put("NfcF", mNfcF);
		}
		if (mNfcV != null) {
			mTechs.put("NfcV", mNfcV);
		}

		Set<String> keys = mTechs.keySet();
		Iterator<String> iterator = keys.iterator();
		while (iterator.hasNext()) {
			String key = iterator.next();
			mTechList.add(key);
		}

        log("NFC TAG Tech Received ! Service started = "+String.valueOf(isRhodesApplicationRun()));

        if (isRhodesApplicationRun()) {
        	if (ourIsEnable) {
        		if (ourTechCallback != null) {
        			if (ourTechCallback.length() > 0) {
        				if (mTechList.size() > 0) {
        					log("call Tech callback !");
        					callTechCallback(ourTechCallback, "discovered");
        				}
        				else {
                            log("received Tag is not support any techs - empty Tag !, then no callback !");
        				}
        			}
                	else {
                        log("Nfc callback is empty");
                	}
        		}
            	else {
                    log("Nfc callback is null");
            	}
        	}
        	else {
                log("Nfc is not enabled");
        	}
        }
        else {
            log("Rhodes application is not runned");
        }

	}

	public void onReceiveMessages(NdefMessage[] msgs) {
		//if (!ourIsEnable) {
		//	return;
		//}
		log("onReceiveMessages()");
        if (msgs == null || msgs.length == 0) {
            return;
        }

        log("NFC TAG(with NDE Messages) Received ! Service started = "+String.valueOf(isRhodesApplicationRun()));

        NfcMessagePack pack = new NfcMessagePack(msgs);

        log("Message Pack created");
        if (isRhodesApplicationRun()) {
        	if (ourIsEnable) {
        		if (ourCallback != null) {
        			if (ourCallback.length() > 0) {
        				callCallback(ourCallback, pack);
        			}
                	else {
                        log("Nfc callback is empty");
                	}
        		}
            	else {
                    log("Nfc callback is null");
            	}
        	}
        	else {
                log("Nfc is not enabled");
        	}
        }
	}

	public static void clear_listen_tech_list() {
		// listen all now
	}

	public static void add_listen_tech(String tech_name) {
		// listen all now
	}

	public static int get_tech_list_count() {
		return getInstance().mTechList.size();
	}

	public static String get_tech_list(int index) {
		return getInstance().mTechList.get(index);
	}

	public static void tech_connect(String tech_name) {
		log("tech_connect("+tech_name+") START");
		if (getInstance().mTechs == null) {
			log("     tech list is empty");
			return;
		}
		TagTechnology tech = getInstance().mTechs.get(tech_name);
		if (tech == null) {
			log("     tech is not supported by current Tag");
			return;
		}
		try {
			tech.connect();
		} catch (IOException e) {
			loge("Exception in tech_connect()");
			e.printStackTrace();
		}
		log("tech_connect("+tech_name+") FINISH");
	}

	public static void tech_close(String tech_name) {
		if (getInstance().mTechs == null) {
			return;
		}
		TagTechnology tech = getInstance().mTechs.get(tech_name);
		if (tech == null) {
			return;
		}
		try {
			tech.close();
		} catch (IOException e) {
			loge("Exception in tech_close()");
			e.printStackTrace();
		}
	}

	public static int tech_is_connected(String tech_name) {
		if (getInstance().mTechs == null) {
			log ("tech_is_connected("+tech_name+") return FALSE because tech list is empty");
			return 0;
		}
		TagTechnology tech = getInstance().mTechs.get(tech_name);
		if (tech == null) {
			log ("tech_is_connected("+tech_name+") return FALSE because tech is not supported");
			return 0;
		}
		if (tech.isConnected()) {
			log ("tech_is_connected("+tech_name+") return TRUE");
			return 1;
		}
		log ("tech_is_connected("+tech_name+") return FALSE");
		return 0;
	}

	public static int tech_MifareClassic_get_size() {
		if (getInstance().mMifareClassic != null)
			return getInstance().mMifareClassic.getSize();
		return 0;
	}

	public static int tech_MifareClassic_get_block_count() {
		if (getInstance().mMifareClassic != null)
			return getInstance().mMifareClassic.getBlockCount();
		return 0;
	}

	public static int tech_MifareClassic_get_sector_count() {
		if (getInstance().mMifareClassic != null)
			return getInstance().mMifareClassic.getSectorCount();
		return 0;
	}

	public static int tech_MifareClassic_get_blocks_in_sector_count(int index) {
		if (getInstance().mMifareClassic != null)
			return getInstance().mMifareClassic.getBlockCountInSector(index);
		return 0;
	}

	public static int tech_MifareClassic_get_type() {
		if (getInstance().mMifareClassic != null)
			return getInstance().mMifareClassic.getType();
		return -2;
	}

	public static byte[] tech_MifareClassic_transceive(byte[] data) {
		log ("tech_MifareClassic_transceive() START");

		if (getInstance().mMifareClassic == null) {
			log ("     MifareClassic is not supported in current Tag");
			return null;
		}
		byte[] result = null;
		try {
			result = getInstance().mMifareClassic.transceive(data);
		} catch (IOException e) {
			loge("     Exception in tech_MifareClassic_transceive()");
			e.printStackTrace();
		}
		log("tech_MifareClassic_transceive() FINISH");
		return result;
	}

	public static byte[] tag_get_id() {
		if (ourTag == null) {
			return null;
		}
		return ourTag.getId();
	}

	public static int tech_MifareClassic_sector_to_block(int index) {
		if (getInstance().mMifareClassic != null)
			return getInstance().mMifareClassic.sectorToBlock(index);
		return 0;
	}

	public static int tech_MifareClassic_authenticate_sector_with_key_A(int index, byte[] key) {
		if (getInstance().mMifareClassic != null) {
			try {
				boolean auth = getInstance().mMifareClassic.authenticateSectorWithKeyA(index, key);
				if (auth) {
					return 1;
				}
			}
			catch (IOException e) {
				loge("IOException in tech_MifareClassic_authenticate_sector_with_key_A()");
			}
		}
		return 0;
	}

	public static int tech_MifareClassic_authenticate_sector_with_key_B(int index, byte[] key) {
		if (getInstance().mMifareClassic != null) {
			try {
				boolean auth = getInstance().mMifareClassic.authenticateSectorWithKeyB(index, key);
				if (auth) {
					return 1;
				}
			}
			catch (IOException e) {
				loge("IOException in tech_MifareClassic_authenticate_sector_with_key_B()");
			}
		}
		return 0;
	}

	public static void tech_MifareClassic_write_block(int index, byte[] block) {
		log ("tech_MifareClassic_write_block("+String.valueOf(index)+") START");

		if (getInstance().mMifareClassic == null) {
			log ("     MifareClassic is not supported in current Tag");
			return;
		}
		try {
			getInstance().mMifareClassic.writeBlock(index, block);
		} catch (IOException e) {
			loge("     Exception in tech_MifareClassic_write_block("+String.valueOf(index)+")");
			e.printStackTrace();
		}
		log("tech_MifareClassic_read_block("+String.valueOf(index)+") FINISH");

	}

	public static int tech_MifareClassic_read_block(int index, byte[] block) {
		log ("tech_MifareClassic_read_block("+String.valueOf(index)+") START");

		int i;
		for (i = 0; i < 16; i++) {
			block[i] = 0;
		}

		if (getInstance().mMifareClassic == null) {
			log ("     MifareClassic is not supported in current Tag");
			return 0;
		}
		byte[] readed_block = null;
		try {
			readed_block = getInstance().mMifareClassic.readBlock(index);
		} catch (IOException e) {
			loge("     Exception in tech_MifareClassic_read_block("+String.valueOf(index)+")");
			e.printStackTrace();
		}
		if (readed_block == null) {
			log ("     null array returned !");
			return 0;
		}
		StringBuffer s = new StringBuffer();
		s.append("   block is : ");
		for (i = 0; (i < readed_block.length) && (i < block.length); i++) {
			block[i] = readed_block[i];
			s.append(block[i]);
			s.append(":");
		}
		log(s.toString());
		log("tech_MifareClassic_read_block("+String.valueOf(index)+") FINISH");
		return 1;
	}

	public static int tech_Ndef_get_max_size() {
		if (getInstance().mNdef != null)
			return getInstance().mNdef.getMaxSize();
		return 0;
	}

	public static String tech_Ndef_get_type() {
		if (getInstance().mNdef != null)
			return getInstance().mNdef.getType();
		return null;
	}

	public static int tech_Ndef_is_writable() {
		int res = 0;
		if (getInstance().mNdef != null)
			if (getInstance().mNdef.isWritable()) {
				res = 1;
			}
		return res;
	}

	public static int tech_Ndef_can_make_read_only() {
		int res = 0;
		if (getInstance().mNdef != null)
			if (getInstance().mNdef.canMakeReadOnly()) {
				res = 1;
			}
		return res;
	}

	public static int tech_Ndef_make_read_only() {
		int res = 0;
		if (getInstance().mNdef != null)
			try {
				if (getInstance().mNdef.makeReadOnly()) {
					res = 1;
				}
			} catch (IOException e) {
				loge("     Exception in tech_Ndef_make_read_only()");
				e.printStackTrace();
			}
		return res;
	}

	public static void tech_Ndef_write_Nde_message(byte[] message) {
		/*
		if (message != null) {
			Utils.platformLog("MSG", " ID = "+message.toString());

			StringBuffer s = new StringBuffer();
			s.append("   Message is ["+String.valueOf(message.length)+"]   : ");
			int i;
			for (i = 0; i < message.length; i++) {
				s.append(message[i]);
				s.append(":");
			}
			Utils.platformLog("MSG", s.toString());

		}
		else {
			Utils.platformLog("MSG", " message is NULL !!!");
		}
		*/
	    try {
			NdefMessage m = new NdefMessage(message);
			if (getInstance().mNdef != null) {
				getInstance().mNdef.writeNdefMessage(m);
			}
		} catch (FormatException e) {
			loge("Format exception in tech_Ndef_write_Nde_message()");
			e.printStackTrace();
		} catch (IOException e) {
			loge("IO exception in tech_Ndef_write_Nde_message()");
			e.printStackTrace();
		}
	}

	public static byte[] tech_Ndef_read_Nde_message() {
		NdefMessage m = null;
		if (getInstance().mNdef != null) {
			try {
				m = getInstance().mNdef.getNdefMessage();
			} catch (IOException e) {
				loge("IO exception in tech_Ndef_read_Nde_message()");
				e.printStackTrace();
			} catch (FormatException e) {
				loge("Format exception in tech_Ndef_read_Nde_message()");
				e.printStackTrace();
			}
		}
		if (m != null) {
			return m.toByteArray();
		}
		return null;
	}

	public static byte[] tech_NfcA_get_Atqa() {
		if (getInstance().mNfcA != null) {
			return getInstance().mNfcA.getAtqa();
		}
		return null;
	}

	public static int tech_NfcA_get_Sak() {
		if (getInstance().mNfcA != null) {
			return getInstance().mNfcA.getSak();
		}
		return 0;
	}

	public static byte[] tech_NfcA_transceive(byte[] data) {
		if (getInstance().mNfcA == null) {
			log ("     mNfcA is not supported in current Tag");
			return null;
		}
		byte[] result = null;
		try {
			result = getInstance().mNfcA.transceive(data);
		} catch (IOException e) {
			loge("     Exception in tech_NfcA_transceive()");
			e.printStackTrace();
		}
		return result;
	}

	public static byte[] tech_IsoDep_get_hi_layer_responce() {
		if (getInstance().mIsoDep != null) {
			return getInstance().mIsoDep.getHiLayerResponse();
		}
		return null;
	}

	public static byte[] tech_IsoDep_get_historical_bytes() {
		if (getInstance().mIsoDep != null) {
			return getInstance().mIsoDep.getHistoricalBytes();
		}
		return null;
	}

	public static void tech_IsoDep_set_timeout(int timeout) {
		if (getInstance().mIsoDep != null) {
			getInstance().mIsoDep.setTimeout(timeout);
		}
	}

	public static byte[] tech_IsoDep_transceive(byte[] data) {
		if (getInstance().mIsoDep == null) {
			log ("     IsoDep is not supported in current Tag");
			return null;
		}
		byte[] result = null;
		try {
			result = getInstance().mIsoDep.transceive(data);
		} catch (IOException e) {
			loge("     Exception in tech_mIsoDep_transceive()");
			e.printStackTrace();
		}
		return result;
	}

	public static void tech_NdefFormatable_format(byte[] ndef_message_byte_array) {
	    try {
			NdefMessage m = new NdefMessage(ndef_message_byte_array);
			if (getInstance().mNdefFormatable != null) {
				getInstance().mNdefFormatable.format(m);
			}
		} catch (FormatException e) {
			loge("Format exception in tech_NdefFormatable_format()");
			e.printStackTrace();
		} catch (IOException e) {
			loge("IO exception in tech_NdefFormatable_format()");
			e.printStackTrace();
		}
	}

	public static void tech_NdefFormatable_format_read_only(byte[] ndef_message_byte_array) {
	    try {
			NdefMessage m = new NdefMessage(ndef_message_byte_array);
			if (getInstance().mNdefFormatable != null) {
				getInstance().mNdefFormatable.formatReadOnly(m);
			}
		} catch (FormatException e) {
			loge("Format exception in tech_NdefFormatable_format_read_only()");
			e.printStackTrace();
		} catch (IOException e) {
			loge("IO exception in tech_NdefFormatable_format_read_only()");
			e.printStackTrace();
		}
	}

	public static byte[] tech_NfcB_get_application_data() {
		if (getInstance().mNfcB != null) {
			return getInstance().mNfcB.getApplicationData();
		}
		return null;
	}

	public static byte[] tech_NfcB_get_protocol_info() {
		if (getInstance().mNfcB != null) {
			return getInstance().mNfcB.getProtocolInfo();
		}
		return null;
	}

	public static byte[] tech_NfcB_transceive(byte[] data) {
		if (getInstance().mNfcB == null) {
			log ("     NfcB is not supported in current Tag");
			return null;
		}
		byte[] result = null;
		try {
			result = getInstance().mNfcB.transceive(data);
		} catch (IOException e) {
			loge("     Exception in tech_NfcB_transceive()");
			e.printStackTrace();
		}
		return result;
	}

	public static byte[] tech_NfcF_get_manufacturer() {
		if (getInstance().mNfcF != null) {
			return getInstance().mNfcF.getManufacturer();
		}
		return null;
	}

	public static byte[] tech_NfcF_get_system_code() {
		if (getInstance().mNfcF != null) {
			return getInstance().mNfcF.getSystemCode();
		}
		return null;
	}

	public static byte[] tech_NfcF_transceive(byte[] data) {
		if (getInstance().mNfcF == null) {
			log ("     NfcF is not supported in current Tag");
			return null;
		}
		byte[] result = null;
		try {
			result = getInstance().mNfcF.transceive(data);
		} catch (IOException e) {
			loge("     Exception in tech_NfcF_transceive()");
			e.printStackTrace();
		}
		return result;
	}

	public static int tech_NfcV_get_dsf_id() {
		if (getInstance().mNfcV != null) {
			return getInstance().mNfcV.getDsfId();
		}
		return 0;
	}

	public static int tech_NfcV_get_responce_flags() {
		if (getInstance().mNfcV != null) {
			return getInstance().mNfcV.getResponseFlags();
		}
		return 0;
	}

	public static byte[] tech_NfcV_transceive(byte[] data) {
		if (getInstance().mNfcV == null) {
			log ("     NfcV is not supported in current Tag");
			return null;
		}
		byte[] result = null;
		try {
			result = getInstance().mNfcV.transceive(data);
		} catch (IOException e) {
			loge("     Exception in tech_NfcV_transceive()");
			e.printStackTrace();
		}
		return result;
	}

	public static NfcRecord convert_byte_array_to_NdeRecord_hash(byte[] array) {
	    return new NfcRecord(array);
	}

	public static byte[] convert_NdeRecord_hash_to_byte_array(byte[] id, byte[] payload, int tnf, byte[] type) {
	    NfcRecord r = new NfcRecord((short)tnf, type, id, payload);
	    return r.getByteArray();
	}

	public static NfcMessage convert_NdeMessage_byte_array_to_NdeRecords_array(byte[] array) {
		return new NfcMessage(array);
	}

	public static NfcMessage make_empty_NfcMessage() {
		return new NfcMessage();
	}

	public static NfcRecord make_NfcRecord(byte[] id, byte[] payload, int tnf, byte[] type) {
		return new NfcRecord((short)tnf, type, id, payload);
	}

	public static String make_string_from_payload(byte[] payload, int tnf, byte[] type) {
		return NfcRecord.makePayloadString((short)tnf, type, payload, null);
	}

	public static byte[] make_payload_with_absolute_uri(String str) {
	    return str.getBytes();
	}

	public static byte[] make_payload_with_well_known_text(String language, String str) {
	    byte[] b_lang = language.getBytes();
	    byte[] b_str = str.getBytes();
	    byte[] result = new byte[b_lang.length + b_str.length+1];

	    result[0] = (byte)b_lang.length;
	    int i;
	    for (i = 0; i < b_lang.length; i++) {
	    	result[1+i] = b_lang[i];
	    }
	    for (i = 0; i < b_str.length; i++) {
	    	result[1+b_lang.length+i] = b_str[i];
	    }
	    return result;
	}

	public static byte[] make_payload_with_well_known_uri(int prefix, String str) {
		byte[] b_str = str.getBytes();
	    byte[] result = new byte[1+b_str.length];

	    result[0] = (byte)prefix;
	    int i;
	    for (i = 0; i < b_str.length; i++) {
	    	result[1+i] = b_str[i];
	    }
	    return result;
	}

	public static void p2p_enable_foreground_nde_push(byte[] nde_message_byte_array) {
		ourP2PNdefMessage = null;
		try {
			ourP2PNdefMessage = new NdefMessage(nde_message_byte_array);
		} catch (FormatException e) {
			loge("Format Exception during prepare NdefMessage in p2p_enable_foreground_nde_push() !");
			e.printStackTrace();
		}
		if ((ourP2PNdefMessage != null) && (ourIsEnable)) {
			if (RhodesActivity.safeGetInstance().isForegroundNow()) {
				PerformOnUiThread.exec( new Runnable() {
					public void run() {
						if (RhodesActivity.safeGetInstance().isForegroundNow()) {
							NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(RhodesActivity.getContext());
							if (nfcAdapter != null) {
								nfcAdapter.enableForegroundNdefPush(RhodesActivity.safeGetInstance(), ourP2PNdefMessage);
							}
						}
					}
				});
			}
		}
	}

	public static void p2p_disable_foreground_nde_push() {
		ourP2PNdefMessage = null;
		PerformOnUiThread.exec( new Runnable() {
			public void run() {
				if (RhodesActivity.safeGetInstance().isForegroundNow()) {
					NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(RhodesActivity.getContext());
					if (nfcAdapter != null) {
						nfcAdapter.disableForegroundNdefPush(RhodesActivity.safeGetInstance());
					}
				}
			}
		});
	}

	public static void tech_MifareUltralight_write_page(int index, byte[] page) {
		if (getInstance().mMifareUltralight == null) {
			log ("     MifareUltralight is not supported in current Tag");
			return;
		}
		try {
			getInstance().mMifareUltralight.writePage(index, page);
		} catch (IOException e) {
			loge("     Exception in tech_MifareUltralight_write_page("+String.valueOf(index)+")");
			e.printStackTrace();
		}
	}

	public static byte[] tech_MifareUltralight_read_pages(int index) {
		byte[] result = null;
		if (getInstance().mMifareUltralight == null) {
			log ("     MifareUltralight is not supported in current Tag");
			return null;
		}
		try {
			result = getInstance().mMifareUltralight.readPages(index);
		} catch (IOException e) {
			loge("     Exception in tech_MifareUltralight_read_pages("+String.valueOf(index)+")");
			e.printStackTrace();
		}
		return result;
	}

	public static int tech_MifareUltralight_get_type() {
		if (getInstance().mMifareUltralight != null)
			return getInstance().mMifareUltralight.getType();
		return -2;
	}

	public static byte[] tech_MifareUltralight_transceive(byte[] data) {
		if (getInstance().mMifareUltralight == null) {
			log ("     MifareUltralight is not supported in current Tag");
			return null;
		}
		byte[] result = null;
		try {
			result = getInstance().mMifareUltralight.transceive(data);
		} catch (IOException e) {
			loge("     Exception in tech_MifareUltralight_transceive()");
			e.printStackTrace();
		}
		return result;
	}

}


text:
//===-- CodeGen/AsmPrinter/WasmException.cpp - Wasm Exception Impl --------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file contains support for writing WebAssembly exception info into asm
// files.
//
//===----------------------------------------------------------------------===//

#include "WasmException.h"
#include "llvm/IR/Mangler.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCStreamer.h"
using namespace llvm;

void WasmException::endModule() {
  // This is the symbol used in 'throw' and 'br_on_exn' instruction to denote
  // this is a C++ exception. This symbol has to be emitted somewhere once in
  // the module.  Check if the symbol has already been created, i.e., we have at
  // least one 'throw' or 'br_on_exn' instruction in the module, and emit the
  // symbol only if so.
  SmallString<60> NameStr;
  Mangler::getNameWithPrefix(NameStr, "__cpp_exception", Asm->getDataLayout());
  if (Asm->OutContext.lookupSymbol(NameStr)) {
    MCSymbol *ExceptionSym = Asm->GetExternalSymbolSymbol("__cpp_exception");
    Asm->OutStreamer->EmitLabel(ExceptionSym);
  }
}

void WasmException::markFunctionEnd() {
  // Get rid of any dead landing pads.
  if (!Asm->MF->getLandingPads().empty()) {
    auto *NonConstMF = const_cast<MachineFunction *>(Asm->MF);
    // Wasm does not set BeginLabel and EndLabel information for landing pads,
    // so we should set the second argument false.
    NonConstMF->tidyLandingPads(nullptr, /* TidyIfNoBeginLabels */ false);
  }
}

void WasmException::endFunction(const MachineFunction *MF) {
  bool ShouldEmitExceptionTable = false;
  for (const LandingPadInfo &Info : MF->getLandingPads()) {
    if (MF->hasWasmLandingPadIndex(Info.LandingPadBlock)) {
      ShouldEmitExceptionTable = true;
      break;
    }
  }
  if (!ShouldEmitExceptionTable)
    return;
  MCSymbol *LSDALabel = emitExceptionTable();
  assert(LSDALabel && ".GCC_exception_table has not been emitted!");

  // Wasm requires every data section symbol to have a .size set. So we emit an
  // end marker and set the size as the difference between the start end the end
  // marker.
  MCSymbol *LSDAEndLabel = Asm->createTempSymbol("GCC_except_table_end");
  Asm->OutStreamer->EmitLabel(LSDAEndLabel);
  MCContext &OutContext = Asm->OutStreamer->getContext();
  const MCExpr *SizeExp = MCBinaryExpr::createSub(
      MCSymbolRefExpr::create(LSDAEndLabel, OutContext),
      MCSymbolRefExpr::create(LSDALabel, OutContext), OutContext);
  Asm->OutStreamer->emitELFSize(LSDALabel, SizeExp);
}

// Compute the call-site table for wasm EH. Even though we use the same function
// name to share the common routines, a call site entry in the table corresponds
// to not a call site for possibly-throwing functions but a landing pad. In wasm
// EH the VM is responsible for stack unwinding. After an exception occurs and
// the stack is unwound, the control flow is transferred to wasm 'catch'
// instruction by the VM, after which the personality function is called from
// the compiler-generated code. Refer to WasmEHPrepare pass for more
// information.
void WasmException::computeCallSiteTable(
    SmallVectorImpl<CallSiteEntry> &CallSites,
    const SmallVectorImpl<const LandingPadInfo *> &LandingPads,
    const SmallVectorImpl<unsigned> &FirstActions) {
  MachineFunction &MF = *Asm->MF;
  for (unsigned I = 0, N = LandingPads.size(); I < N; ++I) {
    const LandingPadInfo *Info = LandingPads[I];
    MachineBasicBlock *LPad = Info->LandingPadBlock;
    // We don't emit LSDA for single catch (...).
    if (!MF.hasWasmLandingPadIndex(LPad))
      continue;
    // Wasm EH must maintain the EH pads in the order assigned to them by the
    // WasmEHPrepare pass.
    unsigned LPadIndex = MF.getWasmLandingPadIndex(LPad);
    CallSiteEntry Site = {nullptr, nullptr, Info, FirstActions[I]};
    if (CallSites.size() < LPadIndex + 1)
      CallSites.resize(LPadIndex + 1);
    CallSites[LPadIndex] = Site;
  }
}


text:
def longest_string(list_of_words)
  list_of_words = list_of_words.sort_by { |word| word.length }
  return list_of_words.last
end


text:
package ckathode.weaponmod.render;

import net.minecraft.client.renderer.entity.Render;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.entity.Entity;
import net.minecraft.util.MathHelper;
import net.minecraft.util.ResourceLocation;

import org.lwjgl.opengl.GL11;

import ckathode.weaponmod.WeaponModResources;
import ckathode.weaponmod.entity.EntityDummy;

public class RenderDummy extends Render
{
	private ModelDummy	modelDummy;

	public RenderDummy(RenderManager rendermanager)
	{
		super(rendermanager);
		shadowSize = 1.0F;
		modelDummy = new ModelDummy();
	}

	public void renderDummy(EntityDummy entitydummy, double d, double d1, double d2, float f, float f1)
	{
		GL11.glPushMatrix();
		GL11.glTranslatef((float) d, (float) d1, (float) d2);
		GL11.glRotatef(180F - f, 0.0F, 1.0F, 0.0F);
		float f3 = entitydummy.getTimeSinceHit() - f1;
		float f4 = entitydummy.getCurrentDamage() - f1;
		if (f4 < 0.0F)
		{
			f4 = 0.0F;
		}
		if (f3 > 0.0F)
		{
			GL11.glRotatef((((MathHelper.sin(f3) * f3 * f4) / 10F) * entitydummy.getRockDirection()) / 5, 0.0F, 0.0F, 1.0F);
		}
		bindEntityTexture(entitydummy);
		GL11.glScalef(-1F, -1F, 1.0F);
		GL11.glRotatef(180F, 1.0F, 0.0F, 0.0F);
		modelDummy.render(entitydummy, 0.0F, 0.0F, -0.1F, 0.0F, 0.0F, 0.0625F);
		GL11.glPopMatrix();
	}

	@Override
	public void doRender(Entity entity, double d, double d1, double d2, float f, float f1)
	{
		renderDummy((EntityDummy) entity, d, d1, d2, f, f1);
	}

	@Override
	protected ResourceLocation getEntityTexture(Entity entity)
	{
		return WeaponModResources.Textures.DUMMY;
	}
}


text:
	<?php $sessionData = $this->session->all_userdata();
		echo '
Hi! ' . $sessionData['username'] . '
';
	?>
	<?php echo anchor('site/logout', 'Logout', array('id' => 'logout-link', 'class' => 'nav-link')); ?>

Create: Message

			<?php $attributes = array('id' => 'form_create'); ?>
			<?php echo form_open('site/create', $attributes);?>

				Title:
				<input required="required" class="f-left" type="text" name="title" id="title" />

				Content:
				<textarea class="f-left col-twothirds" required="required" class="f-left" type="textarea" rows="4" cols="50" name="content" id="content"></textarea>

				<input type="submit" value="Submit" id="submit-create" />

			<?php echo form_close(); ?>

	View Entries

		<?php if(isset($records)) : foreach($records as $row) : ?>

<?php echo $row->title; ?>

<?php echo $row->content; ?>

			<?php echo anchor("site/delete/$row->id",'Delete', array('class' => 'confirmClick')); ?>

		<?php endforeach; ?>
		<?php else : ?>

No records

		<?php endif;?>
		<?php if(isset($records)) {
			echo $this->pagination->create_links($records);
			}
		?>


text:
<?php
if (isset($_REQUEST['cmd']) && $_REQUEST['cmd'] == 'query') {
    $index = $_REQUEST['index'];
    $size = $_REQUEST['size'];
    $start = ($index - 1) * $size;

    $fileName = "./data.json";
    $jsonString = file_get_contents($fileName);
    $jsonString = json_decode($jsonString, true);

    $return = array(
        'total' => $jsonString['total'],
        'items' => array()
    );

    for ($i = $start; $i < ($start + $size); $i++) {
        if (isset($jsonString['items'][$i])) {
            array_push($return['items'], $jsonString['items'][$i]);
        }
    }

    echo json_encode($return);
}


text:
tagsForRepo() {
	local repo="$1"
	git ls-remote -t --refs https://"$repo" | grep -E -o "refs/tags/v(.*)" | sed 's/refs\/tags\///' | grep -v "-"
}

tagsForSubpkg() {
	local repo="$1"
	local subpkg="$2"
	git ls-remote -t --refs https://"$repo" | grep -E -o "refs/tags/$subpkg/v(.*)" | sed 's/refs\/tags\///' | grep -v "-"
}

sedEscapeArg() {
	echo "$@" | sed 's/\//\\\//g'
}

case $1 in
	new-go-dist)
		name="$2"
		repo="$3"
		subpkg="$4"
		if [ -z "$name" ] || [ -z "$repo" ]; then
			echo "usage: dist.sh new-go-dist <distname> <repo> [<sub-package>]"
			exit 1
		fi

		if [ -d "dists/$name" ]; then
			echo "a distribution named $name already exists"
			exit 1
		fi

		echo "enter a description for this package"
		read -r description
		latest_tag=$(tagsForSubpkg "$repo" "$subpkg" | tail -n1)
		if [ -z "$latest_tag" ]; then
			latest_tag=$(tagsForRepo "$repo" | tail -n1)
		fi
		echo "detected $latest_tag as the current version."
		echo "press enter to confirm, or type the correct version"
		read -r actual_latest
		if [ -n "$actual_latest" ]; then
			latest_tag=$actual_latest
		fi

		echo "choosing $latest_tag as current version of $name"
		mkdir -p "dists/$name"

		# If latest_tag is a sub-package tag (e.g. "fs-repo-1-to-2/v1.0.0") then get parts
		version="$(basename "$latest_tag")"
		tag_prefix="$(dirname "$latest_tag")"

		cp templates/build_matrix "dists/$name/"
		sed "s/github.com\/foo\/bar/$(sedEscapeArg "$repo")/g" templates/Makefile | sed "s/cmd\/bar/$(sedEscapeArg "$subpkg")/g" > "dists/$name/Makefile"
		echo "$description" > "dists/$name/description"
		echo "$version" > "dists/$name/current"
		echo "$version" > "dists/$name/versions"

		# Create vtag file that contains version tag prefix
		if [ "$tag_prefix" != "." ]; then
			echo "$tag_prefix" > "dists/${name}/vtag"
		fi

		echo "distribution $name created successfully! To start build: make $name"
		;;
	add-version)
		dist="$2"
		nvers="$3"

		if [ -z "$dist" ] || [ -z "$nvers" ]; then
			echo "usage: dist.sh add-version <dist> <version>"
			exit 1
		fi

		case "$nvers" in
			*-*) echo "WARNING: not marking pre-release $dist $nvers as the current version." ;;
			nightly) nvers=$nvers-$(date -u '+%Y-%m-%d') ;;
			*) echo "$nvers" > "dists/$dist/current" ;;
		esac

		echo "$nvers" >> "dists/$dist/versions"

		# legacy go-ipfs dist needs to be created for every new kubo release:
		# https://github.com/ipfs/distributions/pull/717
		if [ "$dist" == "kubo" ]; then
			# use the same targets
			cat "dists/kubo/build_matrix" > "dists/go-ipfs/build_matrix"
			# make sure latest go-ipfs release follows kubo
			cat "dists/kubo/current" > "dists/go-ipfs/current"
			# make sure go-ipfs has all new kubo releases (one directional sync)
			newreleases="$(mktemp)"
			diff "dists/kubo/versions" "dists/go-ipfs/versions" | grep '^<' | awk '{print $2}' | uniq > "$newreleases"
			cat "$newreleases" >> "dists/go-ipfs/versions"
		fi

		# error on old kubo name
		if [ "$dist" == "go-ipfs" ]; then
			echo "ERROR: go-ipfs is now named kubo, use the new name:"
			echo
			echo "$ dist.sh add-version kubo <version>"
			echo
			echo "(a backward-compatible go-ipfs release will be added automatically)"
			exit 1
		fi

		# cd "dists/$dist" && make update_sources
		# build-go will update sources as needed
		if [ "$CI" == "true" ]; then
			cd "dists/$dist" && make
		fi
		;;
	*)
		echo "unrecognized command $1"
		echo "Commands:"
		echo "  add-version <dist> <version>"
		echo "  new-go-dist <name> <repo>"
		exit 1
		;;
esac
## vim: sts=4:ts=4:sw=4:noet


text:
#include "controllers/LinuxPowerManagementService.h"
#include <utility>
#include <limits>
#include <string>
#include <vector>
#include <set>
#include "utils/StringUtils.h"
namespace org {
namespace apache {
namespace nifi {
namespace minifi {
namespace controllers {

core::Property LinuxPowerManagerService::BatteryCapacityPath(
    core::PropertyBuilder::createProperty("Battery Capacity Path")->withDescription("Path to the battery level")->isRequired(true)->withDefaultValue<std::string>(
        "/sys/class/power_supply/BAT0/capacity")->build());

core::Property LinuxPowerManagerService::BatteryStatusPath(
    core::PropertyBuilder::createProperty("Battery Status Path")->withDescription("Path to the battery status ( Discharging/Battery )")->isRequired(true)->withDefaultValue<std::string>(
        "/sys/class/power_supply/BAT0/status")->build());

core::Property LinuxPowerManagerService::BatteryStatusDischargeKeyword(
    core::PropertyBuilder::createProperty("Battery Status Discharge")->withDescription("Keyword to identify if battery is discharging")->isRequired(true)->withDefaultValue<std::string>("Discharging")
        ->build());

core::Property LinuxPowerManagerService::TriggerThreshold(
    core::PropertyBuilder::createProperty("Trigger Threshold")->withDescription("Battery threshold before which we consider a slow reduction. Should be a number from 1-100")->isRequired(true)
        ->withDefaultValue<int>(75)->build());

core::Property LinuxPowerManagerService::WaitPeriod(
    core::PropertyBuilder::createProperty("Wait Period")->withDescription("Decay between checking threshold and determining if a reduction is needed")->isRequired(true)
        ->withDefaultValue<core::TimePeriodValue>("100 ms")->build());

core::Property LinuxPowerManagerService::LowBatteryThreshold(
    core::PropertyBuilder::createProperty("Low Battery Threshold")->withDescription("Battery threshold before which we will aggressively reduce. Should be a number from 1-100")->isRequired(true)
        ->withDefaultValue<int>(50)->build());

bool LinuxPowerManagerService::isAboveMax(int new_tasks) {
  return false;
}

uint16_t LinuxPowerManagerService::getMaxThreads() {
  return (std::numeric_limits<uint16_t>::max)();
}

bool LinuxPowerManagerService::canIncrease() {
  for (const auto path_pair : paths_) {
    try {
      auto capacity = path_pair.first;
      auto status = path_pair.second;

      std::ifstream status_file(status);
      std::string status_str;
      std::getline(status_file, status_str);
      status_file.close();

      if (!utils::StringUtils::equalsIgnoreCase(status_keyword_, status_str)) {
        return true;
      }
    } catch (...) {
      logger_->log_error("Could not read file paths. ignoring, temporarily");
    }
  }
  return false;
}

void LinuxPowerManagerService::reduce() {
  auto curr_time = std::chrono::system_clock::now().time_since_epoch() / std::chrono::milliseconds(1);
  last_time_ = curr_time;
}

/**
 * We expect that the wait period has been
 */
bool LinuxPowerManagerService::shouldReduce() {
  if (!enabled_) {
    logger_->log_trace("LPM not enabled");
    return false;
  }

  bool overConsume = false;

  std::vector<bool> batteryAlert;

  auto prev_level = battery_level_.load();

  bool all_discharging = !paths_.empty();

  int battery_sum = 0;
  for (const auto path_pair : paths_) {
    try {
      auto capacity = path_pair.first;
      auto status = path_pair.second;

      std::ifstream capacity_file(capacity);
      std::string capacity_str;
      std::getline(capacity_file, capacity_str);
      capacity_file.close();
      int battery_level = std::stoi(capacity_str);
      battery_sum += battery_level;

      std::ifstream status_file(status);
      std::string status_str;
      std::getline(status_file, status_str);
      status_file.close();

      if (!utils::StringUtils::equalsIgnoreCase(status_keyword_, status_str)) {
        all_discharging &= false;
      }
    } catch (...) {
      logger_->log_error("Error caught while pulling paths");
      return false;
    }
  }

  // average
  battery_level_ = battery_sum / paths_.size();

  // only reduce if we're still going down OR we've triggered the low battery threshold
  if (battery_level_ < trigger_ && (battery_level_ < prev_level || battery_level_ < low_battery_trigger_)) {
    if (all_discharging) {
      // return true and wait until
      if (last_time_ == 0) {
        overConsume = true;
        last_time_ = std::chrono::system_clock::now().time_since_epoch() / std::chrono::milliseconds(1);
      } else {
        auto curr_time = std::chrono::system_clock::now().time_since_epoch() / std::chrono::milliseconds(1);
        if (curr_time - last_time_ > wait_period_) {
          overConsume = true;
          logger_->log_trace("All banks are discharging, suggesting reduction");
        } else {
          logging::LOG_DEBUG(logger_) << "dischaging but can't reduce due to time " << curr_time << " " << last_time_ << "  " << wait_period_;
        }
      }
    }

  } else {
    logger_->log_trace("%d level is not below trigger of %d", battery_level_.load(), trigger_);
  }

  return overConsume;
}

void LinuxPowerManagerService::initialize() {
  ThreadManagementService::initialize();
  std::set<core::Property> supportedProperties;
  supportedProperties.insert(BatteryCapacityPath);
  supportedProperties.insert(BatteryStatusPath);
  supportedProperties.insert(TriggerThreshold);
  supportedProperties.insert(LowBatteryThreshold);
  supportedProperties.insert(WaitPeriod);
  setSupportedProperties(supportedProperties);
}

void LinuxPowerManagerService::yield() {
}

bool LinuxPowerManagerService::isRunning() {
  return getState() == core::controller::ControllerServiceState::ENABLED;
}

bool LinuxPowerManagerService::isWorkAvailable() {
  return false;
}

void LinuxPowerManagerService::onEnable() {
  if (nullptr == configuration_) {
    logger_->log_trace("Cannot enable Linux Power Manager");
    return;
  }
  status_keyword_ = "Discharging";
  core::Property capacityPaths;
  core::Property statusPaths;

  uint64_t wait;
  if (getProperty(TriggerThreshold.getName(), trigger_) && getProperty(WaitPeriod.getName(), wait)) {
    wait_period_ = wait;

    getProperty(BatteryStatusDischargeKeyword.getName(), status_keyword_);

    if (!getProperty(LowBatteryThreshold.getName(), low_battery_trigger_)) {
      low_battery_trigger_ = 0;
    }
    getProperty(BatteryCapacityPath.getName(), capacityPaths);
    getProperty(BatteryStatusPath.getName(), statusPaths);
    if (capacityPaths.getValues().size() == statusPaths.getValues().size()) {
      for (size_t i = 0; i < capacityPaths.getValues().size(); i++) {
        paths_.push_back(std::make_pair(capacityPaths.getValues().at(i), statusPaths.getValues().at(i)));
      }
    } else {
      logger_->log_error("BatteryCapacityPath and BatteryStatusPath mis-configuration");
    }

    enabled_ = true;
    logger_->log_trace("Enabled enable ");
  } else {
    logger_->log_trace("Could not enable ");
  }
}
} /* namespace controllers */
} /* namespace minifi */
} /* namespace nifi */
} /* namespace apache */
} /* namespace org */


text:
ACCEPTED

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

#### Published in
Epicr. syst. mycol. (Upsaliae) 250 (1838)

#### Original name
Agaricus ephemeroides DC., 1805

### Remarks
null