text:
package org.iplantcollaborative.irods;

import java.io.Closeable;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.iplantcollaborative.conf.DataStoreConf;
import org.irods.jargon.core.connection.IRODSAccount;
import org.irods.jargon.core.connection.auth.AuthResponse;
import org.irods.jargon.core.exception.AuthenticationException;
import org.irods.jargon.core.exception.DataNotFoundException;
import org.irods.jargon.core.exception.JargonException;
import org.irods.jargon.core.pub.CollectionAO;
import org.irods.jargon.core.pub.DataObjectAO;
import org.irods.jargon.core.pub.IRODSAccessObjectFactory;
import org.irods.jargon.core.pub.IRODSFileSystem;
import org.irods.jargon.core.pub.IRODSGenQueryExecutor;
import org.irods.jargon.core.pub.io.IRODSFile;
import org.irods.jargon.core.query.IRODSGenQuery;
import org.irods.jargon.core.query.IRODSQueryResultRow;
import org.irods.jargon.core.query.IRODSQueryResultSet;
import org.irods.jargon.core.query.JargonQueryException;
import org.irods.jargon.core.query.RodsGenQueryEnum;

/**
 *
 * @author iychoi
 */
public class DataStoreClient implements Closeable {

    private static final Log LOG = LogFactory.getLog(DataStoreClient.class);

    private DataStoreConf datastoreConf;
    private IRODSFileSystem irodsFS;
    private IRODSAccount irodsAccount;
    private IRODSAccessObjectFactory accessObjectFactory;
    private IRODSGenQueryExecutor irodsGenQueryExecutor;
    private Thread keepAliveThread;

    public DataStoreClient(DataStoreConf datastoreConf) {
        if (datastoreConf == null) {
            throw new IllegalArgumentException("datastoreConf is null");
        }

        initialize(datastoreConf);
    }

    private void initialize(DataStoreConf datastoreConf) {
        this.datastoreConf = datastoreConf;
    }

    private String makeDefaultHome(String zone) {
        String defaultdir = "/" + zone.trim();
        return defaultdir;
    }

    private String makeDefaultStorageResource() {
        return "";
    }

    private IRODSAccount createIRODSAccount(String host, int port, String zone, String user, String password) throws IOException {
        IRODSAccount account = null;
        String home = makeDefaultHome(zone);
        String resource = makeDefaultStorageResource();

        try {
            account = IRODSAccount.instance(host, port, user, password, home, zone, resource);
            return account;
        } catch (JargonException ex) {
            throw new IOException(ex);
        }
    }

    public synchronized void connect() throws IOException {
        try {
            this.irodsFS = IRODSFileSystem.instance();
        } catch (JargonException ex) {
            throw new IOException(ex);
        }
        this.irodsAccount = createIRODSAccount(this.datastoreConf.getHostname(), this.datastoreConf.getPort(),
                this.datastoreConf.getZone(), this.datastoreConf.getUserId(), this.datastoreConf.getUserPwd());

        AuthResponse response;
        try {
            response = this.irodsFS.getIRODSAccessObjectFactory().authenticateIRODSAccount(this.irodsAccount);
            LOG.info("irods client connected - " + this.datastoreConf.getHostname() + ":" + this.datastoreConf.getPort());

            this.accessObjectFactory = this.irodsFS.getIRODSAccessObjectFactory();
            this.irodsGenQueryExecutor = accessObjectFactory.getIRODSGenQueryExecutor(this.irodsAccount);
        } catch (AuthenticationException ex) {
            LOG.error("Exception occurred while logging in", ex);
            throw new IOException(ex);
        } catch (JargonException ex) {
            throw new IOException(ex);
        }

        if (!response.isSuccessful()) {
            throw new IOException("Cannot authenticate to IRODS");
        }

        Runnable keepAliveWorker = new Runnable() {

            @Override
            public void run() {
                while(true) {
                    sendKeepAlive();
                    try {
                        Thread.sleep(5*60*1000);
                    } catch (InterruptedException ex) {
                        LOG.error("keep alive worker got interrupted", ex);
                        break;
                    }
                }
            }

        };
        this.keepAliveThread = new Thread(keepAliveWorker);
        this.keepAliveThread.start();
    }

    @Override
    public synchronized void close() throws IOException {
        try {
            if(this.keepAliveThread != null) {
                this.keepAliveThread.interrupt();
                this.keepAliveThread = null;
            }
            this.irodsFS.close();
        } catch (JargonException ex) {
            throw new IOException(ex);
        }
    }

    private synchronized void sendKeepAlive() {
        try {
            LOG.info("sending keep-alive");
            IRODSFile instanceIRODSFile = this.accessObjectFactory.getIRODSFileFactory(irodsAccount).instanceIRODSFile("/");
            if(instanceIRODSFile.exists()) {
                // okey
            } else {
                LOG.error("disconnected?");
            }
        } catch (JargonException ex) {
            LOG.error("failed to send keep alive", ex);
        }
    }

    private synchronized IRODSQueryResultSet queryDataObjectUUID(String entity) throws JargonException, JargonQueryException {
        StringBuilder q = new StringBuilder();
        q.append("select ");
        q.append(RodsGenQueryEnum.COL_COLL_NAME.getName()).append(", ");
        q.append(RodsGenQueryEnum.COL_DATA_NAME.getName());
        q.append(" where ");
        q.append(RodsGenQueryEnum.COL_META_DATA_ATTR_NAME.getName());
        q.append(" = ");
        q.append("'ipc_UUID'");
        q.append(" AND ");
        q.append(RodsGenQueryEnum.COL_META_DATA_ATTR_VALUE.getName());
        q.append(" = ");
        q.append("'").append(entity).append("'");

        IRODSGenQuery irodsQuery = IRODSGenQuery.instance(q.toString(), 1);
        IRODSQueryResultSet resultSet = this.irodsGenQueryExecutor.executeIRODSQuery(irodsQuery, 0);
        return resultSet;
    }

    private synchronized IRODSQueryResultSet queryCollectionUUID(String entity) throws JargonException, JargonQueryException {
        StringBuilder q = new StringBuilder();
        q.append("select ");
        q.append(RodsGenQueryEnum.COL_COLL_NAME.getName());
        q.append(" where ");
        q.append(RodsGenQueryEnum.COL_META_COLL_ATTR_NAME.getName());
        q.append(" = ");
        q.append("'ipc_UUID'");
        q.append(" AND ");
        q.append(RodsGenQueryEnum.COL_META_COLL_ATTR_VALUE.getName());
        q.append(" = ");
        q.append("'").append(entity).append("'");

        IRODSGenQuery irodsQuery = IRODSGenQuery.instance(q.toString(), 1);
        IRODSQueryResultSet resultSet = this.irodsGenQueryExecutor.executeIRODSQuery(irodsQuery, 0);
        return resultSet;
    }

    public synchronized String convertUUIDToPathForDataObject(String entity) throws IOException {
        // test dataobject
        try {
            IRODSQueryResultSet dataObjectResult = queryDataObjectUUID(entity);
            IRODSQueryResultRow firstDataObjectResult = dataObjectResult.getFirstResult();
            if(firstDataObjectResult != null) {
                String parent = firstDataObjectResult.getColumn(0);
                String file = firstDataObjectResult.getColumn(1);
                if(parent.endsWith("/")) {
                    return parent + file;
                } else {
                    return parent + "/" + file;
                }
            }
        } catch (DataNotFoundException ex) {
            return null;
        } catch (JargonException ex) {
            LOG.error("Exception occurred while querying", ex);
            throw new IOException(ex);
        } catch (JargonQueryException ex) {
            LOG.error("Exception occurred while querying", ex);
            throw new IOException(ex);
        }

        return null;
    }

    public synchronized String convertUUIDToPathForCollection(String entity) throws IOException {
        // test collection
        try {
            IRODSQueryResultSet collectionResult = queryCollectionUUID(entity);
            IRODSQueryResultRow firstCollectionResult = collectionResult.getFirstResult();
            if(firstCollectionResult != null) {
                String parent = firstCollectionResult.getColumn(0);
                return parent;
            }
        } catch (DataNotFoundException ex) {
            // fall
            return null;
        } catch (JargonException ex) {
            LOG.error("Exception occurred while querying", ex);
            throw new IOException(ex);
        } catch (JargonQueryException ex) {
            LOG.error("Exception occurred while querying", ex);
            throw new IOException(ex);
        }

        return null;
    }

    public synchronized boolean hasAccessPermissionsForDataObject(String path, String user) throws IOException, FileNotFoundException {
        // test dataobject
        try {
            DataObjectAO dataObjectAO = this.accessObjectFactory.getDataObjectAO(this.irodsAccount);
            return dataObjectAO.isUserHasAccess(path, user);
        } catch (org.irods.jargon.core.exception.FileNotFoundException ex) {
            throw new FileNotFoundException("file " + path + " not found");
        } catch (DataNotFoundException ex) {
            throw new FileNotFoundException("file " + path + " not found");
        } catch (JargonException ex) {
            LOG.error("Exception occurred while querying", ex);
            throw new IOException(ex);
        }
    }

    public synchronized boolean hasAccessPermissionsForCollection(String path, String user) throws IOException, FileNotFoundException {
        // test dataobject
        try {
            CollectionAO collectionAO = this.accessObjectFactory.getCollectionAO(this.irodsAccount);
            return collectionAO.isUserHasAccess(path, user);
        } catch (org.irods.jargon.core.exception.FileNotFoundException ex) {
            throw new FileNotFoundException("file " + path + " not found");
        } catch (DataNotFoundException ex) {
            throw new FileNotFoundException("file " + path + " not found");
        } catch (JargonException ex) {
            LOG.error("Exception occurred while querying", ex);
            throw new IOException(ex);
        }
    }
}


text:
PCA decomposition

In PCA_implementations.py one finds both standard and Kernel PCA

In PCA_Prob.py one finds an in progress version of probabilistic PCA

  - Not tested at all
  - No calculation of sig² from data yet
  - Does not take care of missing data yet, which is kind of the point
  - Bottom line: DO NOT try to use it (probabilistic PCA) as of now

redpajama_set_name: RedPajamaGithub


text:
<Record>
<Term>Seractide</Term>
<SemanticType>Pharmacologic Substance</SemanticType>
<SemanticType>Organic Chemical</SemanticType>
<ParentTerm>Recombinant Corticotropin</ParentTerm>
<ParentTerm>Pituitary Agent</ParentTerm>
<ClassificationPath>Chemicals_and_Drugs_Kind/Drug, Food, Chemical or Biomedical Material/Pharmacologic Substance/Therapeutic Hormone/Pituitary Agent/Seractide Acetate</ClassificationPath>
<ClassificationPath>Chemicals_and_Drugs_Kind/Drug, Food, Chemical or Biomedical Material/Pharmacologic Substance/Therapeutic Hormone/Pituitary Agent/Recombinant Corticotropin/Seractide</ClassificationPath>
<BroaderTerm>Seractide Acetate</BroaderTerm>
<BroaderTerm>Chemicals_and_Drugs_Kind</BroaderTerm>
<BroaderTerm>Recombinant Corticotropin</BroaderTerm>
<BroaderTerm>Pituitary Agent</BroaderTerm>
<BroaderTerm>Seractide</BroaderTerm>
<BroaderTerm>Pharmacologic Substance</BroaderTerm>
<BroaderTerm>Therapeutic Hormone</BroaderTerm>
<BroaderTerm>Drug, Food, Chemical or Biomedical Material</BroaderTerm>
<Synonym>Seractide Acetate</Synonym>
<Synonym>Seractide acetate</Synonym>
<Synonym>SERACTIDE ACETATE</Synonym>
<Synonym>Seractide</Synonym>
<Synonym>Acthar Gel-synthetic</Synonym>
<Synonym>SERACTIDE</Synonym>
<Source>FDA Registry</Source>
<Source>NCI Thesaurus</Source>
</Record>


