text:
package edu.harvard.iq.dataverse.dataaccess;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import java.util.logging.Logger;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.LinkedHashMap;

import edu.harvard.iq.dataverse.DataFile;
import edu.harvard.iq.dataverse.datavariable.DataVariable;
import edu.harvard.iq.dataverse.datavariable.VariableCategory;
import edu.harvard.iq.dataverse.util.FileUtil;
import edu.harvard.iq.dataverse.rserve.*;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.channels.Channel;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 4.0 implementation of the Data Access "optional service" that offers
 * access to "subsettable" (tabular) data files in alternative formats.
 * In reality, there will only be 1 alternative format supported in 4.0:
 * R data. The module will still provide functionality for supporting
 * multiple alternative formats.
 *
 * @author Leonid Andreev
 */
public class DataConverter {
    private static Logger logger = Logger.getLogger(DataConverter.class.getPackage().getName());

    public DataConverter() {
    }

    public static String FILE_TYPE_TAB = "tab";
    public static String FILE_TYPE_RDATA = "RData";

    public static String SERVICE_REQUEST_CONVERT = "convert";

    public static DataFileIO performFormatConversion(DataFile file, DataFileIO dataFileIO, String formatRequested, String formatType) {
        if (!file.isTabularData()) {
            return null;
        }

        // if the format requested is "D00", and it's already a TAB file,
        // we don't need to do anything:
        if (formatRequested.equals(FILE_TYPE_TAB) && file.getContentType().equals("text/tab-separated-values")) {

            return dataFileIO;
        }

        InputStream convertedFileStream = null;
        long convertedFileSize = 0;

        // We may already have a cached copy of this
        // format:
        try {
            convertedFileStream = Channels.newInputStream((ReadableByteChannel) dataFileIO.openAuxChannel(formatRequested));
            convertedFileSize = dataFileIO.getAuxObjectSize(formatRequested);
        } catch (IOException ioex) {
            logger.fine("No cached copy for file format "+formatRequested+", file "+file.getStorageIdentifier());
            convertedFileStream = null;
        }

        // If not cached, run the conversion:
        if (convertedFileStream == null) {

            File tabFile = null;

            boolean tempFilesRequired = false;

            try {
                Path tabFilePath = dataFileIO.getFileSystemPath();
                tabFile = tabFilePath.toFile();
            } catch (UnsupportedDataAccessOperationException uoex) {
                // this means there is no direct filesystem path for this object; it's ok!
                logger.fine("Could not open source file as a local Path - will go the temp file route.");
                tempFilesRequired = true;
            } catch (IOException ioex) {
                // this is likely a fatal condition, as in, the file is unaccessible:
                return null;
            }

            if (tempFilesRequired) {
                ReadableByteChannel tabFileChannel = null;
                try {
                    logger.fine("opening datafFileIO for the source tabular file...");
                    dataFileIO.open();
                    tabFileChannel = dataFileIO.getReadChannel();

                    FileChannel tempFileChannel;
                    tabFile = File.createTempFile("tempTabFile", ".tmp");
                    tempFileChannel = new FileOutputStream(tabFile).getChannel();
                    tempFileChannel.transferFrom(tabFileChannel, 0, dataFileIO.getSize());
                } catch (IOException ioex) {
                    logger.warning("caught IOException trying to store tabular file " + dataFileIO.getDataFile().getStorageIdentifier() + " as a temp file.");

                    return null;
                }
            }

            if (tabFile == null) {
                return null;
            }

            if (tabFile.length() > 0) {
                File formatConvertedFile = runFormatConversion(file, tabFile, formatRequested);

                // cache the result for future use:
                if (formatConvertedFile != null && formatConvertedFile.exists()) {

                    try {
                        dataFileIO.savePathAsAux(Paths.get(formatConvertedFile.getAbsolutePath()), formatRequested);

                    } catch (IOException ex) {
                        logger.warning("failed to save cached format " + formatRequested + " for " + file.getStorageIdentifier());
                        // We'll assume that this is a non-fatal condition.
                    }

                    // re-open the generated file:
                    try {
                        convertedFileStream = new FileInputStream(formatConvertedFile);
                        convertedFileSize = formatConvertedFile.length();
                    } catch (IOException ioex) {
                        logger.warning("Failed to open generated format " + formatRequested + " for " + file.getStorageIdentifier());
                        return null;
                    }
                }

            }
        }

        // Now check the converted stream, and return the IO object back to the
        // download API instance writer:
        if (convertedFileStream != null && convertedFileSize > 0) {

            InputStreamIO inputStreamIO = null;
            try {
                inputStreamIO = new InputStreamIO(convertedFileStream, convertedFileSize);
            } catch (IOException ioex) {
                return null;
            }

            inputStreamIO.setMimeType(formatType);

            String fileName = dataFileIO.getFileName();
            if (fileName == null || fileName.equals("")) {
                fileName = "f" + file.getId().toString();
            }
            inputStreamIO.setFileName(generateAltFileName(formatRequested, fileName));

            return inputStreamIO;
        }

        return null;
    } // end of performformatconversion();

    // Method for (subsettable) file format conversion.
    // The method needs the subsettable file saved on disk as in the
    // TAB-delimited format.
    // Meaning, if this is a remote subsettable file, it needs to be downloaded
    // and stored locally as a temporary file; and if it's a fixed-field file, it
    // needs to be converted to TAB-delimited, before you can feed the file
    // to this method. (See performFormatConversion() method)
    // The method below takes the tab file and sends it to the R server
    // (possibly running on a remote host) and gets back the transformed copy,
    // providing error-checking and diagnostics in the process.
    // This is mostly Akio Sone's code from DVN3.
    // (hence some obsolete elements in the comment above: ALL of the tabular
    // data files in Dataverse are saved in tab-delimited format - we no longer
    // support fixed-field files!

    private static File runFormatConversion (DataFile file, File tabFile, String formatRequested) {

        if ( formatRequested.equals (FILE_TYPE_TAB) ) {
            // if the *requested* format is TAB-delimited, we don't
            // need to call R to do any conversions, we can just
            // send back the TAB file we have just produced.

            // (OK, so that the assumption is, if this is a fixed-field file --
            // from ICPSR or otherwise -- the Access service has already
            // converted it to tab-delimited... TODO: review this logic;
            // perhaps fixed-field to tabular should also be handled here?
            // -- L.A. 4.0 alpha 1)

            return tabFile;
        }

        File formatConvertedFile = null;
        // create the service instance
        RemoteDataFrameService dfs = new RemoteDataFrameService();

        if ("RData".equals(formatRequested)) {
            List<DataVariable> dataVariables = file.getDataTable().getDataVariables();
            Map<String, Map<String, String>> vls = null;

            vls = getValueTableForRequestedVariables(dataVariables);
            logger.fine("format conversion: variables(getDataVariableForRequest())=" + dataVariables + "\n");
            logger.fine("format conversion: variables(dataVariables)=" + dataVariables + "\n");
            logger.fine("format conversion: value table(vls)=" + vls + "\n");
            RJobRequest sro = new RJobRequest(dataVariables, vls);

            sro.setTabularDataFileName(tabFile.getAbsolutePath());
            sro.setRequestType(SERVICE_REQUEST_CONVERT);
            sro.setFormatRequested(FILE_TYPE_RDATA);

            // execute the service
            Map<String, String> resultInfo = dfs.execute(sro);

            //resultInfo.put("offlineCitation", citation);
            logger.fine("resultInfo="+resultInfo+"\n");

            // check whether a requested file is actually created

            if ("true".equals(resultInfo.get("RexecError"))){
                logger.fine("R-runtime error trying to convert a file.");
                return  null;
            } else {
                String dataFrameFileName = resultInfo.get("dataFrameFileName");
                logger.fine("data frame file name: "+dataFrameFileName);

                formatConvertedFile = new File(dataFrameFileName);
            }
        } else if ("prep".equals(formatRequested)) {
            formatConvertedFile = dfs.runDataPreprocessing(file);
        } else {
            logger.warning("Unsupported file format requested: "+formatRequested);
            return null;
        }

        if (formatConvertedFile.exists()) {
            logger.fine("frmtCnvrtdFile:length=" + formatConvertedFile.length());
        } else {
            logger.warning("Format-converted file was not properly created.");
            return null;
        }

        return formatConvertedFile;
    }

    private static Map<String, Map<String, String>> getValueTableForRequestedVariables(List<DataVariable> dvs){
        Map<String, Map<String, String>> vls = new LinkedHashMap<String, Map<String, String>>();
        for (DataVariable dv : dvs){
            List<VariableCategory> varCat = new ArrayList<VariableCategory>();
            varCat.addAll(dv.getCategories());
            Map<String, String> vl = new HashMap<String, String>();
            for (VariableCategory vc : varCat){
                if (vc.getLabel() != null){
                    vl.put(vc.getValue(), vc.getLabel());
                }
            }
            if (vl.size() > 0){
                vls.put("v"+dv.getId(), vl);
            }
        }
        return vls;
    }

    private static String generateAltFileName(String formatRequested, String xfileId) {
        String altFileName = xfileId;

        if ( altFileName == null || altFileName.equals("")) {
            altFileName = "Converted";
        }

        if ( formatRequested != null ) {
            altFileName = FileUtil.replaceExtension(altFileName, formatRequested);
        }

        return altFileName;
    }

}


text:
package org.encuestame.mvc.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.encuestame.core.files.PathUtil;
import org.encuestame.core.security.SecurityUtils;
import org.encuestame.utils.enums.EnMePermission;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.servlet.ModelAndView;

/**
 * Description.
 * @author Picado, Juan juanATencuestame.org
 * @since May 5, 2011
 */
public class SignInInterceptor extends AbstractEnMeInterceptor{

    private static Logger log = Logger.getLogger(SignInInterceptor.class);

    /*
     * (non-Javadoc)
     * @see org.springframework.web.servlet.HandlerInterceptor#afterCompletion(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)
     */
    @Override
    public void afterCompletion(HttpServletRequest arg0,
            HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     * @see org.springframework.web.servlet.HandlerInterceptor#postHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.web.servlet.ModelAndView)
     */
    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
            Object arg2, ModelAndView arg3) throws Exception {
        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     * @see org.springframework.web.servlet.HandlerInterceptor#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object)
     */
    @Override
    public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
            Object arg2) throws Exception {
        String context = arg0.getContextPath();
        StringBuilder path = new StringBuilder(context);
        path.append(PathUtil.signIn);
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        log.trace("Sign In Auth:{ " + authentication);
        if (arg0.getRequestURI().equals(path.toString())) {
            log.debug("Sign In are equals:{ "+arg0.getRequestURI());
            if (authentication != null) {
                if (!SecurityUtils.checkIsSessionIsAnonymousUser(authentication)) {
                    log.debug("Sign In session is valid");
                    for (GrantedAuthority auth : authentication.getAuthorities()) {
                        log.debug("Sign In Auth:{ "+auth.getAuthority());
                        if (EnMePermission.getPermissionString(
                                auth.getAuthority()).equals(
                                EnMePermission.ENCUESTAME_USER)) {
                            log.debug("User is logged, redirec to dashboard");
                            arg1.sendRedirect(arg0.getContextPath() + "/user/dashboard");
                            break;
                        }
                    }
                }
            }
        }
        return true;
    }

}

