text:
package net.unicon.sakora.impl.csv;

import java.text.DateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import net.unicon.sakora.api.csv.CsvHandler;
import net.unicon.sakora.api.csv.CsvSyncContext;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.sakaiproject.component.api.ServerConfigurationService;
import org.sakaiproject.coursemanagement.api.CourseManagementAdministration;
import org.sakaiproject.coursemanagement.api.CourseManagementService;

/**
 * Handled any common processing that needs to be chared between the CSV handlers
 * during processing (or idle time)
 *
 * @author Aaron Zeckoski azeckoski@unicon.net
 */
public class CsvCommonHandlerService {
    static final Log log = LogFactory.getLog(CsvCommonHandlerService.class);

    public static final String SYNC_VAR_ID = "id";
    public static final String SYNC_VAR_CONTEXT = "context";
    public static final String SYNC_VAR_STATUS = "status";
    public static final String SYNC_VAR_HANDLER = "handler";
    public static final String SYNC_VAR_HANDLER_STATE = "handler_state";
    public static final String SYNC_VAR_HANDLER_STATS = "handler_stats";
    public static final String SYNC_VAR_STARTDATE = "start_date";
    public static final String SYNC_VAR_SUMMARY = "summary";

    public static final String SYNC_STATE_RUNNING = "running";
    public static final String SYNC_STATE_FAILED = "failed";
    public static final String SYNC_STATE_COMPLETE = "complete";

    public static final String STATE_START = "start";
    public static final String STATE_READ = "read";
    public static final String STATE_PROCESS = "process";
    public static final String STATE_CLEANUP = "cleanup";
    public static final String STATE_FAIL = "fail";
    public static final String STATE_DONE = "done";

    public static final String URM_DELETE = "delete";
    public static final String URM_DISABLE = "disable";
    public static final String URM_IGNORE = "ignore";
    private static final String[] URM_VALIDS = {URM_DISABLE,URM_DELETE,URM_IGNORE};

    private static final String CURRENT_ENROLLMENT_SET_EIDS = "currentEnrollmentSetEids";
    private static final String CURRENT_SECTION_EIDS = "currentSectionEids";
    private static final String CURRENT_COURSE_OFFERING_EIDS = "currentCourseOfferingEids";
    private static final String CURRENT_SESSION_EIDS = "currentSessionEids";

    private static final String IGNORE_MEMBERSHIP_REMOVALS = "ignoreMembershipRemovals";
    private static final String IGNORE_MISSING_SESSIONS = "ignoreMissingSessions";
    private static final String USER_REMOVAL_MODE = "userRemoveMode";

    protected ServerConfigurationService configurationService;
    protected CourseManagementAdministration cmAdmin;
    protected CourseManagementService cmService;

    private volatile int runCounter = 0;
    private ConcurrentHashMap<String, Object> syncVars = new ConcurrentHashMap<String, Object>();

    public void init() {
        // load common config values
        ignoreMissingSessions = configurationService.getBoolean("net.unicon.sakora.csv.ignoreMissingSessions", ignoreMissingSessions);
        if (ignoreMissingSessions()) {
            log.info("SakoraCSV ignoreMissingSessions is enabled: all data related to sessions not included in sessions.csv will be left skipped or otherwise unchanged");
        } else {
            log.info("SakoraCSV set to process missing sessions (ignoreMissingSessions=false): all data related to sessions not included in sessions.csv will be processed and REMOVED");
        }
        ignoreMembershipRemovals = configurationService.getBoolean("net.unicon.sakora.csv.ignoreMembershipRemovals", ignoreMembershipRemovals);
        if (ignoreMembershipRemovals()) {
            log.info("SakoraCSV ignoreMembershipRemovals is enabled: all enrollment removal processing will be skipped");
        }
        setUserRemoveMode(configurationService.getString("net.unicon.sakora.csv.userRemovalMode", userRemoveMode));
        log.info("SakoraCSV userRemoveMode is set to "+userRemoveMode);
    }

    public void destroy() {
        syncVars = null;
    }

    /* We won't allow multiple syncs to run so no need for the thread safety -AZ
    private static final ThreadLocal<HashMap<String, Object>> runVars = new ThreadLocal<HashMap<String,Object>>() {
        @Override
        protected HashMap<String, Object> initialValue() {
            return new HashMap<String, Object>();
        }
    };*/

    public synchronized String initRun(CsvSyncContext context) {
        // run this before a run starts
        syncVars.clear(); //runVars.remove(); // reset the run vars
        // setup the run id
        String runId = ++runCounter + ":" + (new Date().getTime() / 1000);
        syncVars.put(SYNC_VAR_ID, runId);
        syncVars.put(SYNC_VAR_STATUS, SYNC_STATE_RUNNING);
        syncVars.put(SYNC_VAR_CONTEXT, context);
        syncVars.put(SYNC_VAR_STARTDATE, new Date());
        // Do some logging
        log.info("SakoraCSV sync run ("+runId+") starting: "+context);
        // process context overrides
        if (context.getProperties().containsKey(IGNORE_MISSING_SESSIONS)) {
            Boolean ims = Boolean.parseBoolean(context.getProperties().get(IGNORE_MISSING_SESSIONS));
            overrideIgnoreMissingSessions(ims);
            log.info("SakoraCSV sync run ("+runId+") overriding "+IGNORE_MISSING_SESSIONS+": "+ims);
        }
        if (context.getProperties().containsKey(IGNORE_MEMBERSHIP_REMOVALS)) {
            Boolean ier = Boolean.parseBoolean(context.getProperties().get(IGNORE_MEMBERSHIP_REMOVALS));
            overrideIgnoreMembershipRemovals(ier);
            log.info("SakoraCSV sync run ("+runId+") overriding "+IGNORE_MEMBERSHIP_REMOVALS+": "+ier);
        }
        if (context.getProperties().containsKey(USER_REMOVAL_MODE)) {
            String urm = context.getProperties().get(USER_REMOVAL_MODE);
            overrideUserRemoveMode(urm);
            log.info("SakoraCSV sync run ("+runId+") overriding "+USER_REMOVAL_MODE+": "+urm);
        }
        return runId;
    }

    public synchronized void completeRun(boolean success) {
        // run this after a run completes
        String runId = getCurrentSyncRunId();
        Date start = (Date) syncVars.get(SYNC_VAR_STARTDATE);
        log.info("SakoraCSV sync complete ("+(success?"success":"FAILED")+") for run ("+runId+") started on "+DateFormat.getDateTimeInstance().format(start));
        syncVars.put(SYNC_VAR_STATUS, success?SYNC_STATE_COMPLETE:SYNC_STATE_FAILED);
        if (success) {
            StringBuilder sb = new StringBuilder();
            int total_lines = 0;
            int total_errors = 0;
            int total_adds = 0;
            int total_updates = 0;
            int total_deletes = 0;
            int total_seconds = 0;
            // compile and output the stats data to the logs
            @SuppressWarnings("unchecked")
            Map<String, Map<String, Integer>> stats = getCurrentSyncVar(SYNC_VAR_HANDLER_STATS, Map.class);
            for (Map.Entry<String, Map<String, Integer>> entry : stats.entrySet()) {
                String handler = entry.getKey();
                Map<String, Integer> handlerStats = entry.getValue();
                int lines   = handlerStats.get("lines");
                int errors  = handlerStats.get("errors");
                int adds    = handlerStats.get("adds");
                int updates = handlerStats.get("updates");
                int deletes = handlerStats.get("deletes");
                int seconds = handlerStats.get("seconds");
                total_lines += lines;
                total_errors += errors;
                total_adds += adds;
                total_updates += updates;
                total_deletes += deletes;
                total_seconds += seconds;
                sb.append("  - ");
                sb.append(StringUtils.rightPad(handler, 20));
                sb.append(": processed ");
                sb.append(String.format("%6d", lines));
                sb.append(" lines with ");
                sb.append(String.format("%4d", errors));
                sb.append(" errors in ");
                sb.append(String.format("%4d", seconds));
                sb.append(" seconds: ");
                sb.append(String.format("%4d", adds));
                sb.append(" adds, ");
                sb.append(String.format("%4d", updates));
                sb.append(" updates, ");
                sb.append(String.format("%4d", deletes));
                sb.append(" deletes\n");
            }
            // total summary (start, end, totals)
            sb.append("  --- TOTAL:         processed ");
            sb.append(String.format("%6d", total_lines));
            sb.append(" lines with ");
            sb.append(String.format("%5d", total_errors));
            sb.append(" errors in ");
            sb.append(String.format("%5d", total_seconds));
            sb.append(" seconds: ");
            sb.append(String.format("%5d", total_adds));
            sb.append(" adds, ");
            sb.append(String.format("%5d", total_updates));
            sb.append(" updates, ");
            sb.append(String.format("%5d", total_deletes));
            sb.append(" deletes\n");
            syncVars.put(SYNC_VAR_SUMMARY, sb.toString());
            log.info("SakoraCSV sync statistics for run ("+runId+"):\n"+sb.toString());
        }
    }

    /**
     * Retrieve a variable stored for the current sync processing if it is set
     *
     * @param name string key
     * @param type the type of the variable (for compiler happiness only, will not be converted)
     * @return the value OR null if it is not set
     */
    @SuppressWarnings("unchecked")
    public <T> T getCurrentSyncVar(String name, Class<T> type) {
        if (syncVars.containsKey(name)) {
            return (T) syncVars.get(name);
        }
        return null;
    }

    /**
     * Add a variable and value to the thread for this sync run,
     * using null value will remove the variable,
     * adding existing will replace
     *
     * @param name any string name
     * @param value any object, if null then the var is removed
     */
    public void setCurrentSyncVar(String name, Object value) {
        if (value == null) {
            syncVars.remove(name);
        } else {
            syncVars.put(name, value);
       }
    }

    /**
     * @return the current sync run for this thread OR null if there is not one (no sync is running)
     */
    public String getCurrentSyncRunId() {
        return getCurrentSyncVar(SYNC_VAR_ID, String.class);
    }

    /**
     * @return the current sync context for this thread OR null if there is not one (no sync is running)
     */
    public CsvSyncContext getCurrentSyncRunContext() {
        return getCurrentSyncVar(SYNC_VAR_CONTEXT, CsvSyncContext.class);
    }

    public String getCurrentSyncState() {
        String status = getCurrentSyncVar(SYNC_VAR_STATUS, String.class);
        if (status.equals(SYNC_STATE_RUNNING)) {
            String state = getCurrentSyncVar(SYNC_VAR_HANDLER_STATE, String.class);
            CsvHandler handler = getCurrentSyncVar(SYNC_VAR_HANDLER, CsvHandler.class);
            if (handler != null) {
                String handlerName = handler.getName();
                status = "Sync ("+getCurrentSyncRunId()+"): "+handlerName+" state is: "+state;
            }
        }
        return status;
    }

    public void setCurrentHandlerState(String state, CsvHandler handler) {
        /* Allows us to take actions when the state changes (like logging for example)
         */
        setCurrentSyncVar(SYNC_VAR_HANDLER_STATE, state);
        setCurrentSyncVar(SYNC_VAR_HANDLER, handler);
        String handlerName = handler.getName();
        log.info("SakoraCSV: Sync ("+getCurrentSyncRunId()+"): "+handlerName+" state is: "+state);
        if (STATE_DONE.equals(state)) {
            // store the stats in the overall set
            @SuppressWarnings("unchecked")
            Map<String, Map<String, Integer>> stats = getCurrentSyncVar(SYNC_VAR_HANDLER_STATS, Map.class);
            if (stats == null) {
                stats = new LinkedHashMap<String, Map<String,Integer>>(); // want to maintain the ordering
            }
            stats.put(handlerName, handler.getStats());
            setCurrentSyncVar(SYNC_VAR_HANDLER_STATS, stats);
        }
    }