text:
/*
 * Defines an instruction (decoder), based on the current location of
 * the instruction iterator. The instruction decoder takes a list
 * of candidate opcode (instruction) patterns, and searches for the
 * first candidate that matches the requirements of the opcode pattern.
 */

#include "native_client/src/trusted/validator/x86/decoder/nc_inst_state.h"

/* To turn on debugging of instruction decoding, change value of
 * DEBUGGING to 1.
 */
#define DEBUGGING 0

/*
 * This .c file contains includes, static functions, and constants that are used
 * in nc_inst_state.c, but have been factored out and put into this file, so
 * that we can test them. That is, to allow nc_inst_state.c and
 * nc_inst_state_Tests.cc to use them.
 */
#include "native_client/src/trusted/validator/x86/decoder/nc_inst_state_statics.c"

/* Returns true if the parsed instruction may be replaceable with a (hard coded)
 * opcode sequence. Used to prefer hard-coded opcode sequences over general
 * matches. These hard-coded opcode sequences are special nop opcode sequences,
 * most of which are generated by compilers and linkers. The need for these
 * hard-coded sequences is to accept nops with prefixes that would not otherwise
 * be accepted (such as "6666666666662e0f1f840000000000").
 */
static Bool NaClMaybeHardCodedNop(NaClInstState* state) {
  /* Note: This code is based on the hard-coded instructions
   * defined in function NaClDefNops in
   * src/trusted/validator_x86/ncdecode_tablegen.c.
   * If you change the hard-coded instructions defined in this
   * function, be sure that this predicate is updated accordingly to
   * return true for all such hard-coded instructions (it can
   * return true on other instructions without breaking the validator).
   */

  /* Check the first opcode byte to see if it is a special case. */
  switch (state->bytes.byte[state->num_prefix_bytes]) {
    case 0x90:
      /* If the first opcode byte is 90, it can be the NOP instruction.
       * Return true that this can be a nop.
       */
      if (state->num_opcode_bytes == 1) return TRUE;
      break;
    case 0x0f:
      /* Check that the second opcode byte is 1F or 0B. That is,
       * can the instruction be a NOP (0f1f) or the UD2 instruction.
       */
      if (state->num_opcode_bytes == 2) {
        uint8_t opcode_2 =
            state->bytes.byte[state->num_prefix_bytes + 1];
        if ((opcode_2 == 0x1f) || (opcode_2 == 0x0b)) return TRUE;
      }
      break;
    default:
      break;
  }
  /* If reached, can't be a (hard-coded) NOP instruction. */
  return FALSE;
}

/* Given the current location of the (relative) pc of the given instruction
 * iterator, update the given state to hold the (found) matched opcode
 * (instruction) pattern. If no matching pattern exists, set the state
 * to a matched undefined opcode (instruction) pattern. In all cases,
 * update the state to hold all information on the matched bytes of the
 * instruction. Note: The iterator expects that the opcode field is
 * changed from NULL to non-NULL by this fuction.
 */
void NaClDecodeInst(NaClInstIter* iter, NaClInstState* state) {
  uint8_t inst_length = 0;
  const NaClInst* cand_insts;
  Bool found_match = FALSE;

  /* Start by consuming the prefix bytes, and getting the possible
   * candidate opcode (instruction) patterns that can match, based
   * on the consumed opcode bytes.
   */
  NaClInstStateInit(iter, state);
  if (NaClConsumePrefixBytes(state)) {
    NaClInstPrefixDescriptor prefix_desc;
    Bool continue_loop = TRUE;
    NaClConsumeInstBytes(state, &prefix_desc);
    inst_length = state->bytes.length;
    while (continue_loop) {
      /* Try matching all possible candidates, in the order they are specified
       * (from the most specific prefix match, to the least specific prefix
       * match). Quit when the first pattern is matched.
       */
      if (prefix_desc.matched_prefix == NaClInstPrefixEnumSize) {
        continue_loop = FALSE;
      } else {
        uint8_t cur_opcode_prefix = prefix_desc.opcode_prefix;
        cand_insts = NaClGetNextInstCandidates(state, &prefix_desc,
                                               &inst_length);
        while (cand_insts != NULL) {
          NaClClearInstState(state, inst_length);
          state->inst = cand_insts;
          DEBUG(NaClLog(LOG_INFO, "try opcode pattern:\n"));
          DEBUG_OR_ERASE(NaClInstPrint(NaClLogGetGio(), state->decoder_tables,
                                       state->inst));
          if (NaClConsumeAndCheckOperandSize(state) &&
              NaClConsumeAndCheckAddressSize(state) &&
              NaClConsumeModRm(state) &&
              NaClConsumeSib(state) &&
              NaClConsumeDispBytes(state) &&
              NaClConsumeImmediateBytes(state) &&
              NaClValidatePrefixFlags(state)) {
            if (state->inst->flags & NACL_IFLAG(Opcode0F0F) &&
                /* Note: If all of the above code worked correctly,
                 * there should be no need for the following test.
                 * However, just to be safe, it is added.
                 */
                (state->num_imm_bytes == 1)) {
              /* Special 3DNOW instructions where opcode is in parsed
               * immediate byte at end of instruction. Look up in table,
               * and replace if found. Otherwise, let the default 0F0F lookup
               * act as the matching (invalid) instruction.
               */
              const NaClInst* cand_inst;
              uint8_t opcode_byte = state->bytes.byte[state->first_imm_byte];
              DEBUG(NaClLog(LOG_INFO,
                            "NaClConsume immediate byte opcode char: %"
                            NACL_PRIx8"\n", opcode_byte));
              cand_inst = NaClGetPrefixOpcodeInst(state->decoder_tables,
                                                  Prefix0F0F, opcode_byte);
              if (NULL != cand_inst) {
                state->inst = cand_inst;
                DEBUG(NaClLog(LOG_INFO, "Replace with 3DNOW opcode:\n"));
                DEBUG_OR_ERASE(NaClInstPrint(NaClLogGetGio(),
                                             state->decoder_tables,
                                             state->inst));
              }
            }

            /* found a match, exit loop. */
            found_match = TRUE;
            continue_loop = FALSE;
            state->num_opcode_bytes = inst_length - state->num_prefix_bytes;
            state->opcode_prefix = cur_opcode_prefix;

            /* If an instruction has both a general form, and a (hard-coded)
             * explicit opcode sequence, prefer the latter for the match.
             * Note: This selection to the (hard-coded) explicit opcode
             * sequence is necessary if we are to handle special nops with
             * multiple prefix bytes in the x86-64 validator.
             */
            if (NaClMaybeHardCodedNop(state)) {
              NaClConsumeHardCodedNop(state);
            }
            break;
          } else {
            /* match failed, try next candidate pattern. */
            cand_insts = NaClGetOpcodeInst(state->decoder_tables,
                                           cand_insts->next_rule);
          }
        }
        DEBUG(if (! found_match) {
            NaClLog(LOG_INFO, "no more candidates for this prefix\n");
          });
      }
    }
  }

  if (!found_match) {
    /* No instruction matched. Double check that it can't be a hard-coded
     * NOP instruction before we assume that we can't can accept the
     * instruction.
     */
    if (NaClConsumeHardCodedNop(state)) return;

    /* We did not match a defined opcode, match the undefined opcode,
     * forcing the inst field to be non-NULL, and to read at least one byte.
     */
    DEBUG(NaClLog(LOG_INFO, "no instruction found, converting to undefined\n"));
    state->inst = state->decoder_tables->undefined;
    if (state->bytes.length == 0 && state->bytes.length < state->length_limit) {
      /* Make sure we eat at least one byte. */
      NCInstBytesReadInline(&state->bytes);
    }
  }
}

const NaClInst* NaClInstStateInst(NaClInstState* state) {
  return state->inst;
}

NaClPcAddress NaClInstStatePrintableAddress(NaClInstState* state) {
  return state->iter->segment->vbase + state->inst_addr;
}

NaClExpVector* NaClInstStateExpVector(NaClInstState* state) {
  if (!state->nodes.is_defined) {
    state->nodes.is_defined = TRUE;
    NaClBuildExpVector(state);
  }
  return &state->nodes;
}

Bool NaClInstStateIsValid(NaClInstState* state) {
  return InstInvalid != state->inst->name;
}

uint8_t NaClInstStateLength(NaClInstState* state) {
  return state->bytes.length;
}

uint8_t NaClInstStateByte(NaClInstState* state, uint8_t index) {
  assert(index < state->bytes.length);
  return state->bytes.byte[index];
}

uint8_t NaClInstStateOperandSize(NaClInstState* state) {
  return state->operand_size;
}