redpajama_set_name: RedPajamaGithub


text:
<?php

$factory->define(\NUSWhispers\Models\ApiKey::class, function ($faker) {
    return [
        'key' => $faker->word,
        'user_id' => function () {
            return factory(\NUSWhispers\Models\User::class)->create()->getKey();
        },
    ];
});


text:
{-
Copyright 2015 Tristan Aubrey-Jones
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}

{-|
Copyright   : (c) Tristan Aubrey-Jones, 2015
License     : Apache-2
Maintainer  : developer@flocc.net
Stability   : experimental

For more information please see <http://www.flocc.net/>
-}
module Compiler.Back.AllTemplates (templates) where

import Control.Monad.Catch

import Compiler.Back.Graph
import Compiler.Back.GenDecls
import Compiler.Back.Gen

import Compiler.Back.ScalTemplates (scalTemplates)
import Compiler.Back.ControlTemplates (ctrlTemplates)
import Compiler.Back.Maps.STemplates (smapTemplates)
import Compiler.Back.Maps.VTemplates (vmapTemplates)
import Compiler.Back.Maps.HTemplates (hmapTemplates)
import Compiler.Back.Maps.TTemplates (tmapTemplates)

templates :: (Monad m, MonadCatch m) => [(Id, Template m)]
templates =
     scalTemplates
  ++ ctrlTemplates
  ++ smapTemplates
  ++ vmapTemplates
  ++ hmapTemplates
  ++ tmapTemplates


