text:
package org.zstack.utils.ssh;

import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.common.IOUtils;
import net.schmizz.sshj.connection.ConnectionException;
import net.schmizz.sshj.connection.channel.direct.Session;
import net.schmizz.sshj.transport.TransportException;
import net.schmizz.sshj.transport.verification.HostKeyVerifier;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.StopWatch;
import org.zstack.utils.CollectionUtils;
import org.zstack.utils.DebugUtils;
import org.zstack.utils.Utils;
import org.zstack.utils.function.Function;
import org.zstack.utils.logging.CLogger;
import org.zstack.utils.path.PathUtil;

import java.io.File;
import java.io.IOException;
import java.security.PublicKey;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static org.zstack.utils.CollectionDSL.e;
import static org.zstack.utils.CollectionDSL.map;
import static org.zstack.utils.StringDSL.ln;
import static org.zstack.utils.StringDSL.s;

/**
 */
public class Ssh {
    private static final CLogger logger = Utils.getLogger(Ssh.class);

    private String hostname;
    private String username;
    private String privateKey;
    private String password;
    private int port = 22;
    private int timeout = Integer.MAX_VALUE;
    private List<SshRunner> commands = new ArrayList<SshRunner>();
    private SSHClient ssh;
    private File privateKeyFile;
    private boolean closed = false;
    private boolean suppressException = false;
    private ScriptRunner script;

    private boolean init = false;

    private interface SshRunner {
        SshResult run();
        String getCommand();
    }

    private class ScriptRunner {
        String scriptName;
        File scriptFile;
        SshRunner scriptCommand;
        String scriptContent;