uint8_t NaClInstStateAddressSize(NaClInstState* state) {
  return state->address_size;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type='text/xsl' href='../../../../../../../../../../../test.xsl'?>
<!--
    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You under the Apache License, Version 2.0
    (the "License"); you may not use this file except in compliance with
    the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-->
<!DOCTYPE Test SYSTEM '../../../../../../../../../../../test.dtd'>
<!--
-->

<Test
    ID="AbstractDocumentTest"
    date-of-creation="2005-06-03"
    timeout="1"
    >

    <MulticaseTestDescription>
        <TestedClass name="javax.swing.text.AbstractDocument"/>

        <Case ID="testConstructorContent">
            <TestedMethod name="protected AbstractDocument(AbstractDocument.Content data)"/>
            <Precondition></Precondition>
            <Description>create a child of AbstractAbstractDocument</Description>
            <Expected>a certain sequence of events</Expected>
        </Case>

        <Case ID="testConstructorContentContext">
            <TestedMethod name="protected AbstractDocument(AbstractDocument.Content data, AbstractDocument.AttributeContext context)"/>
            <Precondition></Precondition>
            <Description>create a child of AbstractAbstractDocument</Description>
            <Expected>a certain sequence of events</Expected>
        </Case>

        <Case ID="testAddDocumentListener">
            <TestedMethod name="public void addDocumentListener(DocumentListener listener)"/>
            <Precondition>create a child of AbstractAbstractDocument</Precondition>
            <Description>add a document listener</Description>
            <Expected>a certain sequence of events</Expected>
        </Case>

        <Case ID="testCreateLeafElement">
            <TestedMethod name="protected Element createLeafElement(Element parent,  AttributeSet a,int p0, int p1)"/>
            <Precondition>create a child of AbstractAbstractDocument</Precondition>
            <Description>call createLeafElement</Description>
            <Expected>a certain sequence of events</Expected>
        </Case>

        <Case ID="testCreatePosition">
            <TestedMethod name="public Position createPosition(int offs)"/>
            <Precondition>create a child of AbstractAbstractDocument</Precondition>
            <Description>call public createPosition(int offs)</Description>
            <Expected>a certain sequence of events</Expected>
        </Case>

        <Case ID="testGetBidiRootElement">
            <TestedMethod name="public Element getBidiRootElement()"/>
            <Precondition>create a child of AbstractAbstractDocument instrumented with logging</Precondition>
            <Description>call public getBidiRootElement()</Description>
            <Expected>a certain sequence of events; element is not null</Expected>
        </Case>

        <Case ID="testGetCurrentWriter">
            <TestedMethod name="protected final Thread getCurrentWriter()"/>
            <Precondition>create a child of AbstractAbstractDocument instrumented with logging</Precondition>
            <Description>acquire a lock on it using writeLock() and release using writeUnlock()</Description>
            <Expected>getCurrentWriter() returns correct values in all cases</Expected>
        </Case>

        <Case ID="testDocumentProperties">
            <TestedMethod name="public Dictionary<Object,Object> getDocumentProperties()"/>
            <Precondition>create a child of AbstractAbstractDocument instrumented with logging</Precondition>
            <Description>call getDocumentProperties()</Description>
            <Expected>no more methods called</Expected>
        </Case>

        <Case ID="testGetLength">
            <TestedMethod name="public int getLength()"/>
            <Precondition>create a child of AbstractAbstractDocument instrumented with logging</Precondition>
            <Description>call getLength()</Description>
            <Expected>content length - 1</Expected>
        </Case>

        <Case ID="testGetProperty">
            <TestedMethod name="public final Object getProperty(Object key)"/>
            <Precondition>create a child of AbstractAbstractDocument instrumented with logging</Precondition>
            <Description>call getProperty()</Description>
            <Expected>getDocumentProperties().get(key) is called</Expected>
        </Case>

        <Case ID="testGetText">
            <TestedMethod name="public String getText(int offset, int length)"/>
            <Precondition>create a child of AbstractAbstractDocument instrumented with logging</Precondition>
            <Description>call getText(int offset, int length)</Description>
            <Expected>a certain sequence of events and exception where expected</Expected>
        </Case>

        <Case ID="testGetTextSegment">
            <TestedMethod name="public void getText(int offset, int length, Segment txt)"/>
            <Precondition>create a child of AbstractAbstractDocument instrumented with logging</Precondition>
            <Description>call getText(int offset, int length, Segment txt)</Description>
            <Expected>a certain sequence of events and exception where expected</Expected>
        </Case>

        <Case ID="testInsertString">
            <TestedMethod name="public void insertString(int offs,  String str, AttributeSet a)"/>
            <Precondition>create a child of AbstractAbstractDocument instrumented with logging</Precondition>
            <Description>call insertString(...) several times</Description>
            <Expected>a certain sequence of events</Expected>
        </Case>

        <Case ID="testInsertUpdate">
            <TestedMethod name="protected void insertUpdate(AbstractDocument.DefaultDocumentEvent chng, AttributeSet attr)"/>
            <Precondition>create a child of AbstractAbstractDocument instrumented with logging</Precondition>
            <Description>call insertUpdate(...) several times</Description>
            <Expected>a certain sequence of events and exception where needed</Expected>
        </Case>

        <Case ID="testPostRemoveUpdate">
            <TestedMethod name="protected void postRemoveUpdate(AbstractDocument.DefaultDocumentEvent chng)"/>
            <Precondition>create a child of AbstractAbstractDocument instrumented with logging</Precondition>
            <Description>call postRemoveUpdate(...) several times</Description>
            <Expected>a certain sequence of events and exception where needed</Expected>
        </Case>

        <Case ID="testRemoveUpdate">
            <TestedMethod name="protected void removeUpdate(AbstractDocument.DefaultDocumentEvent chng)"/>
            <Precondition>create a child of AbstractAbstractDocument instrumented with logging</Precondition>
            <Description>call removeUpdate(...) several times</Description>
            <Expected>a certain sequence of events and exception where needed</Expected>
        </Case>

        <Case ID="testPutProperty">
            <TestedMethod name="public final void putProperty(Object key, Object value)"/>
            <Precondition>create a child of AbstractAbstractDocument instrumented with logging</Precondition>
            <Description>call putProperty(...)</Description>
            <Expected>getDocumentProperties().put(key, value) called</Expected>
        </Case>

        <Case ID="testNestedLocks">
            <TestedMethod name="public final void readLock()"/>
            <TestedMethod name="public final void readUnlock()"/>
            <TestedMethod name="protected final void writeLock()"/>
            <TestedMethod name="protected final void writeUnlock()"/>

            <Precondition>create a child of AbstractAbstractDocument instrumented with logging</Precondition>
            <Description>readLock, readUnlock, writeLock, writeUnlock several times</Description>
            <Expected>writelock/unlock, readlock/unlock should be balanced</Expected>
        </Case>

        <Case ID="testLockDeadWriter">
            <TestedMethod name="protected final void writeLock()"/>

            <Precondition>create a child of AbstractAbstractDocument instrumented with logging</Precondition>
            <Description>thread acquires lock and dies</Description>
            <Expected>document still locked</Expected>
        </Case>

        <Case ID="testRemove">
            <TestedMethod name="public void remove(int offs, int len)"/>
            <Precondition>create a child of AbstractAbstractDocument instrumented with logging</Precondition>
            <Description>call remove(...)</Description>
            <Expected>a certain sequence of events</Expected>
        </Case>

    </MulticaseTestDescription>

    <Keyword name="functional"/>
    <Keyword name="gui"/>
    <Source name="AbstractDocumentTest.java"/>

    <Runner ID="Runtime">
        <Param name="toRun" value="org.apache.harmony.test.func.api.javax.swing.text.AbstractDocument.AbstractDocumentTest">
        </Param>
    </Runner>
    <Restriction name="OtherVMOnly"/>
</Test>


text:
#ifndef SHIFTH
#define SHIFTH

#define BYTE 8
#define SHIFT_BYTES 6

#include <avr/io.h>
#include <stdint.h>
#include <macro.h>

struct byte_pair {
  uint8_t bh;
  uint8_t bl;
};

struct byte_pair bytes_of_uint16_t (uint16_t v);

void data_on (void);
void data_off (void);

void shift_on (void);
void shift_off (void);

void store_on (void);
void store_off (void);

uint16_t get_char_bits (char c);
uint16_t get_shift_digit (uint8_t i);
void shift_output (uint16_t bits);
void shift_bytes (uint8_t *bytes);
void init_shift(void);

#endif


text:
package mobi.nordpos.dao.factory;

import com.j256.ormlite.dao.CloseableWrappedIterable;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.support.ConnectionSource;
import com.openbravo.pos.ticket.TicketLineInfo;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import mobi.nordpos.dao.model.Product;
import mobi.nordpos.dao.model.SharedTicket;
import mobi.nordpos.dao.model.Tax;
import mobi.nordpos.dao.model.Ticket;
import mobi.nordpos.dao.model.TicketLine;
import mobi.nordpos.dao.ormlite.TicketLineDao;

/**
 * @author Andrey Svininykh <svininykh@gmail.com>
 */
public class TicketLinePersist implements PersistFactory {

    ConnectionSource connectionSource;
    TicketLineDao ticketLineDao;

    @Override
    public void init(ConnectionSource connectionSource) throws SQLException {
        this.connectionSource = connectionSource;
        ticketLineDao = new TicketLineDao(connectionSource);
    }

    @Override
    public TicketLine read(Object id) throws SQLException {
        try {
            return ticketLineDao.queryForId((String) id);
        } finally {
            if (connectionSource != null) {
                connectionSource.close();
            }
        }
    }

    @Override
    public List<TicketLine> readList() throws SQLException {
        try {
            return ticketLineDao.queryForAll();
        } finally {
            if (connectionSource != null) {
                connectionSource.close();
            }
        }
    }

    @Override
    public TicketLine find(String column, Object value) throws SQLException {
        try {
            QueryBuilder qb = ticketLineDao.queryBuilder();
            qb.where().like(column, value);
            return (TicketLine) qb.queryForFirst();
        } finally {
            if (connectionSource != null) {
                connectionSource.close();
            }
        }
    }

    @Override
    public TicketLine add(Object application) throws SQLException {
        try {
            return ticketLineDao.createIfNotExists((TicketLine) application);
        } finally {
            if (connectionSource != null) {
                connectionSource.close();
            }
        }
    }

    @Override
    public Boolean change(Object application) throws SQLException {
        try {
            return ticketLineDao.update((TicketLine) application) > 0;
        } finally {
            if (connectionSource != null) {
                connectionSource.close();
            }
        }
    }

    @Override
    public Boolean delete(Object id) throws SQLException {
        try {
            return ticketLineDao.deleteById((String) id) > 0;
        } finally {
            if (connectionSource != null) {
                connectionSource.close();
            }
        }
    }

    public List<TicketLine> readTicketLineList(Ticket ticket) throws SQLException {
        CloseableWrappedIterable<TicketLine> iterator = ticket.getTicketLineCollection().getWrappedIterable();
        List<TicketLine> list = new ArrayList<>();
        try {
            for (TicketLine line : iterator) {
                list.add(line);
            }
            return list;
        } finally {
            iterator.close();
        }
    }

    public Integer addTicketLineList(SharedTicket order, Ticket ticket) throws SQLException {
        try {
            Integer counter = 0;
            for (TicketLineInfo lineInfo : order.getContent().getLines()) {
                TicketLine line = new TicketLine();
                line.setTicket(ticket);
                line.setNumber(lineInfo.getM_iLine());
                line.setPrice(BigDecimal.valueOf(lineInfo.getPrice()));
                line.setUnit(BigDecimal.valueOf(lineInfo.getMultiply()));

                Product product = new Product();
                product.setId(lineInfo.getProductid());
                line.setProduct(product);

                Tax tax = new Tax();
                tax.setId(lineInfo.getTax().getId());
                line.setTax(tax);

                counter = counter + ticketLineDao.create(line);
            }
            return counter;
        } finally {
            if (connectionSource != null) {
                connectionSource.close();
            }
        }
    }
}


text:
AWS operation using the Lambda
==============================

Tool to automate the AWS of operation using the Lambda.

Provides
-----------------------------
- [Instance Start/Stop/CheckState](./instance/README.md)
    - Make the start and stop of the instance(multiple instances) with the specified schedule in CloudWatchEvent.
    - When a parameter to you set the QueueName and Endpoint, request of the start or stop of the instance is to create a message in and thrown successfully SQS.
    - You can be sure that the messages that have been made to SQS regularly instance by polling has been successfully start or stop.
- [EBSSnapshot](./ebs-snapshot/README.md)
    - Do the acquisition and generation management of ebssnapshot at the timing set by the CloudWatchEvent.
    - To identify the target of volume to get a snapshot There are three ways.
        - 1. To specify the volume ID in json
        - 2. To specify multiple volume ID in json
        - 3. To specify the tag that has been granted to the EBS in json
- [Create Image(AMI)](./create-image/README.md)
    - Do AMI creation and generation management along the set schedule in CloudWatchEvents.
        - 1. To specify the instance ID in json
        - 2. To specify multiple instance ID in json
- [EBSCopySnapshot](./ebs-copy-snapshot/README.md)
    - Get the EBS Copy Snapshot, perform the generation management.
    - To identify the target of volume to get a snapshot There are three ways.
        - 1. To specify the volume ID in json
        - 2. To specify multiple volume ID in json
        - 3. To specify the snapshot ID in json
- [DeregisterImage](./deregister-image/README.md)
     - At the timing of the AMI is deregistration to remove the EBS snapshot
- [RunCommand](./run-command/README.md)
     - Run ShellScript, Powershell using AWS RunCommand
     - On a regular basis by combining the Cloudwatch events can be used to execute commands on EC2

Setting of common
-----------------------------
It may be called multiple times and call the Lambda from CloudwatchEvent.
In order to prevent the creation or deletion of unexpected resources, it has secured the idempotence using DynamoDB.

Please be sure that you create the following table

- table_name: lambda_locks
- primary_key: function_name(String)
- partition_key: key(String)

VolumeID is stored if EBSSnapshot the key. If the creation of Image instanceID is stored

Author
----------------------------
[uzresk](https://twitter.com/uzresk)

License
----------------------------
MIT


text:
layout: post
title: 202
date: 2011-05-02 22:34
comments: false
categories: [aphorisms]
---

More than fair is unfair.


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Cryptosporium hypodermium var. silphii Grove

### Remarks
null


text:
<?xml version="1.0" encoding="UTF-8"?>
<ldswebml type="image" uri="/media-library/images/objects#rusty-padlock-889343" xml:lang="eng" locale="eng" status="publish" xmlns:its="http://www.w3.org/2005/11/its">
  <search-meta>
      <uri-title its:translate="no">rusty-padlock-889343</uri-title>
      <source>rusty-padlock-889343</source>
      <publication-type its:translate="no">image</publication-type>
      <media-type its:translate="no">image</media-type>
      <publication value="ldsorg">LDS.org</publication>
      <publication-date value="2012-05-30">2012-05-30</publication-date>
      <title/>
      <description/>
      <collections>
          <collection its:translate="no">global-search</collection>
          <collection its:translate="no">media</collection>
          <collection its:translate="no">images</collection>
      </collections>
      <subjects>
          <subject>padlock</subject>
          <subject>lock</subject>
          <subject>locks</subject>
          <subject>gate</subject>
          <subject>rusty</subject>
          <subject>old</subject>
          <subject>rust</subject>
          <subject>spin</subject>
          <subject>door</subject>
          <subject>keep out</subject>
      </subjects>
  </search-meta>
  <no-search>
      <path>http://media.ldscdn.org/images/media-library/objects/rusty-padlock-889343-gallery.jpg</path>
      <images>
          http://media.ldscdn.org/images/media-library/objects/rusty-padlock-889343-thumbnail.jpg
      </images>
          <download-urls>
              <download-url>
                  Mobile
                  <size>310 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/objects/rusty-padlock-889343-mobile.jpg</path>
              </download-url>
              <download-url>
                  Tablet
                  <size>351 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/objects/rusty-padlock-889343-tablet.jpg</path>
              </download-url>
              <download-url>
                  Print
                  <size>735 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/objects/rusty-padlock-889343-print.jpg</path>
              </download-url>
              <download-url>
                  Wallpaper
                  <size>1.5 MB</size>
                  <path>http://media.ldscdn.org/images/media-library/objects/rusty-padlock-889343-wallpaper.jpg</path>
              </download-url>
          </download-urls>
  </no-search>
</ldswebml>


text:
__author__ = 'Team'

from abstractpipeline import *
import pandas as pd
from datetime import date, datetime
from dateutil.relativedelta import relativedelta
from util import cred # import credentials
from util.SQL_helpers import connect_to_db
from sklearn import metrics
import importlib
from modeling.featurepipeline.scikitmodel import *
from modeling.featurepipeline import dataloader
import time, datetime
import config
import warnings
import os
import matplotlib.pyplot as plt
import pickle
import markdown

class Experiment(AbstractPipelineConfig):

    def __init__(self, model, feature_list, dloader, id=None,nan_handling='strict',
                 logFolder='modeling_logs',looplog=None, summary_only=False):

        if nan_handling not in ['strict','lax']:
            raise ValueError("nan_handling must be either 'lax' or 'strict'")
        self.nan_handling = nan_handling

        self.model = model
        self.id = id
        self.feature_list = feature_list
        self.dloader = dloader
        self.looplog = looplog
        self.logFolder = logFolder
        self.summary_only = summary_only

        #copy the dataframe from the dataloader, subset by the columns
        self.train_rows = dloader.subset_data(feature_list, 'train')
        self.test_rows = dloader.subset_data(feature_list, 'test')
        self.target_col = dloader.target[0]['test'].feature_col

    def apply_postprocessors(self):
        ''' Gets the dataframe, applies all the relevant postprocessors to the features and returns the dataframe
            Asks the dataloader for the relevant postprocessors, does logic to see which postprocessors to apply
            TODO: implement the logic
            then applies them
            Note: under the current system only features get postprocessed. We'll need to add the target if it
            needs to be postprocessed as well
        '''

        pps = self.dloader.get_postprocessors(self.feature_list)

        # iterate through every column in the dictionary and apply the postprocessors

        for key in pps.keys():
            # TODO IMPLEMENT LOGIC HERE
            # For now, just run these
            for postprocessor, kwargs in pps[key].items():
                self.train_rows = postprocessor(self.train_rows, columns = [key], **kwargs)
                self.test_rows = postprocessor(self.test_rows,columns = [key], **kwargs)

    def handle_NAs(self):

        train_nans = self.train_rows.shape[0] - self.train_rows.count().min()
        test_nans = self.test_rows.shape[0] - self.test_rows.count().min()

        self.train_rows_dropped = 0
        self.test_rows_dropped = 0
        self.nan_column_log = 'None'

        if max(train_nans,test_nans) > 0:

            if self.nan_handling == 'strict':
                raise ValueError("There are rows with NaNs, and nan_handling is set to strict.")

            elif self.nan_handling == 'lax':
                warnings.warn("There are rows with NaNs in the data, dropping them!")

                print "Training data: Dropping %d out of %d rows."%(train_nans, self.train_rows.shape[0])
                print "Test data: Dropping %d out of %d rows."%(test_nans, self.test_rows.shape[0])

                # Log the number of missings in each column in both train and test
                train_miss_count = self.train_rows.isnull().sum(axis=0)
                train_miss_perc =  train_miss_count.divide(self.train_rows.shape[0]).round(3) * 100

                test_miss_count = self.test_rows.isnull().sum(axis=0)
                test_miss_perc =  test_miss_count.divide(self.test_rows.shape[0]).round(3) * 100

                nan_count_df = pd.concat([train_miss_count, train_miss_perc, test_miss_count, test_miss_perc], axis=1)
                nan_count_df.columns = ['Train Count NaN', 'Train Percentage NaN', 'Test Count NaN', 'Test Percentage NaN']
                nan_count_df.fillna('DNE')
                self.nan_column_log = nan_count_df.to_string()

                # Log the number of dropped rows
                self.train_rows_dropped = train_nans
                self.test_rows_dropped = test_nans

                # Drop the NaNs
                self.train_rows.dropna(how='any',axis=0,inplace=True)
                self.test_rows.dropna(how='any',axis=0,inplace=True)

    def run_experiment(self):

        self.starttime = time.time()

        #apply postprocessors

        self.apply_postprocessors()

        #handle NAs

        self.handle_NAs()

        # need to make sure that we only select the columns that are the same across train and test, need the intersection
        test_cols = set(self.test_rows.columns.values)
        train_cols = set(self.train_rows.columns.values)

        predictor_cols = list(test_cols & train_cols)

        predictor_cols.remove(self.target_col)

        self.model.fit(X_train=self.train_rows[predictor_cols],
                        y_train=self.train_rows[self.target_col])

        y_pred = self.model.predict(self.test_rows[predictor_cols])
        # evaluations
        cm = self.model.cm(y_test=self.test_rows[self.target_col], y_predicted=y_pred)
        coefs = self.model.coefs()
        clf_report = self.model.clf_report(y_test=self.test_rows[self.target_col], y_predicted=y_pred)
        auc = self.model.auc(y_test=self.test_rows[self.target_col], X_test = self.test_rows[predictor_cols])
        pr0_precision_top_10 = self.model.precision_top_k_percent(0.1, X_test = self.test_rows[predictor_cols], y_test = self.test_rows[self.target_col], y_predicted = y_pred, pos_label = 0)
        pr0_precision_top_25 = self.model.precision_top_k_percent(0.25, X_test = self.test_rows[predictor_cols], y_test = self.test_rows[self.target_col], y_predicted = y_pred, pos_label = 0)
        aupr0 = self.model.aupr(y_test=self.train_rows[self.target_col], X_test = self.train_rows[predictor_cols], pos_label=0)

        # get the within-training set ROC, AUC, precision-recall curves
        y_pred_train = self.model.predict(self.train_rows[predictor_cols])
        # evaluations
        cm_train = self.model.cm(y_test=self.train_rows[self.target_col], y_predicted=y_pred_train)
        clf_report_train = self.model.clf_report(y_test=self.train_rows[self.target_col], y_predicted=y_pred_train)
        auc_train = self.model.auc(y_test=self.train_rows[self.target_col], X_test = self.train_rows[predictor_cols])

        # TODO just for debugging
        self.auc_train = auc_train
        self.auc = auc

        if not self.summary_only:
            cm_plt = self.model.plot_cm(cm=cm)
            roc_plt = self.model.plot_roc(y_test=self.test_rows[self.target_col], X_test = self.test_rows[predictor_cols])
            pr1_plt = self.model.plot_precision_recall(y_test=self.test_rows[self.target_col], X_test = self.test_rows[predictor_cols], pos_label=1)
            pr0_plt = self.model.plot_precision_recall(y_test=self.test_rows[self.target_col], X_test = self.test_rows[predictor_cols], pos_label=0)
            cm_plt_train = self.model.plot_cm(cm=cm_train)
            roc_plt_train = self.model.plot_roc(y_test=self.train_rows[self.target_col], X_test = self.train_rows[predictor_cols])
            pr1_plt_train = self.model.plot_precision_recall(y_test=self.train_rows[self.target_col], X_test = self.train_rows[predictor_cols], pos_label=1)
            pr0_plt_train = self.model.plot_precision_recall(y_test=self.train_rows[self.target_col], X_test = self.train_rows[predictor_cols], pos_label=0)
        else:
            cm_plt = None
            roc_plt = None
            pr1_plt = None
            pr0_plt = None
            cm_plt_train = None
            roc_plt_train = None
            pr1_plt_train = None
            pr0_plt_train = None

        # record ending time
        self.endtime = time.time()

        # write log
        self.write_log(cm=cm, cm_plt=cm_plt, roc_plt=roc_plt, clf_report=clf_report, coefs=coefs,
                        auc=auc, pr0_precision_top_10 = pr0_precision_top_10, pr0_precision_top_25 = pr0_precision_top_25,aupr0 = aupr0, pr1_plt=pr1_plt, pr0_plt=pr0_plt,
                        roc_plt_train=roc_plt_train, cm_train=cm_train, cm_plt_train=cm_plt_train, clf_report_train=clf_report_train,
                        auc_train=auc_train, pr1_plt_train=pr1_plt_train, pr0_plt_train=pr0_plt_train)

        # plt.close(cm_plt)
        # plt.close(cm_plt_train)
        # plt.close(roc_plt)
        # plt.close(roc_plt_train)
        # plt.close(pr1_plt)
        # plt.close(pr1_plt_train)
        plt.close('all')

    def write_log(self, cm, cm_plt, roc_plt, clf_report, coefs, auc, pr0_precision_top_10, pr0_precision_top_25,aupr0,pr1_plt, pr0_plt,
                    roc_plt_train, cm_train, cm_plt_train, clf_report_train, auc_train, pr1_plt_train, pr0_plt_train):

        if not os.path.isdir(os.path.join(config.PERSISTENCE_PATH, self.logFolder)):
            os.makedirs(os.path.join(config.PERSISTENCE_PATH, self.logFolder))

        if not self.summary_only:

            # String with common folder name
            logsubfoldername = '_'+datetime.datetime.fromtimestamp(self.starttime).strftime('%Y-%m-%d_%H-%M-%S')
            logpath = os.path.join(config.PERSISTENCE_PATH, self.logFolder,logsubfoldername)

            # Check that folder does not already exist (an experiment took <1 sec)
            if os.path.isdir(logpath):
                i=1
                logpathstub = logpath
                while os.path.isdir(logpath):
                    i += 1
                    logpath = logpathstub + '_' + str(i)

            # Make log folder
            logpath += '/'
            os.makedirs(logpath)

            # Write pickle
            pickle.dump(self, open(logpath + 'experiment.p', "wb" ) )

        # Write figures to a folder
        if cm_plt!= None: cm_plt.savefig(logpath+'cm_plt.png', pad_inches=1)
        if roc_plt!= None: roc_plt.savefig(logpath+'roc_plt.png')
        if pr1_plt!= None: pr1_plt.savefig(logpath+'pr1_plt.png')
        if pr0_plt!= None: pr0_plt.savefig(logpath+'pr0_plt.png')

        # write figures for training set results to folder
        if cm_plt_train != None: cm_plt_train.savefig(logpath+'cm_plt_train.png', pad_inches=1)
        if roc_plt_train != None: roc_plt_train.savefig(logpath+'roc_plt_train.png')
        if pr1_plt_train != None: pr1_plt_train.savefig(logpath+'pr1_plt_train.png')
        if pr0_plt_train != None: pr0_plt_train.savefig(logpath+'pr0_plt_train.png')

        # Write detailed log to markdown file
        if not self.summary_only:
            with open(logpath+'log.md', 'w') as f:
                markdown_log_template='''
# Experiment log

## Run time

**Start time:** {starttime}
**End time:** {endtime}

## Experiment

**Outcome:**
{target}

**Restrictions:**
{listofrestrictions}

**Train-test split**
* Train start = {trainstart}
* Split date = {splitdate}
* Test end = {testend}

**Features:**
{listoffeatures}

## Model

**Classifier:** {clf}

**Parameters:**
{params}

## Data loading

Megaquery for train split:
```sql
{train_megaquery}
```

Megaquery for test split:
```sql
{test_megaquery}
```

**Dropped rows with NaNs:**
Training data: Dropped {train_nans} out of {train_rows} rows.
Test data: Dropped {test_nans} out of {test_rows} rows.

NaNs for each feature:
```
{nan_column_log}
```

## Results on Training Set

Confusion matrix table:

| | **Predicted Negative** | **Predicted Positive** |
| ----------------- |:----:|:----:|
| **True Negative** | {TN_train} | {FP_train} |
| **True Positive** | {FN_train} | {TP_train} |

Confusion matrix plot:
![Confusion Matrix]({path_to_cm_plt_train})

ROC curve:
![ROC Curve]({path_to_roc_plt_train})

Precision-Recall curves for **dropping out**:
![PR Curve 0]({path_to_pr0_plt_train})

Precision-Recall curves for **persisting**:
![PR Curve 1]({path_to_pr1_plt_train})

**Precision recall report:**
```
{clf_report_train}
```

## Results on Test Set

Confusion matrix table:

| | **Predicted Negative** | **Predicted Positive** |
| ----------------- |:----:|:----:|
| **True Negative** | {TN} | {FP} |
| **True Positive** | {FN} | {TP} |

Confusion matrix plot:
![Confusion Matrix]({path_to_cm_plt})

ROC curve:
![ROC Curve]({path_to_roc_plt})

Precision-Recall curves for **dropping out**:
![PR Curve 0]({path_to_pr0_plt})

Precision-Recall curves for **persisting**:
![PR Curve 1]({path_to_pr1_plt})

**Precision recall report:**
```
{clf_report}
```

**Parameter coefficients:**
```
{coefs}
```
'''
                f.write(
                    markdown_log_template.format(
                        starttime=datetime.datetime.fromtimestamp(self.starttime).strftime('%Y-%m-%d %H:%M:%S'),
                        endtime=datetime.datetime.fromtimestamp(self.endtime).strftime('%Y-%m-%d %H:%M:%S'),
                        target=self.target_col,
                        listofrestrictions='\n'.join([r['test'].feature_col + r['restriction'] for r in self.dloader.restrictors]),
                        splitdate=self.dloader.split_date,
                        trainstart=self.dloader.train_start,
                        testend=self.dloader.test_end,
                        listoffeatures='\n'.join(self.feature_list),
                        clf=self.model.scikit_class.__name__,
                        params='\n'.join(['* '+param+': '+str(val)   for param,val in self.model.scikit_params.items()]),
                        train_megaquery=self.dloader.train_megaquery,
                        test_megaquery=self.dloader.test_megaquery,
                        train_nans=self.train_rows_dropped,
                        train_rows=self.train_rows.shape[0],
                        test_nans=self.test_rows_dropped,
                        test_rows=self.test_rows.shape[0],
                        nan_column_log=self.nan_column_log,
                        TN=cm[0,0],
                        FP=cm[0,1],
                        FN=cm[1,0],
                        TP=cm[1,1],
                        TN_train=cm_train[0,0],
                        FP_train=cm_train[0,1],
                        FN_train=cm_train[1,0],
                        TP_train=cm_train[1,1],
                        path_to_cm_plt='cm_plt.png',
                        path_to_roc_plt='roc_plt.png',
                        path_to_pr0_plt='pr0_plt.png',
                        path_to_pr1_plt='pr1_plt.png',
                        coefs=coefs,
                        clf_report=clf_report,
                        path_to_cm_plt_train='cm_plt_train.png',
                        path_to_roc_plt_train='roc_plt_train.png',
                        path_to_pr0_plt_train='pr0_plt_train.png',
                        path_to_pr1_plt_train='pr1_plt_train.png',
                        clf_report_train=clf_report_train

                    )
                )

        # Add experiment to looplog
        if self.looplog!=None:
            looplogpath = os.path.join(config.PERSISTENCE_PATH, self.logFolder, self.looplog)

            # Prepare string describing target & restrictors
            if len(self.dloader.restrictors)==0:
                outcome = self.target_col
            else:
                outcome = self.target_col + '
WHERE
' + '
AND '.join([r['test'].feature_col + r['restriction'] for r in self.dloader.restrictors])

            # If looplog file does not exist, create empty looplog with headers
            if os.path.isfile(looplogpath)==False:
                with open(looplogpath, 'w') as f:
                    f.write(
'''| Run time | Outcome | Train Start | Split Date | Test End | Classifier | Features | AUC | AUC (Train) | Precision Top 10% | Precision Top 25% | AUPR | Log |
| -- | -- | -- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |''')

            # Add new row to looplog
            with open(looplogpath, "a") as f:
                looplog_row_template='''
| {starttime} | {outcome} | {trainstart} | {splitdate} | {testend} | {clf} | {listoffeatures} | {auc} | {auc_train} | {pr0_precision_top_10}| {pr0_precision_top_25}| {aupr0} | [Link]({logpath}) |'''

                f.write(
                    looplog_row_template.format(
                        starttime=datetime.datetime.fromtimestamp(self.starttime).strftime('%Y-%m-%d %H:%M:%S'),
                        outcome=outcome,
                        splitdate=self.dloader.split_date,
                        trainstart=self.dloader.train_start,
                        testend=self.dloader.test_end,
                        clf='**' + self.model.scikit_class.__name__ + '**' + '
' + '
'.join(['* '+str(param).replace('\n','')+': '+str(val).replace('\n','')   for param,val in self.model.scikit_params.items()]),
                        listoffeatures='
 '.join(self.feature_list),
                        auc=round(auc,3),
                        auc_train=round(auc_train,3),
                        pr0_precision_top_10 = round(pr0_precision_top_10,3),
                        pr0_precision_top_25 = round(pr0_precision_top_25,3),
                        aupr0 = round(aupr0, 3),
                        logpath='' if self.summary_only else logsubfoldername+'/log.md'
                    )
                )

            # # Render looplog Markdown to HTML
            # markdown.markdownFromFile(input=looplogpath,
            #                           output=os.path.join(config.PERSISTENCE_PATH, self.logFolder,'looplog.html'),
            #                           extensions=['markdown.extensions.tables']
            #                         )

# if __name__ == '__main__':

#     from sklearn.linear_model import LogisticRegression
#     m = ScikitModel(   scikit_class=LogisticRegression,
#                                                 scikit_params={
#                                                     "penalty":"l2",
#                                                     "dual":False,
#                                                     "C":1.0
#                                                   }
#                                             )

#     e = Experiment(model=m, target=['PersistThreeSemesters'],
#         feature_list=['StudentAgeAtEnrollment','StudentGender'],
#         restrictors=['PersistOneSemester'],
#         split_date='2013-06-01', train_window=365, test_window=365, name='just a test')


text:
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.

package com.intellij.codeInspection.dataFlow.lang.ir;

import com.intellij.codeInspection.dataFlow.interpreter.DataFlowInterpreter;
import com.intellij.codeInspection.dataFlow.memory.DfaMemoryState;
import org.jetbrains.annotations.NotNull;

import java.util.Objects;

/**
 * An (instruction, memoryState) pair that represents single possible abstract interpreter state.
 */
public class DfaInstructionState implements Comparable<DfaInstructionState> {
  public static final DfaInstructionState[] EMPTY_ARRAY = new DfaInstructionState[0];
  private final DfaMemoryState myBeforeMemoryState;
  private final Instruction myInstruction;

  public DfaInstructionState(@NotNull Instruction myInstruction, @NotNull DfaMemoryState myBeforeMemoryState) {
    this.myBeforeMemoryState = myBeforeMemoryState;
    this.myInstruction = myInstruction;
  }

  @NotNull
  public Instruction getInstruction() {
    return myInstruction;
  }

  /**
   * A helper method to create the resulting states for linear instruction
   *
   * @param interpreter interpreter that interprets current IR
   * @return an array of single instruction state containing the next instruction.
   */
  public DfaInstructionState[] nextStates(DataFlowInterpreter interpreter) {
    return myInstruction.nextStates(interpreter, myBeforeMemoryState);
  }

  @NotNull
  public DfaMemoryState getMemoryState() {
    return myBeforeMemoryState;
  }

  public String toString() {
    return getInstruction().getIndex() + " " + getInstruction() + ":   " + getMemoryState();
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    DfaInstructionState state = (DfaInstructionState)o;
    return Objects.equals(myBeforeMemoryState, state.myBeforeMemoryState) &&
           Objects.equals(myInstruction, state.myInstruction);
  }

  @Override
  public int hashCode() {
    return Objects.hash(myBeforeMemoryState, myInstruction);
  }

  @Override
  public int compareTo(@NotNull DfaInstructionState o) {
    return Integer.compare(myInstruction.getIndex(), o.myInstruction.getIndex());
  }
}


text:
// flow-typed signature: d23d035a68961c2114eabe89ed158698
// flow-typed version: <<STUB>>/@babel/helper-module-imports_v^7.8.3/flow_v0.121.0

/**
 * This is an autogenerated libdef stub for:
 *
 *   '@babel/helper-module-imports'
 *
 * Fill this stub out by replacing all the `any` types.
 *
 * Once filled out, we encourage you to share your work with the
 * community by sending a pull request to:
 * https://github.com/flowtype/flow-typed
 */

declare module '@babel/helper-module-imports' {
  declare module.exports: any;
}

/**
 * We include stubs for each file inside this npm package in case you need to
 * require those files directly. Feel free to delete any files that aren't
 * needed.
 */
declare module '@babel/helper-module-imports/lib/import-builder' {
  declare module.exports: any;
}

declare module '@babel/helper-module-imports/lib/import-injector' {
  declare module.exports: any;
}

declare module '@babel/helper-module-imports/lib' {
  declare module.exports: any;
}

declare module '@babel/helper-module-imports/lib/is-module' {
  declare module.exports: any;
}

// Filename aliases
declare module '@babel/helper-module-imports/lib/import-builder.js' {
  declare module.exports: $Exports<'@babel/helper-module-imports/lib/import-builder'>;
}
declare module '@babel/helper-module-imports/lib/import-injector.js' {
  declare module.exports: $Exports<'@babel/helper-module-imports/lib/import-injector'>;
}
declare module '@babel/helper-module-imports/lib/index' {
  declare module.exports: $Exports<'@babel/helper-module-imports/lib'>;
}
declare module '@babel/helper-module-imports/lib/index.js' {
  declare module.exports: $Exports<'@babel/helper-module-imports/lib'>;
}
declare module '@babel/helper-module-imports/lib/is-module.js' {
  declare module.exports: $Exports<'@babel/helper-module-imports/lib/is-module'>;
}


text:
block('menu').mod('focused', true).js()(function() {
    return this.extend(applyNext(), { live : false });
});


text:
@interface QKQRCodeViewController ()<AVCaptureMetadataOutputObjectsDelegate>
@property(nonatomic,strong)AVCaptureSession * session;
@property(nonatomic,weak)UIView * maskView;
@end

@implementation QKQRCodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor lightGrayColor];
    self.navigationController.navigationBar.hidden = YES;
    self.view.clipsToBounds = YES;
    [self setupMaskView];
    [self setupBottomBar];
    [self setupScanWindowView];
    [self beginScanning];

}