text:
<?xml version="1.0" encoding="utf-8"  ?>
<dds xmlns="http://www.eprosima.com/XMLSchemas/fastRTPS_Profiles">
    <profiles>
        <library_settings>
            <intraprocess_delivery>FULL</intraprocess_delivery>
        </library_settings>
        <participant profile_name="test_participant_profile_string">
            <domainId>2042</domainId>
            <rtps>
                <allocation>
                    <remote_locators>
                        <max_unicast_locators>10</max_unicast_locators>
                        <max_multicast_locators>3</max_multicast_locators>
                    </remote_locators>
                    <total_participants>
                        <initial>5</initial>
                        <maximum>8</maximum>
                        <increment>3</increment>
                    </total_participants>
                    <total_readers>
                        <initial>5</initial>
                        <maximum>8</maximum>
                        <increment>3</increment>
                    </total_readers>
                    <total_writers>
                        <initial>5</initial>
                        <maximum>8</maximum>
                        <increment>3</increment>
                    </total_writers>
                    <send_buffers>
                        <preallocated_number>65</preallocated_number>
                        <dynamic>true</dynamic>
                    </send_buffers>
                </allocation>
                <defaultUnicastLocatorList>
                    <locator>
                        <udpv4>
                            <address>192.168.1.3</address>
                            <port>2020</port>
                        </udpv4>
                    </locator>
                </defaultUnicastLocatorList>
                <defaultMulticastLocatorList>
                    <locator>
                        <udpv4>
                            <address>239.255.0.1</address>
                            <port>2022</port>
                        </udpv4>
                    </locator>
                </defaultMulticastLocatorList>
                <builtin>
                    <discovery_config>
                        <discoveryProtocol>SIMPLE</discoveryProtocol>
                        <EDP>SIMPLE</EDP>
                        <ignoreParticipantFlags>FILTER_SAME_PROCESS</ignoreParticipantFlags>
                        <leaseAnnouncement>
                            <sec>5</sec>
                            <nanosec>0</nanosec>
                        </leaseAnnouncement>
                        <leaseDuration>
                            <sec>120</sec>
                        </leaseDuration>
                        <initialAnnouncements>
                            <count>3</count>
                            <period>
                                <sec>2</sec>
                                <nanosec>0</nanosec>
                            </period>
                        </initialAnnouncements>
                        <simpleEDP>
                            <PUBWRITER_SUBREADER>false</PUBWRITER_SUBREADER>
                            <PUBREADER_SUBWRITER>true</PUBREADER_SUBWRITER>
                        </simpleEDP>
                    </discovery_config>
                    <avoid_builtin_multicast>false</avoid_builtin_multicast>
                    <use_WriterLivelinessProtocol>false</use_WriterLivelinessProtocol>
                    <metatrafficUnicastLocatorList>
                        <locator>
                            <udpv4>
                                <address>192.168.2.5</address>
                                <port>8888</port>
                            </udpv4>
                        </locator>
                        <locator>
                            <udpv4>
                                <address>192.168.2.6</address>
                                <port>7777</port>
                            </udpv4>
                        </locator>
                    </metatrafficUnicastLocatorList>
                    <metatrafficMulticastLocatorList>
                        <locator>
                            <udpv4>
                                <address>239.255.2.2</address>
                                <port>3333</port>
                            </udpv4>
                        </locator>
                        <locator>
                            <udpv4>
                                <address>239.255.2.3</address>
                                <port>2222</port>
                            </udpv4>
                        </locator>
                    </metatrafficMulticastLocatorList>
                    <initialPeersList>
                        <locator>
                            <udpv4>
                                <address>239.255.2.1</address>
                                <port>6666</port>
                            </udpv4>
                        </locator>
                    </initialPeersList>
                    <readerHistoryMemoryPolicy>PREALLOCATED</readerHistoryMemoryPolicy>
                    <writerHistoryMemoryPolicy>PREALLOCATED</writerHistoryMemoryPolicy>
                    <mutation_tries>10</mutation_tries>
                </builtin>
                <port>
                    <portBase>7400</portBase>
                    <domainIDGain>200</domainIDGain>
                    <participantIDGain>10</participantIDGain>
                    <offsetd0>0</offsetd0>
                    <offsetd1>1</offsetd1>
                    <offsetd2>2</offsetd2>
                    <offsetd3>3</offsetd3>
                </port>
                <participantID>66</participantID>
                <throughputController>
                    <bytesPerPeriod>8192</bytesPerPeriod>
                    <periodMillisecs>1000</periodMillisecs>
                </throughputController>
                <useBuiltinTransports>true</useBuiltinTransports>
                <name>test_name</name>
            </rtps>
        </participant>

        <participant profile_name="test_default_participant_profile_string" is_default_profile="true">
            <domainId>2019102</domainId>
            <rtps>
                <allocation>
                    <remote_locators>
                        <max_unicast_locators>4</max_unicast_locators>
                        <max_multicast_locators>1</max_multicast_locators>
                    </remote_locators>
                    <total_participants>
                        <initial>10</initial>
                        <maximum>20</maximum>
                        <increment>2</increment>
                    </total_participants>
                    <total_readers>
                        <initial>10</initial>
                        <maximum>20</maximum>
                        <increment>2</increment>
                    </total_readers>
                    <total_writers>
                        <initial>10</initial>
                        <maximum>20</maximum>
                        <increment>2</increment>
                    </total_writers>
                    <send_buffers>
                        <preallocated_number>127</preallocated_number>
                        <dynamic>true</dynamic>
                    </send_buffers>
                </allocation>
                <defaultUnicastLocatorList>
                    <locator>
                        <udpv4>
                            <address>192.168.1.2</address>
                            <port>2019</port>
                        </udpv4>
                    </locator>
                </defaultUnicastLocatorList>
                <defaultMulticastLocatorList>
                    <locator>
                        <udpv4>
                            <address>239.255.0.1</address>
                            <port>2021</port>
                        </udpv4>
                    </locator>
                </defaultMulticastLocatorList>
                <builtin>
                    <discovery_config>
                        <discoveryProtocol>SIMPLE</discoveryProtocol>
                        <EDP>SIMPLE</EDP>
                        <ignoreParticipantFlags>FILTER_SAME_PROCESS | FILTER_DIFFERENT_HOST</ignoreParticipantFlags>
                        <leaseAnnouncement>
                            <sec>10</sec>
                            <nanosec>333</nanosec>
                        </leaseAnnouncement>
                        <leaseDuration>
                            <sec>DURATION_INFINITY</sec>
                        </leaseDuration>
                        <initialAnnouncements>
                            <count>2</count>
                            <period>
                                <sec>1</sec>
                                <nanosec>827</nanosec>
                            </period>
                        </initialAnnouncements>
                        <simpleEDP>
                            <PUBWRITER_SUBREADER>false</PUBWRITER_SUBREADER>
                            <PUBREADER_SUBWRITER>true</PUBREADER_SUBWRITER>
                        </simpleEDP>
                    </discovery_config>
                    <avoid_builtin_multicast>false</avoid_builtin_multicast>
                    <use_WriterLivelinessProtocol>false</use_WriterLivelinessProtocol>
                    <metatrafficUnicastLocatorList>
                        <locator>
                            <udpv4>
                                <address>192.168.1.5</address>
                                <port>9999</port>
                            </udpv4>
                        </locator>
                        <locator>
                            <udpv4>
                                <address>192.168.1.6</address>
                                <port>6666</port>
                            </udpv4>
                        </locator>
                    </metatrafficUnicastLocatorList>
                    <metatrafficMulticastLocatorList>
                        <locator>
                            <udpv4>
                                <address>239.255.0.2</address>
                                <port>32</port>
                            </udpv4>
                        </locator>
                        <locator>
                            <udpv4>
                                <address>239.255.0.3</address>
                                <port>2112</port>
                            </udpv4>
                        </locator>
                    </metatrafficMulticastLocatorList>
                    <initialPeersList>
                        <locator>
                            <udpv4>
                                <address>239.255.0.1</address>
                                <port>21120</port>
                            </udpv4>
                        </locator>
                    </initialPeersList>
                    <readerHistoryMemoryPolicy>PREALLOCATED</readerHistoryMemoryPolicy>
                    <writerHistoryMemoryPolicy>PREALLOCATED</writerHistoryMemoryPolicy>
                    <mutation_tries>55</mutation_tries>
                </builtin>
                <port>
                    <portBase>7400</portBase>
                    <domainIDGain>200</domainIDGain>
                    <participantIDGain>10</participantIDGain>
                    <offsetd0>0</offsetd0>
                    <offsetd1>1</offsetd1>
                    <offsetd2>2</offsetd2>
                    <offsetd3>3</offsetd3>
                </port>
                <participantID>99</participantID>
                <throughputController>
                    <bytesPerPeriod>8192</bytesPerPeriod>
                    <periodMillisecs>1000</periodMillisecs>
                </throughputController>
                <useBuiltinTransports>true</useBuiltinTransports>
                <name>default_name</name>
            </rtps>
        </participant>

        <publisher profile_name="test_publisher_profile_string">
            <topic>
                <kind>NO_KEY</kind>
                <name>samplePubSubTopic</name>
                <dataType>samplePubSubTopicType</dataType>
                <historyQos>
                    <kind>KEEP_ALL</kind>
                    <depth>500</depth>
                </historyQos>
                <resourceLimitsQos>
                    <max_samples>10</max_samples>
                    <max_instances>5</max_instances>
                    <max_samples_per_instance>2</max_samples_per_instance>
                    <allocated_samples>10</allocated_samples>
                </resourceLimitsQos>
            </topic>
            <qos>
                <durability>
                    <kind>VOLATILE</kind>
                </durability>
                <liveliness>
                    <kind>MANUAL_BY_TOPIC</kind>
                    <lease_duration>
                        <sec>5</sec>
                        <nanosec>0</nanosec>
                    </lease_duration>
                    <announcement_period>
                        <sec>5</sec>
                        <nanosec>0</nanosec>
                    </announcement_period>
                </liveliness>
                <reliability>
                    <kind>RELIABLE</kind>
                    <max_blocking_time>
                        <sec>5</sec>
                        <nanosec>0</nanosec>
                    </max_blocking_time>
                </reliability>
                <partition>
                    <names>
                        <name>partition_name_c</name>
                        <name>partition_name_d</name>
                    </names>
                </partition>
                <publishMode>
                    <kind>ASYNCHRONOUS</kind>
                </publishMode>
            </qos>
            <times>
                <initialHeartbeatDelay>
                    <sec>5</sec>
                    <nanosec>0</nanosec>
                </initialHeartbeatDelay>
                <heartbeatPeriod>
                    <sec>5</sec>
                    <nanosec>0</nanosec>
                </heartbeatPeriod>
                <nackResponseDelay>
                    <sec>5</sec>
                    <nanosec>0</nanosec>
                </nackResponseDelay>
                <nackSupressionDuration>
                    <sec>120</sec>
                    <nanosec>500</nanosec>
                </nackSupressionDuration>
            </times>
            <unicastLocatorList>
                <locator>
                    <udpv4>
                        <address>192.168.2.3</address>
                        <port>200</port>
                    </udpv4>
                </locator>
                <locator>
                    <udpv4>
                        <address>192.168.3.9</address>
                        <port>300</port>
                    </udpv4>
                </locator>
            </unicastLocatorList>
            <multicastLocatorList>
                <locator>
                    <udpv4>
                        <address>239.255.4.1</address>
                        <port>400</port>
                    </udpv4>
                </locator>
                <locator>
                    <udpv4></udpv4>
                </locator>
                <locator>
                    <udpv4>
                        <port>500</port>
                    </udpv4>
                </locator>
            </multicastLocatorList>
            <throughputController>
                <bytesPerPeriod>1024</bytesPerPeriod>
                <periodMillisecs>500</periodMillisecs>
            </throughputController>
            <historyMemoryPolicy>PREALLOCATED_WITH_REALLOC</historyMemoryPolicy>
            <userDefinedID>40</userDefinedID>
            <entityID>40</entityID>
            <matchedSubscribersAllocation>
                <initial>5</initial>
                <maximum>20</maximum>
                <increment>5</increment>
            </matchedSubscribersAllocation>
        </publisher>

        <publisher profile_name="test_default_publisher_profile_string"
        is_default_profile="true">
            <topic>
                <kind>NO_KEY</kind>
                <name>samplePubSubTopic</name>
                <dataType>samplePubSubTopicType</dataType>
                <historyQos>
                    <kind>KEEP_LAST</kind>
                    <depth>50</depth>
                </historyQos>
                <resourceLimitsQos>
                    <max_samples>432</max_samples>
                    <max_instances>1</max_instances>
                    <max_samples_per_instance>100</max_samples_per_instance>
                    <allocated_samples>123</allocated_samples>
                </resourceLimitsQos>
            </topic>
            <qos>
                <durability>
                    <kind>TRANSIENT_LOCAL</kind>
                </durability>
                <liveliness>
                    <kind>MANUAL_BY_PARTICIPANT</kind>
                    <lease_duration>
                        <sec>1</sec>
                        <nanosec>2</nanosec>
                    </lease_duration>
                    <announcement_period>
                        <sec>DURATION_INFINITY</sec>
                    </announcement_period>
                </liveliness>
                <reliability>
                    <kind>BEST_EFFORT</kind>
                    <max_blocking_time>
                        <sec>0</sec>
                        <nanosec>0</nanosec>
                    </max_blocking_time>
                </reliability>
                <partition>
                    <names>
                        <name>partition_name_a</name>
                        <name>partition_name_b</name>
                    </names>
                </partition>
                <publishMode>
                    <kind>ASYNCHRONOUS</kind>
                </publishMode>
            </qos>
            <times>
                <initialHeartbeatDelay>
                    <sec>0</sec>
                    <nanosec>0</nanosec>
                </initialHeartbeatDelay>
                <heartbeatPeriod>
                    <sec>11</sec>
                    <nanosec>32</nanosec>
                </heartbeatPeriod>
                <nackResponseDelay>
                    <sec>0</sec>
                    <nanosec>0</nanosec>
                </nackResponseDelay>
                <nackSupressionDuration>
                    <sec>121</sec>
                    <nanosec>332</nanosec>
                </nackSupressionDuration>
            </times>
            <unicastLocatorList>
                <locator>
                    <udpv4>
                        <address>192.168.1.3</address>
                        <port>197</port>
                    </udpv4>
                </locator>
                <locator>
                    <udpv4>
                        <address>192.168.1.9</address>
                        <port>219</port>
                    </udpv4>
                </locator>
            </unicastLocatorList>
            <multicastLocatorList>
                <locator>
                    <udpv4>
                        <address>239.255.0.1</address>
                        <port>2020</port>
                    </udpv4>
                </locator>
                <locator>
                    <udpv4></udpv4>
                </locator>
                <locator>
                    <udpv4>
                        <port>1989</port>
                    </udpv4>
                </locator>
            </multicastLocatorList>
            <throughputController>
                <bytesPerPeriod>9236</bytesPerPeriod>
                <periodMillisecs>234</periodMillisecs>
            </throughputController>
            <historyMemoryPolicy>DYNAMIC</historyMemoryPolicy>
            <userDefinedID>67</userDefinedID>
            <entityID>87</entityID>
            <matchedSubscribersAllocation>
                <initial>10</initial>
                <maximum>10</maximum>
                <increment>0</increment>
            </matchedSubscribersAllocation>
        </publisher>

        <subscriber profile_name="test_subscriber_profile_string">
            <topic>
                <kind>NO_KEY</kind>
                <name>otherSamplePubSubTopic</name>
                <dataType>otherSamplePubSubTopicType</dataType>
                <historyQos>
                    <kind>KEEP_LAST</kind>
                    <depth>500</depth>
                </historyQos>
                <resourceLimitsQos>
                    <max_samples>10</max_samples>
                    <max_instances>5</max_instances>
                    <max_samples_per_instance>2</max_samples_per_instance>
                    <allocated_samples>10</allocated_samples>
                </resourceLimitsQos>
            </topic>
            <qos>
                <durability>
                    <kind>VOLATILE</kind>
                </durability>
                <liveliness>
                    <kind>MANUAL_BY_TOPIC</kind>
                    <lease_duration>
                        <sec>5</sec>
                        <nanosec>0</nanosec>
                    </lease_duration>
                    <announcement_period>
                        <sec>DURATION_INFINITY</sec>
                    </announcement_period>
                </liveliness>
                <reliability>
                    <kind>BEST_EFFORT</kind>
                    <max_blocking_time>
                        <sec>5</sec>
                    </max_blocking_time>
                </reliability>
                <partition>
                    <names>
                        <name>partition_name_a</name>
                        <name>partition_name_b</name>
                        <name>partition_name_c</name>
                        <name>partition_name_d</name>
                    </names>
                </partition>
            </qos>
            <times>
                <initialAcknackDelay>
                    <sec>5</sec>
                    <nanosec>0</nanosec>
                </initialAcknackDelay>
                <heartbeatResponseDelay>
                    <sec>5</sec>
                    <nanosec>0</nanosec>
                </heartbeatResponseDelay>
            </times>
            <unicastLocatorList>
                <locator>
                    <udpv4>
                        <address>192.168.2.10</address>
                        <port>200</port>
                    </udpv4>
                </locator>
                <locator>
                    <udpv4>
                        <port>201</port>
                    </udpv4>
                </locator>
            </unicastLocatorList>
            <multicastLocatorList>
                <locator>
                    <udpv4>
                        <address>239.255.3.10</address>
                        <port>300</port>
                    </udpv4>
                </locator>
                <locator>
                    <udpv4>
                    </udpv4>
                </locator>
                <locator>
                    <udpv4>
                        <address>239.255.4.11</address>
                        <port>400</port>
                    </udpv4>
                </locator>
            </multicastLocatorList>
            <expectsInlineQos>false</expectsInlineQos>
            <historyMemoryPolicy>DYNAMIC</historyMemoryPolicy>
            <userDefinedID>40</userDefinedID>
            <entityID>40</entityID>
            <matchedPublishersAllocation>
                <initial>5</initial>
                <maximum>20</maximum>
                <increment>5</increment>
            </matchedPublishersAllocation>
        </subscriber>

        <subscriber profile_name="test_default_subscriber_profile_string" is_default_profile="true">
            <topic>
                <kind>WITH_KEY</kind>
                <name>otherSamplePubSubTopic</name>
                <dataType>otherSamplePubSubTopicType</dataType>
                <historyQos>
                    <kind>KEEP_ALL</kind>
                    <depth>1001</depth>
                </historyQos>
                <resourceLimitsQos>
                    <max_samples>52</max_samples>
                    <max_instances>25</max_instances>
                    <max_samples_per_instance>32</max_samples_per_instance>
                    <allocated_samples>37</allocated_samples>
                </resourceLimitsQos>
            </topic>
            <qos>
                <durability>
                    <kind>TRANSIENT_LOCAL</kind>
                </durability>
                <liveliness>
                    <kind>MANUAL_BY_TOPIC</kind>
                    <lease_duration>
                        <sec>11</sec>
                        <nanosec>22</nanosec>
                    </lease_duration>
                    <announcement_period>
                        <sec>0</sec>
                        <nanosec>0</nanosec>
                    </announcement_period>
                </liveliness>
                <reliability>
                    <kind>RELIABLE</kind>
                    <max_blocking_time>
                        <sec>DURATION_INFINITY</sec>
                    </max_blocking_time>
                </reliability>
                <partition>
                    <names>
                        <name>partition_name_c</name>
                        <name>partition_name_d</name>
                        <name>partition_name_e</name>
                        <name>partition_name_f</name>
                    </names>
                </partition>
            </qos>
            <times>
                <initialAcknackDelay>
                    <sec>0</sec>
                    <nanosec>0</nanosec>
                </initialAcknackDelay>
                <heartbeatResponseDelay>
                    <sec>18</sec>
                    <nanosec>81</nanosec>
                </heartbeatResponseDelay>
            </times>
            <unicastLocatorList>
                <locator>
                    <udpv4>
                        <address>192.168.1.10</address>
                        <port>196</port>
                    </udpv4>
                </locator>
                <locator>
                    <udpv4>
                        <port>212</port>
                    </udpv4>
                </locator>
            </unicastLocatorList>
            <multicastLocatorList>
                <locator>
                    <udpv4>
                        <address>239.255.0.10</address>
                        <port>220</port>
                    </udpv4>
                </locator>
                <locator>
                    <udpv4>
                    </udpv4>
                </locator>
                <locator>
                    <udpv4>
                        <address>239.255.0.11</address>
                        <port>9891</port>
                    </udpv4>
                </locator>
            </multicastLocatorList>
            <expectsInlineQos>true</expectsInlineQos>
            <historyMemoryPolicy>PREALLOCATED_WITH_REALLOC</historyMemoryPolicy>
            <userDefinedID>13</userDefinedID>
            <entityID>31</entityID>
            <matchedPublishersAllocation>
                <initial>10</initial>
                <maximum>10</maximum>
                <increment>0</increment>
            </matchedPublishersAllocation>
        </subscriber>
        <topic profile_name = "test_topic_profile_string">
            <historyQos>
                <kind>KEEP_LAST</kind>
                <depth>20</depth>
            </historyQos>
            <resourceLimitsQos>
                <max_samples>200</max_samples>
                <max_instances>20</max_instances>
                <max_samples_per_instance>100</max_samples_per_instance>
                <allocated_samples>50</allocated_samples>
            </resourceLimitsQos>
        </topic>
    </profiles>