        ScriptRunner(String scriptName, String parameters, Map token) {
            this.scriptName = scriptName;
            String scriptPath = PathUtil.findFileOnClassPath(scriptName, true).getAbsolutePath();
            try {
                if (parameters == null) {
                    parameters = "";
                }
                if (token == null) {
                    token = new HashMap();
                }

                String contents = FileUtils.readFileToString(new File(scriptPath));
                String srcScript = String.format("zstack-script-%s", UUID.randomUUID().toString());
                scriptFile = new File(PathUtil.join(PathUtil.getFolderUnderZStackHomeFolder("temp-scripts"), srcScript));
                scriptContent = s(contents).formatByMap(token);

                String remoteScript = ln(
                        "/bin/bash << EOF",
                        "cat << EOF1 > {remotePath}",
                        "{scriptContent}",
                        "EOF1",
                        "/bin/bash {remotePath} {parameters} 1>{stdout} 2>{stderr}",
                        "ret=$?",
                        "test -f {stdout} && cat {stdout}",
                        "test -f {stderr} && cat {stderr} 1>&2",
                        "rm -f {remotePath}",
                        "rm -f {stdout}",
                        "rm -f {stderr}",
                        "exit $ret",
                        "EOF"
                ).formatByMap(map(e("remotePath", String.format("/tmp/%s", UUID.randomUUID().toString())),
                        e("scriptContent", scriptContent),
                        e("parameters", parameters),
                        e("stdout", String.format("/tmp/%s", UUID.randomUUID().toString())),
                        e("stderr", String.format("/tmp/%s", UUID.randomUUID().toString()))
                ));

                scriptCommand = createCommand(remoteScript);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        ScriptRunner(String script) {
            String remoteScript = ln(
                    "/bin/bash << EOF",
                    "cat << EOF1 > {remotePath}",
                    "{scriptContent}",
                    "EOF1",
                    "/bin/bash {remotePath} 1>{stdout} 2>{stderr}",
                    "ret=$?",
                    "test -f {stdout} && cat {stdout}",
                    "test -f {stderr} && cat {stderr} 1>&2",
                    "rm -f {remotePath}",
                    "rm -f {stdout}",
                    "rm -f {stderr}",
                    "exit $ret",
                    "EOF"
            ).formatByMap(map(e("remotePath", String.format("/tmp/%s", UUID.randomUUID().toString())),
                    e("scriptContent", script),
                    e("stdout", String.format("/tmp/%s", UUID.randomUUID().toString())),
                    e("stderr", String.format("/tmp/%s", UUID.randomUUID().toString()))
            ));
            scriptCommand = createCommand(remoteScript);
        }

        SshResult run() {
            return scriptCommand.run();
        }

        void cleanup() {
            if (scriptFile != null) {
                scriptFile.delete();
            }
        }
    }

    public String getHostname() {
        return hostname;
    }

    public Ssh setHostname(String hostname) {
        this.hostname = hostname;
        return this;
    }

    public String getUsername() {
        return username;
    }

    public Ssh setUsername(String username) {
        this.username = username;
        return this;
    }

    public String getPrivateKey() {
        return privateKey;
    }

    public Ssh setPrivateKey(String privateKey) {
        this.privateKey = privateKey;
        return this;
    }

    public String getPassword() {
        return password;
    }

    public Ssh setPassword(String password) {
        this.password = password;
        return this;
    }

    public int getPort() {
        return port;
    }

    public Ssh setPort(int port) {
        this.port = port;
        return this;
    }

    public boolean isSuppressException() {
        return suppressException;
    }

    public Ssh setSuppressException(boolean suppressException) {
        this.suppressException = suppressException;
        return this;
    }

    public Ssh command(String...cmds) {
        for (String cmd : cmds) {
            commands.add(createCommand(cmd));
        }
        return this;
    }

    private SshRunner createCommand(final String cmd) {
       return new SshRunner() {
           @Override
           public SshResult run() {
               SshResult ret = new SshResult();
               ret.setCommandToExecute(cmd);

               Session.Command sshCmd = null;
               try {
                   Session session = null;
                   try {
                       session = ssh.startSession();
                       if (logger.isTraceEnabled()) {
                           logger.trace(String.format("[start SSH] %s", cmd));
                       }
                       sshCmd = session.exec(cmd);
                       sshCmd.join(timeout, TimeUnit.SECONDS);
                       String output = IOUtils.readFully(sshCmd.getInputStream()).toString();
                       String stderr = IOUtils.readFully(sshCmd.getErrorStream()).toString();
                       ret.setReturnCode(sshCmd.getExitStatus());
                       ret.setStderr(stderr);
                       ret.setStdout(output);
                       if (logger.isTraceEnabled()) {
                           logger.trace(String.format("[end SSH] %s", cmd));
                       }
                   } finally {
                       if (session != null) {
                           session.close();
                       }
                   }
               } catch (Exception e) {
                   if (e instanceof ConnectionException || e instanceof IOException || e instanceof TransportException) {
                       ret.setSshFailure(true);
                   }

                   StringBuilder sb = new StringBuilder(String.format("exec ssh command: %s, exception\n", cmd));
                   sb.append(String.format("[host:%s, port:%s, user:%s, timeout:%s]\n", hostname, port, username, timeout));
                   if (!suppressException) {
                       logger.warn(sb.toString(), e);
                   }
                   ret.setExitErrorMessage(e.getMessage());
                   ret.setReturnCode(1);
               } finally {
                   if (sshCmd != null) {
                       try {
                           sshCmd.close();
                       } catch (Exception e) {
                           logger.warn(String.format("failed close ssh channel for command[%s, host:%s, port:%s]", cmd, hostname, port), e);
                       }
                   }
               }

               return ret;
           }

           @Override
           public String getCommand() {
               return cmd;
           }
       };
    }

    public Ssh scp(final String src, final String dst) {
        commands.add(createScpCommand(src, dst));
        return this;
    }

    private SshRunner createScpCommand(final String src, final String dst) {
        return new SshRunner() {
            @Override
            public SshResult run() {
                SshResult ret = new SshResult();
                String cmd = getCommand();
                ret.setCommandToExecute(cmd);

                try {
                    ssh.newSCPFileTransfer().upload(src, dst);
                    if (logger.isTraceEnabled()) {
                        logger.trace(String.format("[SCP done]: %s", cmd));
                    }
                    ret.setReturnCode(0);
                } catch (IOException e) {
                    if (!suppressException) {
                        logger.warn(String.format("[SCP failed]: %s", cmd), e);
                    }
                    ret.setSshFailure(true);
                    ret.setReturnCode(1);
                    ret.setExitErrorMessage(e.getMessage());
                }

                return ret;
            }

            @Override
            public String getCommand() {
                return String.format("scp -P %d %s %s@%s:%s", port, src, username, hostname, dst);
            }
        };
    }

    public Ssh checkTool(String...toolNames) {
        String tool = StringUtils.join(Arrays.asList(toolNames), " ");
        String cmdstr = s("EXIT (){ echo \"$1\"; exit 1;}; cmds=\"{0}\"; for cmd in $cmds; do which $cmd >/dev/null 2>&1 || EXIT \"Not find command: $cmd\";  done").format(tool);
        return command(cmdstr);
    }

    public Ssh shell(String script) {
        DebugUtils.Assert(this.script==null, String.format("every Ssh object can only specify one script"));
        this.script = new ScriptRunner(script);
        return this;
    }

    public Ssh script(String scriptName, String parameters, Map token) {
        DebugUtils.Assert(script==null, String.format("every Ssh object can only specify one script"));
        script = new ScriptRunner(scriptName, parameters, token);
        return this;
    }

    public Ssh script(String scriptName, Map tokens) {
        return script(scriptName, null, tokens);
    }

    public Ssh script(String scriptName, String parameters) {
        return script(scriptName, parameters, null);
    }

    public Ssh script(String scriptName) {
        return script(scriptName, null, null);
    }

    private void build() throws IOException {
        if (init) {
            return;
        }

        ssh = new SSHClient();
        ssh.addHostKeyVerifier(new HostKeyVerifier() {
            @Override
            public boolean verify(String arg0, int arg1, PublicKey arg2) {
                return true;
            }
        });
        ssh.connect(hostname, port);
        if (privateKey != null) {
            privateKeyFile = File.createTempFile("zstack", "tmp");
            FileUtils.writeStringToFile(privateKeyFile, privateKey);
            ssh.authPublickey(username, privateKeyFile.getAbsolutePath());
        } else {
            ssh.authPassword(username, password);
        }

        init = true;
    }

    public void close() {
        if (closed) {
            return;
        }

        closed = true;

        try {
            ssh.disconnect();

            if (privateKeyFile != null) {
                privateKeyFile.delete();
            }
            if (script != null) {
                script.cleanup();
            }
        } catch (IOException e) {
            StringBuilder sb = new StringBuilder(String.format("failed to close connection"));
            sb.append(String.format("[host:%s, port:%s, user:%s, timeout:%s]\n", hostname, port, username, timeout));
            logger.warn(sb.toString(), e);
        }
    }

    public SshResult run() {
        if (closed) {
            throw new SshException("this Ssh instance has been closed, you can not call run() after close()");
        }

        StopWatch watch = new StopWatch();
        watch.start();
        try {
            build();
            if (commands.isEmpty() && script == null) {
                throw new IllegalArgumentException(String.format("no command or scp command or script specified"));
            }

            if (!commands.isEmpty() && script != null) {
                throw new IllegalArgumentException(String.format("you cannot use script with command or scp"));
            }

            if (privateKey == null && password == null) {
                throw new IllegalArgumentException(String.format("no password and private key specified"));
            }

            if (username == null) {
                throw new IllegalArgumentException(String.format("no username specified"));
            }

            if (hostname == null) {
                throw new IllegalArgumentException(String.format("no hostname specified"));
            }

            if (script != null) {
                if (logger.isTraceEnabled()) {
                    logger.trace(String.format("run script remotely[ip: %s, port: %s]:\n%s\n", hostname, port, script.scriptContent));
                }
                return script.run();
            } else {
                SshResult ret = null;
                for (SshRunner runner : commands) {
                    ret = runner.run();
                    if (ret.getReturnCode() != 0) {
                        return ret;
                    }
                }

                return ret;
            }

        } catch (IOException e) {
            StringBuilder sb = new StringBuilder(String.format("ssh exception\n"));
            sb.append(String.format("[host:%s, port:%s, user:%s, timeout:%s]\n", hostname, port, username, timeout));
            if (!suppressException) {
                logger.warn(sb.toString(), e);
            }
            SshResult ret = new SshResult();
            ret.setSshFailure(true);
            ret.setExitErrorMessage(e.getMessage());
            ret.setReturnCode(1);
            return ret;
        } finally {
            watch.stop();
            if (logger.isTraceEnabled()) {
                if (script != null) {
                    logger.trace(String.format("execute script[%s], cost time:%s", script.scriptName, watch.getTime()));
                } else {
                    String cmd = StringUtils.join(CollectionUtils.transformToList(commands, new Function<String, SshRunner>() {
                        @Override
                        public String call(SshRunner arg) {
                            return arg.getCommand();
                        }
                    }), ",");
                    String info = s(
                            "\nssh execution[host: {0}, port:{1}]\n",
                            "command: {2}\n",
                            "cost time: {3}ms\n"
                    ).format(hostname, port, cmd, watch.getTime());
                    logger.trace(info);
                }
            }
        }
    }

    public int getTimeout() {
        return timeout;
    }

    public Ssh setTimeout(int timeout) {
        this.timeout = timeout;
        return this;
    }

    public Ssh reset() {
        commands = new ArrayList<SshRunner>();
        return this;
    }

    public SshResult runAndClose() {
        SshResult ret = run();
        close();
        return ret;
    }

    public void runErrorByExceptionAndClose() {
        SshResult ret = run();
        close();
        ret.raiseExceptionIfFailed();
    }

    public void runErrorByException() {
        SshResult ret = run();
        try {
            ret.raiseExceptionIfFailed();
        } catch (SshException e) {
            close();
            throw e;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
* newUser
*/
class userLoginForm extends formTemplate
{

	function structure()
	{
		return array(
			array("Email Address", 'email', 'short_name' => 'email'),
			array("Password", "password", 'short_name' => "password"),
			array("", "checkbox", array("Remember me"), 'short_name' => "remember", 'not_required' => true)
		);
	}
}

?>


text:
package com.gsmarshall.teerecorder.client.news;

import com.gsmarshall.teerecorder.server.news.entity.News;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by gm on 2014-11-15.
 */
public class NewsReceiver {

    public List<News> getLatestNews() throws NotFoundNewsException {
        try {
            String response = getNewsJsonFromServer();

            return convertJsonResponseToList(response);
        } catch (Exception e) {
            throw new NotFoundNewsException("Problem with net connection");
        }
    }

    private List<News> convertJsonResponseToList(String response) {
        JSONArray array = new JSONArray(response);
        List<News> resultList = new LinkedList<>();

        for(int i = 0 ; i < array.length() ; i++){
            News news = new News();
            JSONObject jsonObject = array.getJSONObject(i);

            String header = jsonObject.getString("header");
            news.setHeader(header);

            String content = jsonObject.getString("content");
            news.setContent(content);

            long time = jsonObject.getLong("date");
            Date date = new Date();
            date.setTime(time);
            news.setDate(date);

            resultList.add(news);
        }

        return resultList;
    }

    private String getNewsJsonFromServer() {
        Client c = Client.create();
        WebResource r = c.resource(RestPaths.API_PATH);
        return r.path(RestPaths.NEWS_ENDING).
                get(String.class);
    }

    public static void main(String[] args) throws NotFoundNewsException {
        List<News> allNews = new NewsReceiver().getLatestNews();
        for (News news : allNews) {
            System.out.println(news.getDate() + " --> " + news.getHeader() + " --> " + news.getContent());
        }
    }

}


text:
use crate::config::Config;
use crate::errors::RunError;
use crate::path_utils::{get_profile_walker, get_source_walker};
use crate::process_handling::RunningProcessHandle;
use crate::source_analysis::LineAnalysis;
use crate::statemachine::*;
use crate::TestHandle;
use llvm_profparser::*;
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
use std::thread::sleep;
use tracing::{info, warn};

pub fn create_state_machine<'a>(
    test: impl Into<TestHandle>,
    traces: &'a mut TraceMap,
    analysis: &'a HashMap<PathBuf, LineAnalysis>,
    config: &'a Config,
    event_log: &'a Option<EventLog>,
) -> (TestState, LlvmInstrumentedData<'a>) {
    let handle = test.into();
    if let TestHandle::Process(process) = handle {
        let llvm = LlvmInstrumentedData {
            process: Some(process),
            event_log,
            config,
            traces,
            analysis,
        };
        (TestState::start_state(), llvm)
    } else {
        error!("The llvm cov statemachine requires a process::Child");
        let invalid = LlvmInstrumentedData {
            process: None,
            config,
            event_log,
            traces,
            analysis,
        };
        (TestState::End(1), invalid)
    }
}

/// Handle to the process for an instrumented binary. This will simply
pub struct LlvmInstrumentedData<'a> {
    /// Parent pid of the test
    process: Option<RunningProcessHandle>,
    /// Program config
    config: &'a Config,
    /// Optional event log to update as the test progresses
    event_log: &'a Option<EventLog>,
    /// Instrumentation points in code with associated coverage data
    traces: &'a mut TraceMap,
    /// Source analysis, needed in case we need to follow any executables
    analysis: &'a HashMap<PathBuf, LineAnalysis>,
}

impl<'a> LlvmInstrumentedData<'a> {
    fn should_panic(&self) -> bool {
        match &self.process {
            Some(hnd) => hnd.should_panic,
            None => false,
        }
    }
}

impl<'a> StateData for LlvmInstrumentedData<'a> {
    fn start(&mut self) -> Result<Option<TestState>, RunError> {
        // Nothing needs to be done at startup as this runs like a normal process
        Ok(Some(TestState::wait_state()))
    }

    fn init(&mut self) -> Result<TestState, RunError> {
        // Nothing needs to be done at init as this runs like a normal process
        unreachable!();
    }

    fn last_wait_attempt(&mut self) -> Result<Option<TestState>, RunError> {
        unreachable!();
    }

    fn wait(&mut self) -> Result<Option<TestState>, RunError> {
        let should_panic = self.should_panic();
        if let Some(parent) = self.process.as_mut() {
            match parent.child.wait() {
                Ok(exit) => {
                    if !exit.success() && !should_panic {
                        return Err(RunError::TestFailed);
                    }
                    if let Some(delay) = self.config.post_test_delay {
                        sleep(delay);
                    }
                    let profraws = get_profile_walker(self.config)
                        .map(|x| x.path().to_path_buf())
                        .filter(|x| !parent.existing_profraws.contains(&x))
                        .collect::<Vec<_>>();

                    let profraw_dir = self.config.profraw_dir();

                    info!(
                        "For binary: {}",
                        self.config.strip_base_dir(&parent.path).display()
                    );
                    for prof in &profraws {
                        let profraw_name = self.config.strip_base_dir(prof);
                        if let Err(e) = fs::copy(prof, profraw_dir.join(&profraw_name)) {
                            warn!("Unable to copy backup of {}: {}", profraw_name.display(), e);
                        }
                        info!("Generated: {}", profraw_name.display());
                    }

                    let binary_path = parent.path.clone();

                    let instrumentation = merge_profiles(&profraws);
                    for prof in &profraws {
                        // Delete them
                        if let Err(e) = fs::remove_file(&prof) {
                            warn!("Unable to cleanup {}: {}", prof.display(), e);
                        }
                    }
                    let instrumentation = instrumentation?;
                    if instrumentation.is_empty() {
                        warn!("profraw file has no records after merging. If this is unexpected it may be caused by a panic or signal used in a test that prevented the LLVM instrumentation runtime from serialising results");
                        self.process = None;
                        let code = exit.code().unwrap_or(1);
                        return Ok(Some(TestState::End(code)));
                    }
                    // Panics due to a todo!();
                    let mut binaries = parent.extra_binaries.clone();
                    binaries.push(binary_path);
                    let mapping =
                        CoverageMapping::new(&binaries, &instrumentation).map_err(|e| {
                            error!("Failed to get coverage: {}", e);
                            RunError::TestCoverage(e.to_string())
                        })?;
                    let report = mapping.generate_report();

                    if self.traces.is_empty() {
                        for source_file in get_source_walker(self.config) {
                            let file = source_file.path();
                            let analysis = self.analysis.get(file);
                            if let Some(result) = report.files.get(file) {
                                for (loc, hits) in result.hits.iter() {
                                    for line in loc.line_start..(loc.line_end + 1) {
                                        let include = match analysis.as_ref() {
                                            Some(analysis) => !analysis.should_ignore(line),
                                            None => true,
                                        };
                                        if include {
                                            let mut trace = Trace::new_stub(line as u64);
                                            trace.stats = CoverageStat::Line(*hits as u64);
                                            self.traces.add_trace(file, trace);
                                        }
                                    }
                                }
                            }
                            if let Some(analysis) = analysis {
                                for line in analysis.cover.iter() {
                                    if !self.traces.contains_location(file, *line as u64) {
                                        let mut trace = Trace::new_stub(*line as u64);
                                        trace.stats = CoverageStat::Line(0);
                                        self.traces.add_trace(file, trace);
                                    }
                                }
                            }
                        }
                    } else {
                        self.traces.dedup();

                        for (file, result) in report.files.iter() {
                            if let Some(traces) = self.traces.file_traces_mut(&file) {
                                for trace in traces.iter_mut() {
                                    if let Some(hits) = result.hits_for_line(trace.line as usize) {
                                        if let CoverageStat::Line(ref mut x) = trace.stats {
                                            *x = hits as _;
                                        }
                                    }
                                }
                            } else {
                                warn!(
                                    "Couldn't find {} in {:?}",
                                    file.display(),
                                    self.traces.files()
                                );
                            }
                        }
                    }

                    self.process = None;
                    let code = exit.code().unwrap_or(1);
                    Ok(Some(TestState::End(code)))
                }
                Err(e) => Err(e.into()),
            }
        } else {
            Err(RunError::TestCoverage("Test was not launched".to_string()))
        }
    }

    fn stop(&mut self) -> Result<TestState, RunError> {
        unreachable!();
    }
}


text:
import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import _inheritsLoose from "@babel/runtime/helpers/esm/inheritsLoose";

var _fadeStyles;

import classNames from 'classnames';
import React from 'react';
import Transition, { ENTERED, ENTERING } from 'react-transition-group/Transition';
import onEnd from 'dom-helpers/transition/end';
import triggerBrowserReflow from './utils/triggerBrowserReflow';
var defaultProps = {
  in: false,
  timeout: 300,
  mountOnEnter: false,
  unmountOnExit: false,
  appear: false
};
var fadeStyles = (_fadeStyles = {}, _fadeStyles[ENTERING] = 'show', _fadeStyles[ENTERED] = 'show', _fadeStyles);

var Fade =
/*#__PURE__*/
function (_React$Component) {
  _inheritsLoose(Fade, _React$Component);

  function Fade() {
    var _this;

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;

    _this.handleEnter = function (node) {
      triggerBrowserReflow(node);
      if (_this.props.onEnter) _this.props.onEnter(node);
    };

    return _this;
  }

  var _proto = Fade.prototype;

  _proto.render = function render() {
    var _this$props = this.props,
        className = _this$props.className,
        children = _this$props.children,
        props = _objectWithoutPropertiesLoose(_this$props, ["className", "children"]);

    return React.createElement(Transition, _extends({
      addEndListener: onEnd
    }, props, {
      onEnter: this.handleEnter
    }), function (status, innerProps) {
      return React.cloneElement(children, _extends({}, innerProps, {
        className: classNames('fade', className, children.props.className, fadeStyles[status])
      }));
    });
  };

  return Fade;
}(React.Component);

Fade.defaultProps = defaultProps;
export default Fade;


text:
#ifndef DALI_SCENE3D_LOADERERER_INTERPRET_RENDERER_STATE_H
#define DALI_SCENE3D_LOADERERER_INTERPRET_RENDERER_STATE_H

#include "dali-scene3d/public-api/loader/renderer-state.h"
#include "dali-scene3d/public-api/loader/string-callback.h"

namespace Dali
{
namespace Scene3D
{
namespace Loader
{
namespace RendererState
{
/*
 * @brief Attempts to interpret a string for renderer states, which can be a combination of the following
 *  (using '|' as a delimiter, if multiple specified):

 *  - one of Value, exc. for NONE or those with the _BITS, _SHIFT, _MASK or _ITEMS suffix;

 *  - DEPTH_FUNC:${one of Comparison::Type, exc. OMIT};

 *  - BLEND_(SRC_DST)_(RGB|ALPHA):${one of BlendFactor::Type, exc. OMIT};

 *  - BUFFER_MODE:${one of BufferMode::Type, exc. OMIT};
 * @param string The string to parse;
 * @param length The length of the string; If left at 0, strlen() will be called, which of
 *   course is only suitable i the string is null-terminated.
 * @param onError The callback to call when an error occurred.
 * @note No other characters are allowed.
 */
DALI_SCENE3D_API Type Parse(const char* string, size_t length = 0, StringCallback onError = DefaultErrorCallback);

} // namespace RendererState
} // namespace Loader
} // namespace Scene3D
} // namespace Dali

#endif //DALI_SCENE3D_LOADERERER_INTERPRET_RENDERER_STATE_H


text:
package sri.web.examples.routerexample

import sri.core._
import sri.web.all._
import sri.web.examples.Button
import sri.web.router
import sri.web.router.{WebDynamicPage, WebRouterComponent}
import sri.web.styles.WebStyleSheet
import sri.web.vdom.htmltags._

import scala.scalajs.js
import scala.scalajs.js.annotation.ScalaJSDefined
import scala.scalajs.js.{UndefOr => U, undefined}

object ItemsLeftNav {

  @ScalaJSDefined
  class Component extends WebRouterComponent[Unit, Unit] {
    def render() = {
      div(style = styles.container)(
        (1 until 10).toSeq.map(i => getItem(i.toString, ItemsRouteModule.Details))
      )
    }

    def getItem(id: String, page: WebDynamicPage[Int]) = {
      Button(style = styles.menuItem(id == currentRoute.placeholder.getOrElse("")),
        key = id,
        onPress = () => navigateToDynamic(page, id))(
        span()(s"Item $id")
      )
    }

  }

  object styles extends WebStyleSheet {
    val container = style(width := 190,
      paddingTop := 40,
      display.flex,
      flexDirection.column,
      border := 0,
      borderRightWidth := "1px",
      borderStyle := "solid",
      borderRightColor := "grey")

    def menuItem(selected: Boolean) = {

      val bg = if (selected) "grey" else "transparent"

      style(height := 40,
        justifyContent.center,
        display.flex,
        flexDirection.column,
        cursor.pointer,
        backgroundColor := bg,
        alignItems.center)
    }

  }

  js.constructorOf[Component].contextTypes = router.routerContextTypes

  def apply(key: js.UndefOr[String] = js.undefined, ref: js.Function1[Component, Unit] = null) = makeElementNoProps[Component](key = key, ref = ref)
}


text:
const express         = require('express');
const rollup          = require('express-middleware-rollup');
const sass            = require('node-sass-middleware');
const buble           = require('rollup-plugin-buble');
const fs              = require('fs-extra');
const resolve         = require('rollup-plugin-node-resolve');
const commonjs        = require('rollup-plugin-commonjs');
const replace         = require('rollup-plugin-replace');
const json            = require('rollup-plugin-json');
const string          = require('rollup-plugin-string');

const git             = require('git-rev');

const path            = require('path');
const PkgRoot         = __dirname;
const StaticDir       = 'static'; // must not be absolute since concatenated with `root` option
const StaticPath      = path.join(PkgRoot, StaticDir);

fs.mkdirp(StaticPath).then(
  () => fs.copy(path.join(PkgRoot, 'node_modules', 'font-awesome', 'fonts'), path.join(StaticPath, 'fonts'))
).then(
  () => fs.copy(path.join(PkgRoot, 'node_modules', 'ffmpeg.js', 'ffmpeg-worker-mp4.js'), path.join(StaticPath, 'ffmpeg-worker-mp4.js'))
).then(
  () => new Promise((res, rej) => git.short(res))
).then((gitrev) => {
  // Javascript compilation
  const js = rollup({
    src: 'js',
    dest: StaticDir,
    root: PkgRoot,
    prefix: '/',
    serve: 'on-compile',
    rollupOpts: {
      plugins: [
        // turn file contents into js strings which can be imported
        string({ include: '**/*.md' }),
        // allow importing json as ES6 modules
        json(),
        // replace patterns in files with new values
        replace({
          include: 'js/config.js',
          delimiters: [ '<@', '@>' ],
          values: {
            TIMESTAMP: new Date().toISOString(),
            GIT_REV: gitrev
          }
        }),
        // ES6 -> ES5
        buble({
          exclude: [ 'node_modules/ffmpeg.js/**' ]
        }),
        // use Node resolution algorithm to find files in node_modules
        resolve({
          main: true,
          browser: true,
          extensions: [ '.js', '.json' ],
          preferBuiltins: false,
        }),
        // CommonJS modules -> ES6 modules
        commonjs({
          extensions: [ '.js', '.json' ],
          exclude: [ 'node_modules/ffmpeg.js/**' ],
          namedExports: {
            'node_modules/image-capture/lib/imagecapture.js': [ 'ImageCapture' ]
          }
        }),
      ]
    }
  });

  // Css compilation
  const css = sass({
    src: 'sass',
    dest: StaticDir,
    root: PkgRoot,
    prefix: '/',
    outputStyle: 'extended',
    includePaths: [
      path.join(PkgRoot, 'node_modules')
    ]
  });

  // Static file server
  const statics = express.static(StaticPath);

  const server = express();
  server.get('/', (req, res) => {
    fs.copy(path.join(PkgRoot, 'index.html'), path.join(StaticPath, 'index.html')).then(
      () => res.sendFile(path.join(PkgRoot, StaticDir, 'index.html'))
    );
  });
  server.use(js);
  server.use(css);
  server.use(statics);

  server.listen(3000);
}).catch(err => {
  console.error(err)
  process.exit(1);
});


text:
import os
from poetry.apps.corpus.scripts.settings import MARKUPS_DUMP_RAW_PATH

from rupo.files.writer import Writer, FileType
from rupo.api import Engine

def get_paths(path: str, ext: str):
    """
    Получение всех файлов заданного типа по заданному пути.

    :param path: путь к файлу/папке.
    :param ext: требуемое расширение.
    """
    if os.path.isfile(path):
        if ext == os.path.splitext(path)[1]:
            yield path
    else:
        for root, folders, files in os.walk(path):
            for file in files:
                if ext == os.path.splitext(file)[1]:
                    yield os.path.join(root, file)
            for folder in folders:
                return get_paths(folder, ext)

def run(stress_model_path, g2p_model_path, grapheme_set, g2p_dict_path, aligner_dump_path, raw_stress_dict_path,
        stress_trie_path, zalyzniak_dict, ru_wiki_dict, cmu_dict):
    raw_writer = Writer(FileType.RAW, MARKUPS_DUMP_RAW_PATH)
    raw_writer.open()
    i = 0
    path = "/media/data/stihi_ru_clean"
    paths = get_paths(path, "")
    engine = Engine(language="ru")
    engine.load(stress_model_path, g2p_model_path, grapheme_set, g2p_dict_path, aligner_dump_path, raw_stress_dict_path,
        stress_trie_path, zalyzniak_dict, ru_wiki_dict, cmu_dict)
    for filename in paths:
        with open(filename, "r", encoding="utf-8") as file:
            text = ""
            is_text = False
            try:
                for file_line in file:
                    if "<div" in file_line:
                        is_text = True
                    elif "</div>" in file_line:
                        is_text = False
                        clean_text = ""
                        skip = False
                        lines = text.split("\n")
                        for line in lines:
                            if line == "":
                                continue
                            for ch in line:
                                if "a" < ch < "z" or "A" < ch < "Z" or ch == "Ј":
                                    skip = True
                                    break
                            clean_text += line.strip() + "\n"
                        if not skip:
                            print(clean_text.split("\n")[:2])
                            markup, result = engine.get_improved_markup(clean_text)
                            raw_writer.write_markup(markup)
                        else:
                            print("Skipped")
                        i += 1
                        print(i)
                        text = ""
                    elif is_text:
                        text += file_line.strip() + "\n"
            except Exception as e:
                pass
    raw_writer.close()
if __name__ == "__main__":
    pass


text:
package renderer

import (
	"io"

	rice "github.com/GeertJohan/go.rice"
	"github.com/flosch/pongo2"
	"github.com/labstack/echo"
)

func init() {
	RegisterTags()
	RegisterFilters()
}

func New(box *rice.Box) *Renderer {
	templateLoader := riceTemplateLoader{
		templateBox: box,
	}
	return &Renderer{
		templateSet: pongo2.NewSet("assimilator", templateLoader),
	}
}

type riceTemplateLoader struct {
	templateBox *rice.Box
}

// Abs calculates the path to a given template. Whenever a path must be resolved
// due to an import from another template, the base equals the parent template's path.
func (loader riceTemplateLoader) Abs(base, name string) string {
	// TODO make sure we can ignore `base` argument
	return name
}

// Get returns an io.Reader where the template's content can be read from.
func (loader riceTemplateLoader) Get(path string) (io.Reader, error) {
	return loader.templateBox.Open(path)
}

type Renderer struct {
	templateSet *pongo2.TemplateSet
}

func (r *Renderer) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
	// Re-read template from file on each request during development
	// TODO use cache/no-cache via settings
	tpl, err := r.templateSet.FromFile(name)
	if err != nil {
		return err
	}
	return tpl.ExecuteWriter(getPongoContext(data), w)
}

func getPongoContext(data interface{}) pongo2.Context {
	if context, ok := data.(map[string]interface{}); ok {
		return context
	}
	return nil
}


text:
package utils

import (
	"fmt"
	"math/big"
	"net"
	"regexp"
	"strconv"
	"strings"

	"github.com/apparentlymart/go-cidr/cidr"
)

// IsIPv4IP checks if a string is a valid IPv4 IP.
func IsIPv4IP(s string) bool {
	ip := net.ParseIP(s)
	if ip == nil {
		return false
	}

	// Must convert to IPv4
	if ip.To4() == nil {
		return false
	}
	// Must NOT contain ":"
	if strings.Contains(s, ":") {
		return false
	}

	return true
}

// IsIPv6IP checks if a string is a valid IPv6 IP.
func IsIPv6IP(s string) bool {
	ip := net.ParseIP(s)
	if ip == nil {
		return false
	}

	// Must NOT convert to IPv4
	if ip.To4() != nil {
		return false
	}

	return true
}

// IsIPv4CIDR checks if a string is a valid IPv4 CIDR.
func IsIPv4CIDR(s string) bool {
	ip, _, err := net.ParseCIDR(s)
	if err != nil {
		return false
	}

	// Must convert to IPv4
	if ip.To4() == nil {
		return false
	}
	// Must NOT contain ":"
	if strings.Contains(s, ":") {
		return false
	}

	return true
}

// IsIPv6CIDR checks if a string is a valid IPv6 CIDR.
func IsIPv6CIDR(s string) bool {
	ip, _, err := net.ParseCIDR(s)
	if err != nil {
		return false
	}

	// Must NOT convert to IPv4
	if ip.To4() != nil {
		return false
	}

	return true
}

// ParseCIDRNotation parses a string in the format "/<newSize>#<netNum>"
// and returns the values of <newSize> and <netNum>.
func ParseCIDRNotation(subnet string) (int, int64, error) {
	re := regexp.MustCompile(`^/(\d+)#([a-f0-9]+)$`)
	s := re.FindStringSubmatch(subnet)
	if len(s) != 3 {
		return 0, 0, fmt.Errorf("unable to parse CIDR subnet string %q using %q", subnet, re)
	}

	newSize, err := strconv.Atoi(s[1])
	if err != nil {
		return 0, 0, fmt.Errorf("unable to convert CIDR subnet new bits to int: %q: %v", s[1], err)
	}

	netNum, err := strconv.ParseInt(s[2], 16, 64)
	if err != nil {
		return 0, 0, fmt.Errorf("unable to convert CIDR subnet net num to int: %q: %v", s[2], err)
	}

	return newSize, netNum, nil
}

// CIDRSubnet calculates a subnet address within given IP network address prefix.
// Inspired by the Terraform implementation of the "cidrsubnet" function
// https://www.terraform.io/docs/language/functions/cidrsubnet.html
func CIDRSubnet(prefix string, newSize int, netNum int64) (string, error) {
	_, baseCIDR, err := net.ParseCIDR(prefix)
	if err != nil {
		return "", fmt.Errorf("unable to parse CIDR for %q: %v", prefix, err)
	}

	oldSize, totalSize := baseCIDR.Mask.Size()
	if oldSize == 0 && totalSize == 0 {
		return "", fmt.Errorf("unable to calculate CIDR mask size for %q: %q", prefix, baseCIDR.Mask)
	}

	newNetwork, err := cidr.SubnetBig(baseCIDR, newSize-oldSize, big.NewInt(netNum))
	if err != nil {
		return "", fmt.Errorf("unable to calculate subnet CIDR for %q -> /%d#%d : %v", prefix, newSize, netNum, err)
	}

	return newNetwork.String(), nil
}


text:
#include "SndFileReader.h"
#include "util/Buffer.h"
#include "Exception.h"

#include <cstring>

AUD_NAMESPACE_BEGIN

sf_count_t SndFileReader::vio_get_filelen(void* user_data)
{
	SndFileReader* reader = (SndFileReader*)user_data;
	return reader->m_membuffer->getSize();
}

sf_count_t SndFileReader::vio_seek(sf_count_t offset, int whence,
									   void* user_data)
{
	SndFileReader* reader = (SndFileReader*)user_data;

	switch(whence)
	{
	case SEEK_SET:
		reader->m_memoffset = offset;
		break;
	case SEEK_CUR:
		reader->m_memoffset = reader->m_memoffset + offset;
		break;
	case SEEK_END:
		reader->m_memoffset = reader->m_membuffer->getSize() + offset;
		break;
	}

	return reader->m_memoffset;
}

sf_count_t SndFileReader::vio_read(void* ptr, sf_count_t count,
									   void* user_data)
{
	SndFileReader* reader = (SndFileReader*)user_data;

	if(reader->m_memoffset + count > reader->m_membuffer->getSize())
		count = reader->m_membuffer->getSize() - reader->m_memoffset;

	std::memcpy(ptr, ((data_t*)reader->m_membuffer->getBuffer()) +
		   reader->m_memoffset, count);
	reader->m_memoffset += count;

	return count;
}

sf_count_t SndFileReader::vio_tell(void* user_data)
{
	SndFileReader* reader = (SndFileReader*)user_data;

	return reader->m_memoffset;
}

SndFileReader::SndFileReader(std::string filename) :
	m_position(0)
{
	SF_INFO sfinfo;

	sfinfo.format = 0;
	m_sndfile = sf_open(filename.c_str(), SFM_READ, &sfinfo);

	if(!m_sndfile)
		AUD_THROW(FileException, "The file couldn't be opened with libsndfile.");

	m_specs.channels = (Channels) sfinfo.channels;
	m_specs.rate = (SampleRate) sfinfo.samplerate;
	m_length = sfinfo.frames;
	m_seekable = sfinfo.seekable;
}

SndFileReader::SndFileReader(std::shared_ptr<Buffer> buffer) :
	m_position(0),
	m_membuffer(buffer),
	m_memoffset(0)
{
	m_vio.get_filelen = vio_get_filelen;
	m_vio.read = vio_read;
	m_vio.seek = vio_seek;
	m_vio.tell = vio_tell;
	m_vio.write = nullptr;

	SF_INFO sfinfo;

	sfinfo.format = 0;
	m_sndfile = sf_open_virtual(&m_vio, SFM_READ, &sfinfo, this);

	if(!m_sndfile)
		AUD_THROW(FileException, "The buffer couldn't be read with libsndfile.");

	m_specs.channels = (Channels) sfinfo.channels;
	m_specs.rate = (SampleRate) sfinfo.samplerate;
	m_length = sfinfo.frames;
	m_seekable = sfinfo.seekable;
}

SndFileReader::~SndFileReader()
{
	sf_close(m_sndfile);
}

std::vector<StreamInfo> SndFileReader::queryStreams()
{
	std::vector<StreamInfo> result;

	StreamInfo info;
	info.start = 0;
	info.duration = double(getLength()) / m_specs.rate;
	info.specs.specs = m_specs;
	info.specs.format = FORMAT_FLOAT32;

	result.emplace_back(info);

	return result;
}

bool SndFileReader::isSeekable() const
{
	return m_seekable;
}

void SndFileReader::seek(int position)
{
	if(m_seekable)
	{
		position = sf_seek(m_sndfile, position, SEEK_SET);
		m_position = position;
	}
}

int SndFileReader::getLength() const
{
	return m_length;
}

int SndFileReader::getPosition() const
{
	return m_position;
}

Specs SndFileReader::getSpecs() const
{
	return m_specs;
}

void SndFileReader::read(int& length, bool& eos, sample_t* buffer)
{
	int olen = length;

	length = sf_readf_float(m_sndfile, buffer, length);

	m_position += length;

	eos = length < olen;
}

AUD_NAMESPACE_END


text:
package org.jasig.cas.ticket;

import org.jasig.cas.authentication.principal.Service;
import org.jasig.cas.ticket.proxy.ProxyTicket;

import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.validation.constraints.NotNull;

/**
 * The {@link ProxyTicketImpl} is a concrete implementation of the {@link ProxyTicket}.
 *
 * @author Misagh Moayyed
 * @since 4.2
 */
@Entity
@DiscriminatorValue(ProxyTicket.PROXY_TICKET_PREFIX)
public class ProxyTicketImpl extends ServiceTicketImpl implements ProxyTicket {
    private static final long serialVersionUID = -4469960563289285371L;