-(void)setupMaskView
{
    UIView * mask = [[UIView alloc]init];
    self.maskView = mask;
    mask.layer.borderColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.3].CGColor;
    mask.layer.borderWidth = (self.view.height - ScanViewWidthAndHeight)/2;

    mask.bounds = CGRectMake(0, 0, self.view.width *(self.view.height/self.view.width) , self.view.height);
    mask.centerX = self.view.centerX;
    mask.y = 0;
    UIImageView * imageView =[[UIImageView alloc]init];
    [imageView setImage:[UIImage imageNamed:@"scan_icon"]];
    imageView.size = CGSizeMake(40, 40);
    imageView.x = 0;
    imageView.y = 0;
    UILabel * label = [[UILabel alloc]init];
    label.text = @"把二维码放到框框里就可以扫描了";
//    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor greenColor];
    label.numberOfLines= 2;
    label.font = [UIFont systemFontOfSize:14];
    label.size = CGSizeMake(120, 40);
    label.x = CGRectGetMaxX(imageView.frame)+5;
    label.y = 0;
    UIView * iconAndLabelView = [[UIView alloc]init];
    iconAndLabelView.backgroundColor = [UIColor clearColor];
    iconAndLabelView.size = CGSizeMake(165, 40);
    iconAndLabelView.x = (self.view.width - iconAndLabelView.width)/2;
    iconAndLabelView.y = self.view.height * 0.2;
    [iconAndLabelView addSubview:imageView];
    [iconAndLabelView addSubview:label];
    [self.view addSubview:iconAndLabelView];
    [self.view addSubview:mask];

}
- (void)setupBottomBar
{
    UIView *bottomBar = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.height * 0.9, self.view.width, self.view.height * 0.1)];
    bottomBar.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.8];
    UIButton * backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [backButton setTitle:@"取消" forState:UIControlStateNormal];
    backButton.x = 5;
    backButton.width = 50;
    backButton.height = 30;
    backButton.y = (bottomBar.height - backButton.height)/2;

    [backButton addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
    [bottomBar addSubview:backButton];
    [self.view addSubview:bottomBar];
}
- (void)setupScanWindowView
{

    UIView *scanWindow = [[UIView alloc] init];
    scanWindow.width = ScanViewWidthAndHeight;
    scanWindow.height = ScanViewWidthAndHeight;
    scanWindow.y = (self.view.height - scanWindow.height) / 2;
    scanWindow.x =(self.view.width - scanWindow.width)/2;
    scanWindow.clipsToBounds = YES;
    [self.view addSubview:scanWindow];

    CGFloat scanNetImageViewH = ScanViewWidthAndHeight;
    CGFloat scanNetImageViewW = scanWindow.width;
    UIImageView *scanNetImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"scan_net"]];
    scanNetImageView.frame = CGRectMake(0, -scanNetImageViewH, scanNetImageViewW, scanNetImageViewH);
    CABasicAnimation *scanNetAnimation = [CABasicAnimation animation];
    scanNetAnimation.keyPath = @"transform.translation.y";
    scanNetAnimation.byValue = @(scanWindow.height);
    scanNetAnimation.duration = 1.5;
    scanNetAnimation.repeatCount = MAXFLOAT;
    [scanNetImageView.layer addAnimation:scanNetAnimation forKey:nil];
    [scanWindow addSubview:scanNetImageView];