</dds>


text:
package org.apache.fluo.recipes.types;

import org.apache.fluo.api.data.Bytes;

/**
 * Transforms Java primitives to and from bytes using desired encoding
 *
 * @since 1.0.0
 */
public interface Encoder {

  /**
   * Encodes an integer to {@link Bytes}
   */
  Bytes encode(int i);

  /**
   * Encodes a long to {@link Bytes}
   */
  Bytes encode(long l);

  /**
   * Encodes a String to {@link Bytes}
   */
  Bytes encode(String s);

  /**
   * Encodes a float to {@link Bytes}
   */
  Bytes encode(float f);

  /**
   * Encodes a double to {@link Bytes}
   */
  Bytes encode(double d);

  /**
   * Encodes a boolean to {@link Bytes}
   */
  Bytes encode(boolean b);

  /**
   * Decodes an integer from {@link Bytes}
   */
  int decodeInteger(Bytes b);

  /**
   * Decodes a long from {@link Bytes}
   */
  long decodeLong(Bytes b);

  /**
   * Decodes a String from {@link Bytes}
   */
  String decodeString(Bytes b);

  /**
   * Decodes a float from {@link Bytes}
   */
  float decodeFloat(Bytes b);

  /**
   * Decodes a double from {@link Bytes}
   */
  double decodeDouble(Bytes b);

  /**
   * Decodes a boolean from {@link Bytes}
   */
  boolean decodeBoolean(Bytes b);
}


text:
require 'formula'