    /**
     * REMOVAL MODE handling
     * If false (DEFAULT), remove all memberships which are missing from current feed.
     * If true, no memberships removals are processed for feed (all removal processing is skipped)
     *
     * controlled by net.unicon.sakora.csv.ignoreMembershipRemovals, Default: false
     */
    protected boolean ignoreMembershipRemovals = false;
    public void setIgnoreMembershipRemovals(boolean ignoreMembershipRemovals) {
        this.ignoreMembershipRemovals = ignoreMembershipRemovals;
    }
    public boolean isIgnoreMembershipRemovals() {
        return ignoreMembershipRemovals;
    }
    /**
     * Allows the current setting to be overridden for the current sync run only
     * @param ier null clears the override, see {@link #ignoreMembershipRemovals}
     */
    public void overrideIgnoreMembershipRemovals(Boolean ier) {
        setCurrentSyncVar(IGNORE_MEMBERSHIP_REMOVALS, ier);
        if (ier != null) {
            log.info("Overriding the ignoreMembershipRemovals value of "+ignoreMembershipRemovals+" with "+ier.booleanValue()+" for current sync: "+getCurrentSyncRunId());
        }
    }
    public boolean ignoreMembershipRemovals() {
        Boolean ier = getCurrentSyncVar(IGNORE_MEMBERSHIP_REMOVALS, Boolean.class);
        if (ier != null) {
            // override from the current run
            return ier.booleanValue();
        }
        return ignoreMembershipRemovals;
    }

    /**
     * USER REMOVAL handling
     * disable: (DEFAULT): assign the user a type which matches the "suspended" key in the PersonHandler (defaults to "suspended")
     * delete: removes the user from the system
     * ignore: skips over the user removal processing entirely
     */
    protected String userRemoveMode = "disable";
    public void setUserRemoveMode(String userRemoveMode) {
        if (ArrayUtils.contains(URM_VALIDS, userRemoveMode)) {
            this.userRemoveMode = userRemoveMode;
        } else {
            this.userRemoveMode = URM_DISABLE;
            log.warn("SakoraCSV userRemoveMode ("+userRemoveMode+") is invalid: resetting to default (disable), must match one of these: "+ArrayUtils.toString(URM_VALIDS));
        }
    }
    public String getUserRemoveMode() {
        return userRemoveMode;
    }
    /**
     * Allows the current setting to be overridden for the current sync run only
     * @param urm null clears the override, see {@link #userRemoveMode}
     */
    public void overrideUserRemoveMode(String urm) {
        if (ArrayUtils.contains(URM_VALIDS, userRemoveMode) || urm == null) {
            setCurrentSyncVar(USER_REMOVAL_MODE, urm);
            if (urm != null) {
                log.info("Overriding the "+USER_REMOVAL_MODE+" value of "+userRemoveMode+" with "+urm+" for current sync: "+getCurrentSyncRunId());
            }
        } else {
            log.warn("SakoraCSV userRemoveMode override ("+urm+") is invalid: ignoring the override, must match one of these: "+ArrayUtils.toString(URM_VALIDS));
        }
    }
    public String userRemoveMode() {
        String urm = getCurrentSyncVar(USER_REMOVAL_MODE, String.class);
        if (urm != null) {
            // override from the current run
            return urm;
        }
        return userRemoveMode;
    }

    /**
     * Academic Session Skip handling:
     * If the flag is set then all data processing for anything not in the current (i.e. included in the feed) academic sessions
     * will be skipped. This includes the sessions themselves (they will not be disabled or removed or flagged),
     * the course offerings, the enrollment sets, and the enrollments.
     *
     * controlled by net.unicon.sakora.csv.ignoreMissingSessions config, Default: false
     */
    protected boolean ignoreMissingSessions = false;
    public void setIgnoreMissingSessions(boolean ignoreMissingSessions) {
        this.ignoreMissingSessions = ignoreMissingSessions;
    }
    public boolean isIgnoreMissingSessions() {
        return ignoreMissingSessions;
    }
    /**
     * Allows the current setting to be overridden for the current sync run only
     * @param ims null clears the override, see {@link #ignoreMissingSessions}
     */
    public void overrideIgnoreMissingSessions(Boolean ims) {
        setCurrentSyncVar(IGNORE_MISSING_SESSIONS, ims);
        if (ims != null) {
            log.info("Overriding the ignoreMissingSessions value of "+ignoreMissingSessions+" with "+ims.booleanValue()+" for current sync: "+getCurrentSyncRunId());
        }
    }
    public boolean ignoreMissingSessions() {
        Boolean ims = getCurrentSyncVar(IGNORE_MISSING_SESSIONS, Boolean.class);
        if (ims != null) {
            // override from the current run
            return ims.booleanValue();
        }
        return ignoreMissingSessions;
    }

    // ACADEMIC SESSIONS
    protected int setCurrentAcademicSessions(String[] sessions) {
        HashSet<String> currentAcademicSessionEids;
        if (sessions != null) {
            currentAcademicSessionEids = new HashSet<String>(sessions.length);
            for (int i = 0; i < sessions.length; i++) {
                currentAcademicSessionEids.add(sessions[i]);
            }
        } else {
            currentAcademicSessionEids = new HashSet<String>(0);
        }
        if (currentAcademicSessionEids.isEmpty()) {
            log.warn("SakoraCSV has no current academic sessions, this is typically not a valid state, please check your sessions.csv file");
        }
        setCurrentSyncVar(CURRENT_SESSION_EIDS, currentAcademicSessionEids);
        return currentAcademicSessionEids.size();
    }

    protected boolean processAcademicSession(String academicSessionEid) {
        boolean process;
        if (ignoreMissingSessions()) {
            // check the list of sessions which are current and if this is not in that set then false
            @SuppressWarnings("unchecked")
            Set<String> currentAcademicSessionEids = (Set<String>) getCurrentSyncVar(CURRENT_SESSION_EIDS, Set.class);
            if (currentAcademicSessionEids != null && currentAcademicSessionEids.contains(academicSessionEid)) {
                process = true;
            } else {
                process = false;
            }
        } else {
            // standard processing, process all sessions
            process = true;
        }
        return process;
    }

    protected Set<String> getCurrentAcademicSessionEids() {
        @SuppressWarnings("unchecked")
        Set<String> currentSessionEids = (Set<String>) getCurrentSyncVar(CURRENT_SESSION_EIDS, Set.class);
        if (currentSessionEids == null) {
            currentSessionEids = new HashSet<String>(0);
        }
        return currentSessionEids;
    }

    // COURSE OFFERINGS
    protected int addCurrentCourseOffering(String courseOfferingEid) {
        @SuppressWarnings("unchecked")
        Set<String> currentCourseOfferingEids = (Set<String>) getCurrentSyncVar(CURRENT_COURSE_OFFERING_EIDS, Set.class);
        if (currentCourseOfferingEids == null) {
            currentCourseOfferingEids = new HashSet<String>();
            setCurrentSyncVar(CURRENT_COURSE_OFFERING_EIDS, currentCourseOfferingEids);
        }
        if (courseOfferingEid != null) {
            currentCourseOfferingEids.add(courseOfferingEid);
        }
        return currentCourseOfferingEids.size();
    }

    protected boolean processCourseOffering(String courseOfferingEid) {
        boolean process;
        if (ignoreMissingSessions()) {
            // check the list of offerings which are current and if course offering is not in that then skip it
            @SuppressWarnings("unchecked")
            Set<String> currentCourseOfferingEids = (Set<String>) getCurrentSyncVar(CURRENT_COURSE_OFFERING_EIDS, Set.class);
            if (currentCourseOfferingEids != null && currentCourseOfferingEids.contains(courseOfferingEid)) {
                process = true;
            } else {
                process = false;
            }
        } else {
            // standard processing, process all course offerings
            process = true;
        }
        return process;
    }

    protected Set<String> getCurrentCourseOfferingEids() {
        @SuppressWarnings("unchecked")
        Set<String> currentCourseOfferingEids = (Set<String>) getCurrentSyncVar(CURRENT_COURSE_OFFERING_EIDS, Set.class);
        if (currentCourseOfferingEids == null) {
            currentCourseOfferingEids = new HashSet<String>(0);
        }
        return currentCourseOfferingEids;
    }

    // SECTIONS
    protected int addCurrentSection(String sectionEid) {
        @SuppressWarnings("unchecked")
        Set<String> currentSectionEids = (Set<String>) getCurrentSyncVar(CURRENT_SECTION_EIDS, Set.class);
        if (currentSectionEids == null) {
            currentSectionEids = new HashSet<String>();
            setCurrentSyncVar(CURRENT_SECTION_EIDS, currentSectionEids);
        }
        if (sectionEid != null) {
            currentSectionEids.add(sectionEid);
        }
        return currentSectionEids.size();
    }

    protected boolean processSection(String sectionEid) {
        boolean process;
        if (ignoreMissingSessions()) {
            // check the list of sections which are current and if section is not in that then skip it
            @SuppressWarnings("unchecked")
            Set<String> currentSectionEids = (Set<String>) getCurrentSyncVar(CURRENT_SECTION_EIDS, Set.class);
            if (currentSectionEids != null && currentSectionEids.contains(sectionEid)) {
                process = true;
            } else {
                process = false;
            }
        } else {
            // standard processing, process all course offerings
            process = true;
        }
        return process;
    }

    protected Set<String> getCurrentSectionEids() {
        @SuppressWarnings("unchecked")
        Set<String> currentSectionEids = (Set<String>) getCurrentSyncVar(CURRENT_SECTION_EIDS, Set.class);
        if (currentSectionEids == null) {
            currentSectionEids = new HashSet<String>(0);
        }
        return currentSectionEids;
    }

    // ENROLLMENT SETS
    protected int addCurrentEnrollmentSet(String enrollmentSetEid) {
        @SuppressWarnings("unchecked")
        Set<String> currentEnrollmentSetEids = (Set<String>) getCurrentSyncVar(CURRENT_ENROLLMENT_SET_EIDS, Set.class);
        if (currentEnrollmentSetEids == null) {
            currentEnrollmentSetEids = new HashSet<String>();
            setCurrentSyncVar(CURRENT_ENROLLMENT_SET_EIDS, currentEnrollmentSetEids);
        }
        if (enrollmentSetEid != null) {
            currentEnrollmentSetEids.add(enrollmentSetEid);
        }
        return currentEnrollmentSetEids.size();
    }

    protected boolean processEnrollmentSet(String enrollmentSetEid) {
        boolean process;
        if (ignoreMissingSessions()) {
            // check the list of offerings which are current and if course offering is not in that then skip it
            @SuppressWarnings("unchecked")
            Set<String> currentEnrollmentSetEids = (Set<String>) getCurrentSyncVar(CURRENT_ENROLLMENT_SET_EIDS, Set.class);
            if (currentEnrollmentSetEids != null && currentEnrollmentSetEids.contains(enrollmentSetEid)) {
                process = true;
            } else {
                process = false;
            }
        } else {
            // standard processing, process all course offerings
            process = true;
        }
        return process;
    }

    protected Set<String> getCurrentEnrollmentSets() {
        @SuppressWarnings("unchecked")
        Set<String> currentEnrollmentSetEids = (Set<String>) getCurrentSyncVar(CURRENT_ENROLLMENT_SET_EIDS, Set.class);
        if (currentEnrollmentSetEids == null) {
            currentEnrollmentSetEids = new HashSet<String>(0);
        }
        return currentEnrollmentSetEids;
    }

    public void setConfigurationService(ServerConfigurationService configurationService) {
        this.configurationService = configurationService;
    }

    public void setCmAdmin(CourseManagementAdministration cmAdmin) {
        this.cmAdmin = cmAdmin;
    }

    public void setCmService(CourseManagementService cmService) {
        this.cmService = cmService;
    }

}


text:
@class NSData, NSString;

@interface WFAntFSClientChannel : WFAntFSChannel
{
    id <WFAntFSClientChannelDelegate> antFSDelegate;
    struct ANTFSClientChannel *pclANTFSClient;
    NSData *downloadData;
    NSString *fitDirectory;
}