//  设置4个边框
    CGFloat buttonWH = 18;

    UIButton *topLeft = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, buttonWH, buttonWH)];
    [topLeft setImage:[UIImage imageNamed:@"scan_1"] forState:UIControlStateNormal];
    [scanWindow addSubview:topLeft];

    UIButton *topRight = [[UIButton alloc] initWithFrame:CGRectMake(scanWindow.width - buttonWH, 0, buttonWH, buttonWH)];
    [topRight setImage:[UIImage imageNamed:@"scan_2"] forState:UIControlStateNormal];
    [scanWindow addSubview:topRight];

    UIButton *bottomLeft = [[UIButton alloc] initWithFrame:CGRectMake(0, scanWindow.height - buttonWH, buttonWH, buttonWH)];
    [bottomLeft setImage:[UIImage imageNamed:@"scan_3"] forState:UIControlStateNormal];
    [scanWindow addSubview:bottomLeft];

    UIButton *bottomRight = [[UIButton alloc] initWithFrame:CGRectMake(topRight.x, bottomLeft.y, buttonWH, buttonWH)];
    [bottomRight setImage:[UIImage imageNamed:@"scan_4"] forState:UIControlStateNormal];
    [scanWindow addSubview:bottomRight];
}

- (void)beginScanning
{
    //获取摄像设备
    AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    //创建输入流
    AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    if (!input) return;
    //创建输出流
    AVCaptureMetadataOutput * output = [[AVCaptureMetadataOutput alloc]init];
    output.rectOfInterest = CGRectMake(((self.view.height-ScanViewWidthAndHeight)/2)/self.view.height,((self.view.width-ScanViewWidthAndHeight)/2)/self.view.width,ScanViewWidthAndHeight/QKScreenHeight,ScanViewWidthAndHeight/QKScreenWidth);
    //设置代理 在主线程里刷新
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];

    //初始化链接对象
    _session = [[AVCaptureSession alloc]init];
    //高质量采集率
    [_session setSessionPreset:AVCaptureSessionPresetHigh];

    [_session addInput:input];
    [_session addOutput:output];
    //设置扫码支持的编码格式(如下设置条形码和二维码兼容)
    output.metadataObjectTypes=@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];

    AVCaptureVideoPreviewLayer * layer = [AVCaptureVideoPreviewLayer layerWithSession:_session];
    layer.videoGravity=AVLayerVideoGravityResizeAspectFill;
    layer.frame= self.view.layer.bounds;
    [self.view.layer insertSublayer:layer atIndex:0];

    //开始捕获
    [_session startRunning];

}
-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    if (metadataObjects.count>0) {

        AppDelegate * appDelegate = [UIApplication sharedApplication].delegate;
        if (appDelegate.isExistenceNetwork == NO) {
            [_session stopRunning];
            [MBProgressHUD showError:@"请检查网络"];
        }else{
            [_session stopRunning];
            AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex : 0 ];
            QKScanWebViewController * webVC = [[QKScanWebViewController alloc]init];

            QKAnswerViewController * answerVC = [[QKAnswerViewController alloc]init];

            webVC.urlStr = metadataObject.stringValue;
//            DCLog(@"扫描结果---%@",metadataObject.stringValue);
            if([metadataObject.stringValue hasPrefix:@"http://qkhl-api.com/math/"]||[metadataObject.stringValue hasPrefix:@"http://qkhl-api.com/english/"]||[metadataObject.stringValue hasPrefix:@"http://qkhl-api.com/chinese/"]){
                NSString * str = metadataObject.stringValue;
                NSString * str2 = [str componentsSeparatedByString:@"com/"].lastObject;
                NSString * str3 =[str2 componentsSeparatedByString:@".p"].firstObject;
                NSString *strUrl = [str3 stringByReplacingOccurrencesOfString:@"/" withString:@""];
//                DCLog(@"拆分字符串-%@",strUrl);
                answerVC.unique_code = strUrl;
                [self.navigationController pushViewController:answerVC animated:YES];

            }else{
                [self.navigationController pushViewController:webVC animated:YES];
            }
        }
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"扫描结果" message:metadataObject.stringValue delegate:self cancelButtonTitle:@"退出" otherButtonTitles:@"再次扫描", nil];
//        [alert show];

    }
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    [_session startRunning];
}