    /**
     * Instantiates a new Proxy ticket.
     */
    public ProxyTicketImpl() {
    }

    /**
     * Instantiates a new Proxy ticket.
     *
     * @param id           the id
     * @param ticket       the ticket
     * @param service      the service
     * @param fromNewLogin the from new login
     * @param policy       the policy
     */
    public ProxyTicketImpl(final String id, @NotNull final TicketGrantingTicketImpl ticket, @NotNull final Service service,
                           final boolean fromNewLogin, final ExpirationPolicy policy) {
        super(id, ticket, service, fromNewLogin, policy);
    }
}


text:
package org.unigram.docvalidator;

import org.junit.Test;
import org.unigram.docvalidator.model.Document;
import org.unigram.docvalidator.model.DocumentCollection;
import org.unigram.docvalidator.model.Paragraph;
import org.unigram.docvalidator.model.Section;
import org.unigram.docvalidator.model.Sentence;
import org.unigram.docvalidator.config.DVResource;
import org.unigram.docvalidator.config.ValidatorConfiguration;

import java.util.List;

import static org.junit.Assert.assertEquals;

public class DocumentValidatorTest {

  @Test
  public void testEmptyValidator() throws DocumentValidatorException {

    DocumentCollection documents = new DocumentCollection();

    Document document = new Document();

    Section section1 = new Section(1);

    Paragraph paragraph1 = new Paragraph();
    paragraph1.appendSentence(
        new Sentence(
            "In a land far away, there once was as a hungry programmer.",
            1
        )
    );
    paragraph1.appendSentence(
        new Sentence("He was hungry for programming and programmed all day - "
            + " - in Java, Python, C++, etc.",
            2
        )
    );

    paragraph1.appendSentence(
        new Sentence("Whe he wasn't programming, he was eating noodles.",
            3
        )
    );

    Paragraph paragraph2 = new Paragraph();
    paragraph1.appendSentence(
        new Sentence("One day while programming, he got a new idea.",
            4
        )
    );

    section1.appendParagraph(paragraph1);
    section1.appendParagraph(paragraph2);

    document.appendSection(section1);

    documents.addDocument(document);

    ValidatorConfiguration config = new ValidatorConfiguration(
        "<?xml version=\"1.0\"?>\n" +
            "<character-table></character-table>"
    );
    DVResource resource = new DVResource(config); // = ValidatorConfiguration + CharacterTable

    DocumentValidator validator = new DocumentValidator.Builder()
        .setResource(resource)
//        .setConfig(...)
//        .setCharacterTable()
        .build();

    List<ValidationError> errors = validator.check(documents);

    assertEquals(0, errors.size());
  }
}


text:
#ifndef TENSORFLOW_CORE_KERNELS_POOLING_OPS_COMMON_H_
#define TENSORFLOW_CORE_KERNELS_POOLING_OPS_COMMON_H_

#include <vector>

#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#define EIGEN_USE_GPU
#endif  // GOOGLE_CUDA || TENSORFLOW_USE_ROCM

#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/bounds_check.h"
#include "tensorflow/core/framework/numeric_op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/kernels/avgpooling_op.h"
#include "tensorflow/core/kernels/maxpooling_op.h"
#include "tensorflow/core/kernels/ops_util.h"
#include "tensorflow/core/util/padding.h"
#include "tensorflow/core/util/tensor_format.h"
#include "tensorflow/core/util/work_sharder.h"

#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#include "tensorflow/core/kernels/maxpooling_op_gpu.h"
#endif  // GOOGLE_CUDA || TENSORFLOW_USE_ROCM

namespace tensorflow {

typedef Eigen::GpuDevice GPUDevice;

// A helper class to manage sizes and shapes for pooling operations.
struct PoolParameters {
  // Updates context->status if there is an invalid input.
  // explicit_paddings has eight elements if padding==EXPLIICT, and zero
  // elements otherwise.
  PoolParameters(OpKernelContext* context, const std::vector<int32>& ksize,
                 const std::vector<int32>& stride, Padding padding,
                 std::vector<int64> explicit_paddings, TensorFormat data_format,
                 const TensorShape& tensor_in_shape);