class OpenBabel < Formula
  homepage 'http://www.openbabel.org'
  url 'https://downloads.sourceforge.net/project/openbabel/openbabel/2.3.2/openbabel-2.3.2.tar.gz'
  sha1 'b8831a308617d1c78a790479523e43524f07d50d'

  option 'with-cairo',  'Support PNG depiction'
  option 'with-java',   'Compile Java language bindings'

  depends_on 'pkg-config' => :build
  depends_on 'cmake' => :build
  depends_on :python => :optional
  depends_on 'wxmac' => :optional
  depends_on 'cairo' => :optional
  depends_on 'eigen' if build.with?('python') || build.with?('java')

  # Patch to fix Molecule.draw() in pybel in accordance with upstream commit df59c4a630cf753723d1318c40479d48b7507e1c
  patch do
    url "https://gist.github.com/fredrikw/5858168/raw/e4b5899e781d5707f5c386e436b5fc7810f2010d/ob-2-3-2-patch.diff"
    sha1 "e304c308b39a465b632b397aa669c26f4b375da1"
  end

  # Patch to support Mavericks's libc++, a backport of upstream commit c3abbddae78e654df9322ad1020ff79dd6332946
  patch do
    url "https://gist.github.com/erlendurj/40689d57bea3b0b0c767/raw/f8c87557bcdbd79fb796e06088cdd77123c9260a/ob-mavericks.patch"
    sha1 "3ea95b20fdbe50f656f3073ef8916974495b569a"
  end

  def install
    args = %W[ -DCMAKE_INSTALL_PREFIX=#{prefix} ]
    args << "-DJAVA_BINDINGS=ON" if build.with? 'java'
    args << "-DBUILD_GUI=ON" if build.with? 'wxmac'
    # Looking for Cairo in HOMEBREW_PREFIX
    # setting the arguments separately, joining them in one string fails with the 'system "cmake", *args' command
    args << "-DCAIRO_INCLUDE_DIRS='#{HOMEBREW_PREFIX}/include/cairo'" if build.with? 'cairo'
    args << "-DCAIRO_LIBRARIES='#{HOMEBREW_PREFIX}/lib/libcairo.dylib'" if build.with? 'cairo'

    args << "-DPYTHON_BINDINGS=ON" if build.with? 'python'

    args << '..'

    mkdir 'build' do
      system "cmake", *args
      system "make"
      system "make install"
    end

    if build.with? 'python'
      (lib+'python2.7/site-packages').install lib/'openbabel.py', lib/'pybel.py', lib/'_openbabel.so'
    end
  end

  def caveats
    <<-EOS.undent
      Java libraries are installed to #{HOMEBREW_PREFIX}/lib so this path should be
      included in the CLASSPATH environment variable.
    EOS
  end

end


text:
package com.laurivan.dbflowlistview;

import com.raizlabs.android.dbflow.annotation.Column;
import com.raizlabs.android.dbflow.annotation.PrimaryKey;
import com.raizlabs.android.dbflow.annotation.Table;
import com.raizlabs.android.dbflow.structure.BaseModel;

/**
 * A sample table with an id (autoincrementing) and a name
 * Created by ivanlla on 22/10/2015.
 */
@Table(databaseName = SampleDatabase.NAME)
public class SampleTable extends BaseModel {

    @Column
    @PrimaryKey(autoincrement = true)
    long id;

    @Column
    String name;

}


text:
using SqlMapper.Common.Models;
using System.Collections.Generic;
using SqlMapper.Common.Abstracts;

namespace SqlMapper.Helpers
{
    internal class MapperMain<T> : IMapperMain<T>
    {
        public IList<GrouppingProperties> Groups { get; set; }
        public IList<T> ItemsList { get; set; }
        public bool AddToItems { get; set; }

        internal MapperMain()
        {
            Groups = new List<GrouppingProperties>();
            ItemsList = new List<T>();
        }

        public void Map(CommandResult data, T instance, IList<Property> typeProperties)
        {
            AddToItems = true;

            foreach (var property in typeProperties)
                property.Mapper.Map(instance, data, property, this);

            if (AddToItems)
                ItemsList.Add(instance);
        }
    }
}


text:
A small project to experiment with Pop and animate nicely a morphing button

## Screenshot/Preview

<img src="Screenshot/morphing-button.gif" width="240px" />

## References
Useful resources that I used for this small project:
* [Pop animation library](https://github.com/facebook/pop)
* [Popping examples](https://github.com/schneiderandre/popping)
* [Morphing button on codrops](http://tympanus.net/Development/ButtonComponentMorph/index.html)
* [Andrew McKay color scheme from Dribbble](https://dribbble.com/shots/1697494-Freebie-Psd-Flat-Ui-Kit)


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<rss version="2.0">
    <channel>
        <title>Physics - Saturday Physics for Everyone</title>
        <link>http://illinois.edu/calendar/list/75</link>
        <description>Saturday Physics for Everyone calendar</description>
    </channel>
</rss>


text:
package com.chrisrm.idea.ui;

import com.chrisrm.idea.MTConfig;
import com.chrisrm.idea.themes.models.MTThemeable;
import com.intellij.openapi.ui.GraphicsConfig;
import com.intellij.ui.ColorUtil;
import com.intellij.ui.components.OnOffButton;
import com.intellij.util.ui.GraphicsUtil;
import com.intellij.util.ui.JBDimension;
import com.intellij.util.ui.JBInsets;
import com.intellij.util.ui.JBUI;

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicToggleButtonUI;
import java.awt.*;

public class MTOnOffButtonUI extends BasicToggleButtonUI {
  private static final Dimension TOGGLE_SIZE = new JBDimension(18, 18);
  private static final Dimension BUTTON_SIZE = new JBDimension(32, 14);
  private static final Border BUTTON_BORDER = JBUI.Borders.empty(1, 10);

  public static ComponentUI createUI(final JComponent c) {
    c.setBorder(BUTTON_BORDER);
    return new MTOnOffButtonUI();
  }

  /**
   * The size of the switch
   *
   * @param c
   */
  @Override
  public Dimension getPreferredSize(final JComponent c) {
    final Dimension size = new Dimension(BUTTON_SIZE);
    JBInsets.addTo(size, BUTTON_BORDER.getBorderInsets(c));
    return size;
  }

  /**
   * Maximum size
   *
   * @param c
   */
  @Override
  public Dimension getMaximumSize(final JComponent c) {
    return getPreferredSize(c);
  }

  /**
   * Minimum size
   *
   * @param c
   */
  @Override
  public Dimension getMinimumSize(final JComponent c) {
    return getPreferredSize(c);
  }

  /**
   * Paint component
   *
   * @param g
   * @param c
   */
  @Override
  public void paint(final Graphics g, final JComponent c) {
    if (!(c instanceof OnOffButton)) {
      return;
    }

    final MTThemeable theme = MTConfig.getInstance().getSelectedTheme().getTheme();
    final Color bgColor = theme.getForegroundColor();
    final Color thumbColor = bgColor.brighter().brighter();
    final Color accentColor = ColorUtil.fromHex(MTConfig.getInstance().getAccentColor());
    final Color selectedAccentColor = accentColor.darker().darker();

    final OnOffButton b = (OnOffButton) c;
    final Graphics2D g2 = (Graphics2D) g.create();
    final GraphicsConfig config = GraphicsUtil.setupAAPainting(g2);

    try {
      final Insets i = c.getInsets();
      final Point origin = new Point((c.getWidth() - BUTTON_SIZE.width) / 2 + i.left,
          (c.getHeight() - BUTTON_SIZE.height) / 2 + i.top);

      // Background
      g2.setColor(b.isSelected() ? selectedAccentColor : bgColor);
      g2.fillRoundRect(origin.x, origin.y, BUTTON_SIZE.width, BUTTON_SIZE.height, 16, 16);

      // Fill
      g2.setColor(b.isSelected() ? accentColor : thumbColor);

      final Point location = new Point(
          (b.isSelected() ? JBUI.scale(20) : JBUI.scale(-2)) + origin.x,
          JBUI.scale(-2) + origin.y);
      g2.fillOval(location.x, location.y, TOGGLE_SIZE.width, TOGGLE_SIZE.height);

      config.restore();
    } finally {
      g2.dispose();
    }
  }
}


text:
"""
homeassistant.components.sensor.demo
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Demo platform that has a couple of fake sensors.
"""
from homeassistant.const import ATTR_BATTERY_LEVEL, TEMP_CELCIUS
from homeassistant.helpers.entity import Entity

# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
    """ Sets up the Demo sensors. """
    add_devices([
        DemoSensor('Outside Temperature', 15.6, TEMP_CELCIUS, 12),
        DemoSensor('Outside Humidity', 54, '%', None),
    ])

class DemoSensor(Entity):
    """ A Demo sensor. """

    def __init__(self, name, state, unit_of_measurement, battery):
        self._name = name
        self._state = state
        self._unit_of_measurement = unit_of_measurement
        self._battery = battery

    @property
    def should_poll(self):
        """ No polling needed for a demo sensor. """
        return False

    @property
    def name(self):
        """ Returns the name of the device. """
        return self._name

    @property
    def state(self):
        """ Returns the state of the device. """
        return self._state

    @property
    def unit_of_measurement(self):
        """ Unit this state is expressed in. """
        return self._unit_of_measurement

    @property
    def device_state_attributes(self):
        """ Returns the state attributes. """
        if self._battery:
            return {
                ATTR_BATTERY_LEVEL: self._battery,
            }


text:
<?php

namespace pami\Http\Controllers\Web;

use Illuminate\Http\Request;
use pami\Http\Controllers\Controller;
use pami\Post;
use pami\Category;

class PageController extends Controller
{
    public function blog(){
    	$posts= Post::orderBy('id','DESC')->where('status', 'PUBLISHED')->paginate(3);
    	return view ('web.posts', compact('posts'));
    }

    public function category($slug){
    	$category = Category::where('slug', $slug)->pluck('id')->first();
    	$posts    = Post::where('category_id', $category)
    		->orderBy('id', 'DESC')->where('status', 'PUBLISHED')->paginate(3);
    	return view ('web.posts', compact('posts'));
    }

    public function tag($slug){
    	$posts = Post::whereHas('tags', function($query) use($slug){
    		$query->where('slug', $slug);
    	})->orderBy('id', 'DESC')->where('status', 'PUBLISHED')->paginate(3);
    	return view ('web.posts', compact('posts'));
    }

    public function post($slug){
    	$post = Post::where('slug', $slug)->first();
    	return view ('web.post', compact('post'));
    }
}


text:
#include <stdio.h>
#include <errno.h>
#include <netdb.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
#include "iperf.h"
#include "iperf_api.h"

/* Do a printf to stderr. */
void
iperf_err(struct iperf_test *test, const char *format, ...)
{
    va_list argp;
    char str[1000];

    va_start(argp, format);
    vsnprintf(str, sizeof(str), format, argp);
    if (test != NULL && test->json_output && test->json_top != NULL)
	cJSON_AddStringToObject(test->json_top, "error", str);
    else
	if (test && test->outfile) {
	    fprintf(test->outfile, "iperf3: %s\n", str);
	}
	else {
	    fprintf(stderr, "iperf3: %s\n", str);
	}
    va_end(argp);
}

/* Do a printf to stderr or log file as appropriate, then exit. */
void
iperf_errexit(struct iperf_test *test, const char *format, ...)
{
    va_list argp;
    char str[1000];

    va_start(argp, format);
    vsnprintf(str, sizeof(str), format, argp);
    if (test != NULL && test->json_output && test->json_top != NULL) {
	cJSON_AddStringToObject(test->json_top, "error", str);
	iperf_json_finish(test);
    } else
	if (test && test->outfile) {
	    fprintf(test->outfile, "iperf3: %s\n", str);
	}
	else {
	    fprintf(stderr, "iperf3: %s\n", str);
	}
    va_end(argp);
    iperf_delete_pidfile(test);
    exit(1);
}

int i_errno;

char *
iperf_strerror(int i_errno)
{
    static char errstr[256];
    int len, perr, herr;
    perr = herr = 0;

    len = sizeof(errstr);
    memset(errstr, 0, len);

    switch (i_errno) {
        case IENONE:
            snprintf(errstr, len, "no error");
            break;
        case IESERVCLIENT:
            snprintf(errstr, len, "cannot be both server and client");
            break;
        case IENOROLE:
            snprintf(errstr, len, "must either be a client (-c) or server (-s)");
            break;
        case IESERVERONLY:
            snprintf(errstr, len, "some option you are trying to set is server only");
            break;
        case IECLIENTONLY:
            snprintf(errstr, len, "some option you are trying to set is client only");
            break;
        case IEDURATION:
            snprintf(errstr, len, "test duration too long (maximum = %d seconds)", MAX_TIME);
            break;
        case IENUMSTREAMS:
            snprintf(errstr, len, "number of parallel streams too large (maximum = %d)", MAX_STREAMS);
            break;
        case IEBLOCKSIZE:
            snprintf(errstr, len, "block size too large (maximum = %d bytes)", MAX_BLOCKSIZE);
            break;
        case IEBUFSIZE:
            snprintf(errstr, len, "socket buffer size too large (maximum = %d bytes)", MAX_TCP_BUFFER);
            break;
        case IEINTERVAL:
            snprintf(errstr, len, "invalid report interval (min = %g, max = %g seconds)", MIN_INTERVAL, MAX_INTERVAL);
            break;
        case IEBIND:
            snprintf(errstr, len, "--bind must be specified to use --cport");
            break;
        case IEUDPBLOCKSIZE:
            snprintf(errstr, len, "block size too large (maximum = %d bytes)", MAX_UDP_BLOCKSIZE);
            break;
        case IEMSS:
            snprintf(errstr, len, "TCP MSS too large (maximum = %d bytes)", MAX_MSS);
            break;
        case IENOSENDFILE:
            snprintf(errstr, len, "this OS does not support sendfile");
            break;
        case IEOMIT:
            snprintf(errstr, len, "bogus value for --omit");
            break;
        case IEUNIMP:
            snprintf(errstr, len, "an option you are trying to set is not implemented yet");
            break;
        case IEFILE:
            snprintf(errstr, len, "unable to open -F file");
            perr = 1;
            break;
        case IEBURST:
            snprintf(errstr, len, "invalid burst count (maximum = %d)", MAX_BURST);
            break;
        case IEENDCONDITIONS:
            snprintf(errstr, len, "only one test end condition (-t, -n, -k) may be specified");
            break;
	case IELOGFILE:
	    snprintf(errstr, len, "unable to open log file");
	    perr = 1;
	    break;
	case IENOSCTP:
	    snprintf(errstr, len, "no SCTP support available");
	    break;
        case IENEWTEST:
            snprintf(errstr, len, "unable to create a new test");
            perr = 1;
            break;
        case IEINITTEST:
            snprintf(errstr, len, "test initialization failed");
            perr = 1;
            break;
        case IELISTEN:
            snprintf(errstr, len, "unable to start listener for connections");
            perr = 1;
            break;
        case IECONNECT:
            snprintf(errstr, len, "unable to connect to server");
            perr = 1;
            break;
        case IEACCEPT:
            snprintf(errstr, len, "unable to accept connection from client");
            herr = 1;
            perr = 1;
            break;
        case IESENDCOOKIE:
            snprintf(errstr, len, "unable to send cookie to server");
            perr = 1;
            break;
        case IERECVCOOKIE:
            snprintf(errstr, len, "unable to receive cookie at server");
            perr = 1;
            break;
        case IECTRLWRITE:
            snprintf(errstr, len, "unable to write to the control socket");
            perr = 1;
            break;
        case IECTRLREAD:
            snprintf(errstr, len, "unable to read from the control socket");
            perr = 1;
            break;
        case IECTRLCLOSE:
            snprintf(errstr, len, "control socket has closed unexpectedly");
            break;
        case IEMESSAGE:
            snprintf(errstr, len, "received an unknown control message");
            break;
        case IESENDMESSAGE:
            snprintf(errstr, len, "unable to send control message");
            perr = 1;
            break;
        case IERECVMESSAGE:
            snprintf(errstr, len, "unable to receive control message");
            perr = 1;
            break;
        case IESENDPARAMS:
            snprintf(errstr, len, "unable to send parameters to server");
            perr = 1;
            break;
        case IERECVPARAMS:
            snprintf(errstr, len, "unable to receive parameters from client");
            perr = 1;
            break;
        case IEPACKAGERESULTS:
            snprintf(errstr, len, "unable to package results");
            perr = 1;
            break;
        case IESENDRESULTS:
            snprintf(errstr, len, "unable to send results");
            perr = 1;
            break;
        case IERECVRESULTS:
            snprintf(errstr, len, "unable to receive results");
            perr = 1;
            break;
        case IESELECT:
            snprintf(errstr, len, "select failed");
            perr = 1;
            break;
        case IECLIENTTERM:
            snprintf(errstr, len, "the client has terminated");
            break;
        case IESERVERTERM:
            snprintf(errstr, len, "the server has terminated");
            break;
        case IEACCESSDENIED:
            snprintf(errstr, len, "the server is busy running a test. try again later");
            break;
        case IESETNODELAY:
            snprintf(errstr, len, "unable to set TCP/SCTP NODELAY");
            perr = 1;
            break;
        case IESETMSS:
            snprintf(errstr, len, "unable to set TCP/SCTP MSS");
            perr = 1;
            break;
        case IESETBUF:
            snprintf(errstr, len, "unable to set socket buffer size");
            perr = 1;
            break;
        case IESETTOS:
            snprintf(errstr, len, "unable to set IP TOS");
            perr = 1;
            break;
        case IESETCOS:
            snprintf(errstr, len, "unable to set IPv6 traffic class");
            perr = 1;
            break;
        case IESETFLOW:
            snprintf(errstr, len, "unable to set IPv6 flow label");
            break;
        case IEREUSEADDR:
            snprintf(errstr, len, "unable to reuse address on socket");
            perr = 1;
            break;
        case IENONBLOCKING:
            snprintf(errstr, len, "unable to set socket to non-blocking");
            perr = 1;
            break;
        case IESETWINDOWSIZE:
            snprintf(errstr, len, "unable to set socket window size");
            perr = 1;
            break;
        case IEPROTOCOL:
            snprintf(errstr, len, "protocol does not exist");
            break;
        case IEAFFINITY:
            snprintf(errstr, len, "unable to set CPU affinity");
            perr = 1;
            break;
	case IEDAEMON:
	    snprintf(errstr, len, "unable to become a daemon");
	    perr = 1;
	    break;
        case IECREATESTREAM:
            snprintf(errstr, len, "unable to create a new stream");
            herr = 1;
            perr = 1;
            break;
        case IEINITSTREAM:
            snprintf(errstr, len, "unable to initialize stream");
            herr = 1;
            perr = 1;
            break;
        case IESTREAMLISTEN:
            snprintf(errstr, len, "unable to start stream listener");
            perr = 1;
            break;
        case IESTREAMCONNECT:
            snprintf(errstr, len, "unable to connect stream");
            herr = 1;
            perr = 1;
            break;
        case IESTREAMACCEPT:
            snprintf(errstr, len, "unable to accept stream connection");
            perr = 1;
            break;
        case IESTREAMWRITE:
            snprintf(errstr, len, "unable to write to stream socket");
            perr = 1;
            break;
        case IESTREAMREAD:
            snprintf(errstr, len, "unable to read from stream socket");
            perr = 1;
            break;
        case IESTREAMCLOSE:
            snprintf(errstr, len, "stream socket has closed unexpectedly");
            break;
        case IESTREAMID:
            snprintf(errstr, len, "stream has an invalid id");
            break;
        case IENEWTIMER:
            snprintf(errstr, len, "unable to create new timer");
            perr = 1;
            break;
        case IEUPDATETIMER:
            snprintf(errstr, len, "unable to update timer");
            perr = 1;
            break;
        case IESETCONGESTION:
            snprintf(errstr, len, "unable to set TCP_CONGESTION: "
                                  "Supplied congestion control algorithm not supported on this host");
            break;
	case IEPIDFILE:
            snprintf(errstr, len, "unable to write PID file");
            perr = 1;
            break;
	case IEV6ONLY:
	    snprintf(errstr, len, "Unable to set/reset IPV6_V6ONLY");
	    perr = 1;
	    break;
        case IESETSCTPDISABLEFRAG:
            snprintf(errstr, len, "unable to set SCTP_DISABLE_FRAGMENTS");
            perr = 1;
            break;
        case IESETSCTPNSTREAM:
            snprintf(errstr, len, "unable to set SCTP_INIT num of SCTP streams\n");
            perr = 1;
            break;
    }

    if (herr || perr)
        strncat(errstr, ": ", len - strlen(errstr) - 1);
    if (h_errno && herr) {
        strncat(errstr, hstrerror(h_errno), len - strlen(errstr) - 1);
    } else if (errno && perr) {
        strncat(errstr, strerror(errno), len - strlen(errstr) - 1);
    }

    return errstr;
}


text:
package org.apache.commons.math3.util;

import org.apache.commons.math3.exception.DimensionMismatchException;
import org.apache.commons.math3.exception.OutOfRangeException;
import org.apache.commons.math3.exception.NotStrictlyPositiveException;
import org.junit.Assert;
import org.junit.Test;

/**
 *
 */
public class MultidimensionalCounterTest {
    @Test
    public void testPreconditions() {
        MultidimensionalCounter c;

        try {
            c = new MultidimensionalCounter(0, 1);
            Assert.fail("NotStrictlyPositiveException expected");
        } catch (NotStrictlyPositiveException e) {
            // Expected.
        }
        try {
            c = new MultidimensionalCounter(2, 0);
            Assert.fail("NotStrictlyPositiveException expected");
        } catch (NotStrictlyPositiveException e) {
            // Expected.
        }
        try {
            c = new MultidimensionalCounter(-1, 1);
            Assert.fail("NotStrictlyPositiveException expected");
        } catch (NotStrictlyPositiveException e) {
            // Expected.
        }

        c = new MultidimensionalCounter(2, 3);
        try {
            c.getCount(1, 1, 1);
            Assert.fail("DimensionMismatchException expected");
        } catch (DimensionMismatchException e) {
            // Expected.
        }
        try {
            c.getCount(3, 1);
            Assert.fail("OutOfRangeException expected");
        } catch (OutOfRangeException e) {
            // Expected.
        }
        try {
            c.getCount(0, -1);
            Assert.fail("OutOfRangeException expected");
        } catch (OutOfRangeException e) {
            // Expected.
        }
        try {
            c.getCounts(-1);
            Assert.fail("OutOfRangeException expected");
        } catch (OutOfRangeException e) {
            // Expected.
        }
        try {
            c.getCounts(6);
            Assert.fail("OutOfRangeException expected");
        } catch (OutOfRangeException e) {
            // Expected.
        }
    }

    @Test
    public void testIteratorPreconditions() {
        MultidimensionalCounter.Iterator iter = (new MultidimensionalCounter(2, 3)).iterator();
        try {
            iter.getCount(-1);
            Assert.fail("IndexOutOfBoundsException expected");
        } catch (IndexOutOfBoundsException e) {
            // Expected.
        }
        try {
            iter.getCount(2);
            Assert.fail("IndexOutOfBoundsException expected");
        } catch (IndexOutOfBoundsException e) {
            // Expected.
        }
    }

    @Test
    public void testMulti2UniConversion() {
        final MultidimensionalCounter c = new MultidimensionalCounter(2, 4, 5);
        Assert.assertEquals(c.getCount(1, 2, 3), 33);
    }

    @Test
    public void testAccessors() {
        final int[] originalSize = new int[] {2, 6, 5};
        final MultidimensionalCounter c = new MultidimensionalCounter(originalSize);
        final int nDim = c.getDimension();
        Assert.assertEquals(nDim, originalSize.length);

        final int[] size = c.getSizes();
        for (int i = 0; i < nDim; i++) {
            Assert.assertEquals(originalSize[i], size[i]);
        }
    }

    @Test
    public void testIterationConsistency() {
        final MultidimensionalCounter c = new MultidimensionalCounter(2, 3, 4);
        final int[][] expected = new int[][] {
            { 0, 0, 0 },
            { 0, 0, 1 },
            { 0, 0, 2 },
            { 0, 0, 3 },
            { 0, 1, 0 },
            { 0, 1, 1 },
            { 0, 1, 2 },
            { 0, 1, 3 },
            { 0, 2, 0 },
            { 0, 2, 1 },
            { 0, 2, 2 },
            { 0, 2, 3 },
            { 1, 0, 0 },
            { 1, 0, 1 },
            { 1, 0, 2 },
            { 1, 0, 3 },
            { 1, 1, 0 },
            { 1, 1, 1 },
            { 1, 1, 2 },
            { 1, 1, 3 },
            { 1, 2, 0 },
            { 1, 2, 1 },
            { 1, 2, 2 },
            { 1, 2, 3 }
        };

        final int totalSize = c.getSize();
        final int nDim = c.getDimension();
        final MultidimensionalCounter.Iterator iter = c.iterator();
        for (int i = 0; i < totalSize; i++) {
            if (!iter.hasNext()) {
                Assert.fail("Too short");
            }
            final int uniDimIndex = iter.next();
            Assert.assertEquals("Wrong iteration at " + i, i, uniDimIndex);

            for (int dimIndex = 0; dimIndex < nDim; dimIndex++) {
                Assert.assertEquals("Wrong multidimensional index for [" + i + "][" + dimIndex + "]",
                                    expected[i][dimIndex], iter.getCount(dimIndex));
            }

            Assert.assertEquals("Wrong unidimensional index for [" + i + "]",
                                c.getCount(expected[i]), uniDimIndex);

            final int[] indices = c.getCounts(uniDimIndex);
            for (int dimIndex = 0; dimIndex < nDim; dimIndex++) {
                Assert.assertEquals("Wrong multidimensional index for [" + i + "][" + dimIndex + "]",
                                    expected[i][dimIndex], indices[dimIndex]);
            }
        }

        if (iter.hasNext()) {
            Assert.fail("Too long");
        }
    }
}


text:
@protocol JLYInteractorInput <JLYBaseInteractorIO>

- (void)jly_doSomething;

@end

@protocol JLYInteractorOutput <JLYBaseInteractorIO>

@end


text:
Given(/^an envelope with a document constucted in ruby$/) do
  @envelope = Philographer::Envelope.new({
    emailBlurb: 'Test email is testing',
    emailSubject: 'Test email',
  })
  path = File.expand_path('../../../spec/test_files/basic.pdf', __FILE__)
  @envelope.documents << Philographer::Document.new({
    path: path.to_s,
    id: 1
  })

  recipient = Philographer::Recipient.new({
    type: 'signer',
    email: 'test@test.com',
    name: 'Jon Doe'
  })
  recipient.tabs << Philographer::Tab.new({
    type: 'signHere',
    x_position: 100,
    y_position: 100,
    document_id: 1,
    page_number: 1
  })
  @envelope.recipients << recipient
end

When(/^the constucted envelope has been submitted to DocuSign$/) do
  load_credentials(true)
  @envelope.save
end

Then(/^the envelope should have the DocuSign ID available$/) do
  @envelope.id.wont_be_nil
end

Given(/^an envelope with a template constructed in ruby$/) do
  @envelope = Philographer::Envelope.new({
    status: 'sent',
    template_id: "2912c004-7aea-4305-8ec7-3e58ac444b30"
  })

  recipient = Philographer::TemplateRole.new({
    role_name: 'mySigner',
    email: 'test@test.com',
    name: 'Jon Doe'
  })

  @envelope.template_roles << recipient
end

When(/^a philographer user has requested data on envelopes$/) do
  load_credentials(true)
  @envelopes = Philographer::Envelope.fetch(from_date: Date.civil(2013), status: 'Completed')
end

Then(/^an array of relevant envelope objects should be retrieved$/) do
  assert @envelopes.all?{|e| e.is_a?(Philographer::Envelope)}, "Expected all returned objects to be of type Philographer::Envelope, instead found: #{@envelopes.map{|e| e.class}.inspect}"
end


text:
from results.models import Drawing, PrizesWon, GroupTicket
import datetime

def calcprize(numnumbers, megaball):
    if numnumbers==5 and megaball:
        return 15000000
    if numnumbers==5 and not megaball:
        return 1000000
    if numnumbers==4 and megaball:
        return 5000
    if numnumbers==4 and not megaball:
        return 500
    if numnumbers==3 and megaball:
        return 50
    if numnumbers==3 and not megaball:
        return 5
    if numnumbers==2 and megaball:
        return 5
    if numnumbers==1 and megaball:
        return 2
    if numnumbers==0 and megaball:
        return 1
    else:
        return None

def calcprizeAfterNovember2017(numnumbers, megaball):
    if numnumbers==5 and megaball:
        return 15000000
    if numnumbers==5 and not megaball:
        return 1000000
    if numnumbers==4 and megaball:
        return 10000
    if numnumbers==4 and not megaball:
        return 500
    if numnumbers==3 and megaball:
        return 200
    if numnumbers==3 and not megaball:
        return 10
    if numnumbers==2 and megaball:
        return 10
    if numnumbers==1 and megaball:
        return 4
    if numnumbers==0 and megaball:
        return 2
    else:
        return None

def checkprize(drawingid,ticketid):
    a = Drawing.objects.get(pk=drawingid)
    b = GroupTicket.objects.get(pk=ticketid)
    nummatch = 0
    megamatch = False
    for val in b.numbers_as_list():
        if val in a.numbers_as_list():
            nummatch = nummatch + 1
    if b.megaBall==a.megaBall:
        megamatch=True
    if a.drawingDate > datetime.date(2017, 10, 31):
        prizeamount = calcprizeAfterNovember2017(numnumbers=nummatch, megaball=megamatch)
    else:
        prizeamount = calcprize(numnumbers=nummatch, megaball=megamatch)
    if prizeamount:
        c = PrizesWon(drawing=a,ticket=b,groupPrizeAmount=prizeamount)
        c.save()
        print (c)


text:
import re
from playbook import *

class Event(object):

    def __init__(self, strategy, reason, snap):
        self.strategy = strategy
        self.reason = reason
        self.snap = snap
        self.action = None

    def add_action(self, a):
        if self.action is None:
            self.action = []
        self.action.append(a)

    def format(self):
        return {
            "strategy": self.strategy,
            "action": self.action,
            "reason": self.reason,
            "snap": self.snap
            }

    def __str__(self):
        return self.format()

class History(HookState):

    def __init__(self, hook, sudoku):
        HookState.__init__(self, hook)
        self.sudoku = sudoku
        self.events = list()

    """
    Return the last event in the history if it matches the
    specified strategy and reason.
    """
    def find_event(self, strategy, reason):
        if self.events:
            event = self.events[-1]
            if event.reason is reason and event.strategy is strategy:
                return event
        return None

    """
    Record the specified action in the history. It may be part
    of an existing event or a new one.
    """
    def record_action(self, strategy, reason, action):
        event = self.find_event(strategy, reason)
        if not event:
            snap = self.sudoku.save()
            event = Event(strategy, reason, snap)
            self.events.append(event)
        if action:
            event.add_action(action)

    def format(self):
        return [x.format() for x in self.events];

    def __str__(self):
        return self.format()

class Snap(Hook):

    __metaclass__ = HookMeta

    def __init__(self):
        Hook.__init__(self, "SNAP")

    def pre_run(self, plan, strategy):
        return True

    def post_run(self, plan, strategy, status):
        if plan.get_sudoku().is_complete():
            self.snap(plan, strategy, "final", None)
        return True

    def pre_update(self, plan, strategy, reason, action):
        self.snap(plan, strategy, reason, action)
        return True

    def post_update(self, plan, strategy, reason, action):
        return True

    def snap(self, plan, strategy, reason, action):
        parm = plan.get_parm(self)
        if parm and not re.match(parm, strategy.get_name()):
            return True
        if strategy.get_name() == "SINGLETON" or not reason:
            return True
        # Skip all trial and error strategies.
        if strategy.get_name().startswith("TRIAL"):
            return True
        history = plan.get_attr(self)
        if not history:
            history = History(self, plan.get_sudoku())
            plan.set_attr(self, history)
        history.record_action(strategy, reason, action)

    """
    Enable the SNAP hook by default since the web based UI relies
    on the JSON output it generates.
    """
    def default(self):
        return True


text:
namespace Google.Cloud.OsLogin.V1.Snippets
{
    // [START oslogin_v1_generated_OsLoginService_DeletePosixAccount_sync_flattened]
    using Google.Cloud.OsLogin.V1;

    public sealed partial class GeneratedOsLoginServiceClientSnippets
    {
        /// <summary>Snippet for DeletePosixAccount</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public void DeletePosixAccount()
        {
            // Create client
            OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create();
            // Initialize request argument(s)
            string name = "users/[USER]/projects/[PROJECT]";
            // Make the request
            osLoginServiceClient.DeletePosixAccount(name);
        }
    }
    // [END oslogin_v1_generated_OsLoginService_DeletePosixAccount_sync_flattened]
}


text:
var events = require('../events');
var query = require('../rest/budgets');

function BudgetCollection() {
  this.poplarBudgets = [];
  this.budgetIds = [];

  // main data hash, currently stored in memory
  this.data = {};

  this.clear = function() {
    this.data = {};
    this.budgetIds = [];
  }

  this.get = function(id) {
    if( this.data[id] ) return this.data[id];
    for( var i = 0; i < this.poplarBudgets.length; i++ ) {
      if( this.poplarBudgets[i].budget.getId() === id ) return this.poplarBudgets[i];
    }
  }

  // called by parcels collection
  this.addBudgetId = function(id) {
    if( this.budgetIds.indexOf(id) > -1 ) return;
    this.budgetIds.push(id);
  }

  this.load = function(callback) {
    events.emit('budgets-update-start');

    // this uses the budgetsId array which is set by
    query.getAll(this, (data) => {
      this.data = data;
      events.emit('budgets-update-end');
      if( callback ) callback();
    });
  };

  this.setPoplarBudgets = function(budgets) {
    this.poplarBudgets = budgets;
  }

  this.getPoplarBudget = function(pyield) {
    for( var i = 0; i < this.poplarBudgets.length; i++ ) {
      if( pyield >= this.poplarBudgets[i].lowerBound && pyield <= this.poplarBudgets[i].upperBound ) {
        return this.poplarBudgets[i];
      }
    }

    // console.warn('No poplar budget for yield: '+pyield);
    return this.poplarBudgets[0];
  }

  events.on('get-budget', (e) => {
    e.handler(this.get(e.id));
  });

}

module.exports = new BudgetCollection();


text:
package com.iluwatar.ambassador;

/**
 * Interface shared by ({@link RemoteService}) and ({@link ServiceAmbassador}).
 */
interface RemoteServiceInterface {
  int FAILURE = -1;

  long doRemoteFunction(int value) throws Exception;
}


text:
class Qt < Formula
  desc "Cross-platform application and UI framework"
  homepage "https://www.qt.io/"
  revision 1

  stable do
    url "https://download.qt.io/official_releases/qt/4.8/4.8.7/qt-everywhere-opensource-src-4.8.7.tar.gz"
    mirror "https://www.mirrorservice.org/sites/download.qt-project.org/official_releases/qt/4.8/4.8.7/qt-everywhere-opensource-src-4.8.7.tar.gz"
    sha256 "e2882295097e47fe089f8ac741a95fef47e0a73a3f3cdf21b56990638f626ea0"
  end

  bottle do
    sha256 "48e2e4d7f4659409c74e6acb9b59fdf9ab5d8e4b7f9b438a73e3d0ca03635e93" => :el_capitan
    sha256 "8e041b0a48c8a0785022c8a77e8c40efeb9d57cd701b635cc0a7ce46692c0c5f" => :yosemite
    sha256 "fe687f9a9b657d33b7c11ad4ccd7208deddd8e96d2104df2df98de13b0c5d5d7" => :mavericks
  end

  # Backport of Qt5 commit to fix the fatal build error on OS X El Capitan.
  # http://code.qt.io/cgit/qt/qtbase.git/commit/?id=b06304e164ba47351fa292662c1e6383c081b5ca
  if MacOS.version >= :el_capitan
    patch do
      url "https://raw.githubusercontent.com/Homebrew/patches/480b7142c4e2ae07de6028f672695eb927a34875/qt/el-capitan.patch"
      sha256 "c8a0fa819c8012a7cb70e902abb7133fc05235881ce230235d93719c47650c4e"
    end
  end

  head "https://code.qt.io/qt/qt.git", :branch => "4.8"

  option :universal
  option "with-qt3support", "Build with deprecated Qt3Support module support"
  option "with-docs", "Build documentation"
  option "with-developer", "Build and link with developer options"

  depends_on "openssl"
  depends_on "d-bus" => :optional
  depends_on "mysql" => :optional
  depends_on "postgresql" => :optional

  deprecated_option "qtdbus" => "with-d-bus"
  deprecated_option "developer" => "with-developer"

  resource "test-project" do
    url "https://gist.github.com/tdsmith/f55e7e69ae174b5b5a03.git",
        :revision => "6f565390395a0259fa85fdd3a4f1968ebcd1cc7d"
  end

  def install
    ENV.universal_binary if build.universal?

    # Fix this error:
    # /bin/ld: warning: libQtCLucene.so.4, needed by libQtHelp.so, not found
    # libQtHelp.so: undefined reference to `QCLuceneIndexWriter::setMergeFactor(int)'
    ENV["LD_LIBRARY_PATH"] = buildpath/"lib" if OS.linux?

    args = ["-prefix", prefix,
            "-system-zlib",
            "-qt-libtiff", "-qt-libpng", "-qt-libjpeg",
            "-confirm-license", "-opensource",
            "-nomake", "demos", "-nomake", "examples",
            "-cocoa", "-fast", "-release"]

    if ENV.compiler == :clang
      args << "-platform"

      if MacOS.version >= :mavericks
        args << "unsupported/macx-clang-libc++"
      else
        args << "unsupported/macx-clang"
      end
    end

    args << "-openssl-linked"
    args << "-I" << Formula["openssl"].opt_include
    args << "-L" << Formula["openssl"].opt_lib

    args << "-plugin-sql-mysql" if build.with? "mysql"
    args << "-plugin-sql-psql" if build.with? "postgresql"

    if build.with? "d-bus"
      dbus_opt = Formula["d-bus"].opt_prefix
      args << "-I#{dbus_opt}/lib/dbus-1.0/include"
      args << "-I#{dbus_opt}/include/dbus-1.0"
      args << "-L#{dbus_opt}/lib"
      args << "-ldbus-1"
      args << "-dbus-linked"
    end

    if build.with? "qt3support"
      args << "-qt3support"
    else
      args << "-no-qt3support"
    end

    args << "-nomake" << "docs" if build.without? "docs"

    if MacOS.prefer_64_bit? || build.universal?
      args << "-arch" << "x86_64"
    end

    if !MacOS.prefer_64_bit? || build.universal?
      args << "-arch" << "x86"
    end

    args << "-developer-build" if build.with? "developer"

    system "./configure", *args
    system "make"
    ENV.j1
    system "make", "install"

    # what are these anyway?
    (bin+"pixeltool.app").rmtree if OS.mac?
    (bin+"qhelpconverter.app").rmtree if OS.mac?
    # remove porting file for non-humans
    (prefix+"q3porting.xml").unlink if build.without? "qt3support"

    # Some config scripts will only find Qt in a "Frameworks" folder
    frameworks.install_symlink Dir["#{lib}/*.framework"]

    # The pkg-config files installed suggest that headers can be found in the
    # `include` directory. Make this so by creating symlinks from `include` to
    # the Frameworks' Headers folders.
    Pathname.glob("#{lib}/*.framework/Headers") do |path|
      include.install_symlink path => path.parent.basename(".framework")
    end

    Pathname.glob("#{bin}/*.app") { |app| mv app, prefix }
  end

  test do
    Encoding.default_external = "UTF-8" unless RUBY_VERSION.start_with? "1."
    resource("test-project").stage testpath
    system bin/"qmake"
    system "make"
    assert_match /GitHub/, pipe_output(testpath/"qtnetwork-test 2>&1", nil, 0)
  end

  def caveats; <<-EOS.undent
    We agreed to the Qt opensource license for you.
    If this is unacceptable you should uninstall.
    EOS
  end
end


text:
package engineer.echo.bigandroid;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ScrollView;

/**
 * 分红全球购
 * 青岛芳林信息版权所有
 * author:Created by Plucky on 16/10/18-下午5:19.
 * 功能描述: 为了扩展滑动监听
 */
public class EEScrollView extends ScrollView {

    public EEScrollView(Context context) {
        this(context, null);
    }

    public EEScrollView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public EEScrollView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        if (listener != null) {
            listener.onEEChange(l, t, oldl, oldt);
        }
    }

    private EEScrollChangeListener listener;

    public void setListener(EEScrollChangeListener listener) {
        this.listener = listener;
    }

    public interface EEScrollChangeListener {
        void onEEChange(int l, int t, int oldl, int oldt);
    }
}


text:
import { TestBed, inject } from '@angular/core/testing';

import { Service819Service } from './service-819.service';

describe('Service819Service', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [Service819Service]
    });
  });

  it('should ...', inject([Service819Service], (service: Service819Service) => {
    expect(service).toBeTruthy();
  }));
});