@property(nonatomic) id <WFAntFSClientChannelDelegate> antFSDelegate; // @synthesize antFSDelegate;
- (void)stopSerialThread;
- (void)serialThreadMain:(id)arg1;
- (CDStruct_6fa72116 *)fitFileIdForFile:(id)arg1;
- (BOOL)fitEntry:(CDStruct_ffca6faa *)arg1 forFile:(id)arg2;
- (id)fitFileDataForIndex:(unsigned short)arg1;
- (BOOL)configureFitDirectory;
- (void)startDownload;
- (void)antFSThreadMain:(id)arg1;
- (BOOL)startAntFS;
- (void)setTxPower:(unsigned char)arg1 beaconPower:(unsigned char)arg2;
- (void)setBeaconTimeout:(unsigned char)arg1;
- (BOOL)openBeacon:(unsigned short)arg1 withParams:(CDStruct_b30d3dab *)arg2;
- (BOOL)closeBeacon;
- (void)delegateResponse:(id)arg1;
- (void)close;
- (BOOL)addFITFile:(id)arg1;
- (int)antFSResponseFromClientResponse:(int)arg1;
- (id)initWithDelegate:(id)arg1 channelNumber:(unsigned char)arg2;
- (void)dealloc;

@end

redpajama_set_name: RedPajamaGithub


text:
import {hasSnippets} from './utils';
import * as eslint from 'eslint';
import {Statement} from 'estree';

const block = `process.on('unhandledRejection', err => {
  console.error(err.message);
  process.exitCode = 1;
});
`;

export const noErrorHandlingMessageId = 'no-error-handling';
export const noErrorHandlingMessage = `Sample must capture unhandled errors. Please add the following block *before* your call to 'main':\n\n ${block}\n`;

export const handlesErrors: eslint.Rule.RuleModule = {
  meta: {
    type: 'problem',
    docs: {
      description: 'ensure there is a global error handler',
    },
    fixable: 'code',
    messages: {
      [noErrorHandlingMessageId]: noErrorHandlingMessage,
    },
  },
  create: function (context) {
    return {
      Program(node) {
        if (!hasSnippets(node)) {
          return;
        }
        const source = context.getSourceCode().text.trim();
        const hasBlock = source.includes(block);

        // only attempt to fix this if the final node in the file is
        // a call to `main()`.
        let canFix = false;
        let mainNode: Statement;
        if (node.body.length) {
          mainNode = node.body[node.body.length - 1] as Statement;
          if (
            mainNode &&
            mainNode.type === 'ExpressionStatement' &&
            mainNode.expression.type === 'CallExpression' &&
            mainNode.expression.callee.type === 'Identifier' &&
            mainNode.expression.callee.name === 'main'
          ) {
            canFix = true;
          }
        }

        if (!hasBlock) {
          if (canFix) {
            context.report({
              node,
              messageId: noErrorHandlingMessageId,
              fix: fixer => fixer.insertTextBefore(mainNode, block),
            });
          } else {
            context.report({
              node,
              messageId: noErrorHandlingMessageId,
            });
          }
        }
      },
    };
  },
};


text:
export BOOST_ROOT=/src/monero/boost_1_70_0
export OPENSSL_ROOT_DIR=/src/monero/openssl-1.1.1g

cd monero
sed -i -e 's/include(FindCcache)/# include(FindCcache)/' CMakeLists.txt
git submodule init
git submodule update
mkdir -p build
cd build
export CXXFLAGS="$CXXFLAGS -fPIC"
cmake -D OSSFUZZ=ON -D STATIC=ON -D BUILD_TESTS=ON -D USE_LTO=OFF -D ARCH="default" ..

TESTS="\
  base58_fuzz_tests \
  block_fuzz_tests \
  transaction_fuzz_tests \
  load-from-binary_fuzz_tests \
  load-from-json_fuzz_tests \
  parse-url_fuzz_tests \
  http-client_fuzz_tests \
  levin_fuzz_tests \
  bulletproof_fuzz_tests \
  tx-extra_fuzz_tests \
"

# only libfuzzer can run the slow to start ones
if test "x$FUZZING_ENGINE" == 'xlibfuzzer'
then
  TESTS="$TESTS \
    signature_fuzz_tests \
    cold-outputs_fuzz_tests \
    cold-transaction_fuzz_tests \
  "
fi

make -C tests/fuzz $TESTS