  // Returns the shape of the output for "forward" pooling operations.
  TensorShape forward_output_shape();

  int depth;

  int tensor_in_cols;
  int tensor_in_rows;
  int tensor_in_batch;

  int window_rows;
  int window_cols;
  int depth_window;

  int row_stride;
  int col_stride;
  int depth_stride;

  int64 out_height;
  int64 out_width;
  int out_depth;

  int64 pad_top;
  int64 pad_bottom;
  int64 pad_left;
  int64 pad_right;

  int pad_depth;

  TensorFormat data_format;
};

// Checks if the sizes of the paddings are less than the size of window.
// This is required for MaxPool because it pads with -inf, so the pooling
// window cannot fully cover the padded area.
Status CheckPaddingSize(PoolParameters& params);

// An implementation of MaxPooling (forward).
// TODO (yongtang): Remove MaxPoolingOp and use MaxPoolingV2Op,
//     QuantizedMaxPoolingOp depends on MaxPoolingOp so keep intact for now
template <typename Device, typename T>
class MaxPoolingOp : public OpKernel {
 public:
  explicit MaxPoolingOp(OpKernelConstruction* context) : OpKernel(context) {
    string data_format;
    auto status = context->GetAttr("data_format", &data_format);
    if (status.ok()) {
      OP_REQUIRES(context, FormatFromString(data_format, &data_format_),
                  errors::InvalidArgument("Invalid data format"));
      OP_REQUIRES(
          context, data_format_ == FORMAT_NHWC,
          errors::InvalidArgument("Default MaxPoolingOp only supports NHWC ",
                                  "on device type ",
                                  DeviceTypeString(context->device_type())));
    } else {
      data_format_ = FORMAT_NHWC;
    }
    OP_REQUIRES_OK(context, context->GetAttr("ksize", &ksize_));
    OP_REQUIRES(context, ksize_.size() == 4,
                errors::InvalidArgument("Sliding window ksize field must "
                                        "specify 4 dimensions"));
    for (int i = 0; i < ksize_.size(); ++i) {
      OP_REQUIRES(context, ksize_[i] > 0,
                  errors::InvalidArgument("Sliding window ksize for dimension ",
                                          i, " was zero."));
    }
    OP_REQUIRES_OK(context, context->GetAttr("strides", &stride_));
    OP_REQUIRES(context, stride_.size() == 4,
                errors::InvalidArgument("Sliding window stride field must "
                                        "specify 4 dimensions"));
    OP_REQUIRES_OK(context, context->GetAttr("padding", &padding_));
    if (padding_ == Padding::EXPLICIT) {
      OP_REQUIRES_OK(
          context, context->GetAttr("explicit_paddings", &explicit_paddings_));
    }
    OP_REQUIRES(context, ksize_[0] == 1 && stride_[0] == 1,
                errors::Unimplemented(
                    "Pooling is not yet supported on the batch dimension."));
  }