text:
<!DOCTYPE html>

    <link type="text/css" rel="stylesheet" href="../stylesheets/blog-stylesheet.css"/>

Anthony's Blog

Week 7: My 7th Cultural Blog

Affirmation and Stereotype Threat

Established Nov 2nd, 2014

When I think of the last time in my life where I've been the happiest, the proudest. and the most satisfied, the following values come to my mind:

Accomplishment

I like having the feeling of accomplishment. It always makes you fell happy, proud, and satistied. It is because when you set some goal for yourself, you are expecting yourself to accomplish it no matter what obstacles you have out there. Therefore, when you were able to accomplish something, it shows that you have the ability to promise yourself. It tells yourself that you are capable of doing something difficult.

Confidence

Having confidence is very important to me. It is because I always believe that when you are happy, you are always confident during that moment. Being confident about something means you have faith about it, you are good at it, and you are willing to accomplish it no matter what. Thus, being confident in your life is very important, especially during some important moment in your life: Taking an exam, Meeting someone important, Doing something impactful, etc. Sometimes, I believe that the more confident you are, the more happier you are.

Reputation

People wants reputation. I can think of reputation is the value of your personal brand. The more reputation you have, the better your personal brand is. So that also means if you have a very high reputation, people will believe that you are credible, reliable, trustable and powerful. Therefore, when I felt like I was proudest person in the world, I actually believe I have a very high value of reputation among all others.