cd /src/monero/monero/build/tests/fuzz
for fuzzer in *_fuzz_tests
do
  cp "$fuzzer" "$OUT"
  base=$(echo $fuzzer | sed -e s/_fuzz_tests//)
  cd "/src/monero/monero/tests/data/fuzz/$base"
  rm -f "${OUT}/${fuzzer}_seed_corpus.zip"
  for f in *
  do
    h=$(sha1sum "$f" | awk '{print $1}')
    cp "$f" "$h"
    zip "${OUT}/${fuzzer}_seed_corpus.zip" "$h"
    rm -f "$h"
  done
  cd -
done


text:
package org.hisp.dhis.appcache;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletContext;

import org.apache.struts2.ServletActionContext;
import org.hisp.dhis.i18n.locale.LocaleManager;
import org.hisp.dhis.system.SystemInfo;
import org.hisp.dhis.system.SystemService;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.Action;

/**
 * @author Abyot Asalefew Gizaw <abyota@gmail.com>
 *
 */
public class CacheManifestAction
    implements Action
{
    @Autowired
    private SystemService systemService;

    @Autowired
    private LocaleManager localeManager;

    private String appPath;

    public void setAppPath( String appPath )
    {
        this.appPath = appPath;
    }

    private String i18nPath;

    public void setI18nPath( String i18nPath )
    {
        this.i18nPath = i18nPath;
    }

    private String appCache;

    public void setAppCache( String appCache )
    {
        this.appCache = appCache;
    }

    private InputStream inputStream;

    public InputStream getInputStream()
    {
        return inputStream;
    }

    // -------------------------------------------------------------------------
    // Action implementation
    // -------------------------------------------------------------------------

    @Override
    public String execute()
    {
        File cacheManifest = null;
        File i18nFolder = null;
        StringBuilder builder = null;

        String locale = localeManager.getCurrentLocale().toString();

        SystemInfo info = systemService.getSystemInfo();
        String revisionTag = "#Revision:" + info.getRevision();

        String defaultTranslationFile = "i18n_app.properties";
        String translationFile = "";
        if ( locale.equalsIgnoreCase( "en" ) )
        {
            translationFile = defaultTranslationFile;
        }
        else
        {
            translationFile = "i18n_app_" + locale + ".properties";
        }

        if ( appPath != null && appCache != null )
        {

            ServletContext servletContext = ServletActionContext.getServletContext();
            String fullPath = servletContext.getRealPath( appPath );

            File folder = new File( fullPath );
            File[] files = folder.listFiles();

            if ( files != null )
            {
                for ( int i = 0; i < files.length; i++ )
                {
                    if ( files[i].isFile() && files[i].getName().equalsIgnoreCase( appCache ) )
                    {
                        cacheManifest = new File( files[i].getAbsolutePath() );
                    }

                    if ( i18nPath != null && files[i].isDirectory() && files[i].getName().equalsIgnoreCase( i18nPath ) )
                    {
                        i18nFolder = new File( files[i].getAbsolutePath() );
                    }
                }
            }
        }

        if ( cacheManifest != null )
        {
            try ( BufferedReader bufferedReader = new BufferedReader( new FileReader( cacheManifest ) ) )
            {
                builder = new StringBuilder();
                String line;

                while ( (line = bufferedReader.readLine()) != null )
                {
                    builder.append( line );
                    builder.append( "\n" );
                }

                builder.append( revisionTag );
                builder.append( "\n" );

                if ( i18nFolder != null )
                {
                    Boolean fileExists = false;

                    File[] files = i18nFolder.listFiles();

                    if ( files != null )
                    {
                        for ( int i = 0; i < files.length; i++ )
                        {
                            if ( files[i].isFile() && files[i].getName().equalsIgnoreCase( translationFile ) )
                            {
                                fileExists = true;
                                builder.append( i18nPath + "/" + translationFile );
                                builder.append( "\n" );
                                break;
                            }
                        }
                    }

                    if ( !fileExists )
                    {
                        builder.append( i18nPath + "/" + defaultTranslationFile );
                        builder.append( "\n" );
                    }
                }

                inputStream = new ByteArrayInputStream( builder.toString().getBytes() );

                return SUCCESS;

            }
            catch ( IOException e )
            {
                e.printStackTrace();
            }
        }

        builder = new StringBuilder();
        builder.append( "CACHE MANIFEST" );
        builder.append( revisionTag );
        builder.append( "\n" );
        builder.append( "NETWORK:" );
        builder.append( "\n" );
        builder.append( "*" );

        inputStream = new ByteArrayInputStream( builder.toString().getBytes() );

        return SUCCESS;
    }
}


text:
from __future__ import annotations

from textwrap import dedent

import pytest

from pants.backend.python import target_types_rules
from pants.backend.python.lint.black.rules import BlackRequest
from pants.backend.python.lint.black.rules import rules as black_rules
from pants.backend.python.lint.black.subsystem import Black, BlackFieldSet
from pants.backend.python.lint.black.subsystem import rules as black_subsystem_rules
from pants.backend.python.target_types import PythonSourcesGeneratorTarget
from pants.backend.python.util_rules.interpreter_constraints import InterpreterConstraints
from pants.core.goals.fmt import FmtResult, Partitions
from pants.core.util_rules import config_files, source_files
from pants.core.util_rules.source_files import SourceFiles, SourceFilesRequest
from pants.engine.addresses import Address
from pants.engine.fs import CreateDigest, Digest, FileContent
from pants.engine.internals.native_engine import Snapshot
from pants.engine.target import Target
from pants.testutil.python_interpreter_selection import (
    all_major_minor_python_versions,
    skip_unless_python38_present,
    skip_unless_python39_present,
)
from pants.testutil.rule_runner import QueryRule, RuleRunner

@pytest.fixture
def rule_runner() -> RuleRunner:
    return RuleRunner(
        rules=[
            *black_rules(),
            *black_subsystem_rules(),
            *source_files.rules(),
            *config_files.rules(),
            *target_types_rules.rules(),
            QueryRule(Partitions, (BlackRequest.PartitionRequest,)),
            QueryRule(FmtResult, (BlackRequest.Batch,)),
            QueryRule(SourceFiles, (SourceFilesRequest,)),
        ],
        target_types=[PythonSourcesGeneratorTarget],
    )

GOOD_FILE = 'animal = "Koala"\n'
BAD_FILE = 'name=    "Anakin"\n'
FIXED_BAD_FILE = 'name = "Anakin"\n'
NEEDS_CONFIG_FILE = "animal = 'Koala'\n"  # Note the single quotes.

def run_black(
    rule_runner: RuleRunner,
    targets: list[Target],
    *,
    expected_ics: str = Black.default_interpreter_constraints[0],
    extra_args: list[str] | None = None,
) -> FmtResult:
    rule_runner.set_options(
        ["--backend-packages=pants.backend.python.lint.black", *(extra_args or ())],
        # We propagate LANG and LC_ALL to satisfy click, which black depends upon. Without this we
        # see something like the following in CI:
        #
        # RuntimeError: Click will abort further execution because Python was configured to use
        # ASCII as encoding for the environment. Consult
        # https://click.palletsprojects.com/unicode-support/ for mitigation steps.
        #
        # This system supports the C.UTF-8 locale which is recommended. You might be able to
        # resolve your issue by exporting the following environment variables:
        #
        #     export LC_ALL=C.UTF-8
        #     export LANG=C.UTF-8
        #
        env_inherit={"PATH", "PYENV_ROOT", "HOME", "LANG", "LC_ALL"},
    )
    field_sets = [BlackFieldSet.create(tgt) for tgt in targets]
    input_sources = rule_runner.request(
        SourceFiles,
        [
            SourceFilesRequest(field_set.source for field_set in field_sets),
        ],
    )
    partitions = rule_runner.request(
        Partitions,
        [
            BlackRequest.PartitionRequest(tuple(field_sets)),
        ],
    )
    assert len(partitions) == 1
    partition = partitions[0]
    assert partition.metadata == InterpreterConstraints([expected_ics])
    fmt_result = rule_runner.request(
        FmtResult,
        [
            BlackRequest.Batch(
                "",
                partition.elements,
                partition_metadata=partition.metadata,
                snapshot=input_sources.snapshot,
            ),
        ],
    )
    return fmt_result

def get_snapshot(rule_runner: RuleRunner, source_files: dict[str, str]) -> Snapshot:
    files = [FileContent(path, content.encode()) for path, content in source_files.items()]
    digest = rule_runner.request(Digest, [CreateDigest(files)])
    return rule_runner.request(Snapshot, [digest])

@pytest.mark.platform_specific_behavior
@pytest.mark.parametrize(
    "major_minor_interpreter",
    all_major_minor_python_versions(Black.default_interpreter_constraints),
)
def test_passing(rule_runner: RuleRunner, major_minor_interpreter: str) -> None:
    rule_runner.write_files({"f.py": GOOD_FILE, "BUILD": "python_sources(name='t')"})
    tgt = rule_runner.get_target(Address("", target_name="t", relative_file_path="f.py"))
    interpreter_constraint = (
        ">=3.6.2,<3.7" if major_minor_interpreter == "3.6" else f"=={major_minor_interpreter}.*"
    )
    fmt_result = run_black(
        rule_runner,
        [tgt],
        expected_ics=interpreter_constraint,
        extra_args=[f"--black-interpreter-constraints=['{interpreter_constraint}']"],
    )
    assert "1 file left unchanged" in fmt_result.stderr
    assert fmt_result.output == get_snapshot(rule_runner, {"f.py": GOOD_FILE})
    assert fmt_result.did_change is False

def test_failing(rule_runner: RuleRunner) -> None:
    rule_runner.write_files({"f.py": BAD_FILE, "BUILD": "python_sources(name='t')"})
    tgt = rule_runner.get_target(Address("", target_name="t", relative_file_path="f.py"))
    fmt_result = run_black(rule_runner, [tgt])
    assert "1 file reformatted" in fmt_result.stderr
    assert fmt_result.output == get_snapshot(rule_runner, {"f.py": FIXED_BAD_FILE})
    assert fmt_result.did_change is True

def test_multiple_targets(rule_runner: RuleRunner) -> None:
    rule_runner.write_files(
        {"good.py": GOOD_FILE, "bad.py": BAD_FILE, "BUILD": "python_sources(name='t')"}
    )
    tgts = [
        rule_runner.get_target(Address("", target_name="t", relative_file_path="good.py")),
        rule_runner.get_target(Address("", target_name="t", relative_file_path="bad.py")),
    ]
    fmt_result = run_black(rule_runner, tgts)
    assert "1 file reformatted, 1 file left unchanged" in fmt_result.stderr
    assert fmt_result.output == get_snapshot(
        rule_runner, {"good.py": GOOD_FILE, "bad.py": FIXED_BAD_FILE}
    )
    assert fmt_result.did_change is True

@pytest.mark.parametrize(
    "config_path,extra_args",
    (["pyproject.toml", []], ["custom_config.toml", ["--black-config=custom_config.toml"]]),
)
def test_config_file(rule_runner: RuleRunner, config_path: str, extra_args: list[str]) -> None:
    rule_runner.write_files(
        {
            "f.py": NEEDS_CONFIG_FILE,
            "BUILD": "python_sources(name='t')",
            config_path: "[tool.black]\nskip-string-normalization = 'true'\n",
        }
    )
    tgt = rule_runner.get_target(Address("", target_name="t", relative_file_path="f.py"))
    fmt_result = run_black(rule_runner, [tgt], extra_args=extra_args)
    assert "1 file left unchanged" in fmt_result.stderr
    assert fmt_result.output == get_snapshot(rule_runner, {"f.py": NEEDS_CONFIG_FILE})
    assert fmt_result.did_change is False

def test_passthrough_args(rule_runner: RuleRunner) -> None:
    rule_runner.write_files({"f.py": NEEDS_CONFIG_FILE, "BUILD": "python_sources(name='t')"})
    tgt = rule_runner.get_target(Address("", target_name="t", relative_file_path="f.py"))
    fmt_result = run_black(
        rule_runner, [tgt], extra_args=["--black-args='--skip-string-normalization'"]
    )
    assert "1 file left unchanged" in fmt_result.stderr
    assert fmt_result.output == get_snapshot(rule_runner, {"f.py": NEEDS_CONFIG_FILE})
    assert fmt_result.did_change is False

@skip_unless_python38_present
def test_works_with_python38(rule_runner: RuleRunner) -> None:
    """Black's typed-ast dependency does not understand Python 3.8, so we must instead run Black
    with Python 3.8 when relevant."""
    content = dedent(
        """\
        import datetime

        x = True
        if y := x:
            print("x is truthy and now assigned to y")

        class Foo:
            pass
        """
    )
    rule_runner.write_files(
        {"f.py": content, "BUILD": "python_sources(name='t', interpreter_constraints=['>=3.8'])"}
    )
    tgt = rule_runner.get_target(Address("", target_name="t", relative_file_path="f.py"))
    fmt_result = run_black(rule_runner, [tgt], expected_ics=">=3.8")
    assert "1 file left unchanged" in fmt_result.stderr
    assert fmt_result.output == get_snapshot(rule_runner, {"f.py": content})
    assert fmt_result.did_change is False

@skip_unless_python39_present
def test_works_with_python39(rule_runner: RuleRunner) -> None:
    """Black's typed-ast dependency does not understand Python 3.9, so we must instead run Black
    with Python 3.9 when relevant."""
    content = dedent(
        """\
        @lambda _: int
        def replaced(x: bool) -> str:
            return "42" if x is True else "1/137"
        """
    )
    rule_runner.write_files(
        {"f.py": content, "BUILD": "python_sources(name='t', interpreter_constraints=['>=3.9'])"}
    )
    tgt = rule_runner.get_target(Address("", target_name="t", relative_file_path="f.py"))
    fmt_result = run_black(rule_runner, [tgt], expected_ics=">=3.9")
    assert "1 file left unchanged" in fmt_result.stderr
    assert fmt_result.output == get_snapshot(rule_runner, {"f.py": content})
    assert fmt_result.did_change is False

def test_stub_files(rule_runner: RuleRunner) -> None:
    rule_runner.write_files(
        {
            "good.pyi": GOOD_FILE,
            "good.py": GOOD_FILE,
            "bad.pyi": BAD_FILE,
            "bad.py": BAD_FILE,
            "BUILD": "python_sources(name='t')",
        }
    )

    good_tgts = [
        rule_runner.get_target(Address("", target_name="t", relative_file_path="good.pyi")),
        rule_runner.get_target(Address("", target_name="t", relative_file_path="good.py")),
    ]
    fmt_result = run_black(rule_runner, good_tgts)
    assert "2 files left unchanged" in fmt_result.stderr
    assert fmt_result.output == get_snapshot(
        rule_runner, {"good.pyi": GOOD_FILE, "good.py": GOOD_FILE}
    )
    assert not fmt_result.did_change

    bad_tgts = [
        rule_runner.get_target(Address("", target_name="t", relative_file_path="bad.pyi")),
        rule_runner.get_target(Address("", target_name="t", relative_file_path="bad.py")),
    ]
    fmt_result = run_black(rule_runner, bad_tgts)
    assert "2 files reformatted" in fmt_result.stderr
    assert fmt_result.output == get_snapshot(
        rule_runner, {"bad.pyi": FIXED_BAD_FILE, "bad.py": FIXED_BAD_FILE}
    )
    assert fmt_result.did_change


text:
'use strict';

// used by build and run time
angular.module('app.const.providers-config', []).
constant('satellizerProvidersConfig', function(SatellizerConfig, AppSystem, state) {
  return AppSystem.Providers.map(function(sp) {
    var params = {
      name: sp.Name,
      url: sp.Proxied ? AppSystem.ProxyAuthServer + sp.Path : sp.Path,
      clientId: sp.ClientID,
      state: state,
    };
    if (sp.Scope) {
      params.scope = sp.Scope;
    }

    angular.forEach([
      'defaultUrlParams', 'requiredUrlParams', 'optionalUrlParams',
      'scope', 'scopePrefix', 'scopeDelimiter', 'display', 'confirmLogin', 'popupOptions'
    ], function(k) {
      if (sp[k]) {
        params[k] = sp[k];
      }
    });

    if (SatellizerConfig.providers[sp.Name]) {
      if (sp.RedirectURL) {
        params.redirectUri = sp.RedirectURL;
      }
      params.exist = true;
    } else {
      params.redirectUri = sp.RedirectURL ? sp.RedirectURL : window.location.origin;
      params.authorizationEndpoint = sp.AuthURL;
    }

    return params;
  });
});


text:
package ca.uhn.fhir.util;

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

import org.hl7.fhir.instance.model.api.IBase;

import ca.uhn.fhir.model.api.ICompositeElement;
import ca.uhn.fhir.model.api.IElement;

public class ElementUtil {

	@SuppressWarnings("unchecked")
	public static boolean isEmpty(Object... theElements) {
		if (theElements == null) {
			return true;
		}
		for (int i = 0; i < theElements.length; i++) {
			Object next = theElements[i];
			if (next instanceof List) {
				if (!isEmpty((List<? extends IBase>) next)) {
					return false;
				}
			} else if (next instanceof String && (!((String)next).isEmpty())) {
				return false;
			} else if (next != null && !((IBase) next).isEmpty()) {
				return false;
			}
		}
		return true;
	}

	public static boolean isEmpty(IBase... theElements) {
		if (theElements == null) {
			return true;
		}
		for (int i = 0; i < theElements.length; i++) {
			IBase next = theElements[i];
			if (next != null && !next.isEmpty()) {
				return false;
			}
		}
		return true;
	}

	public static boolean isEmpty(IElement... theElements) {
		if (theElements == null) {
			return true;
		}
		for (int i = 0; i < theElements.length; i++) {
			IBase next = theElements[i];
			if (next != null && !next.isEmpty()) {
				return false;
			}
		}
		return true;
	}

	public static boolean isEmpty(List<? extends IBase> theElements) {
		if (theElements == null) {
			return true;
		}
		for (int i = 0; i < theElements.size(); i++) {
			IBase next;
			try {
				next = theElements.get(i);
			} catch (ClassCastException e) {
				List<?> elements = theElements;
				String s = "Found instance of " + elements.get(i).getClass() + " - Did you set a field value to the incorrect type? Expected " + IBase.class.getName();
				throw new ClassCastException(s);
			}
			if (next != null && !next.isEmpty()) {
				return false;
			}
		}
		return true;
	}

	/**
	 * Note that this method does not work on HL7.org structures
	 */
	public static <T extends IElement> List<T> allPopulatedChildElements(Class<T> theType, Object... theElements) {
		ArrayList<T> retVal = new ArrayList<T>();
		for (Object next : theElements) {
			if (next == null) {
				continue;
			}else if (next instanceof IElement) {
				addElement(retVal, (IElement) next, theType);
			} else if (next instanceof List) {
				for (Object nextElement : ((List<?>)next)) {
					if (!(nextElement instanceof IBase)) {
						throw new IllegalArgumentException("Found element of "+nextElement.getClass());
					}
					addElement(retVal, (IElement) nextElement, theType);
				}
			} else {
				throw new IllegalArgumentException("Found element of "+next.getClass());
			}

		}
		return retVal;
	}

	//@SuppressWarnings("unchecked")
	private static <T extends IElement> void addElement(ArrayList<T> retVal, IElement next, Class<T> theType) {
		if (theType != null && theType.isAssignableFrom(next.getClass())) {
			retVal.add(theType.cast(next));
		}
		if (next instanceof ICompositeElement) {
			ICompositeElement iCompositeElement = (ICompositeElement) next;
			//TODO: Use of a deprecated method should be resolved.
			retVal.addAll(iCompositeElement.getAllPopulatedChildElementsOfType(theType));
		}
	}

}


text:
This is a log4net implementation of EPiServer.Find.Tracing.ITraceListener interface.
It can be used to trace EPiServer.Find requests to the search index.

[License](LICENSE)


text:
/* Authors: Osama */
/*
 * Copyright (c) 2021, The Regents of the University of California
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the University nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "LoadBalancer.h"

#include <boost/bind/bind.hpp>
#include <boost/thread/thread.hpp>

#include "utl/Logger.h"

using boost::asio::ip::udp;

namespace dst {

void LoadBalancer::start_accept()
{
  if (jobs_ != 0 && jobs_ % 100 == 0) {
    logger_->info(utl::DST, 7, "Processed {} jobs", jobs_);
    auto copy = workers_;
    while (!copy.empty()) {
      auto worker = copy.top();
      logger_->report("Worker {}/{} handled {} jobs",
                      worker.ip,
                      worker.port,
                      worker.priority);
      copy.pop();
    }
  }
  jobs_++;
  BalancerConnection::pointer connection
      = BalancerConnection::create(*service, this, logger_);
  acceptor_.async_accept(connection->socket(),
                         boost::bind(&LoadBalancer::handle_accept,
                                     this,
                                     connection,
                                     asio::placeholders::error));
}

LoadBalancer::LoadBalancer(Distributed* dist,
                           asio::io_service& io_service,
                           utl::Logger* logger,
                           const char* ip,
                           const char* workers_domain,
                           unsigned short port)
    : dist_(dist),
      acceptor_(io_service, tcp::endpoint(ip::address::from_string(ip), port)),
      logger_(logger),
      jobs_(0)
{
  // pool_ = std::make_unique<asio::thread_pool>();
  service = &io_service;
  start_accept();
  if (std::strcmp(workers_domain, "") != 0)
    workers_lookup_thread = boost::thread(
        boost::bind(&LoadBalancer::lookUpWorkers, this, workers_domain, port));
}

LoadBalancer::~LoadBalancer()
{
  alive = false;
  if (workers_lookup_thread.joinable())
    workers_lookup_thread.join();
}

bool LoadBalancer::addWorker(std::string ip, unsigned short port)
{
  std::lock_guard<std::mutex> lock(workers_mutex_);
  bool validWorkerState = true;
  if (broadcastData.size() > 0) {
    for (auto data : broadcastData) {
      try {
        asio::io_service io_service;
        tcp::socket socket(io_service);
        socket.connect(tcp::endpoint(ip::address::from_string(ip), port));
        asio::write(socket, asio::buffer(data));
        asio::streambuf receive_buffer;
        asio::read(socket, receive_buffer, asio::transfer_all());
      } catch (std::exception const& ex) {
        if (std::string(ex.what()) != "read: End of file") {
          // Since asio::transfer_all() used with a stream buffer it
          // always reach an eof file exception!
          validWorkerState = false;
          break;
        }
      }
    }
  }
  if (validWorkerState)
    workers_.push(worker(ip::address::from_string(ip), port, 0));
  return validWorkerState;
}
void LoadBalancer::updateWorker(ip::address ip, unsigned short port)
{
  std::lock_guard<std::mutex> lock(workers_mutex_);
  std::priority_queue<worker, std::vector<worker>, CompareWorker> newQueue;
  while (!workers_.empty()) {
    auto worker = workers_.top();
    workers_.pop();
    if (worker.ip == ip && worker.port == port)
      worker.priority--;
    newQueue.push(worker);
  }
  workers_.swap(newQueue);
}
void LoadBalancer::getNextWorker(ip::address& ip, unsigned short& port)
{
  std::lock_guard<std::mutex> lock(workers_mutex_);
  if (!workers_.empty()) {
    worker w = workers_.top();
    workers_.pop();
    ip = w.ip;
    port = w.port;
    if (w.priority != std::numeric_limits<unsigned short>::max())
      w.priority++;
    workers_.push(w);
  }
}

void LoadBalancer::punishWorker(ip::address ip, unsigned short port)
{
  std::lock_guard<std::mutex> lock(workers_mutex_);
  std::priority_queue<worker, std::vector<worker>, CompareWorker> newQueue;
  while (!workers_.empty()) {
    auto worker = workers_.top();
    workers_.pop();
    if (worker.ip == ip && worker.port == port)
      worker.priority = worker.priority == 0 ? 2 : worker.priority * 2;
    newQueue.push(worker);
  }
  workers_.swap(newQueue);
}

void LoadBalancer::removeWorker(ip::address ip, unsigned short port, bool lock)
{
  if (lock)
    workers_mutex_.lock();
  std::priority_queue<worker, std::vector<worker>, CompareWorker> newQueue;
  while (!workers_.empty()) {
    auto worker = workers_.top();
    workers_.pop();
    if (worker.ip == ip && worker.port == port)
      continue;
    newQueue.push(worker);
  }
  workers_.swap(newQueue);
  if (lock)
    workers_mutex_.unlock();
}

void LoadBalancer::lookUpWorkers(const char* domain, unsigned short port)
{
  asio::io_service ios;
  std::vector<worker> workers_set;
  udp::resolver::query resolver_query(
      domain, std::to_string(port), udp::resolver::query::numeric_service);
  udp::resolver resolver(ios);
  while (alive) {
    std::vector<worker> new_workers;
    boost::system::error_code ec;
    auto it = resolver.resolve(resolver_query, ec);
    if (ec)
      logger_->warn(utl::DST,
                    203,
                    "Workers domain resolution failed with error code = {}. "
                    "Message = {}.",
                    ec.value(),
                    ec.message());
    int new_workers_count = 0;
    udp::resolver::iterator it_end;
    for (; it != it_end; ++it) {
      auto discovered_worker = worker(it->endpoint().address(), port, 0);
      if (std::find(workers_set.begin(), workers_set.end(), discovered_worker)
          == workers_set.end()) {
        workers_set.push_back(discovered_worker);
        new_workers.push_back(discovered_worker);
        new_workers_count += 1;
      }
    }

    if (new_workers_count == 0) {
      debugPrint(
          logger_,
          utl::DST,
          "load_balancer",
          1,
          "Discovered 0 new workers with the given domain. Total workers = {}.",
          workers_set.size());
    } else {
      debugPrint(logger_,
                 utl::DST,
                 "load_balancer",
                 1,
                 "Discovered {} new workers with the given domain. Total "
                 "workers = {}.",
                 new_workers_count,
                 workers_set.size());
    }

    for (auto worker : new_workers)
      addWorker(worker.ip.to_string(), worker.port);

    boost::this_thread::sleep(
        boost::posix_time::milliseconds(workers_discovery_period * 1000));
  }
}

void LoadBalancer::handle_accept(BalancerConnection::pointer connection,
                                 const boost::system::error_code& err)
{
  if (!err)
    connection->start();
  start_accept();
}
}  // namespace dst


text:
<?php
/**
 * Smarty plugin
 *
 * @package    Smarty
 * @subpackage PluginsFunction
 */

/**
 * Smarty {counter} function plugin
 * Type:     function

 * Name:     counter

 * Purpose:  print out a counter value
 *
 * @author Monte Ohrt <monte at ohrt dot com>
 * @link   http://www.smarty.net/manual/en/language.function.counter.php {counter}
 *         (Smarty online manual)
 *
 * @param array                    $params   parameters
 * @param Smarty_Internal_Template $template template object
 *
 * @return string|null
 */
function smarty_function_validation_errors($params, $template)
{
    return validation_errors();
}


text:
import wx
import armid
from Borg import Borg

class MLTextPage(wx.Panel):
  def __init__(self,parent,winId):
    wx.Panel.__init__(self,parent)
    topSizer = wx.BoxSizer(wx.VERTICAL)

    narrativeBox = wx.StaticBox(self,-1)
    narrativeBoxSizer = wx.StaticBoxSizer(narrativeBox,wx.HORIZONTAL)
    topSizer.Add(narrativeBoxSizer,1,wx.EXPAND)
    self.narrativeCtrl = wx.TextCtrl(self,winId,'None',style=wx.TE_MULTILINE)
    narrativeBoxSizer.Add(self.narrativeCtrl,1,wx.EXPAND)
    self.SetSizer(topSizer)

class SummaryPage(wx.Panel):
  def __init__(self,parent):
    wx.Panel.__init__(self,parent)
    topSizer = wx.BoxSizer(wx.VERTICAL)

    nameBox = wx.StaticBox(self,-1,'Name')
    nameBoxSizer = wx.StaticBoxSizer(nameBox,wx.HORIZONTAL)
    topSizer.Add(nameBoxSizer,0,wx.EXPAND)
    self.nameCtrl = wx.TextCtrl(self,armid.TEMPLATEREQUIREMENT_TEXTNAME_ID,'')
    nameBoxSizer.Add(self.nameCtrl,1,wx.EXPAND)

    assetBox = wx.StaticBox(self,-1,'Asset')
    assetBoxSizer = wx.StaticBoxSizer(assetBox,wx.HORIZONTAL)
    topSizer.Add(assetBoxSizer,0,wx.EXPAND)

    b = Borg()
    assets = b.dbProxy.getDimensionNames('template_asset')
    self.assetCtrl = wx.ComboBox(self,armid.TEMPLATEREQUIREMENT_COMBOASSET_ID,choices=assets,size=wx.DefaultSize,style=wx.CB_READONLY)
    assetBoxSizer.Add(self.assetCtrl,1,wx.EXPAND)

    typeBox = wx.StaticBox(self,-1,'Type')
    typeBoxSizer = wx.StaticBoxSizer(typeBox,wx.HORIZONTAL)
    topSizer.Add(typeBoxSizer,0,wx.EXPAND)
    typeChoices = ['Functional','Data','Look and Feel','Usability','Performance','Operational','Maintainability','Portability','Security','Cultural and Political','Legal','Privacy']
    self.typeCtrl = wx.ComboBox(self,armid.TEMPLATEREQUIREMENT_COMBOTYPE_ID,choices=typeChoices,size=wx.DefaultSize,style=wx.CB_READONLY)
    typeBoxSizer.Add(self.typeCtrl,1,wx.EXPAND)

    descBox = wx.StaticBox(self,-1,'Description')
    descBoxSizer = wx.StaticBoxSizer(descBox,wx.HORIZONTAL)
    topSizer.Add(descBoxSizer,1,wx.EXPAND)
    self.descriptionCtrl = wx.TextCtrl(self,armid.TEMPLATEREQUIREMENT_TEXTDESCRIPTION_ID,'',style=wx.TE_MULTILINE)
    descBoxSizer.Add(self.descriptionCtrl,1,wx.EXPAND)

    self.SetSizer(topSizer)

class TemplateRequirementNotebook(wx.Notebook):
  def __init__(self,parent):
    wx.Notebook.__init__(self,parent,armid.TEMPLATEREQUIREMENT_NOTEBOOKREQUIREMENT_ID)
    p1 = SummaryPage(self)
    p2 = MLTextPage(self,armid.TEMPLATEREQUIREMENT_TEXTRATIONALE_ID)
    p3 = MLTextPage(self,armid.TEMPLATEREQUIREMENT_TEXTFITCRITERION_ID)
    self.AddPage(p1,'Summary')
    self.AddPage(p2,'Rationale')
    self.AddPage(p3,'Fit Criterion')


text:
if [ "$1" = "" ]; then
        echo "    Usage: ./create_jailkit_user username /path/to/chroot/ /home/webuser /bin/bash"
        exit
fi

CHROOT_USERNAME=$1
CHROOT_HOMEDIR=$2
CHROOT_USERHOMEDIR=$3
CHROOT_SHELL=$4
CHROOT_P_USER=$5
CHROOT_P_USER_HOMEDIR=$6

### Reconfigure the chroot home directory for the user ###
usermod --home=$CHROOT_HOMEDIR/.$CHROOT_USERHOMEDIR $CHROOT_USERNAME 2>/dev/null

### Add the chroot user ###
jk_jailuser -n -s $CHROOT_SHELL -j $CHROOT_HOMEDIR $CHROOT_USERNAME

### We have to reconfigure the chroot home directory for the parent user ###
if [ "$CHROOT_P_USER" != "" ]; then
  usermod --home=$CHROOT_HOMEDIR/.$CHROOT_P_USER_HOMEDIR $CHROOT_P_USER 2>/dev/null
fi


text:
package org.apache.camel.component.aws2.ec2;

import java.util.HashMap;
import java.util.Map;

import org.apache.camel.Component;
import org.apache.camel.component.extension.ComponentVerifierExtension;
import org.apache.camel.test.junit5.CamelTestSupport;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class EC2ComponentVerifierExtensionTest extends CamelTestSupport {

    // *************************************************
    // Tests (parameters)
    // *************************************************
    @Override
    public boolean isUseRouteBuilder() {
        return false;
    }

    @Test
    public void testParameters() throws Exception {
        Component component = context().getComponent("aws2-ec2");

        ComponentVerifierExtension verifier = component.getExtension(ComponentVerifierExtension.class).orElseThrow(IllegalStateException::new);

        Map<String, Object> parameters = new HashMap<>();
        parameters.put("secretKey", "l");
        parameters.put("accessKey", "k");
        parameters.put("region", "l");
        parameters.put("label", "test");
        parameters.put("operation", AWS2EC2Operations.describeInstances.toString());

        ComponentVerifierExtension.Result result = verifier.verify(ComponentVerifierExtension.Scope.PARAMETERS, parameters);

        assertEquals(ComponentVerifierExtension.Result.Status.OK, result.getStatus());
    }

    @Test
    public void testConnectivity() throws Exception {
        Component component = context().getComponent("aws2-ec2");
        ComponentVerifierExtension verifier = component.getExtension(ComponentVerifierExtension.class).orElseThrow(IllegalStateException::new);

        Map<String, Object> parameters = new HashMap<>();
        parameters.put("secretKey", "l");
        parameters.put("accessKey", "k");
        parameters.put("region", "US_EAST_1");
        parameters.put("label", "test");
        parameters.put("operation", AWS2EC2Operations.describeInstances.toString());

        ComponentVerifierExtension.Result result = verifier.verify(ComponentVerifierExtension.Scope.CONNECTIVITY, parameters);

        assertEquals(ComponentVerifierExtension.Result.Status.ERROR, result.getStatus());
    }

    @Test
    public void testConnectivityAndRegion() throws Exception {
        Component component = context().getComponent("aws2-ec2");
        ComponentVerifierExtension verifier = component.getExtension(ComponentVerifierExtension.class).orElseThrow(IllegalStateException::new);

        Map<String, Object> parameters = new HashMap<>();
        parameters.put("secretKey", "l");
        parameters.put("accessKey", "k");
        parameters.put("region", "l");
        parameters.put("label", "test");
        parameters.put("operation", AWS2EC2Operations.describeInstances.toString());

        ComponentVerifierExtension.Result result = verifier.verify(ComponentVerifierExtension.Scope.CONNECTIVITY, parameters);

        assertEquals(ComponentVerifierExtension.Result.Status.ERROR, result.getStatus());
    }

}


text:
This is a [Heroku buildpack][0] for bundling a compatible [wkhtmltox][1] binary with your environment.

## Versions

* Buildpack:   `0.1`
* wkhtmltopdf: `0.12.3-dev-79ff51e (with patched qt)`

## Usage

This buildpack only installs wkhtmltopdf and wkhtmltoimage, it isn't very useful by itself. You'll probably want to use it as part of a multi-buildpack. Here is an example using the Ruby buildpack.

```bash
$ heroku buildpacks:set 'https://github.com/heroku/heroku-buildpack-multi.git'
$ echo 'https://github.com/heroku/heroku-buildpack-ruby.git' >> .buildpacks
$ echo 'https://github.com/amberbit/heroku-buildpack-wkhtmltox.git' >> .buildpacks
$ git add .buildpacks
$ git commit -m 'Add multi-buildpack'
```

[0]: http://devcenter.heroku.com/articles/buildpacks
[1]: http://wkhtmltopdf.org/

## Troubleshooting

If you run into issues when trying to deploy with this buildpack, make sure your app is running on Cedar with Ubuntu 14.04 (`cedar-14`). You can check this with:

```bash
$ heroku stack
```

If you are on an older stack, you can upgrade to `cedar-14` with:

```bash
$ heroku stack:set cedar-14
```

## Credits

This buildpack is based upon awesome
(wkhtmltopdf-buildpack)[https://github.com/dscout/wkhtmltopdf-buildpack]


text:
using System;
using CodeEditor.Collections;

namespace CodeEditor.Text.Data.Implementation
{
	class TextSnapshot : ITextSnapshot
	{
		private readonly ITextBuffer _owner;
		private readonly PieceTable<char> _text;
		private readonly TextSnapshotLines _lines;

		public TextSnapshot(ITextBuffer owner, PieceTable<char> text) : this(owner, text, new TextSnapshotLines(text))
		{
		}

		public TextSnapshot(ITextBuffer owner, PieceTable<char> text, TextSnapshotLines lines)
		{
			_owner = owner;
			_text = text;
			_lines = lines;
			_lines.Owner = this;
		}

		public char this[int index]
		{
			get
			{
				if (index < 0 || index >= Length)
					new ArgumentOutOfRangeException("Index out of range: " + index);
				return _text[index].GetValue();
			}
		}

		public ITextBuffer Buffer
		{
			get { return _owner; }
		}

		public string Text
		{
			get { return GetText(0, Length); }
		}

		public int Length
		{
			get { return _text.Length; }
		}

		public ITextSnapshotLines Lines
		{
			get { return _lines; }
		}

		public string GetText(Span span)
		{
			return GetText(span.Start, span.Length);
		}

		public TextSpan GetSpan(int position, int length)
		{
			return new TextSpan(this, new Span(position, length));
		}

		public int LineNumberForPosition(int position)
		{
			return _lines.LineNumberForPosition(position);
		}

		public string GetText(int index, int amount)
		{
			if (index < 0 || index + amount > Length)
				new ArgumentOutOfRangeException("Index out of range: " + index);

			if (amount == 0)
				return string.Empty;

			return new string(_text.ToArray(index, amount));
		}

		public TextSnapshot Delete(int index, int amount)
		{
			var newText = _text.Delete(index, amount);
			return new TextSnapshot(_owner, newText, new TextSnapshotLines(newText));
			//return new TextSnapshot(_owner, newText, _lines.Delete(index, amount));
		}

		public TextSnapshot Insert(int index, string text)
		{
			// TODO: consider inserting large strings as a single piece
			var newText = _text;
			for (var i = 0; i < text.Length; ++i)
				newText = newText.Insert(index++, text[i]);

			return new TextSnapshot(_owner, newText, new TextSnapshotLines(newText));
			//return new TextSnapshot(_owner, newText, _lines.Insert(index, text));
		}
	}
}


text:
A **while-loop** evaluates a 'test', if it
is truthy a block of code is executed then
the test is evaluated again, if it is truthy
the block of code is executed again then the
test is evaluated again ... the while-loop
exits when the test is falsy:

___e
i = 1

while i < 5
  i;
  i += 1___e|

An **up-loop** counts upwards from one number
to another.

___e
up i 1 4
  'i is: ' + i;___e|

Include a step size if required:

___e
up i 1 9 2
  i;___e|

An up-loop uses `<=` in each test:

___e
// exits when i <= 8 is falsy
up i 1 8 2
  i;___e|

Decimals can be used:

___e
up i 0.3 0.6 0.1
  i;___e|

The loop variable is a normal scalar variable:

___e
up myVar 1 3
  myVar;___e|

The loop variable can still be used after
a loop exits. In the previous example, `myVar`
has the value ___n4___n| after the loop
exits - the value when the test failed.

Use a **down-loop** to count downwards:

___e
down i 4 1
  i;___e|

Use a negative step-size with down-loops:

___e
down i 10 1 3-
  i;___e|

A down-loop uses `>=` in each test:

___e
// exits when i >= 3 is falsy
down i 10 3 2-
  i;___e|

Expressions on the same line as `up` or
`down` that include an operator
must be wrapped in parentheses; this
rule does not apply to the final expression on
the line:

___e
up i (3-) (2*4) 1+2
  i;___e|

The block of code inside a loop can be anything:

___e
s = 0
p = 1
up i 1 5
  s += i
  p *= i
s;___r
p;___r

up i 1 1000
  if .rand > 0.9
    break    // use break to exit a loop
i;           // number of steps to get a random number > 0.9___e|

As shown in the final example, `break` exits
the (innermost) loop. Use `continue` to jump to
the next step of the innermost loop.

`while`, `up`, `down`, `break` and `continue` start new
commands so cannot be included in an expression.


text:
<?php

use Doctrine\Common\Annotations\AnnotationRegistry;
use Composer\Autoload\ClassLoader;

/**
 * @var $loader ClassLoader
 */
$loader = require __DIR__.'/../vendor/autoload.php';

AnnotationRegistry::registerLoader(array($loader, 'loadClass'));

//$loader->registerPrefixes(array('Sailthru_Client' => __DIR__.'/../vendor/sailthru/sailthru-php5-client/sailthru'));

//echo __DIR__.'/../vendor/AuthorizeDotNet/';
 //$loader->registerPrefixes(array('AuthorizeNet' => __DIR__.'/../vendor/AuthorizeDotNetBundle/AuthorizeDotNetBundle/lib'));

return $loader;


text:
layout: post
title: "London calling. Or is it Europe?"
modified:
categories: blog
excerpt:
tags: ["uk", "europe", "yolo", "brexit", "london", "future", "past"]
date: 2018-09-06T13:45:00-00:00
share: true
---

In the winter of 1990-1991, while studying computer science and [natural
language processing][nlp] at the [University of Essex][essexuni], I spent my first
weekend ever in London. [Margaret Thatcher][margaretthatcher]'s 15-year service as Prime Minister
in Her Majesty's Government had just come to a dramatic end.

The Iron Lady left Downing Street just a year after [the Iron Curtain
fell][schabowski]. Back in the idyllic [Ardleigh Park Lodge][ardleigh] in Essex, I saw my
German housemate [Matthias][matthias_jaeschke] cast his vote in the first
all-German multi-party elections since [1933][1933]. The other student in the
house was [Anne-Marie][anne-marie_mineur], nowadays Member of the
European Parliament for the [Dutch Socialistische Partij][sp_nl].

We were young, we were Europeans in England, and the times were historic.

And then, a quarter century later, there was Brexit.

True, I may be skipping a few life events here, like: getting
married and daughters; buying a house; starting and ending a dozen of
jobs. The fact is: like Marcel Proust's mind wandered off to his
madeleines, Brexit threw me back to that snowy winter.

And now, half a year before the United Kingdom is set to leave the
European Union, I'm going back. Back to England. Back to London!

What's more: not just on a visit.

<iframe width="560" height="315"
src="https://www.youtube.com/embed/-Gp6lYQrqSE" frameborder="0"
allow="autoplay; encrypted-media" allowfullscreen></iframe>

Next Monday, I start as Sr. Data Scientist
at [Aire Labs][aire_labs] in [Shoreditch][east_london_tech_city], just north of [the City of
London][city_of_london]. Aire is, in its own words, "a new
credit assessment service" that helps "lenders make more informed
decisions, and borrowers get fairer access to credit".

I will be commuting from Brussels to London on a weekly basis
(Monday-Friday). Weekends will be spent at home, with wife and daughters, as
usual.

I sometimes dream of meeting the Brexit negotiators —my fellow
travellers— on the Eurostar. In the lounge or the restaurant
coach, I would tell them this story. And invite them for a beer. Or,
in my case, a [pint][pint] of semi-skimmed milk.

For old times' sake.

[essexuni]: https://www.essex.ac.uk
[margaretthatcher]: https://en.wikipedia.org/wiki/Margaret_Thatcher
[ardleigh]: https://goo.gl/maps/4h9sCVxy73m
[matthias_jaeschke]: https://www.linkedin.com/in/matthias-jäschke-7394352a/
[anne-marie_mineur]: https://www.linkedin.com/in/annemariemineur/
[nlp]: https://en.wikipedia.org/wiki/Natural_language_processing
[schabowski]: https://www.youtube.com/watch?v=b8GzptqhT68
[aire_labs]: https://aire.io
[zeugma]: https://www.vocabulary.com/dictionary/zeugma
[east_london_tech_city]: https://en.wikipedia.org/wiki/East_London_Tech_City
[city_of_london]: https://en.wikipedia.org/wiki/City_of_London
[sp_nl]: https://www.sp.nl
[1933]: https://en.wikipedia.org/wiki/1933_in_Germany
[pint]: https://en.wikipedia.org/wiki/Pint_glass


text:
//
//  PMTextField.m
//  ProjectileMotion
//
//  Created by Max Luzuriaga on 4/23/13.
//  Copyright (c) 2013 Max Luzuriaga. All rights reserved.
//

#import "PMTextField.h"

@implementation PMTextField

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.keyboardType = UIKeyboardTypeNumberPad;
        self.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.9];
        self.borderStyle = UITextBorderStyleRoundedRect;
        self.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        self.font = [UIFont fontWithName:@"AvenirNext-Medium" size:18];

        UILabel *label = [[UILabel alloc] init];
        label.backgroundColor = [UIColor clearColor];
        label.font = [UIFont fontWithName:@"AvenirNext-DemiBold" size:18];
        label.frame = CGRectMake(0, 0, 0, 45);
        label.textColor = [UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:1.0];
        label.textAlignment = NSTextAlignmentRight;

        self.rightViewMode = UITextFieldViewModeAlways;
        self.rightView = label;
    }
    return self;
}