-(void)dismiss
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}
- (void)willMoveToParentViewController:(UIViewController *)parent
{
    if (!parent) {
        self.navigationController.navigationBar.hidden = NO;
    }
}

@end


text:
package org.gearvrf.bulletphysics.collision.dispatch;

import javax.vecmath.Vector3f;

import org.gearvrf.bulletphysics.collision.broadphase.CollisionAlgorithm;
import org.gearvrf.bulletphysics.collision.broadphase.CollisionAlgorithmConstructionInfo;
import org.gearvrf.bulletphysics.collision.broadphase.DispatcherInfo;
import org.gearvrf.bulletphysics.collision.narrowphase.ConvexCast;
import org.gearvrf.bulletphysics.collision.narrowphase.ConvexPenetrationDepthSolver;
import org.gearvrf.bulletphysics.collision.narrowphase.GjkConvexCast;
import org.gearvrf.bulletphysics.collision.narrowphase.GjkPairDetector;
import org.gearvrf.bulletphysics.collision.narrowphase.PersistentManifold;
import org.gearvrf.bulletphysics.collision.narrowphase.SimplexSolverInterface;
import org.gearvrf.bulletphysics.collision.narrowphase.VoronoiSimplexSolver;
import org.gearvrf.bulletphysics.collision.narrowphase.DiscreteCollisionDetectorInterface.ClosestPointInput;
import org.gearvrf.bulletphysics.collision.shapes.ConvexShape;
import org.gearvrf.bulletphysics.collision.shapes.SphereShape;
import org.gearvrf.bulletphysics.linearmath.Transform;
import org.gearvrf.bulletphysics.stack.Stack;
import org.gearvrf.bulletphysics.util.ObjectArrayList;
import org.gearvrf.bulletphysics.util.ObjectPool;

/**
 * ConvexConvexAlgorithm collision algorithm implements time of impact, convex
 * closest points and penetration depth calculations.
 *
 * @author jezek2
 */
public class ConvexConvexAlgorithm extends CollisionAlgorithm {

	protected final ObjectPool<ClosestPointInput> pointInputsPool = ObjectPool.get(ClosestPointInput.class);

	private GjkPairDetector gjkPairDetector = new GjkPairDetector();

	public boolean ownManifold;
	public PersistentManifold manifoldPtr;
	public boolean lowLevelOfDetail;

	public void init(PersistentManifold mf, CollisionAlgorithmConstructionInfo ci, CollisionObject body0, CollisionObject body1, SimplexSolverInterface simplexSolver, ConvexPenetrationDepthSolver pdSolver) {
		super.init(ci);
		gjkPairDetector.init(null, null, simplexSolver, pdSolver);
		this.manifoldPtr = mf;
		this.ownManifold = false;
		this.lowLevelOfDetail = false;
	}

	@Override
	public void destroy() {
		if (ownManifold) {
			if (manifoldPtr != null) {
				dispatcher.releaseManifold(manifoldPtr);
			}
			manifoldPtr = null;
		}
	}

	public void setLowLevelOfDetail(boolean useLowLevel) {
		this.lowLevelOfDetail = useLowLevel;
	}