In summary, I strongly agree those values I mentioned above. If I have to rate, it would be 5 on a scale of 1 to 5

The last topic that someone asked my advice on was my friend who needed to decide whether he should go back to his hometown while giving up the legal status in the United States. Since that is a very serious topic, I tried to analyze the pros and cons of both optiopns with him. I believe I successfully express the values I mentioned above: Confidence and Reputation because thats probably why my friend had decided to come to me and ask for advice. Eventually, we were able to come up witha a conclusion where he could make the finally decision.

So this is what I think of values. What value do you agree?

About

Linked In

Twitter

GitHub

Facebook


text:
FROM openjdk:8
VOLUME /tmp
ADD build/libs/poly-gateway-0.1.0-SNAPSHOT.jar unidev-poly-gateway.jar
RUN sh -c 'touch /unidev-poly-gateway.jar'
ENV JAVA_OPTS="-server -XX:+UseG1GC -Xmx128M -Dspring.profiles.active=production"
ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /unidev-poly-gateway.jar" ]


text:
package com.pavelsklenar.spring.exploit.example;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class WebsiteUser {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private String name;
    private String email;

    // standard getters and setters
}


text:
class Test : public QObject
{
    Q_OBJECT
public:
    explicit Test(QObject *parent = 0);

private slots:
    void outputRtuTest();
    void outputAsciiTest();
    void outputTcpTest();
    void inputRtuTest();
    void inputAsciiTest();
    void inputTcpTest();

};