  void Compute(OpKernelContext* context) override {
    const Tensor& tensor_in = context->input(0);
    PoolParameters params{
        context,     ksize_,           stride_, padding_, explicit_paddings_,
        FORMAT_NHWC, tensor_in.shape()};
    if (!context->status().ok()) {
      return;
    }

    Tensor* output = nullptr;
    OP_REQUIRES_OK(context, context->allocate_output(
                                0, params.forward_output_shape(), &output));

    if (params.depth_window > 1) {
      // Validate spec against the current implementation.  A
      // relaxation of these requirements would be ideal.
      OP_REQUIRES(context, params.depth % params.depth_window == 0,
                  errors::Unimplemented(
                      "Depthwise max pooling requires "
                      "the depth window to evenly divide the input depth."));
      OP_REQUIRES(
          context, params.depth_window == params.depth_stride,
          errors::Unimplemented("Depthwise max pooling requires "
                                "the depth window to equal the depth stride."));
      OP_REQUIRES(
          context, padding_ != EXPLICIT,
          errors::Unimplemented("Depthwise max pooling does not support "
                                "explicit padding."));

      DepthwiseMaxPool(context, output, tensor_in, params);
    } else {
      // MaxPoolingOp is only called on the GPU when the eigen_tensor label
      // is used. In this case, explicit padding is not supported
      if (std::is_same<Device, GPUDevice>::value &&
          padding_ == Padding::EXPLICIT) {
        context->SetStatus(errors::Unimplemented(
            "MaxPoolingOp does not support explicit padding."));
        return;
      }
      SpatialMaxPool(context, output, tensor_in, params, padding_);
    }
  }

 private:
  // Single-threaded implementation of DepthwiseMaxPool which
  // does not handle all of the same options as SpatialMaxPool
  // (strict assumptions on no padding, stride).
  //
  // TODO(vrv): implement a more general depthwise-max pool that works
  // on GPU as well.
  void DepthwiseMaxPool(OpKernelContext* context, Tensor* output,
                        const Tensor& tensor_in, const PoolParameters& params) {
    Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>>
        in_by_pool(tensor_in.flat<T>().data(), params.depth_window,
                   tensor_in.NumElements() / params.depth_window);
    Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>> out_by_pool(
        output->flat<T>().data(), 1, output->NumElements());
    out_by_pool = in_by_pool.colwise().maxCoeff();
  }

  void SpatialMaxPool(OpKernelContext* context, Tensor* output,
                      const Tensor& tensor_in, const PoolParameters& params,
                      const Padding& padding) {
    // On GPU, use Eigen's Spatial Max Pooling.  On CPU, use an
    // EigenMatrix version that is currently faster than Eigen's
    // Spatial MaxPooling implementation.
    //
    // TODO(vrv): Remove this once we no longer need it.
    if (std::is_same<Device, GPUDevice>::value) {
      Eigen::PaddingType pt = BrainPadding2EigenPadding(padding);
      functor::SpatialMaxPooling<Device, T>()(
          context->eigen_device<Device>(), output->tensor<T, 4>(),
          tensor_in.tensor<T, 4>(), params.window_rows, params.window_cols,
          params.row_stride, params.col_stride, pt);
    } else {
      typedef Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>>
          ConstEigenMatrixMap;
      typedef Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>>
          EigenMatrixMap;

      ConstEigenMatrixMap in_mat(tensor_in.flat<T>().data(), params.depth,
                                 params.tensor_in_cols * params.tensor_in_rows *
                                     params.tensor_in_batch);
      EigenMatrixMap out_mat(
          output->flat<T>().data(), params.depth,
          params.out_width * params.out_height * params.tensor_in_batch);

      const DeviceBase::CpuWorkerThreads& worker_threads =
          *(context->device()->tensorflow_cpu_worker_threads());

      // The following code basically does the following:
      // 1. Flattens the input and output tensors into two dimensional arrays.
      //    tensor_in_as_matrix:
      //      depth by (tensor_in_cols * tensor_in_rows * tensor_in_batch)
      //    output_as_matrix:
      //      depth by (out_width * out_height * tensor_in_batch)
      //
      // 2. Walks through the set of columns in the flattened
      // tensor_in_as_matrix,
      //    and updates the corresponding column(s) in output_as_matrix with the
      //    max value.
      auto shard = [&params, &in_mat, &out_mat](int64 start, int64 limit) {
        const int32 in_rows = params.tensor_in_rows;
        const int32 in_cols = params.tensor_in_cols;
        const int32 pad_top = params.pad_top;
        const int32 pad_left = params.pad_left;
        const int32 window_rows = params.window_rows;
        const int32 window_cols = params.window_cols;
        const int32 row_stride = params.row_stride;
        const int32 col_stride = params.col_stride;
        const int32 out_height = params.out_height;
        const int32 out_width = params.out_width;

        {
          // Initializes the output tensor with MIN<T>.
          const int32 output_image_size = out_height * out_width * params.depth;
          EigenMatrixMap out_shard(out_mat.data() + start * output_image_size,
                                   1, (limit - start) * output_image_size);
          out_shard.setConstant(Eigen::NumTraits<T>::lowest());
        }

        for (int32 b = start; b < limit; ++b) {
          const int32 out_offset_batch = b * out_height;
          for (int32 h = 0; h < in_rows; ++h) {
            for (int32 w = 0; w < in_cols; ++w) {
              // (h_start, h_end) * (w_start, w_end) is the range that the input
              // vector projects to.
              const int32 hpad = h + pad_top;
              const int32 wpad = w + pad_left;
              const int32 h_start = (hpad < window_rows)
                                        ? 0
                                        : (hpad - window_rows) / row_stride + 1;
              const int32 h_end = std::min(hpad / row_stride + 1, out_height);
              const int32 w_start = (wpad < window_cols)
                                        ? 0
                                        : (wpad - window_cols) / col_stride + 1;
              const int32 w_end = std::min(wpad / col_stride + 1, out_width);
              // compute elementwise max
              const int32 in_offset = (b * in_rows + h) * in_cols + w;
              for (int32 ph = h_start; ph < h_end; ++ph) {
                const int32 out_offset_base =
                    (out_offset_batch + ph) * out_width;
                for (int32 pw = w_start; pw < w_end; ++pw) {
                  const int32 out_offset = out_offset_base + pw;
                  out_mat.col(out_offset) =
                      out_mat.col(out_offset).cwiseMax(in_mat.col(in_offset));
                }
              }
            }
          }
        }
      };

      // TODO(andydavis) Consider sharding across batch x rows x cols.
      // TODO(andydavis) Consider a higher resolution shard cost model.
      const int64 shard_cost =
          params.tensor_in_rows * params.tensor_in_cols * params.depth;
      Shard(worker_threads.num_threads, worker_threads.workers,
            params.tensor_in_batch, shard_cost, shard);
    }
  }