	/**
	 * Convex-Convex collision algorithm.
	 */
	@Override
	public void processCollision(CollisionObject body0, CollisionObject body1, DispatcherInfo dispatchInfo, ManifoldResult resultOut) {
		if (manifoldPtr == null) {
			// swapped?
			manifoldPtr = dispatcher.getNewManifold(body0, body1);
			ownManifold = true;
		}
		resultOut.setPersistentManifold(manifoldPtr);

//	#ifdef USE_BT_GJKEPA
//		btConvexShape*				shape0(static_cast<btConvexShape*>(body0->getCollisionShape()));
//		btConvexShape*				shape1(static_cast<btConvexShape*>(body1->getCollisionShape()));
//		const btScalar				radialmargin(0/*shape0->getMargin()+shape1->getMargin()*/);
//		btGjkEpaSolver::sResults	results;
//		if(btGjkEpaSolver::Collide(	shape0,body0->getWorldTransform(),
//									shape1,body1->getWorldTransform(),
//									radialmargin,results))
//			{
//			dispatchInfo.m_debugDraw->drawLine(results.witnesses[1],results.witnesses[1]+results.normal,btVector3(255,0,0));
//			resultOut->addContactPoint(results.normal,results.witnesses[1],-results.depth);
//			}
//	#else

		ConvexShape min0 = (ConvexShape) body0.getCollisionShape();
		ConvexShape min1 = (ConvexShape) body1.getCollisionShape();

		ClosestPointInput input = pointInputsPool.get();
		input.init();

		// JAVA NOTE: original: TODO: if (dispatchInfo.m_useContinuous)
		gjkPairDetector.setMinkowskiA(min0);
		gjkPairDetector.setMinkowskiB(min1);
		input.maximumDistanceSquared = min0.getMargin() + min1.getMargin() + manifoldPtr.getContactBreakingThreshold();
		input.maximumDistanceSquared *= input.maximumDistanceSquared;
		//input.m_stackAlloc = dispatchInfo.m_stackAllocator;

		//	input.m_maximumDistanceSquared = btScalar(1e30);

		body0.getWorldTransform(input.transformA);
		body1.getWorldTransform(input.transformB);

		gjkPairDetector.getClosestPoints(input, resultOut, dispatchInfo.debugDraw);

		pointInputsPool.release(input);
		//	#endif

		if (ownManifold) {
			resultOut.refreshContactPoints();
		}
	}

	private static boolean disableCcd = false;

	@Override
	public float calculateTimeOfImpact(CollisionObject col0, CollisionObject col1, DispatcherInfo dispatchInfo, ManifoldResult resultOut) {
		Vector3f tmp = Stack.alloc(Vector3f.class);

		Transform tmpTrans1 = Stack.alloc(Transform.class);
		Transform tmpTrans2 = Stack.alloc(Transform.class);

		// Rather then checking ALL pairs, only calculate TOI when motion exceeds threshold

		// Linear motion for one of objects needs to exceed m_ccdSquareMotionThreshold
		// col0->m_worldTransform,
		float resultFraction = 1f;

		tmp.sub(col0.getInterpolationWorldTransform(tmpTrans1).origin, col0.getWorldTransform(tmpTrans2).origin);
		float squareMot0 = tmp.lengthSquared();

		tmp.sub(col1.getInterpolationWorldTransform(tmpTrans1).origin, col1.getWorldTransform(tmpTrans2).origin);
		float squareMot1 = tmp.lengthSquared();

		if (squareMot0 < col0.getCcdSquareMotionThreshold() &&
				squareMot1 < col1.getCcdSquareMotionThreshold()) {
			return resultFraction;
		}

		if (disableCcd) {
			return 1f;
		}

		Transform tmpTrans3 = Stack.alloc(Transform.class);
		Transform tmpTrans4 = Stack.alloc(Transform.class);

		// An adhoc way of testing the Continuous Collision Detection algorithms
		// One object is approximated as a sphere, to simplify things
		// Starting in penetration should report no time of impact
		// For proper CCD, better accuracy and handling of 'allowed' penetration should be added
		// also the mainloop of the physics should have a kind of toi queue (something like Brian Mirtich's application of Timewarp for Rigidbodies)

		// Convex0 against sphere for Convex1
		{
			ConvexShape convex0 = (ConvexShape) col0.getCollisionShape();

			SphereShape sphere1 = new SphereShape(col1.getCcdSweptSphereRadius()); // todo: allow non-zero sphere sizes, for better approximation
			ConvexCast.CastResult result = new ConvexCast.CastResult();
			VoronoiSimplexSolver voronoiSimplex = new VoronoiSimplexSolver();
			//SubsimplexConvexCast ccd0(&sphere,min0,&voronoiSimplex);
			///Simplification, one object is simplified as a sphere
			GjkConvexCast ccd1 = new GjkConvexCast(convex0, sphere1, voronoiSimplex);
			//ContinuousConvexCollision ccd(min0,min1,&voronoiSimplex,0);
			if (ccd1.calcTimeOfImpact(col0.getWorldTransform(tmpTrans1), col0.getInterpolationWorldTransform(tmpTrans2),
					col1.getWorldTransform(tmpTrans3), col1.getInterpolationWorldTransform(tmpTrans4), result)) {
				// store result.m_fraction in both bodies

				if (col0.getHitFraction() > result.fraction) {
					col0.setHitFraction(result.fraction);
				}

				if (col1.getHitFraction() > result.fraction) {
					col1.setHitFraction(result.fraction);
				}

				if (resultFraction > result.fraction) {
					resultFraction = result.fraction;
				}
			}
		}

		// Sphere (for convex0) against Convex1
		{
			ConvexShape convex1 = (ConvexShape) col1.getCollisionShape();

			SphereShape sphere0 = new SphereShape(col0.getCcdSweptSphereRadius()); // todo: allow non-zero sphere sizes, for better approximation
			ConvexCast.CastResult result = new ConvexCast.CastResult();
			VoronoiSimplexSolver voronoiSimplex = new VoronoiSimplexSolver();
			//SubsimplexConvexCast ccd0(&sphere,min0,&voronoiSimplex);
			///Simplification, one object is simplified as a sphere
			GjkConvexCast ccd1 = new GjkConvexCast(sphere0, convex1, voronoiSimplex);
			//ContinuousConvexCollision ccd(min0,min1,&voronoiSimplex,0);
			if (ccd1.calcTimeOfImpact(col0.getWorldTransform(tmpTrans1), col0.getInterpolationWorldTransform(tmpTrans2),
					col1.getWorldTransform(tmpTrans3), col1.getInterpolationWorldTransform(tmpTrans4), result)) {
				//store result.m_fraction in both bodies

				if (col0.getHitFraction() > result.fraction) {
					col0.setHitFraction(result.fraction);
				}

				if (col1.getHitFraction() > result.fraction) {
					col1.setHitFraction(result.fraction);
				}

				if (resultFraction > result.fraction) {
					resultFraction = result.fraction;
				}

			}
		}

		return resultFraction;
	}

	@Override
	public void getAllContactManifolds(ObjectArrayList<PersistentManifold> manifoldArray) {
		// should we use ownManifold to avoid adding duplicates?
		if (manifoldPtr != null && ownManifold) {
			manifoldArray.add(manifoldPtr);
		}
	}

	public PersistentManifold getManifold() {
		return manifoldPtr;
	}

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

	public static class CreateFunc extends CollisionAlgorithmCreateFunc {
		private final ObjectPool<ConvexConvexAlgorithm> pool = ObjectPool.get(ConvexConvexAlgorithm.class);

		public ConvexPenetrationDepthSolver pdSolver;
		public SimplexSolverInterface simplexSolver;

		public CreateFunc(SimplexSolverInterface simplexSolver, ConvexPenetrationDepthSolver pdSolver) {
			this.simplexSolver = simplexSolver;
			this.pdSolver = pdSolver;
		}

		@Override
		public CollisionAlgorithm createCollisionAlgorithm(CollisionAlgorithmConstructionInfo ci, CollisionObject body0, CollisionObject body1) {
			ConvexConvexAlgorithm algo = pool.get();
			algo.init(ci.manifold, ci, body0, body1, simplexSolver, pdSolver);
			return algo;
		}

		@Override
		public void releaseCollisionAlgorithm(CollisionAlgorithm algo) {
			pool.release((ConvexConvexAlgorithm)algo);
		}
	}

}


text:
package com.wingtaichi.contextmenuhorizontal.lib;

import android.view.View;

import com.nineoldandroids.animation.AnimatorSet;
import com.nineoldandroids.animation.ObjectAnimator;

public class AnimatorUtils {

    public static ObjectAnimator rotationCloseToRight(View v) {
        return ObjectAnimator.ofFloat(v, "rotationY", 0, -90);
    }

    public static ObjectAnimator rotationOpenFromRight(View v) {
        return ObjectAnimator.ofFloat(v, "rotationY", -90, 0);
    }

    public static ObjectAnimator rotationOpenFromLeft(View v) {
        return ObjectAnimator.ofFloat(v, "rotationY", 90, 0);
    }

    public static ObjectAnimator rotationCloseToLeft(View v) {
        return ObjectAnimator.ofFloat(v, "rotationY", 0, 90);
    }

    public static ObjectAnimator rotationCloseVertical(View v) {
        return ObjectAnimator.ofFloat(v, "rotationX", 0, -90);
    }

    public static ObjectAnimator rotationOpenVertical(View v) {
        return ObjectAnimator.ofFloat(v, "rotationX", -90, 0);
    }

    public static ObjectAnimator rotationOpenVerticalFromBottom(View v) {
        return ObjectAnimator.ofFloat(v, "rotationX", 90, 0);
    }

    public static ObjectAnimator rotationCloseVerticalFromBottom(View v) {
        return ObjectAnimator.ofFloat(v, "rotationX",0, 90);
    }

    public static ObjectAnimator alfaDisappear(View v) {
        return ObjectAnimator.ofFloat(v, "alpha", 1, 0);
    }

    public static ObjectAnimator alfaAppear(View v) {
        return ObjectAnimator.ofFloat(v, "alpha", 0, 1);
    }

    public static ObjectAnimator translationRight(View v, float x) {
        return ObjectAnimator.ofFloat(v, "translationX", 0, x);
    }
    public static ObjectAnimator translationLeft(View v, float x) {
        return ObjectAnimator.ofFloat(v, "translationX", x, 0);
    }

    public static AnimatorSet fadeOutSet(View v, float x){
        AnimatorSet fadeOutSet = new AnimatorSet();
        fadeOutSet.playTogether(alfaDisappear(v), translationRight(v,x));
        return fadeOutSet;
    }

}


text:
const util = require("util")
const Yellow = function (context) {
	this.context = context
}

// Partial evaluate
require("./Yellow.evaluate")(Yellow)

// ----------
// State Logic Implement Below
// ----------

Yellow.prototype.OnUpdate = function(stateData, dt) {
	// Logic Code Here

	return this._evaluate(stateData)
};

Yellow.prototype.OnEnter = function(stateData) {
	// Logic Code Here
	console.log("Yellow - Enter")
};

Yellow.prototype.OnExit = function(stateData) {
	// Logic Code Here
	console.log("Yellow - Exit")
};

Yellow.prototype.OnEvent = function(stateData, args) {
	// Logic Code Here
	console.log("Yellow - On Event ", args)
};

module.exports = Yellow


text:
using System;