- (void)setUnits:(NSString *)units
{
    UILabel *label = (UILabel *)self.rightView;
    label.text = units;

    label.frame = CGRectMake(0, 0, [label.text sizeWithFont:label.font].width, 45);
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end


text:
*jsa.np.rtStrainTyping*: Bacterial strain typing with Oxford Nanopore sequencing
--------------------------------------------------------------------------------

*jsa.np.rtStrainTyping* strain types a bacterial sample from Oxford Nanopore
sequencing in real-time. It reads data in SAM/BAM format from a file or from
a stream and identifies the genes in the samples. Based on the patterns of
gene presence, it makes an inference of the strain, together with the confidence
interval of 95%.

We provide the gene databases for three bacterial species  K. pneumoniae,
E. coli and S. aureus on  http://data.genomicsresearch.org/Projects/npAnalysis/.
Refer to the documentation at https://github.com/mdcao/npAnalysis/ for more
details.

~~~~~~~~
Synopsis
~~~~~~~~

*jsa.np.rtStrainTyping*: Realtime strain typing using Nanopore sequencing data

~~~~~
Usage
~~~~~
::

   jsa.np.rtStrainTyping [options]

~~~~~~~
Options
~~~~~~~
  --geneDB=s       Path to the gene database
                  (REQUIRED)
  --bamFile=s     The bam file
                  (REQUIRED)
  --qual=d        Minimum alignment quality
                  (default='0.0')
  --twodonly      Use only two dimentional reads
                  (default='false')
  --read=i        Minimum number of reads between analyses
                  (default='50')
  --time=i        Minimum number of seconds between analyses
                  (default='30')
  --output=s      Output file
                  (default='output.dat')
  --help          Display this usage and exit
                  (default='false')

~~~~~~~~
See also
~~~~~~~~

jsa.np.npreader_, jsa.np.rtSpeciesTyping_, jsa.np.rtResistGenes_, jsa.util.streamServer_, jsa.util.streamClient_

.. _jsa.np.npreader: jsa.np.npreader.html
.. _jsa.np.rtSpeciesTyping: jsa.np.rtSpeciesTyping.html
.. _jsa.np.rtResistGenes: jsa.np.rtResistGenes.html
.. _jsa.util.streamServer: jsa.util.streamServer.html
.. _jsa.util.streamClient: jsa.util.streamClient.html

~~~~~~~~~~~~~~
Usage examples
~~~~~~~~~~~~~~
If there is a sam/bam file of aligning the Nanopore sequencing to the gene
database (ie, geneFam.fasta in one of the said databases), the program
can read from this file (note, this is not real-time analysis):
::

   jsa.np.rtStrainTyping -geneDB StrainTyping/Escherichia_coli/ -bamFile ecoli.bam -read 100000 -time 1000 -output output.dat

This program can read data from the output stream of an alignment program to
perform analysis in real-time. For example, one can create such a pipeline
to listen on port 3457
::

  jsa.util.streamServer -port 3457 \
  | bwa mem -t 2 -k11 -W20 -r10 -A1 -B1 -O1 -E1 -L0 -Y -K 10000 -a StrainTyping/Escherichia_coli/geneFam.fasta - 2> /dev/null \
  | jsa.np.rtStrainTyping -bam - -geneDB StrainTyping/Escherichia_coli/ -read 0 -time 20 --out EcStrainTyping.dat 2>  kPStrainTyping.log

and streams data to this pipeline using npReader:
::

  jsa.np.npreader -GUI -realtime -folder <DownloadFolder> -fail -output data.fastq -stream serverAddress:3457


text:
package ca.ualberta.smaccr.giftcarder;

import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.text.DecimalFormat;

/**
 * Created by cbli on 11/16/15.
 */

/* UserProfileController handles different states for UserProfileActivity */
public class UserProfileController {
    // Constants
    public static final int OWNER_STATE = 0; // view own profile (has edit button)
    public static final int EDIT_STATE = 1; // edit own profile (has save button)
    public static final int FRIEND_STATE = 3; // view friend's profile (no button)

    /**
     * Sets the view mode of UserProfileActivity based on profileState
     * OWNER_STATE = user views own profile (has edit button)
     * EDIT_STATE = user can edit own profile (has save button)
     * FRIEND_STATE = user views a friend's profile (no buttons)
     *
     * @param  profileState int
     * @param  etCity EditText
     * @param  etPhone EditText
     * @param  etEmail EditText
     * @param  editButton Button
     * @param  saveButton Button
     */
    public void setViewMode(int profileState, EditText etCity, EditText etPhone, EditText etEmail,
                            Button editButton, Button saveButton) {

        if (profileState != EDIT_STATE) {
            etCity.setFocusable(false);
            etPhone.setFocusable(false);
            etEmail.setFocusable(false);
            saveButton.setVisibility(View.GONE);

            if (profileState != FRIEND_STATE) {
                editButton.setVisibility(View.VISIBLE);

            } else {  // in FRIEND_STATE
                editButton.setVisibility(View.GONE);
            }

        } else { // in EDIT_STATE
            etCity.setFocusableInTouchMode(true);
            etPhone.setFocusableInTouchMode(true);
            etEmail.setFocusableInTouchMode(true);
            editButton.setVisibility(View.INVISIBLE);
            saveButton.setVisibility(View.VISIBLE);
        }
    }
}


text:
/* flatpickr v4.0.3, @license MIT */
(function (global, factory) {
	typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
	typeof define === 'function' && define.amd ? define(factory) :
	(global.labelPlugin = factory());
}(this, (function () { 'use strict';

function labelPlugin() {
    return function (fp) {
        return {
            onReady: function () {
                var id = fp.input.id;
                if (fp.altInput && id) {
                    fp.input.removeAttribute("id");
                    fp.altInput.id = id;
                }
            },
        };
    };
}

return labelPlugin;

})));


text:
#include "Firestore/core/src/local/leveldb_transaction.h"

#include <memory>
#include <string>

#include "Firestore/Protos/nanopb/firestore/local/mutation.nanopb.h"
#include "Firestore/Protos/nanopb/firestore/local/target.nanopb.h"
#include "Firestore/core/src/local/leveldb_key.h"
#include "Firestore/core/src/nanopb/byte_string.h"
#include "Firestore/core/src/nanopb/message.h"
#include "Firestore/core/src/nanopb/reader.h"
#include "Firestore/core/src/util/path.h"
#include "Firestore/core/test/unit/local/persistence_testing.h"
#include "Firestore/core/test/unit/testutil/status_testing.h"
#include "absl/strings/string_view.h"
#include "gtest/gtest.h"
#include "leveldb/db.h"

namespace firebase {
namespace firestore {
namespace local {

using leveldb::DB;
using leveldb::Options;
using leveldb::ReadOptions;
using leveldb::Status;
using leveldb::WriteOptions;
using nanopb::ByteString;
using nanopb::Message;
using nanopb::StringReader;
using util::Path;

class LevelDbTransactionTest : public testing::Test {
 protected:
  void SetUp() override;

  std::unique_ptr<DB> db_;
};

void LevelDbTransactionTest::SetUp() {
  Options options;
  options.error_if_exists = true;
  options.create_if_missing = true;

  Path dir = LevelDbDir();
  DB* db = nullptr;
  Status status = DB::Open(options, dir.ToUtf8String(), &db);
  ASSERT_TRUE(status.ok()) << "Failed to create db: "
                           << status.ToString().c_str();
  db_.reset(db);
}

TEST_F(LevelDbTransactionTest, CreateTransaction) {
  LevelDbTransaction transaction(db_.get(), "CreateTransaction");
  std::string key = "key1";

  transaction.Put(key, "value");
  auto iter = transaction.NewIterator();
  iter->Seek(key);
  ASSERT_EQ(key, iter->key());
  iter->Next();
  ASSERT_FALSE(iter->Valid());
}

TEST_F(LevelDbTransactionTest, CanReadCommittedAndMutations) {
  const std::string committed_key1 = "c_key1";
  const std::string committed_value1 = "c_value1";
  const WriteOptions& write_options = LevelDbTransaction::DefaultWriteOptions();
  // add two things committed, mutate one, add another mutation
  // verify you can get the original committed, the mutation, and the addition
  Status status = db_->Put(write_options, committed_key1, committed_value1);
  ASSERT_TRUE(status.ok());

  const std::string committed_key2 = "c_key2";
  const std::string committed_value2 = "c_value2";
  status = db_->Put(write_options, committed_key2, committed_value2);
  ASSERT_TRUE(status.ok());

  LevelDbTransaction transaction(db_.get(), "CanReadCommittedAndMutations");
  const std::string mutation_key1 = "m_key1";
  const std::string mutation_value1 = "m_value1";
  transaction.Put(mutation_key1, mutation_value1);

  const std::string mutation_key2 = committed_key2;
  const std::string mutation_value2 = "m_value2";
  transaction.Put(mutation_key2, mutation_value2);

  std::string value;
  status = transaction.Get(committed_key1, &value);
  ASSERT_TRUE(status.ok());
  ASSERT_EQ(value, committed_value1);

  status = transaction.Get(mutation_key1, &value);
  ASSERT_TRUE(status.ok());
  ASSERT_EQ(value, mutation_value1);

  status = transaction.Get(committed_key2, &value);
  ASSERT_TRUE(status.ok());
  ASSERT_EQ(value, mutation_value2);
}

TEST_F(LevelDbTransactionTest, DeleteCommitted) {
  // add something committed, delete it, verify you can't read it
  for (int i = 0; i < 3; ++i) {
    Status status =
        db_->Put(LevelDbTransaction::DefaultWriteOptions(),
                 "key_" + std::to_string(i), "value_" + std::to_string(i));
    ASSERT_TRUE(status.ok());
  }
  LevelDbTransaction transaction(db_.get(), "DeleteCommitted");
  transaction.Put("key_1", "new_value");
  std::string value;
  Status status = transaction.Get("key_1", &value);
  ASSERT_TRUE(status.ok());
  ASSERT_EQ(value, "new_value");

  transaction.Delete("key_1");
  status = transaction.Get("key_1", &value);
  ASSERT_TRUE(status.IsNotFound());

  LevelDbTransaction::Iterator iter(&transaction);
  iter.Seek("");
  ASSERT_EQ(iter.key(), "key_0");
  iter.Next();
  ASSERT_EQ(iter.key(), "key_2");
  iter.Next();
  ASSERT_FALSE(iter.Valid());
}

TEST_F(LevelDbTransactionTest, MutateDeleted) {
  // delete something, then mutate it, then read it.
  // Also include an actual deletion
  for (int i = 0; i < 4; ++i) {
    Status status =
        db_->Put(LevelDbTransaction::DefaultWriteOptions(),
                 "key_" + std::to_string(i), "value_" + std::to_string(i));
    ASSERT_TRUE(status.ok());
  }
  std::string value;
  LevelDbTransaction transaction(db_.get(), "MutateDeleted");
  transaction.Delete("key_1");
  Status status = transaction.Get("key_1", &value);
  ASSERT_TRUE(status.IsNotFound());

  transaction.Put("key_1", "new_value");
  status = transaction.Get("key_1", &value);
  ASSERT_TRUE(status.ok());
  ASSERT_EQ(value, "new_value");

  transaction.Delete("key_3");

  LevelDbTransaction::Iterator iter(&transaction);
  iter.Seek("");
  ASSERT_EQ(iter.key(), "key_0");
  iter.Next();
  ASSERT_EQ(iter.key(), "key_1");
  ASSERT_EQ(iter.value(), "new_value");
  iter.Next();
  ASSERT_EQ(iter.key(), "key_2");
  iter.Next();
  ASSERT_FALSE(iter.Valid());

  // Commit, then check underlying db.
  transaction.Commit();

  const ReadOptions& read_options = LevelDbTransaction::DefaultReadOptions();
  status = db_->Get(read_options, "key_0", &value);
  ASSERT_TRUE(status.ok());
  ASSERT_EQ("value_0", value);

  status = db_->Get(read_options, "key_1", &value);
  ASSERT_TRUE(status.ok());
  ASSERT_EQ("new_value", value);

  status = db_->Get(read_options, "key_2", &value);
  ASSERT_TRUE(status.ok());
  ASSERT_EQ("value_2", value);

  status = db_->Get(read_options, "key_3", &value);
  ASSERT_TRUE(status.IsNotFound());
}

TEST_F(LevelDbTransactionTest, ProtobufSupport) {
  LevelDbTransaction transaction(db_.get(), "ProtobufSupport");

  Message<firestore_client_Target> target;
  target->target_id = 1;
  target->last_listen_sequence_number = 2;

  std::string key("the_key");
  transaction.Put(key, target);

  std::string value;
  Status status = transaction.Get("the_key", &value);

  ByteString bytes{value};
  StringReader reader{bytes};
  auto parsed = Message<firestore_client_Target>::TryParse(&reader);
  ASSERT_TRUE(reader.ok());
  ASSERT_EQ(target->target_id, parsed->target_id);
  ASSERT_EQ(target->last_listen_sequence_number,
            parsed->last_listen_sequence_number);
}

TEST_F(LevelDbTransactionTest, CanIterateAndDelete) {
  LevelDbTransaction transaction(db_.get(), "CanIterateAndDelete");

  for (int i = 0; i < 4; ++i) {
    transaction.Put("key_" + std::to_string(i), "value_" + std::to_string(i));
  }

  auto it = transaction.NewIterator();
  it->Seek("key_0");
  for (int i = 0; i < 4; ++i) {
    ASSERT_TRUE(it->Valid());
    absl::string_view key = it->key();
    std::string expected = "key_" + std::to_string(i);
    ASSERT_EQ(expected, key);
    transaction.Delete(key);
    it->Next();
  }
}

TEST_F(LevelDbTransactionTest, CanIterateFromDeletionToCommitted) {
  // Write keys key_0 and key_1
  for (int i = 0; i < 2; ++i) {
    Status status =
        db_->Put(LevelDbTransaction::DefaultWriteOptions(),
                 "key_" + std::to_string(i), "value_" + std::to_string(i));
    ASSERT_TRUE(status.ok());
  }

  // Create a transaction, iterate, deleting key_0. Verify we still iterate
  // key_1.
  LevelDbTransaction transaction(db_.get(),
                                 "CanIterateFromDeletionToCommitted");
  auto it = transaction.NewIterator();
  it->Seek("key_0");
  ASSERT_TRUE(it->Valid());
  ASSERT_EQ("key_0", it->key());
  transaction.Delete("key_0");
  it->Next();
  ASSERT_TRUE(it->Valid());
  ASSERT_EQ("key_1", it->key());
  it->Next();
  ASSERT_FALSE(it->Valid());
}

TEST_F(LevelDbTransactionTest, DeletingAheadOfAnIterator) {
  // Write keys
  for (int i = 0; i < 4; ++i) {
    Status status =
        db_->Put(LevelDbTransaction::DefaultWriteOptions(),
                 "key_" + std::to_string(i), "value_" + std::to_string(i));
    ASSERT_TRUE(status.ok());
  }

  // Create a transaction, iterate to key_1, delete key_2. Verify we still
  // iterate key_3.
  LevelDbTransaction transaction(db_.get(), "DeletingAheadOfAnIterator");
  auto it = transaction.NewIterator();
  it->Seek("key_0");
  ASSERT_TRUE(it->Valid());
  ASSERT_EQ("key_0", it->key());
  it->Next();
  ASSERT_TRUE(it->Valid());
  ASSERT_EQ("key_1", it->key());
  transaction.Delete("key_2");
  it->Next();
  ASSERT_TRUE(it->Valid());
  ASSERT_EQ("key_3", it->key());
  ASSERT_TRUE(it->Valid());
  it->Next();
  ASSERT_FALSE(it->Valid());
}

TEST_F(LevelDbTransactionTest, ToString) {
  std::string key = LevelDbMutationKey::Key("user1", 42);
  Message<firestore_client_WriteBatch> message;
  message->batch_id = 42;

  LevelDbTransaction transaction(db_.get(), "ToString");
  std::string description = transaction.ToString();
  ASSERT_EQ(description, "<LevelDbTransaction ToString: 0 changes (0 bytes):>");

  transaction.Put(key, message);
  description = transaction.ToString();
  ASSERT_EQ(description,
            "<LevelDbTransaction ToString: 1 changes (2 bytes):\n"
            "  - Put [mutation: user_id=user1 batch_id=42] (2 bytes)>");

  std::string key2 = LevelDbMutationKey::Key("user1", 43);
  transaction.Delete(key2);
  description = transaction.ToString();
  ASSERT_EQ(description,
            "<LevelDbTransaction ToString: 2 changes (2 bytes):\n"
            "  - Delete [mutation: user_id=user1 batch_id=43]\n"
            "  - Put [mutation: user_id=user1 batch_id=42] (2 bytes)>");
}

}  // namespace local
}  // namespace firestore
}  // namespace firebase


text:
set -o errexit
set -o nounset
set -o pipefail

STARTTIME=$(date +%s)
OS_ROOT=$(dirname "${BASH_SOURCE}")/..
source "${OS_ROOT}/hack/common.sh"
source "${OS_ROOT}/hack/util.sh"
os::log::install_errexit

os::build::build_binaries "$@"
os::build::place_bins "$@"
os::build::make_openshift_binary_symlinks

ret=$?; ENDTIME=$(date +%s); echo "$0 took $(($ENDTIME - $STARTTIME)) seconds"; exit "$ret"


text:
/* Slider */
.slick-slider
{
    position: relative;

    display: block;
    box-sizing: border-box;

    -webkit-user-select: none;
       -moz-user-select: none;
        -ms-user-select: none;
            user-select: none;

    -webkit-touch-callout: none;
    -khtml-user-select: none;
    -ms-touch-action: pan-y;
        touch-action: pan-y;
    -webkit-tap-highlight-color: transparent;
}

.slick-list
{
    position: relative;

    display: block;
    overflow: hidden;

    margin: 0;
    padding: 0;
}
.slick-list:focus
{
    outline: none;
}
.slick-list.dragging
{
    cursor: pointer;
    cursor: hand;
}

.slick-slider .slick-track,
.slick-slider .slick-list
{
    -webkit-transform: translate3d(0, 0, 0);
       -moz-transform: translate3d(0, 0, 0);
        -ms-transform: translate3d(0, 0, 0);
         -o-transform: translate3d(0, 0, 0);
            transform: translate3d(0, 0, 0);
}

.slick-track
{
    position: relative;
    top: 0;
    left: 0;

    display: block;
}
.slick-track:before,
.slick-track:after
{
    display: table;

    content: '';
}
.slick-track:after
{
    clear: both;
}
.slick-loading .slick-track
{
    visibility: hidden;
}

.slick-slide
{
    display: none;
    float: left;

    height: 100%;
    min-height: 1px;
}
[dir='rtl'] .slick-slide
{
    float: right;
}
.slick-slide img
{
    display: block;
}
.slick-slide.slick-loading img
{
    display: none;
}
.slick-slide.dragging img
{
    pointer-events: none;
}
.slick-initialized .slick-slide
{
    display: block;
}
.slick-loading .slick-slide
{
    visibility: hidden;
}
.slick-vertical .slick-slide
{
    display: block;

    height: auto;

    border: 1px solid transparent;
}
.slick-arrow.slick-hidden {
    display: none;
}

/* Slider */
.slick-loading .slick-list
{
    background: #fff url('./ajax-loader.gif') center center no-repeat;
}

/* Icons */
@font-face
{
    font-family: 'slick';
    font-weight: normal;
    font-style: normal;

    src: url('./fonts/slick.eot');
    src: url('./fonts/slick.eot?#iefix') format('embedded-opentype'), url('./fonts/slick.woff') format('woff'), url('./fonts/slick.ttf') format('truetype'), url('./fonts/slick.svg#slick') format('svg');
}
/* Arrows */
.slick-prev,
.slick-next
{
    font-size: 0;
    line-height: 0;

    position: absolute;
    top: 50%;

    display: block;

    width: 20px;
    height: 20px;
    padding: 0;
    -webkit-transform: translate(0, -50%);
    -ms-transform: translate(0, -50%);
    transform: translate(0, -50%);

    cursor: pointer;

    color: transparent;
    border: none;
    outline: none;
    background: transparent;
}
.slick-prev:hover,
.slick-prev:focus,
.slick-next:hover,
.slick-next:focus
{
    color: transparent;
    outline: none;
    background: transparent;
}
.slick-prev:hover:before,
.slick-prev:focus:before,
.slick-next:hover:before,
.slick-next:focus:before
{
    opacity: 1;
}
.slick-prev.slick-disabled:before,
.slick-next.slick-disabled:before
{
    opacity: .25;
}

.slick-prev:before,
.slick-next:before
{
    font-family: 'slick';
    font-size: 20px;
    line-height: 1;

    opacity: .75;
    color: white;

    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

.slick-prev
{
    left: -25px;
}
[dir='rtl'] .slick-prev
{
    right: -25px;
    left: auto;
}
.slick-prev:before
{
    content: '←';
}
[dir='rtl'] .slick-prev:before
{
    content: '→';
}

.slick-next
{
    right: -25px;
}
[dir='rtl'] .slick-next
{
    right: auto;
    left: -25px;
}
.slick-next:before
{
    content: '→';
}
[dir='rtl'] .slick-next:before
{
    content: '←';
}

/* Dots */
.slick-dotted.slick-slider
{
    margin-bottom: 30px;
}

.slick-dots
{
    position: absolute;
    bottom: -25px;

    display: block;

    width: 100%;
    padding: 0;
    margin: 0;

    list-style: none;

    text-align: center;
}
.slick-dots li
{
    position: relative;

    display: inline-block;

    width: 20px;
    height: 20px;
    margin: 0 5px;
    padding: 0;

    cursor: pointer;
}
.slick-dots li button
{
    font-size: 0;
    line-height: 0;

    display: block;

    width: 20px;
    height: 20px;
    padding: 5px;

    cursor: pointer;

    color: transparent;
    border: 0;
    outline: none;
    background: transparent;
}
.slick-dots li button:hover,
.slick-dots li button:focus
{
    outline: none;
}
.slick-dots li button:hover:before,
.slick-dots li button:focus:before
{
    opacity: 1;
}
.slick-dots li button:before
{
    font-family: 'slick';
    font-size: 6px;
    line-height: 20px;

    position: absolute;
    top: 0;
    left: 0;

    width: 20px;
    height: 20px;

    content: '•';
    text-align: center;

    opacity: .25;
    color: black;

    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}
.slick-dots li.slick-active button:before
{
    opacity: .75;
    color: black;
}


text:
<?php
declare(strict_types=1);

use Phinx\Migration\AbstractMigration;

final class CreateUuidCacheTable extends AbstractMigration
{
    public function change(): void
    {
        $table = $this->table('nl2_uuid_cache');

        $table
            ->addColumn('mcname', 'string', ['limit' => 20])
            ->addColumn('uuid', 'string', ['limit' => 64]);

        $table->create();
    }
}