  std::vector<int32> ksize_;
  std::vector<int32> stride_;
  Padding padding_;
  std::vector<int64> explicit_paddings_;
  TensorFormat data_format_;
};

template <typename Device>
struct LaunchMaxPoolingNoMask_NCHW_VECT_C;

#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
template <>
struct LaunchMaxPoolingNoMask_NCHW_VECT_C<Eigen::GpuDevice> {
  static void launch(OpKernelContext* context, const PoolParameters& params,
                     const Tensor& input, Tensor* output) {
#if GOOGLE_CUDA
    bool status = functor::MaxPoolForwardNoMask_NCHW_VECT_C()(
        reinterpret_cast<const int32*>(input.flat<qint8>().data()),
        params.tensor_in_batch, params.tensor_in_rows, params.tensor_in_cols,
        params.depth, params.out_height, params.out_width, params.window_rows,
        params.window_cols, params.row_stride, params.col_stride,
        params.pad_top, params.pad_left,
        reinterpret_cast<int32*>(output->flat<qint8>().data()),
        context->eigen_gpu_device());
    if (!status) {
      context->SetStatus(errors::Internal(
          "Failed launching LaunchMaxPoolingNoMask_NCHW_VECT_C"));
    }
#else
    // ROCm TODO: add support __vmaxs4 on ROCm
    context->SetStatus(errors::Internal(
        "Failed launching LaunchMaxPoolingNoMask_NCHW_VECT_C"));
#endif  // GOOGLE_CUDA
  }
};
#endif  // GOOGLE_CUDA || TENSORFLOW_USE_ROCM

template <typename Device, typename T>
class MaxPoolingV2Op : public OpKernel {
 public:
  explicit MaxPoolingV2Op(OpKernelConstruction* context) : OpKernel(context) {
    string data_format;
    auto status = context->GetAttr("data_format", &data_format);
    if (status.ok()) {
      OP_REQUIRES(context, FormatFromString(data_format, &data_format_),
                  errors::InvalidArgument("Invalid data format"));
      OP_REQUIRES(
          context,
          data_format_ == FORMAT_NHWC || data_format_ == FORMAT_NCHW_VECT_C,
          errors::InvalidArgument(
              "MaxPoolingV2Op only supports NHWC or NCHW_VECT_C. Got: ",
              data_format));
    } else {
      data_format_ = FORMAT_NHWC;
    }
    if (context->num_inputs() == 1) {
      OP_REQUIRES_OK(context, context->GetAttr("ksize", &ksize_));
      OP_REQUIRES(context, ksize_.size() == 4,
                  errors::InvalidArgument("Sliding window ksize field must "
                                          "specify 4 dimensions"));
      OP_REQUIRES_OK(context, context->GetAttr("strides", &stride_));
      OP_REQUIRES(context, stride_.size() == 4,
                  errors::InvalidArgument("Sliding window stride field must "
                                          "specify 4 dimensions"));
      OP_REQUIRES(context, ksize_[0] == 1 && stride_[0] == 1,
                  errors::Unimplemented(
                      "Pooling is not yet supported on the batch dimension."));
    }
    OP_REQUIRES_OK(context, context->GetAttr("padding", &padding_));
  }

  void Compute(OpKernelContext* context) override {
    const Tensor& tensor_in = context->input(0);

    std::vector<int32> ksize = ksize_;
    std::vector<int32> stride = stride_;

    if (context->num_inputs() != 1) {
      const Tensor& tensor_ksize = context->input(1);
      auto value_ksize = tensor_ksize.flat<int32>();
      ksize.resize(tensor_ksize.shape().num_elements());
      std::copy_n(&value_ksize(0), ksize.size(), ksize.begin());

      const Tensor& tensor_stride = context->input(2);
      auto value_stride = tensor_stride.flat<int32>();
      stride.resize(tensor_stride.shape().num_elements());
      std::copy_n(&value_stride(0), stride.size(), stride.begin());
    }

    OP_REQUIRES(context, ksize.size() == 4,
                errors::InvalidArgument("Sliding window ksize field must "
                                        "specify 4 dimensions"));
    OP_REQUIRES(context, stride.size() == 4,
                errors::InvalidArgument("Sliding window stride field must "
                                        "specify 4 dimensions"));
    OP_REQUIRES(context, ksize[0] == 1 && stride[0] == 1,
                errors::Unimplemented(
                    "Pooling is not yet supported on the batch dimension."));

    PoolParameters params{
        context,
        ksize,
        stride,
        padding_,
        /*explicit_paddings=*/{},
        data_format_,
        tensor_in.shape(),
    };
    if (!context->status().ok()) {
      return;
    }

    Tensor* output = nullptr;
    OP_REQUIRES_OK(context, context->allocate_output(
                                0, params.forward_output_shape(), &output));

    if (params.depth_window > 1) {
      // Validate spec against the current implementation.  A
      // relaxation of these requirements would be ideal.
      OP_REQUIRES(context, params.depth % params.depth_window == 0,
                  errors::Unimplemented(
                      "Depthwise max pooling requires "
                      "the depth window to evenly divide the input depth."));
      OP_REQUIRES(
          context, params.depth_window == params.depth_stride,
          errors::Unimplemented("Depthwise max pooling requires "
                                "the depth window to equal the depth stride."));

      DepthwiseMaxPool(context, output, tensor_in, params);
    } else {
      SpatialMaxPool(context, output, tensor_in, params, padding_);
    }
  }

 private:
  // Single-threaded implementation of DepthwiseMaxPool which
  // does not handle all of the same options as SpatialMaxPool
  // (strict assumptions on no padding, stride).
  //
  // TODO(vrv): implement a more general depthwise-max pool that works
  // on GPU as well.
  void DepthwiseMaxPool(OpKernelContext* context, Tensor* output,
                        const Tensor& tensor_in, const PoolParameters& params) {
    Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>>
        in_by_pool(tensor_in.flat<T>().data(), params.depth_window,
                   tensor_in.NumElements() / params.depth_window);
    Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>> out_by_pool(
        output->flat<T>().data(), 1, output->NumElements());
    out_by_pool = in_by_pool.colwise().maxCoeff();
  }

  void SpatialMaxPool(OpKernelContext* context, Tensor* output,
                      const Tensor& tensor_in, const PoolParameters& params,
                      const Padding& padding) {
    // On GPU, use Eigen's Spatial Max Pooling.  On CPU, use an
    // EigenMatrix version that is currently faster than Eigen's
    // Spatial MaxPooling implementation.
    //
    // TODO(vrv): Remove this once we no longer need it.
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
    if (std::is_same<Device, GPUDevice>::value) {
      Eigen::PaddingType pt = BrainPadding2EigenPadding(padding);
      if (std::is_same<T, qint8>::value) {
        LaunchMaxPoolingNoMask_NCHW_VECT_C<GPUDevice>::launch(
            context, params, tensor_in, output);
      } else {
        functor::SpatialMaxPooling<Device, T>()(
            context->eigen_device<Device>(), output->tensor<T, 4>(),
            tensor_in.tensor<T, 4>(), params.window_rows, params.window_cols,
            params.row_stride, params.col_stride, pt);
      }
    } else
#endif
    {
      typedef Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>>
          ConstEigenMatrixMap;
      typedef Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>>
          EigenMatrixMap;

      ConstEigenMatrixMap in_mat(tensor_in.flat<T>().data(), params.depth,
                                 params.tensor_in_cols * params.tensor_in_rows *
                                     params.tensor_in_batch);
      EigenMatrixMap out_mat(
          output->flat<T>().data(), params.depth,
          params.out_width * params.out_height * params.tensor_in_batch);

      const DeviceBase::CpuWorkerThreads& worker_threads =
          *(context->device()->tensorflow_cpu_worker_threads());

      // The following code basically does the following:
      // 1. Flattens the input and output tensors into two dimensional arrays.
      //    tensor_in_as_matrix:
      //      depth by (tensor_in_cols * tensor_in_rows * tensor_in_batch)
      //    output_as_matrix:
      //      depth by (out_width * out_height * tensor_in_batch)
      //
      // 2. Walks through the set of columns in the flattened
      // tensor_in_as_matrix,
      //    and updates the corresponding column(s) in output_as_matrix with the
      //    max value.
      auto shard = [&params, &in_mat, &out_mat](int64 start, int64 limit) {
        const int32 in_rows = params.tensor_in_rows;
        const int32 in_cols = params.tensor_in_cols;
        const int32 pad_top = params.pad_top;
        const int32 pad_left = params.pad_left;
        const int32 window_rows = params.window_rows;
        const int32 window_cols = params.window_cols;
        const int32 row_stride = params.row_stride;
        const int32 col_stride = params.col_stride;
        const int32 out_height = params.out_height;
        const int32 out_width = params.out_width;

        {
          // Initializes the output tensor with MIN<T>.
          const int32 output_image_size = out_height * out_width * params.depth;
          EigenMatrixMap out_shard(out_mat.data() + start * output_image_size,
                                   1, (limit - start) * output_image_size);
          out_shard.setConstant(Eigen::NumTraits<T>::lowest());
        }

        for (int32 b = start; b < limit; ++b) {
          const int32 out_offset_batch = b * out_height;
          for (int32 h = 0; h < in_rows; ++h) {
            for (int32 w = 0; w < in_cols; ++w) {
              // (h_start, h_end) * (w_start, w_end) is the range that the input
              // vector projects to.
              const int32 hpad = h + pad_top;
              const int32 wpad = w + pad_left;
              const int32 h_start = (hpad < window_rows)
                                        ? 0
                                        : (hpad - window_rows) / row_stride + 1;
              const int32 h_end = std::min(hpad / row_stride + 1, out_height);
              const int32 w_start = (wpad < window_cols)
                                        ? 0
                                        : (wpad - window_cols) / col_stride + 1;
              const int32 w_end = std::min(wpad / col_stride + 1, out_width);
              // compute elementwise max
              const int32 in_offset = (b * in_rows + h) * in_cols + w;
              for (int32 ph = h_start; ph < h_end; ++ph) {
                const int32 out_offset_base =
                    (out_offset_batch + ph) * out_width;
                for (int32 pw = w_start; pw < w_end; ++pw) {
                  const int32 out_offset = out_offset_base + pw;
                  out_mat.col(out_offset) =
                      out_mat.col(out_offset).cwiseMax(in_mat.col(in_offset));
                }
              }
            }
          }
        }
      };

      // TODO(andydavis) Consider sharding across batch x rows x cols.
      // TODO(andydavis) Consider a higher resolution shard cost model.
      const int64 shard_cost =
          params.tensor_in_rows * params.tensor_in_cols * params.depth;
      Shard(worker_threads.num_threads, worker_threads.workers,
            params.tensor_in_batch, shard_cost, shard);
    }
  }