#endif // TEST_H


text:
package org.apache.flink.api.java.typeutils;

import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.flink.api.common.typeinfo.AtomicType;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.common.typeutils.CompositeType;
import org.apache.flink.api.java.operators.Keys.ExpressionKeys;

import com.google.common.base.Preconditions;

public abstract class TupleTypeInfoBase<T> extends CompositeType<T> {

	protected final TypeInformation<?>[] types;

	protected final Class<T> tupleType;

	private int totalFields;

	public TupleTypeInfoBase(Class<T> tupleType, TypeInformation<?>... types) {
		super(tupleType);
		this.tupleType = tupleType;
		this.types = types;
		for(TypeInformation<?> type : types) {
			totalFields += type.getTotalFields();
		}
	}

	@Override
	public boolean isBasicType() {
		return false;
	}

	@Override
	public boolean isTupleType() {
		return true;
	}

	@Override
	public int getArity() {
		return types.length;
	}

	@Override
	public int getTotalFields() {
		return totalFields;
	}

	@Override
	public Class<T> getTypeClass() {
		return tupleType;
	}

	/**
	 * Recursively add all fields in this tuple type. We need this in particular to get all
	 * the types.
	 * @param keyId
	 * @param keyFields
	 */
	public void addAllFields(int startKeyId, List<FlatFieldDescriptor> keyFields) {
		for(int i = 0; i < this.getArity(); i++) {
			TypeInformation<?> type = this.types[i];
			if(type instanceof AtomicType) {
				keyFields.add(new FlatFieldDescriptor(startKeyId, type));
			} else if(type instanceof TupleTypeInfoBase<?>) {
				TupleTypeInfoBase<?> ttb = (TupleTypeInfoBase<?>) type;
				ttb.addAllFields(startKeyId, keyFields);
			}
			startKeyId += type.getTotalFields();
		}
	}

	@Override
	public void getKey(String fieldExpression, int offset, List<FlatFieldDescriptor> result) {
		// handle 'select all'
		if(fieldExpression.equals(ExpressionKeys.SELECT_ALL_CHAR) || fieldExpression.equals(ExpressionKeys.SELECT_ALL_CHAR_SCALA)) {
			int keyPosition = 0;
			for(TypeInformation<?> type : types) {
				if(type instanceof AtomicType) {
					result.add(new FlatFieldDescriptor(offset + keyPosition, type));
				} else if(type instanceof CompositeType) {
					CompositeType<?> cType = (CompositeType<?>)type;
					cType.getKey(String.valueOf(ExpressionKeys.SELECT_ALL_CHAR), offset + keyPosition, result);
					keyPosition += cType.getTotalFields()-1;
				} else {
					throw new RuntimeException("Unexpected key type: "+type);
				}
				keyPosition++;
			}
			return;
		}
		// check input
		if(fieldExpression.length() < 2) {
			throw new IllegalArgumentException("The field expression '"+fieldExpression+"' is incorrect. The length must be at least 2");
		}
		if(fieldExpression.charAt(0) != 'f') {
			throw new IllegalArgumentException("The field expression '"+fieldExpression+"' is incorrect for a Tuple type. It has to start with an 'f'");
		}
		// get first component of nested expression
		int dotPos = fieldExpression.indexOf('.');
		String nestedSplitFirst = fieldExpression;
		if(dotPos != -1 ) {
			Preconditions.checkArgument(dotPos != fieldExpression.length()-1, "The field expression can never end with a dot.");
			nestedSplitFirst = fieldExpression.substring(0, dotPos);
		}
		String fieldNumStr = nestedSplitFirst.substring(1, nestedSplitFirst.length());
		if(!StringUtils.isNumeric(fieldNumStr)) {
			throw new IllegalArgumentException("The field expression '"+fieldExpression+"' is incorrect. Field number '"+fieldNumStr+" is not numeric");
		}
		int pos = -1;
		try {
			pos = Integer.valueOf(fieldNumStr);
		} catch(NumberFormatException nfe) {
			throw new IllegalArgumentException("The field expression '"+fieldExpression+"' is incorrect. Field number '"+fieldNumStr+" is not numeric", nfe);
		}
		if(pos < 0) {
			throw new IllegalArgumentException("Negative position is not possible");
		}
		// pass down the remainder (after the dot) of the fieldExpression to the type at that position.
		if(dotPos != -1) { // we need to go deeper
			String rem = fieldExpression.substring(dotPos+1);
			if( !(types[pos] instanceof CompositeType<?>) ) {
				throw new RuntimeException("Element at position "+pos+" is not a composite type. There are no nested types to select");
			}
			CompositeType<?> cType = (CompositeType<?>) types[pos];
			cType.getKey(rem, offset + pos, result);
			return;
		}

		if(pos >= types.length) {
			throw new IllegalArgumentException("The specified tuple position does not exist");
		}

		// count nested fields before "pos".
		for(int i = 0; i < pos; i++) {
			offset += types[i].getTotalFields() - 1; // this adds only something to offset if its a composite type.
		}
		if(types[pos] instanceof CompositeType) {
			throw new IllegalArgumentException("The specified field '"+fieldExpression+"' is refering to a composite type.\n"
					+ "Either select all elements in this type with the '"+ExpressionKeys.SELECT_ALL_CHAR+"' operator or specify a field in the sub-type");
		}
		result.add(new FlatFieldDescriptor(offset + pos, types[pos]));
	}

	public <X> TypeInformation<X> getTypeAt(int pos) {
		if (pos < 0 || pos >= this.types.length) {
			throw new IndexOutOfBoundsException();
		}

		@SuppressWarnings("unchecked")
		TypeInformation<X> typed = (TypeInformation<X>) this.types[pos];
		return typed;
	}

	@Override
	public boolean isKeyType() {
		return isValidKeyType(this);
	}

	@Override
	public boolean equals(Object obj) {
		if (obj instanceof TupleTypeInfoBase) {
			@SuppressWarnings("unchecked")
			TupleTypeInfoBase<T> other = (TupleTypeInfoBase<T>) obj;
			return ((this.tupleType == null && other.tupleType == null) || this.tupleType.equals(other.tupleType)) &&
					Arrays.deepEquals(this.types, other.types);

		} else {
			return false;
		}
	}

	@Override
	public int hashCode() {
		return this.types.hashCode() ^ Arrays.deepHashCode(this.types);
	}

	private boolean isValidKeyType(TypeInformation<?> typeInfo) {
		if(typeInfo instanceof TupleTypeInfoBase) {
			TupleTypeInfoBase<?> tupleType = ((TupleTypeInfoBase<?>)typeInfo);
			for(int i=0;i<tupleType.getArity();i++) {
				if (!isValidKeyType(tupleType.getTypeAt(i))) {
					return false;
				}
			}
			return true;
		} else  {
			return typeInfo.isKeyType();
		}
	}

	@Override
	public String toString() {
		StringBuilder bld = new StringBuilder("Tuple");
		bld.append(types.length).append('<');
		bld.append(types[0]);

		for (int i = 1; i < types.length; i++) {
			bld.append(", ").append(types[i]);
		}

		bld.append('>');
		return bld.toString();
	}

}