namespace SerialLabs
{
    /// <summary>
    /// Provides helping method for manipulating dates. Provides DateTime extension methods too
    /// </summary>
    public static class DateHelper
    {
        /// <summary>
        /// Ensures that local times are converted to UTC times.  Unspecified kinds are recast to UTC with no conversion.
        /// </summary>
        /// <param name="value">The date-time to convert.</param>
        /// <returns>The date-time in UTC time.</returns>
        public static DateTime AsUtc(this DateTime value)
        {
            if (value.Kind == DateTimeKind.Unspecified)
            {
                return new DateTime(value.Ticks, DateTimeKind.Utc);
            }

            return value.ToUniversalTime();
        }
        /// <summary>
        /// Ensures that local times are converted to UTC times.  Unspecified kinds are recast to UTC with no conversion.
        /// </summary>
        /// <param name="value">The nullable date-time to convert.</param>
        /// <returns>The nullable date-time in UTC time.</returns>
        public static DateTime? AsUtc(this DateTime? value)
        {
            if (!value.HasValue) { return null; }
            if (value.Value.Kind == DateTimeKind.Unspecified)
            {
                return new DateTime(value.Value.Ticks, DateTimeKind.Utc);
            }

            return value.Value.ToUniversalTime();
        }
        /// <summary>
        /// Convert a unix timestamp to the corresponding datetime.
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static DateTime FromUnixTime(double value)
        {
            DateTime unixStart = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return unixStart.AddSeconds(value);
        }
        /// <summary>
        /// Convert a datetime to its corresponding unix timestamp value.
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public static long ToUnixTime(DateTime date)
        {
            DateTime unixStart = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            TimeSpan timespan = date - unixStart;
            return (long)Math.Floor(timespan.TotalSeconds);
        }
    }
}


text:
<?php namespace App\Data\Models;

use Doctrine\DBAL\Types\Type;
use Limoncello\Contracts\Application\ModelInterface;
use Limoncello\Contracts\Data\RelationshipTypes;
use Limoncello\Flute\Types\DateTimeType;

/**
 * @package App
 */
class User implements ModelInterface, CommonFields
{
    /** Table name */
    const TABLE_NAME = 'users';

    /** Primary key */
    const FIELD_ID = 'id_user';

    /** Primary key */
    const FIELD_ID_ROLE = Role::FIELD_ID;

    /** Field name */
    const FIELD_EMAIL = 'email';

    /** Field name */
    const FIELD_FIRST_NAME = 'first_name';

    /** Field name */
    const FIELD_LAST_NAME = 'last_name';

    /** Field name */
    const FIELD_PASSWORD_HASH = 'password_hash';

    /** Relationship name */
    const REL_ROLE = 'role';

    /** Relationship name */
    const REL_POSTS = 'posts';

    /** Minimum password length */
    const MIN_PASSWORD_LENGTH = 5;

    /**
     * @inheritdoc
     */
    public static function getTableName(): string
    {
        return static::TABLE_NAME;
    }

    /**
     * @inheritdoc
     */
    public static function getPrimaryKeyName(): string
    {
        return static::FIELD_ID;
    }

    /**
     * @inheritdoc
     */
    public static function getAttributeTypes(): array
    {
        return [
            self::FIELD_ID            => Type::INTEGER,
            self::FIELD_ID_ROLE       => Type::STRING,
            self::FIELD_FIRST_NAME    => Type::STRING,
            self::FIELD_LAST_NAME     => Type::STRING,
            self::FIELD_EMAIL         => Type::STRING,
            self::FIELD_PASSWORD_HASH => Type::STRING,
            self::FIELD_CREATED_AT    => DateTimeType::NAME,
            self::FIELD_UPDATED_AT    => DateTimeType::NAME,
            self::FIELD_DELETED_AT    => DateTimeType::NAME,
        ];
    }

    /**
     * @inheritdoc
     */
    public static function getAttributeLengths(): array
    {
        return [
            self::FIELD_ID_ROLE       => 255,
            self::FIELD_FIRST_NAME    => 100,
            self::FIELD_LAST_NAME     => 100,
            self::FIELD_EMAIL         => 255,
            self::FIELD_PASSWORD_HASH => 100,
        ];
    }

    /**
     * @inheritdoc
     */
    public static function getRelationships(): array
    {
        return [
            RelationshipTypes::BELONGS_TO => [
                self::REL_ROLE => [Role::class, self::FIELD_ID_ROLE, Role::REL_USERS],
            ],
            RelationshipTypes::HAS_MANY   => [
                self::REL_POSTS => [Post::class, Post::FIELD_ID_USER, Post::REL_USER],
            ],
        ];
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.blink</groupId>
    <artifactId>designer</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <artifactId>designer-model</artifactId>
  <dependencies>
  <dependency>
    <groupId>javax.persistence</groupId>
    <artifactId>persistence-api</artifactId>
    <version>1.0.2</version>
</dependency>
  </dependencies>

</project>


text:
new Promise(function(){
    return Promise.resolve(1)
}).then(function(value){
    console.log('Promise.resolve 1 ' + value);
});


text:
#ifndef MIRTK_NormalizedMutualImageInformation_H
#define MIRTK_NormalizedMutualImageInformation_H

#include "mirtk/HistogramImageSimilarity.h"

#include "mirtk/Histogram1D.h"

namespace mirtk {

/**
 * Normalized mutual information image similarity measure
 */
class NormalizedMutualImageInformation : public HistogramImageSimilarity
{
  mirtkEnergyTermMacro(NormalizedMutualImageInformation, EM_NMI);

  // ---------------------------------------------------------------------------
  // Types

  /// Type of marginal histograms
  typedef Histogram1D<BinType> MarginalHistogram;

  // ---------------------------------------------------------------------------
  // Attributes

  /// Marginal histogram w.r.t. target image intensities
  mirtkAttributeMacro(MarginalHistogram, TargetHistogram);

  /// Marginal histogram w.r.t. source image intensities
  mirtkAttributeMacro(MarginalHistogram, SourceHistogram);

  /// Marginal entropy w.r.t. target image intensities
  mirtkAttributeMacro(double, TargetEntropy);

  /// Marginal entropy w.r.t. source image intensities
  mirtkAttributeMacro(double, SourceEntropy);

  /// Joint entropy of target and source image intensities
  mirtkAttributeMacro(double, JointEntropy);

  /// Copy attributes of this class from another instance
  void CopyAttributes(const NormalizedMutualImageInformation &);

  // ---------------------------------------------------------------------------
  // Construction/Destruction
public:

  /// Constructor
  NormalizedMutualImageInformation(const char * = "");

  /// Copy constructor
  NormalizedMutualImageInformation(const NormalizedMutualImageInformation &);

  /// Assignment operator
  NormalizedMutualImageInformation &operator =(const NormalizedMutualImageInformation &);

  /// Destructor
  ~NormalizedMutualImageInformation();

  // ---------------------------------------------------------------------------
  // Evaluation

  /// Update moving image and internal state of similarity measure
  virtual void Update(bool = true);

protected:

  /// Evaluate similarity of images
  virtual double Evaluate();

  /// Evaluate non-parametric similarity gradient w.r.t the given image
  virtual bool NonParametricGradient(const RegisteredImage *, GradientImageType *);

  // ---------------------------------------------------------------------------
  // Debugging
public:

  /// Return unweighted and unnormalized raw energy term value
  /// \remarks Use for progress reporting only.
  virtual double RawValue(double) const;

};

} // namespace mirtk

#endif // MIRTK_NormalizedMutualImageInformation_H


text:
namespace mozart {

namespace builtins {

///////////////////////////
// ForeignPointer module //
///////////////////////////

class ModForeignPointer: public Module {
public:
  ModForeignPointer(): Module("ForeignPointer") {}

  class Is: public Builtin<Is> {
  public:
    Is(): Builtin("is") {}

    void operator()(VM vm, In value, Out result) {
      if (value.isTransient())
        waitFor(vm, value);

      result = build(vm, value.is<ForeignPointer>());
    }
  };

  class ToInt: public Builtin<ToInt> {
  public:
    ToInt(): Builtin("toInt") {}

    void operator()(VM vm, In value, Out result) {
      if (value.is<ForeignPointer>()) {
        auto pointer = value.as<ForeignPointer>().getVoidPointer();
        result = build(vm, reinterpret_cast<nativeint>(pointer.get()));
      } else if (value.isTransient()) {
        waitFor(vm, value);
      } else {
        raiseTypeError(vm, MOZART_STR("ForeignPointer"), value);
      }
    }
  };
};

}

}

#endif // MOZART_GENERATOR

#endif // __MODFOREIGNPOINTER_H


text:
(function () {

    angular.module('angular-semantic-admin')
        .directive('asadminNavbar', Directive);

    function Directive() {
        return {
            restrict: 'E',
            templateUrl: 'angular-semantic-admin/navbar.tpl.html',
            replace: true
        }
    }

})();


text:
<?php
namespace Core\BaseBundle\Service;

use Core\UserBundle\Entity\User;

class Mailer
{
  private $twig;
  private $mailer;
  private $params = [];

  public function __construct(\Twig_Environment $twig, \Swift_Mailer $mailer, $param_base_email, $param_base_contact)
  {
    $this->twig = $twig;
    $this->mailer = $mailer;
    $this->params['base.email'] = $param_base_email;
    $this->params['base.contact'] = $param_base_contact;
  }

  public function sendToUser($template, User $user, $parameters = [])
  {
    $template = $this->twig->loadTemplate($template);
    $parameters['user'] = $user;
    $subject  = $template->renderBlock('subject',   $parameters);
    $bodyHtml = $template->renderBlock('body_html', $parameters);
    $bodyText = $template->renderBlock('body_text', $parameters);

    return $this->send($subject, $bodyText, $bodyHtml,
      [$this->params['base.email'] => $this->params['base.contact']],
      [$user->getEmail() => $user->getUsername()]);
  }

  public function send($subject, $bodyText, $bodyHtml, $from, $to, $reply = '')
  {
    if(!$reply) $reply = $from;

    $mail = \Swift_Message::newInstance()
      ->setSubject($subject)
      ->setBody($bodyText, 'text/plain')
      ->addPart($bodyHtml, 'text/html')
      ->setTo($to)
      ->setFrom($from)
      ->setReplyTo($reply)
    ;

    return $this->mailer->send($mail);
  }
}


text:
using System;
using System.IO;
using System.Text;
using Microsoft.Extensions.Logging;

namespace NetFusion.Redis.Internal
{
    /// <summary>
    /// Implementation that writes Redis connection logs to
    /// the configured logger.
    /// </summary>
    public class RedisLogTextWriter : TextWriter
    {
        private readonly ILogger _logger;
        public override Encoding Encoding { get; } = Encoding.UTF8;

        public RedisLogTextWriter(ILogger logger)
        {
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }

        public override void Write(string value)
        {
            if (! string.IsNullOrWhiteSpace(value))
            {
                _logger.LogTrace(value);
            }
        }
    }
}


text:
namespace DotnetExtensions
{
    public static partial class Extensions
    {
        public static bool IsNull<TSource>(this TSource obj)
            => obj == null;
    }
}


text:
package model.primitive;

import math.Vector2f;
import math.Vector3f;

public class SphereInterpolator implements Interpolator
{
	private Vector3f m_hitNormal;

	public SphereInterpolator(Vector3f hitNormal)
	{
		m_hitNormal = hitNormal;
	}

	@Override
	public Vector3f getFlatNormal()
	{
		return m_hitNormal;
	}

	@Override
	public Vector3f getSmoothNormal()
	{
		return m_hitNormal;
	}

	@Override
	public Vector3f getSmoothColor()
	{
		return new Vector3f();
	}

	@Override
	public Vector2f getSmoothTexCoord()
	{
		return new Vector2f();
	}
}


text:
"""Module that monkey-patches json module when it's imported so
JSONEncoder.default() automatically checks for a special "to_json()"
method and uses it to encode the object if found.
"""
# From: http://stackoverflow.com/questions/18478287/making-object-json-serializable-with-regular-encoder

from json import JSONEncoder

def _default(self, obj):
    return getattr(obj.__class__, "to_json", _default.default)(obj)

_default.default = JSONEncoder().default  # save unmodified default
JSONEncoder.default = _default  # replacement