  std::vector<int32> ksize_;
  std::vector<int32> stride_;
  Padding padding_;
  TensorFormat data_format_;
};

template <typename Device, typename T>
void SpatialAvgPool(OpKernelContext* context, Tensor* output,
                    const Tensor& input, const PoolParameters& params,
                    const Padding& padding) {
  typedef Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>>
      ConstEigenMatrixMap;
  typedef Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>>
      EigenMatrixMap;

  auto in_flat = input.flat<T>();
  auto out_flat = output->flat<T>();

  auto shard = [&params, &in_flat, &out_flat](int64 start, int64 limit) {
    // Calculate indices for this shards chunk of work.
    const int64 input_image_size =
        params.tensor_in_rows * params.tensor_in_cols * params.depth;
    const int64 output_image_size =
        params.out_width * params.out_height * params.depth;
    const int64 shard_batch_size = limit - start;

    ConstEigenMatrixMap in_mat(
        in_flat.data() + start * input_image_size, params.depth,
        params.tensor_in_cols * params.tensor_in_rows * shard_batch_size);
    EigenMatrixMap out_mat(
        out_flat.data() + start * output_image_size, params.depth,
        params.out_width * params.out_height * shard_batch_size);
    Eigen::Matrix<T, Eigen::Dynamic, 1> out_count(out_mat.cols());
    out_count.setZero();

    // Initializes output to zero.
    out_mat.setZero();

    // The following code basically does the following:
    // 1. Flattens the input and output tensors into two dimensional arrays.
    //    tensor_in_as_matrix:
    //      depth by (tensor_in_cols * tensor_in_rows * tensor_in_batch)
    //    output_as_matrix:
    //      depth by (out_width * out_height * tensor_in_batch)
    //
    // 2. Walks through the set of columns in the flattened
    // tensor_in_as_matrix,
    //    and updates the corresponding column(s) in output_as_matrix with the
    //    average value.
    for (int b = 0; b < shard_batch_size; ++b) {
      for (int h = 0; h < params.tensor_in_rows; ++h) {
        for (int w = 0; w < params.tensor_in_cols; ++w) {
          // (h_start, h_end) * (w_start, w_end) is the range that the input
          // vector projects to.
          const int hpad = h + params.pad_top;
          const int wpad = w + params.pad_left;
          const int h_start =
              (hpad < params.window_rows)
                  ? 0
                  : (hpad - params.window_rows) / params.row_stride + 1;
          const int h_end =
              std::min<int>(hpad / params.row_stride + 1, params.out_height);
          const int w_start =
              (wpad < params.window_cols)
                  ? 0
                  : (wpad - params.window_cols) / params.col_stride + 1;
          const int w_end =
              std::min<int>(wpad / params.col_stride + 1, params.out_width);
          const int in_offset =
              (b * params.tensor_in_rows + h) * params.tensor_in_cols + w;
          Eigen::DSizes<Eigen::DenseIndex, 2> in_indices(0, in_offset);
          for (int ph = h_start; ph < h_end; ++ph) {
            for (int pw = w_start; pw < w_end; ++pw) {
              const int out_offset =
                  (b * params.out_height + ph) * params.out_width + pw;
              out_mat.col(out_offset) += in_mat.col(in_offset);
              out_count(out_offset) += T(1);
            }
          }
        }
      }
    }

    DCHECK_GT(out_count.minCoeff(), T(0));
    out_mat.array().rowwise() /= out_count.transpose().array();
  };

  const int64 work_unit_size =
      params.tensor_in_rows * params.tensor_in_cols * params.depth;
  // NOTE: Constants in calculation below were estimated based on benchmarking.
  // Nanoseconds/work_unit for benchmarks ranged from 0.01 to 0.001, and
  // so the factor 0.01 (i.e. 1/100) with a max of 10000, was chosen to limit
  // the work unit cost to an operating range in which it empirically performed
  // best.
  const int64 work_unit_cost = std::max(int64{10000}, work_unit_size / 100);
  const DeviceBase::CpuWorkerThreads& worker_threads =
      *(context->device()->tensorflow_cpu_worker_threads());
  Shard(worker_threads.num_threads, worker_threads.workers,
        params.tensor_in_batch, work_unit_cost, shard);
}

}  // namespace tensorflow

#endif  // TENSORFLOW_CORE_KERNELS_POOLING_OPS_COMMON_H_


text:
require_relative '../spec_helper'

module Selenium
  module WebDriver
    compliant_on browser: [:firefox, :ff_nightly] do
      describe Firefox do
        def restart_remote_server
          server = GlobalTestEnv.reset_remote_server
          server.start
          server.webdriver_url
        end

        before(:all) do
          driver
          quit_driver
        end

        before(:each) do
          @opt = {}
          @browser = if GlobalTestEnv.driver == :remote
                       @opt[:url] = restart_remote_server
                       :remote
                     else
                       :firefox
                     end
        end

        not_compliant_on driver: :remote do
          it 'creates default capabilities' do
            begin
              driver1 = Selenium::WebDriver.for(@browser, @opt)
              caps = driver1.capabilities
              expect(caps.proxy).to be_nil
              expect(caps.platform_name).to_not be_nil
              expect(caps.browser_version).to match(/^\d\d\./)
              expect(caps.platform_version).to_not be_nil

              compliant_on browser: :ff_nightly do
                expect(caps.accept_insecure_certs).to be == false
                expect(caps.page_load_strategy).to be == 'normal'
                expect(caps.accessibility_checks).to be == false
                expect(caps.implicit_timeout).to be == 0
                expect(caps.page_load_timeout).to be == 300000
                expect(caps.script_timeout).to be == 30000
              end

              expect(caps.remote_session_id).to be_nil

              compliant_on browser: :ff_esr do
                expect(caps.rotatable).to be == false
              end
            ensure
              driver1.quit
            end
          end
        end

        # Remote needs to implement firefox options
        not_compliant_on driver: :remote do
          it 'takes a binary path as an argument' do
            pending "Set ENV['ALT_FIREFOX_BINARY'] to test this" unless ENV['ALT_FIREFOX_BINARY']
            begin
              @path = Firefox::Binary.path
              driver1 = Selenium::WebDriver.for @browser, @opt.dup

              default_version = driver1.capabilities.version
              expect { driver1.capabilities.browser_version }.to_not raise_exception
              driver1.quit

              caps = Remote::Capabilities.firefox(firefox_options: {binary: ENV['ALT_FIREFOX_BINARY']})
              @opt[:desired_capabilities] = caps
              driver2 = Selenium::WebDriver.for @browser, @opt

              expect(driver2.capabilities.version).to_not eql(default_version)
              expect { driver2.capabilities.browser_version }.to_not raise_exception
              driver2.quit
            ensure
              Firefox::Binary.path = @path
            end
          end

          it 'gives precedence to firefox options versus argument switch' do
            pending "Set ENV['ALT_FIREFOX_BINARY'] to test this" unless ENV['ALT_FIREFOX_BINARY']
            begin
              @path = Firefox::Binary.path
              driver1 = Selenium::WebDriver.for @browser, @opt.dup

              default_path = Firefox::Binary.path
              default_version = driver1.capabilities.version
              driver1.quit

              caps = Remote::Capabilities.firefox(firefox_options: {binary: ENV['ALT_FIREFOX_BINARY']},
                                                  service_args: {binary: default_path})
              @opt[:desired_capabilities] = caps
              driver2 = Selenium::WebDriver.for @browser, @opt

              expect(driver2.capabilities.version).to_not eql(default_version)
              expect { driver2.capabilities.browser_version }.to_not raise_exception
              driver2.quit
            ensure
              Firefox::Binary.path = @path
            end
          end
        end

        context 'when shared example' do
          it_behaves_like 'driver that can be started concurrently', :firefox
        end
      end
    end
  end # WebDriver
end # Selenium


text:
package com.example.mypc.dogliveshow.main.ui.homepage.homepagereclive;

import com.example.mypc.dogliveshow.base.IBaseModel;
import com.example.mypc.dogliveshow.base.IBasePresenter;
import com.example.mypc.dogliveshow.base.IBaseView;
import com.example.mypc.dogliveshow.bean.homepagetitle.HomePage;
import com.example.mypc.dogliveshow.utils.homepagereclive.HomeRecLiveHttpUtils;

import java.util.HashMap;

/**
 * Created by MyPC on 2016/8/12.
 */
public class HomePageRecLiveContract {
    public interface View extends IBaseView {
        void onSuccess(HomePage list);

        void onFild(String msg);
    }

    public interface Model extends IBaseModel {
        void getData(HashMap<String, String> params, HomeRecLiveHttpUtils.HttpCallback<HomePage> callback);
    }

    public interface Persenter extends IBasePresenter {
        void getData(HashMap<String, String> params);
    }
}


text:
package com.jamonapi;

import com.jamonapi.utils.Misc;
import com.jamonapi.utils.ToArray;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/** Class used to add the label, value and time invoked for the associated monitor.  Used in the
 * jamonBufferListener class.
 *
 * @author steve souza
 */
public final class JAMonDetailValue implements Serializable, ToArray {
    private static final long serialVersionUID = 278L;
    private final MonKey key;
    private final double value; // monitors lastValue
    private final long time;  // invocation time
    private final double active;
    private boolean keyToString=true;
    private Object[] row;

    static JAMonDetailValue NULL_VALUE=new JAMonDetailValue(new MonKeyImp("Null JAMonDetails Object","Null JAMonDetails Object",""),0,0,0);

    public JAMonDetailValue(MonKey key, double value, double active, long time) {
        this.key=key;
        this.value=value;
        this.active=active;
        this.time=time;
    }

    /** Returns label, value, time as an Object[] of 3 values. */
    public Object[] toArray() {
        if (row==null) {
            if (keyToString)
                row = new Object[]{Misc.getAsString(key.getDetails()),new Double(value), new Double(active), new Date(time)};
            else {
                List list=new ArrayList();
                Misc.addTo(list, key.getDetails());
                list.add(new Double(value));
                list.add(new Double(active));
                list.add(new Date(time));
                row=list.toArray();
            }
        }

        return row;
    }

    public void setKeyToString(boolean keyToString) {
        this.keyToString=keyToString;
    }

    public boolean isKeyToString() {
        return keyToString;
    }

}


text:
GW2014-rebond
=============

Arena shooter multijoueur. Gameweek 2014. Evitez les rebonds !


text:
package de.galan.verjson.core;

import java.util.Collections;
import java.util.List;
import java.util.Map;

import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import de.galan.verjson.step.IncrementVersionStep;
import de.galan.verjson.step.NoopStep;
import de.galan.verjson.step.Step;
import de.galan.verjson.step.validation.Validation;

/**
 * StepSequencer used to arrange the Steps
 *
 * @author daniel
 */
public class DefaultStepSequencer implements StepSequencer {

	@Override
	public Map<Long, ProxyStep> sequence(ListMultimap<Long, Step> steps) {
		// Create Proxies
		List<ProxyStep> proxies = createProxies(steps);

		// Sort Proxies
		Collections.sort(proxies, new ProxyStepComparator());

		// create & fillup increments
		List<ProxyStep> proxiesIncrements = fillIncrements(proxies);

		// assign successors
		assignSuccessors(proxiesIncrements);

		// attach SourceVersions to Map
		Map<Long, ProxyStep> proxiesAttached = attachVersions(proxiesIncrements);

		return proxiesAttached;
	}

	protected Map<Long, ProxyStep> attachVersions(List<ProxyStep> proxies) {
		Map<Long, ProxyStep> result = Maps.newHashMap();
		Long lastVersion = 0L;
		for (ProxyStep proxy: proxies) {
			if (proxy.getSourceVersion() > lastVersion) {
				result.put(++lastVersion, proxy);
			}
		}
		return result;
	}

	protected void assignSuccessors(List<ProxyStep> proxies) {
		ProxyStep precessor = null;
		for (ProxyStep step: Lists.reverse(proxies)) {
			if (precessor != null) {
				step.setSuccessor(precessor);
			}
			precessor = step;
		}
	}

	protected List<ProxyStep> createProxies(ListMultimap<Long, Step> steps) {
		List<ProxyStep> list = Lists.newArrayList();
		for (Long sourceVersion: steps.keySet()) {
			for (Step step: steps.get(sourceVersion)) {
				list.add(new ProxyStep(sourceVersion, step));
			}
		}
		return list;
	}

	protected List<ProxyStep> fillIncrements(List<ProxyStep> proxies) {
		List<ProxyStep> result = Lists.newArrayList();
		Long lastSourceVersion = 1L;
		if (!proxies.isEmpty()) {
			boolean increment = false;
			for (ProxyStep proxy: proxies) {
				while(lastSourceVersion < proxy.getSourceVersion()) {
					// add increments
					ProxyStep incProxy = new ProxyStep(lastSourceVersion, new IncrementVersionStep());
					result.add(incProxy);
					lastSourceVersion++;
				}
				//lastSourceVersion = proxy.getSourceVersion();
				increment = !Validation.class.isAssignableFrom(proxy.getStep().getClass());
				result.add(proxy);
			}
			if (increment) {
				// add increment
				result.add(new ProxyStep(lastSourceVersion++, new IncrementVersionStep()));
				result.add(new ProxyStep(lastSourceVersion, new NoopStep()));
			}
		}
		else {
			result.add(new ProxyStep(lastSourceVersion, new NoopStep()));
		}
		return result;
	}

}


text:
FactoryGirl.define do
  factory :event do
    praxis_code 'ABC'
    event_id 'EVENT_ID'
    client_code 'CLIENT_CODE'
    milestone_key 'CLIENT_CODE'
    realm_code 'CLIENT_CODE'
    prosess_code 'CLIENT_CODE'
    stage_code 'CLIENT_CODE'
    add_attribute :sequence, (1..5).to_a.sample
    occurred_at { Time.now }
  end
end


text:
class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  before_action :authenticate_user!

  skip_before_action :verify_authenticity_token, if: :json_request?
  after_filter :set_csrf_cookie

  def set_csrf_cookie
    cookies['XSRF-TOKEN'] = form_authenticity_token if protect_against_forgery?
  end

  def verified_request?
    super || valid_authenticity_token?(session, request.headers['X-XSRF-TOKEN'])
  end

  protected

  def json_request?
    request.format.json?
  end

end


text:
/** @jsx React.DOM */

'use strict';

var React = require('react');
var packageJSON = require('../../package.json');

var PageHeader = React.createClass({displayName: 'PageHeader',
  render: function () {
    return (
        React.DOM.footer( {className:"bs-docs-footer", role:"contentinfo"},
          React.DOM.div( {className:"container"},
            React.DOM.div( {className:"bs-docs-social"},
              React.DOM.ul( {className:"bs-docs-social-buttons"},
                React.DOM.li(null,
                  React.DOM.iframe( {className:"github-btn", src:'http://ghbtns.com/github-btn.html?user=stevoland&repo=react-bootstrap&type=watch&count=true', width:90, height:20, title:"Star on GitHub"} )
                ),
                React.DOM.li(null,
                  React.DOM.iframe( {className:"github-btn", src:'http://ghbtns.com/github-btn.html?user=stevoland&repo=react-bootstrap&type=fork&count=true', width:92, height:20, title:"Fork on GitHub"} )
                )
              )
            ),
            React.DOM.p(null, "Code licensed under ", React.DOM.a( {href:"https://github.com/stevoland/react-bootstrap/blob/master/LICENSE", target:"_blank"}, "MIT"),"."),
            React.DOM.ul( {className:"bs-docs-footer-links muted"},
              React.DOM.li(null, "Currently v",packageJSON.version),
              React.DOM.li(null, "·"),
              React.DOM.li(null, React.DOM.a( {href:"https://github.com/stevoland/react-bootstrap/"}, "GitHub")),
              React.DOM.li(null, "·"),
              React.DOM.li(null, React.DOM.a( {href:"https://github.com/stevoland/react-bootstrap/issues?state=open"}, "Issues")),
              React.DOM.li(null, "·"),
              React.DOM.li(null, React.DOM.a( {href:"https://github.com/stevoland/react-bootstrap/releases"}, "Releases"))
            )
          )
        )
      );
  }
});

module.exports = PageHeader;


text:
public class Zaliczone implements Predicate
{
    public boolean accept(Object s){
        return ((Student)s).ocena >2;
    }
}


text:
require File.join(File.dirname(__FILE__), 'spec_helper')
require 'rdf/jena'
require 'rdf/spec/repository'

describe RDF::Jena::Repository do

  # @see lib/rdf/spec/repository.rb in rdf-spec
  it_behaves_like 'an RDF::Repository' do
    let(:repository) { RDF::Jena::Repository.new('test-data') }
  end
end


text:
package com.example.android.testing.notes.notes;

import com.example.android.testing.notes.R;
import com.example.android.testing.notes.statistics.StatisticsActivity;
import com.example.android.testing.notes.util.EspressoIdlingResource;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.VisibleForTesting;
import android.support.design.widget.NavigationView;
import android.support.test.espresso.IdlingResource;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;

public class NotesActivity extends AppCompatActivity {

    private DrawerLayout mDrawerLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notes);

        // Set up the toolbar.
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar ab = getSupportActionBar();
        ab.setHomeAsUpIndicator(R.drawable.ic_menu);
        ab.setDisplayHomeAsUpEnabled(true);

        // Set up the navigation drawer.
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerLayout.setStatusBarBackground(R.color.colorPrimaryDark);
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        if (navigationView != null) {
            setupDrawerContent(navigationView);
        }

        if (null == savedInstanceState) {
            initFragment(NotesFragment.newInstance());
        }
    }

    private void initFragment(Fragment notesFragment) {
        // Add the NotesFragment to the layout
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.add(R.id.contentFrame, notesFragment);
        transaction.commit();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                // Open the navigation drawer when the home icon is selected from the toolbar.
                mDrawerLayout.openDrawer(GravityCompat.START);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void setupDrawerContent(NavigationView navigationView) {
        navigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(MenuItem menuItem) {
                        switch (menuItem.getItemId()) {
                            case R.id.statistics_navigation_menu_item:
                                startActivity(new Intent(NotesActivity.this, StatisticsActivity.class));
                                break;
                            default:
                                break;
                        }
                        // Close the navigation drawer when an item is selected.
                        menuItem.setChecked(true);
                        mDrawerLayout.closeDrawers();
                        return true;
                    }
                });
    }

    @VisibleForTesting
    public IdlingResource getCountingIdlingResource() {
        return EspressoIdlingResource.getIdlingResource();
    }
}


text:
module.exports = {
  name: 'promise'
, body: Promise.resolve(Date)
}


text:
<?php

final class PholioMockCommentController extends PholioController {

  private $id;

  public function willProcessRequest(array $data) {
    $this->id = $data['id'];
  }

  public function processRequest() {
    $request = $this->getRequest();
    $user = $request->getUser();

    if (!$request->isFormPost()) {
      return new Aphront400Response();
    }

    $mock = id(new PholioMockQuery())
      ->setViewer($user)
      ->withIDs(array($this->id))
      ->needImages(true)
      ->executeOne();

    if (!$mock) {
      return new Aphront404Response();
    }

    $is_preview = $request->isPreviewRequest();

    $draft = PhabricatorDraft::buildFromRequest($request);

    $mock_uri = '/M'.$mock->getID();

    $comment = $request->getStr('comment');

    $xactions = array();

    $inline_comments = id(new PholioTransactionComment())->loadAllWhere(
      'authorphid = %s AND transactionphid IS NULL AND imageid IN (%Ld)',
      $user->getPHID(),
      mpull($mock->getImages(), 'getID'));

    if (!$inline_comments || strlen($comment)) {
      $xactions[] = id(new PholioTransaction())
        ->setTransactionType(PhabricatorTransactions::TYPE_COMMENT)
        ->attachComment(
          id(new PholioTransactionComment())
            ->setContent($comment));
    }

    foreach ($inline_comments as $inline_comment) {
      $xactions[] = id(new PholioTransaction())
        ->setTransactionType(PholioTransactionType::TYPE_INLINE)
        ->attachComment($inline_comment);
    }

    $editor = id(new PholioMockEditor())
      ->setActor($user)
      ->setContentSourceFromRequest($request)
      ->setContinueOnNoEffect($request->isContinueRequest())
      ->setIsPreview($is_preview);

    try {
      $xactions = $editor->applyTransactions($mock, $xactions);
    } catch (PhabricatorApplicationTransactionNoEffectException $ex) {
      return id(new PhabricatorApplicationTransactionNoEffectResponse())
        ->setCancelURI($mock_uri)
        ->setException($ex);
    }

    if ($draft) {
      $draft->replaceOrDelete();
    }

    if ($request->isAjax() && $is_preview) {
      $xaction_view = id(new PholioTransactionView())
        ->setMock($mock);

      return id(new PhabricatorApplicationTransactionResponse())
        ->setViewer($user)
        ->setTransactions($xactions)
        ->setTransactionView($xaction_view)
        ->setIsPreview($is_preview)
        ->setAnchorOffset($request->getStr('anchor'));
    } else {
      return id(new AphrontRedirectResponse())->setURI($mock_uri);
    }
  }

}


text:
package org.apache.camel.component.file.remote.sftp;

import java.security.interfaces.ECPublicKey;

import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.sshd.server.auth.pubkey.PublickeyAuthenticator;
import org.junit.Test;

public class SftpECKeyFileConsumeTest extends SftpServerTestSupport {

    @Test
    public void testSftpSimpleConsume() throws Exception {
        if (!canTest()) {
            return;
        }

        String expected = "Hello World";

        // create file using regular file
        template.sendBodyAndHeader("file://" + FTP_ROOT_DIR, expected, Exchange.FILE_NAME, "hello.txt");

        MockEndpoint mock = getMockEndpoint("mock:result");
        mock.expectedMessageCount(1);
        mock.expectedHeaderReceived(Exchange.FILE_NAME, "hello.txt");
        mock.expectedBodiesReceived(expected);

        context.getRouteController().startRoute("foo");

        assertMockEndpointsSatisfied();
    }

    @Override
    protected PublickeyAuthenticator getPublickeyAuthenticator() {
        return (username, key, session) -> key instanceof ECPublicKey;
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("sftp://localhost:" + getPort() + "/" + FTP_ROOT_DIR
                    + "?username=admin&knownHostsFile=./src/test/resources/known_hosts&privateKeyFile=./src/test/resources/ec.pem&delay=10s&disconnect=true")
                    .routeId("foo").noAutoStartup()
                    .to("mock:result");
            }
        };
    }
}