text:
package org.metaworks;

import java.io.Serializable;
import java.util.*;

import org.metaworks.Type;
import org.metaworks.annotation.*;
import org.metaworks.inputter.CalendarInput;
import org.metaworks.inputter.DateInput;
import org.metaworks.inputter.NumberInput;
import org.metaworks.inputter.SelectInput;
import org.metaworks.inputter.TextInput;

public class WebFieldDescriptor implements Serializable{

	public WebFieldDescriptor(){}

	public WebFieldDescriptor(org.metaworks.FieldDescriptor oldFd){
		setName(oldFd.getName().substring(0, 1).toLowerCase() + oldFd.getName().substring(1));
		setDisplayName(oldFd.getDisplayName().replaceAll("(.)([A-Z])", "$1 $2"));
		setClassName(oldFd.getClassType().getName());

		if(oldFd.getCollectionClass()!=null){
			setCollectionClass(oldFd.getCollectionClass().getName());
		}

		if(oldFd.getViewer()!=null){
			if(oldFd.getViewer() instanceof WebViewer){
				setViewFace(((WebViewer)oldFd.getViewer()).getFace());

			}else
				setViewFace(oldFd.getViewer().getClass().getName());

		}

		if(oldFd.getInputter()!=null && oldFd.getInputter() instanceof SelectInput){
			SelectInput selectInput = (SelectInput) oldFd.getInputter();
			setOptions(selectInput.getSelections());
			setValues(selectInput.getValues());
		}

		if(oldFd.getInputter() instanceof FaceInput){
			FaceInput faceInput = (FaceInput)oldFd.getInputter();

			setInputFace(faceInput.getFace().ejsPath());
			setOptions(faceInput.getFace().options());
			setValues(faceInput.getFace().values());
		}
		else
		if(oldFd.getInputter()!=null
				&& !(oldFd.getInputter() instanceof TextInput)
				&& !(oldFd.getInputter() instanceof NumberInput)
				&& !(oldFd.getInputter() instanceof DateInput)
				&& !(oldFd.getInputter() instanceof CalendarInput)
		)
			setInputFace(WebObjectType.getComponentLocationByEscalation( oldFd.getInputter().getClass(), "genericfaces"));

		if(oldFd.getAttributeTable()!=null){
			for(Object key : oldFd.getAttributeTable().keySet()){
				Object attr = oldFd.getAttribute((String) key);
				//if(attr instanceof Boolean && ((Boolean)attr).booleanValue() == true){
				if(attributes==null)
					attributes = new Properties();

				attributes.put(((String) key).toLowerCase(), attr.toString());//Boolean.valueOf(true));
				//}
			}
		}

	}

	String name;
	@Order(10)
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}

	String displayName;
	@Order(20)
		public String getDisplayName() {
			return displayName;
		}
		public void setDisplayName(String displayName) {
			this.displayName = displayName;
		}

	String className;
	@Order(30)
	@org.metaworks.annotation.Face(options={"vue-component"}, values={"class-selector"})
		public String getClassName() {
			return className;
		}
		public void setClassName(String className) {
			this.className = className;
		}

	String viewFace;
	@Hidden
		public String getViewFace() {
			return viewFace;
		}
		public void setViewFace(String viewFace) {
			this.viewFace = viewFace;
		}

	String inputFace;
	@Hidden
		public String getInputFace() {
			return inputFace;
		}
		public void setInputFace(String editFace) {
			this.inputFace = editFace;
		}

	Object[] options;
	@Hidden
		public Object[] getOptions() {
			return options;
		}
		public void setOptions(Object[] options) {
			this.options = options;
		}

	Object[] values;
	@Hidden
		public Object[] getValues() {
			return values;
		}
		public void setValues(Object[] values) {
			this.values = values;
		}

	String defaultValue;
	@Hidden
		public String getDefaultValue() {
			return defaultValue;
		}

		public void setDefaultValue(String defaultValue) {
			this.defaultValue = defaultValue;
		}

	String collectionClass;
	@Hidden
		public String getCollectionClass() {
			return collectionClass;
		}
		public void setCollectionClass(String collectionClass) {
			this.collectionClass = collectionClass;
		}

//	Map<String, Boolean> boolOptions;
//		public Map<String, Boolean> getBoolOptions() {
//			return boolOptions;
//		}
//		public void setBoolOptions(Map<String, Boolean> boolOptions) {
//			this.boolOptions = boolOptions;
//		}

	Properties attributes;
	@Hidden
		public Properties getAttributes() {
			return attributes;
		}
		public void setAttributes(Properties attributes) {
			this.attributes = attributes;
		}

	public String getAttribute(String name){
		if(attributes != null)
			return attributes.getProperty(name);

		return null;
	}

	public void setAttribute(String propertyName, String s) {

		if(getAttributes()==null) setAttributes(new Properties());

		getAttributes().setProperty(propertyName, s);

	}

	@Override
	public boolean equals(Object obj) {
		if(!(obj instanceof WebFieldDescriptor)) return false;

		if(((WebFieldDescriptor)obj).getName().equals(getName())) return true;

		return false;
	}

}


text:
from docker_scripts.version import version
__version__ = version

redpajama_set_name: RedPajamaGithub


text:
package eta.runtime.interpreter;

import eta.runtime.stg.Value;
import eta.runtime.stg.StgContext;
import eta.runtime.stg.Closure;
import eta.runtime.io.Array;
import eta.runtime.io.ByteArray;

import static eta.runtime.RuntimeLogging.barf;

public class BCO extends Value {
    public final ByteArray instrs;
    public final ByteArray literals;
    public final Array ptrs;
    public final int arity;
    public final int[] bitmap;

    public BCO(ByteArray instrs, ByteArray literals, Array ptrs,
                  int arity, int[] bitmap) {
        this.instrs = instrs;
        this.literals = literals;
        this.ptrs = ptrs;
        this.arity = arity;
        this.bitmap = bitmap;
    }
}


text:
<?php
namespace Slider\Model;

use Zend\InputFilter\Factory as InputFactory;     // <-- Add this import
use Zend\InputFilter\InputFilter;                 // <-- Add this import
use Zend\InputFilter\InputFilterAwareInterface;   // <-- Add this import
use Zend\InputFilter\InputFilterInterface;        // <-- Add this import

class FilterSlider implements InputFilterAwareInterface
{
	public $id;
	public $title;
	public $image;
	public $inputFilter;

	public function exchangeArray($data)
	{
		$this->id     = (isset($data['id']))     ? $data['id']     : null;
		$this->title = (isset($data['title'])) ? $data['title'] : null;
		$this->image = (isset($data['image'])) ? $data['image'] : null;
	}

	// Add content to this method:
	public function setInputFilter(InputFilterInterface $inputFilter)
	{
		throw new \Exception("Not used");
	}

	public function getInputFilter()
	{
		if (!$this->inputFilter) {
			$inputFilter = new InputFilter();
			$factory     = new InputFactory();

			$inputFilter->add($factory->createInput(array(
					'name'     => 'title',
					'required' => true,
					'filters'  => array(
							array('name' => 'StripTags'),
							array('name' => 'StringTrim'),
					),
					'validators' => array(
							array(
									'name'    => 'StringLength',
									'options' => array(
											'encoding' => 'UTF-8',
											'min'      => 1,
											'max'      => 100,
									),
							),
					),
			)));

			$this->inputFilter = $inputFilter;
		}

		return $this->inputFilter;
	}

}


text:
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
 *  Main authors:
 *     Christian Schulte <schulte@gecode.org>
 *
 *  Copyright:
 *     Christian Schulte, 2007
 *
 *  Last modified:
 *     $Date: 2012-09-07 17:31:22 +0200 (Fri, 07 Sep 2012) $ by $Author: schulte $
 *     $Revision: 13068 $
 *
 *  This file is part of Gecode, the generic constraint
 *  development environment:
 *     http://www.gecode.org
 *
 *  Permission is hereby granted, free of charge, to any person obtaining
 *  a copy of this software and associated documentation files (the
 *  "Software"), to deal in the Software without restriction, including
 *  without limitation the rights to use, copy, modify, merge, publish,
 *  distribute, sublicense, and/or sell copies of the Software, and to
 *  permit persons to whom the Software is furnished to do so, subject to
 *  the following conditions:
 *
 *  The above copyright notice and this permission notice shall be
 *  included in all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 *  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 *  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */

#include <gecode/int/rel.hh>
#include <gecode/int/bool.hh>

/**
 * \namespace Gecode::Int::Unshare
 * \brief Unsharing shared variables
 */

namespace Gecode {

 namespace Int { namespace Unshare {

    /// Sort order for variables
    template<class Var>
    class VarPtrLess {
    public:
      forceinline bool
      operator ()(const Var* a, const Var* b) {
        return a->before(*b);
      }
    };

    /// Return a fresh yet equal integer variable
    forceinline ExecStatus
    link(Home home, IntVar** x, int n, IntConLevel icl) {
      if (n > 2) {
        ViewArray<IntView> y(home,n);
        y[0]=*x[0];
        for (int i=1; i<n; i++)
          y[i]=*x[i]=IntVar(home,x[0]->min(),x[0]->max());
        if ((icl == ICL_DOM) || (icl == ICL_DEF)) {
          GECODE_ES_CHECK(Rel::NaryEqDom<IntView>::post(home,y));
        } else {
          GECODE_ES_CHECK(Rel::NaryEqBnd<IntView>::post(home,y));
        }
      } else if (n == 2) {
        *x[1]=IntVar(home,x[0]->min(),x[0]->max());
        if ((icl == ICL_DOM) || (icl == ICL_DEF)) {
          GECODE_ES_CHECK((Rel::EqDom<IntView,IntView>::post
                           (home,*x[0],*x[1])));
        } else {
          GECODE_ES_CHECK((Rel::EqBnd<IntView,IntView>::post
                           (home,*x[0],*x[1])));
        }
      }
      return ES_OK;
    }

    /// Return a fresh yet equal Boolean variable
    forceinline ExecStatus
    link(Home home, BoolVar** x, int n, IntConLevel) {
      if (n > 2) {
        ViewArray<BoolView> y(home,n);
        y[0]=*x[0];
        for (int i=1; i<n; i++)
          y[i]=*x[i]=BoolVar(home,0,1);
        GECODE_ES_CHECK(Bool::NaryEq<BoolView>::post(home,y));
      } else if (n == 2) {
        *x[1] = BoolVar(home,0,1);
        GECODE_ES_CHECK((Bool::Eq<BoolView,BoolView>::post(home,*x[0],*x[1])));
      }
      return ES_OK;
    }

    /// Replace unassigned shared variables by fresh, yet equal variables
    template<class Var>
    forceinline ExecStatus
    unshare(Home home, VarArgArray<Var>& x, IntConLevel icl) {
      int n=x.size();
      if (n < 2)
        return ES_OK;

      Region r(home);
      Var** y = r.alloc<Var*>(n);
      for (int i=n; i--; )
        y[i]=&x[i];

      VarPtrLess<Var> vpl;
      Support::quicksort<Var*,VarPtrLess<Var> >(y,n,vpl);

      // Replace all shared variables with new and equal variables
      for (int i=0; i<n;) {
        int j=i++;
        while ((i<n) && y[j]->same(*y[i]))
          i++;
        if (!y[j]->assigned())
          link(home,&y[j],i-j,icl);
      }
      return ES_OK;
    }

  }}

  void
  unshare(Home home, IntVarArgs& x, IntConLevel icl) {
    if (home.failed()) return;
    GECODE_ES_FAIL(Int::Unshare::unshare<IntVar>(home,x,icl));
  }

  void
  unshare(Home home, BoolVarArgs& x, IntConLevel) {
    if (home.failed()) return;
    GECODE_ES_FAIL(Int::Unshare::unshare<BoolVar>(home,x,ICL_DEF));
  }

}

// STATISTICS: int-post


text:
/*
 * Repo-specific actions - such as deactivation, deletion etc.
 * routes/api/repo.js
 */

var BASE_PATH = '../../lib/';

var _ = require('underscore')
  , logging = require(BASE_PATH + 'logging')
  , User = require(BASE_PATH + 'models').User
  , Job = require(BASE_PATH + 'models').Job
  , Step = require('step')
  ;

/*
 * GET /api/repo
 *
 * @param url Url of repository to look up.
 *
 */

exports.get_index = function(req, res) {

  var url = req.param("url");
  var active = req.param("active");

  function error(err_msg) {
    console.error("repo.get_index() - %s", err_msg);
    var r = {
      errors: [err_msg],
      status: "error"
    };
    res.statusCode = 400;
    return res.end(JSON.stringify(r, null, '\t'));
  }

  function ok(record) {
    var r = {
      errors: [],
      status: "ok",
      results: [record]
    };
    res.statusCode = 200;
    return res.end(JSON.stringify(r, null, '\t'));
  }

  Step(
    function() {
        req.user.get_repo_config(url, this);
    },
    function(err, repo_config, my_access_level, owner_object) {
      if (err) {
        return error("Error fetching Repo Config for url " + url + ": " + err);
      }
      return ok({active: repo_config.active, url:repo_config.url});
    }
  );
};

/*
 * POST /api/repo
 *
 * @param url Url of repository to modify.
 * @param active Boolean specifying whether repo is active or not.
 *
 * Requires admin privileges.
 */

exports.post_index = function(req, res) {

  var url = req.param("url");
  var active = req.param("active");

  function error(err_msg) {
    console.error("repo.post_index() - %s", err_msg);
    var r = {
      errors: [err_msg],
      status: "error"
    };
    res.statusCode = 400;
    return res.end(JSON.stringify(r, null, '\t'));
  }
  function ok() {
    var r = {
      errors: [],
      status: "ok",
      results: []
    };
    res.statusCode = 200;
    return res.end(JSON.stringify(r, null, '\t'));
  }

  if (active == "1" || active.toLowerCase() == "true") {
    active = true;
  } else if (active == "0" || active.toLowerCase() == "false") {
    active = false;
  } else {
    return error("'active' must be one of 1, true, 0, false");
  }

  Step(
    function() {
        req.user.get_repo_config(url, this);
    },
    function(err, repo_config, my_access_level, owner_object) {
      if (err) {
        return error("Error fetching Repo Config for url " + url + ": " + err);
      }
      // must have access_level > 0 to be able to continue;
      if (my_access_level < 1) {
        console.debug("User %s tried to modify activation state of a repo but doesn't have admin privileges on %s (access level: %s)",
          req.user.email, url, my_access_level);
        return error("You must have access level greater than 0 in order to be able to modify activation state.");
      }
      repo_config.active = active;
      owner_object.save(this);
    },
    function(err, repo) {
      if (err) {
        console.error("repo.post_index() - Error modifying active state for url %s by user %s: %s", url, req.user.email, err);
        return error("Error modifying active state for url " + url);
      }
      return ok();
    }
  );
};

/*
 * DELETE /api/repo
 *
 * @param url Url of repository to delete. Also archives all jobs (marks as archived in DB which makes them hidden).
 *
 * Requires admin privs.
 */
exports.delete_index = function(req, res) {

  var url = req.param("url");

  function error(err_msg) {
    console.error("repo.delete_index() - %s", err_msg);
    var r = {
      errors: [err_msg],
      status: "error"
    };
    res.statusCode = 400;
    return res.end(JSON.stringify(r, null, '\t'));
  }
  function ok() {
    var r = {
      errors: [],
      status: "ok",
      results: []
    };
    res.statusCode = 200;
    return res.end(JSON.stringify(r, null, '\t'));
  }

  Step(
    function() {
        req.user.get_repo_config(url, this);
    },
    function(err, repo_config, my_access_level, owner_object) {
      if (err) {
        return error("Error fetching Repo Config for url " + url + ": " + err);
      }
      // must have access_level > 0 to be able to continue;
      if (my_access_level < 1) {
        console.debug("User %s tried to delete repo but doesn't have admin privileges on %s (access level: %s)",
          req.user.email, url, my_access_level);
        return error("You must have access level greater than 0 in order to be able to delete a repo.");
      }
      var now = new Date();
      // Remove the repo config
      User.update({"github_config.url":repo_config.url},
        {$pull:{"github_config":{"url":repo_config.url}}}, this.parallel());
      // Mark all jobs as "archived"
      Job.update({"repo_url":repo_config.url},
        {$set:{"archived_timestamp":now}}, {multi:true}, this.parallel());
    },
    function(err) {
      if (err) {
        console.error("repo.delete_index() - Error deleting repo config for url %s by user %s: %s", url, req.user.email, err);
        return error("Error deleteing repo: " + url);
      }
      return ok();
    }
  );

};


text:
using ppapi::Resource;
using ppapi::URLRequestInfoData;
using ppapi::thunk::EnterResourceNoLock;
using blink::WebData;
using blink::WebHTTPBody;
using blink::WebString;
using blink::WebFrame;
using blink::WebURL;
using blink::WebURLRequest;

namespace content {

namespace {

// Appends the file ref given the Resource pointer associated with it to the
// given HTTP body, returning true on success.
bool AppendFileRefToBody(PP_Instance instance,
                         PP_Resource resource,
                         int64_t start_offset,
                         int64_t number_of_bytes,
                         PP_Time expected_last_modified_time,
                         WebHTTPBody* http_body) {
  base::FilePath platform_path;
  PepperPluginInstanceImpl* instance_impl =
      HostGlobals::Get()->GetInstance(instance);
  if (!instance_impl)
    return false;

  RendererPpapiHost* renderer_ppapi_host =
      instance_impl->module()->renderer_ppapi_host();
  if (!renderer_ppapi_host)
    return false;
  ppapi::host::ResourceHost* resource_host =
      renderer_ppapi_host->GetPpapiHost()->GetResourceHost(resource);
  if (!resource_host || !resource_host->IsFileRefHost())
    return false;
  PepperFileRefRendererHost* file_ref_host =
      static_cast<PepperFileRefRendererHost*>(resource_host);
  switch (file_ref_host->GetFileSystemType()) {
    case PP_FILESYSTEMTYPE_LOCALTEMPORARY:
    case PP_FILESYSTEMTYPE_LOCALPERSISTENT:
      // TODO(kinuko): remove this sync IPC when we fully support
      // AppendURLRange for FileSystem URL.
      RenderThreadImpl::current()->Send(
          new FileSystemHostMsg_SyncGetPlatformPath(
              file_ref_host->GetFileSystemURL(), &platform_path));
      break;
    case PP_FILESYSTEMTYPE_EXTERNAL:
      platform_path = file_ref_host->GetExternalFilePath();
      break;
    default:
      NOTREACHED();
  }
  http_body->appendFileRange(platform_path.AsUTF16Unsafe(),
                             start_offset,
                             number_of_bytes,
                             expected_last_modified_time);
  return true;
}

// Checks that the request data is valid. Returns false on failure. Note that
// method and header validation is done by the URL loader when the request is
// opened, and any access errors are returned asynchronously.
bool ValidateURLRequestData(const URLRequestInfoData& data) {
  if (data.prefetch_buffer_lower_threshold < 0 ||
      data.prefetch_buffer_upper_threshold < 0 ||
      data.prefetch_buffer_upper_threshold <=
          data.prefetch_buffer_lower_threshold) {
    return false;
  }
  return true;
}

}  // namespace

bool CreateWebURLRequest(PP_Instance instance,
                         URLRequestInfoData* data,
                         WebFrame* frame,
                         WebURLRequest* dest) {
  // In the out-of-process case, we've received the URLRequestInfoData
  // from the untrusted plugin and done no validation on it. We need to be
  // sure it's not being malicious by checking everything for consistency.
  if (!ValidateURLRequestData(*data))
    return false;

  dest->initialize();
  dest->setURL(frame->document().completeURL(WebString::fromUTF8(data->url)));
  dest->setDownloadToFile(data->stream_to_file);
  dest->setReportUploadProgress(data->record_upload_progress);

  if (!data->method.empty())
    dest->setHTTPMethod(WebString::fromUTF8(data->method));

  dest->setFirstPartyForCookies(frame->document().firstPartyForCookies());

  const std::string& headers = data->headers;
  if (!headers.empty()) {
    net::HttpUtil::HeadersIterator it(headers.begin(), headers.end(), "\n\r");
    while (it.GetNext()) {
      dest->addHTTPHeaderField(WebString::fromUTF8(it.name()),
                               WebString::fromUTF8(it.values()));
    }
  }

  // Append the upload data.
  if (!data->body.empty()) {
    WebHTTPBody http_body;
    http_body.initialize();
    int file_index = 0;
    for (size_t i = 0; i < data->body.size(); ++i) {
      const URLRequestInfoData::BodyItem& item = data->body[i];
      if (item.is_file) {
        if (!AppendFileRefToBody(instance,
                                 item.file_ref_pp_resource,
                                 item.start_offset,
                                 item.number_of_bytes,
                                 item.expected_last_modified_time,
                                 &http_body))
          return false;
        file_index++;
      } else {
        DCHECK(!item.data.empty());
        http_body.appendData(WebData(item.data));
      }
    }
    dest->setHTTPBody(http_body);
  }

  // Add the "Referer" header if there is a custom referrer. Such requests
  // require universal access. For all other requests, "Referer" will be set
  // after header security checks are done in AssociatedURLLoader.
  if (data->has_custom_referrer_url && !data->custom_referrer_url.empty())
    frame->setReferrerForRequest(*dest, GURL(data->custom_referrer_url));

  if (data->has_custom_content_transfer_encoding &&
      !data->custom_content_transfer_encoding.empty()) {
    dest->addHTTPHeaderField(
        WebString::fromUTF8("Content-Transfer-Encoding"),
        WebString::fromUTF8(data->custom_content_transfer_encoding));
  }

  if (data->has_custom_user_agent) {
    bool was_after_preconnect_request = false;
    RequestExtraData* extra_data = new RequestExtraData();
    extra_data->set_custom_user_agent(
        WebString::fromUTF8(data->custom_user_agent));
    extra_data->set_was_after_preconnect_request(was_after_preconnect_request);
    dest->setExtraData(extra_data);
  }

  return true;
}

bool URLRequestRequiresUniversalAccess(const URLRequestInfoData& data) {
  return data.has_custom_referrer_url ||
         data.has_custom_content_transfer_encoding ||
         data.has_custom_user_agent ||
         url::FindAndCompareScheme(data.url, "javascript", NULL);
}

}  // namespace content


text:
		<ex-dialog id="dialog1" url="/form/agregar/software/" head="Agregar Sotfware" fab="Agregar" icon="add">

		        <paper-button onclick="add_software_envio()">Aceptar</paper-button>
		        <paper-button onclick="close_soft()">Cancelar</paper-button>

		</ex-dialog>


text:
<?php

namespace Cacheable;

class Parts extends Model
{

	public function initialize()
	{
		$this->hasMany('id', 'Cacheable\RobotsParts', 'robots_id', array(
			'alias' => 'RobotsParts'
		));
	}

}


text:
package net.xeger.ssh;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.net.*;
import net.xeger.ssh.ui.*;

import java.util.*;

import javax.swing.SwingUtilities;

public class Application implements Runnable, Session
{
	public static void main(final String args[]) {
		try {
			SwingUtilities.invokeAndWait(new Application(args));
		} catch (InvocationTargetException | InterruptedException e) {
			e.printStackTrace();
			System.exit(-1);
		}
	}

    private Map<String, String>   _parameters  = new HashMap<String, String>();

    private PropertyChangeSupport _thisBean    = new PropertyChangeSupport(this);
    private DialogFrame           _frame       = new DialogFrame("SSH Launcher");
    private GraphicalUI           _ui          = new GraphicalUI(this, _frame);
    private Launchpad             _launchpad   = new Launchpad(_ui);

    public Application(String[] args)
    {
    	for(int i = 0; i < args.length; i++) {
    		String s = args[i];
    		int breakAt = s.indexOf('=');
    		if(breakAt >= 0) {
    			String name = s.substring(0, breakAt);
    			String value = s.substring(breakAt+1);
    			_parameters.put(name, value);
    		}
    		else {
    			String excerpt = s.substring(0, s.length() > 16 ? 16 : s.length());
                throw new IllegalArgumentException(String.format("Malformed command-line argument at position %d; expecting 'k=v', got '%s...'", i, excerpt));
    		}
        }

    	_frame.setContentPane(new net.xeger.ssh.ui.CenteringPanel(_ui));
    }

    /// Run the application.
    public void run()
    {
    	_frame.setVisible(true);

    	Map<KeyFormat, String> privateKeys = new HashMap<KeyFormat, String>();

        try {
	        if( getAuthMethod().equals(AuthMethod.PUBLIC_KEY) ) {
	            if( getUserKeyPath() != null && hasUserKeyFile() ) {
	                privateKeys.put( KeyFormat.OPEN_SSH, getUserPrivateKey() );
	                _ui.log("User OpenSSH private key loaded from local disk");
	            }
	            else if( getSpecialPrivateKey() != null ) {
	                privateKeys.put( KeyFormat.OPEN_SSH, getSpecialPrivateKey() );
	                _ui.log("Server-specific OpenSSH private key loaded from parameters");
	            }
	            else {
	                _ui.log("No OpenSSH private key loaded");
	            }

	            if( getUserKeyPath() != null && hasUserPuttyKeyFile() ) {
	                privateKeys.put( KeyFormat.PUTTY, getUserPuttyPrivateKey() );
	                _ui.log("User PuTTY private key loaded from local disk");
	            }
	            if( getSpecialPuttyPrivateKey() != null ) {
	                privateKeys.put( KeyFormat.PUTTY, getSpecialPuttyPrivateKey() );
	                _ui.log("Server-specific PuTTY private key loaded from local disk");
	            }
	            else {
	                _ui.log("No PuTTY private key loaded");
	            }

	            if(privateKeys.isEmpty() && getUserKeyPath() == null) {
	                throw new IllegalArgumentException("Unable to identify a private key; add openssh-key-material=, putty-key-material= or user-key-path=");
	            }
	        }
	        else if( getAuthMethod().equals(AuthMethod.PASSWORD)) {
	            if(getPassword() != null && getPassword().length() > 0) {
	                _launchpad.setPassword(getPassword());
	            }
	            else {
	                    throw new IllegalArgumentException("Unable to determine password; add password=");
	            }
	        }

	        String uuid = getServerUUID();
	        if(uuid == null) {
	            uuid = getServer();
	        }

	        //Initialize the launchpad business logic
	        _launchpad.setUsername(getUsername());
	        _launchpad.setServer(getServer());
	        _launchpad.setServerUUID(uuid);
	        _launchpad.setPrivateKeys(privateKeys);

			// Arbitrary choose the first available launcher, going through our own setter so
			// we fire a property-change notification for the UI.
			// @todo consult preferences, or ask the user if multiple choices exist
			setLauncher(_launchpad.getLaunchers().get(0));

	        if(_launchpad.isLauncherAvailable()) {
	            _launchpad.run();
	        }
	        else {
	            throw new IllegalArgumentException("No supported SSH client is available.");
	        }
        }
        catch(IllegalArgumentException e) {
            _ui.alert("Cannot launch SSH: " + e.getMessage());
        }
        catch(Exception e) {
            _ui.alert("Cannot launch SSH", e);
        }
    }

    ////
    //// An Applet workalike method for accessing command line parameters, plus getters for the various params we expect
    ////

    protected String getParameter(String name) {
        return _parameters.get(name);
    }

    public String getUsername() {
        String v = getParameter("username");

        if(v != null)
            return v;
        else
            return System.getProperty("user.name");
    }

    public String getServer() {
        String v = getParameter("server");

        if(v != null)
            return v;
        else
            return "localhost";
    }

    public String getServerUUID() {
        return getParameter("server-uuid");
    }

    public String getServerName() {
        String v = getParameter("server-name");

        if(v != null)
            return v;
        else
            return getServer();
    }

    public AuthMethod getAuthMethod() {
        if("password".equals(getParameter("auth-method")))
            return AuthMethod.PASSWORD;
        else
            return AuthMethod.PUBLIC_KEY;
    }

    public String getSpecialPrivateKey() {
        String newline = System.getProperty("line.separator");
        String km = getParameter("openssh-key-material");
        if(km == null) return null;
        return km.replaceAll("\\*", newline);
    }

    public String getSpecialPuttyPrivateKey() {
        String newline = System.getProperty("line.separator");
        String km = getParameter("putty-key-material");
        if(km == null) return null;
        return km.replaceAll("\\*", newline);
    }

    public String getPassword() {
        return getParameter("password");
    }

    public String getUserKeyPath() {
        return getParameter("user-key-path");
    }

    public URL getTroubleshootingLink() {
        try {
            return new URL( getParameter("troubleshooting-url") );
        }
        catch(MalformedURLException e) {
            return null;
        }
    }

    protected File getServerKeyFile() {
        return new File(_launchpad.getSafeDirectory(), getServerUUID());
    }

    protected File getServerPuttyKeyFile() {
        return new File(_launchpad.getSafeDirectory(), getServerUUID() + ".ppk");
    }

    public File getUserKeyFile() {
        String path = getUserKeyPath();
        if(path == null)
            return null;

        //Split the path into elements, accepting either \ or / as a separator
        String[] elements = path.split("/|\\\\");

        String home = System.getProperty("user.home");

        StringBuffer canonPath = new StringBuffer();
        canonPath.append(home);

        for(String elem : elements) {
            canonPath.append(File.separator);
            canonPath.append(elem);
        }

        return new File(canonPath.toString());
    }

	public Launcher getLauncher() {
		return _launchpad.getLauncher();
	}

	public void setLauncher(Launcher launcher) {
		_thisBean.firePropertyChange("launcher", _launchpad.getLauncher(), launcher);
		_launchpad.setLauncher(launcher);
	}

	public void launch() {
		try {
			_launchpad.run();
		} catch (Exception e) {
			_ui.alert("Cannot launch your computer's SSH client", e);
		}
	}

	public void addPropertyChangeListener(PropertyChangeListener listener) {
		_thisBean.addPropertyChangeListener(listener);
	}

	public void removePropertyChangeListener(PropertyChangeListener listener) {
		_thisBean.removePropertyChangeListener(listener);
	}

    protected File getUserPuttyKeyFile() {
        File f = getUserKeyFile();
        String s = f.getPath();

        if(s.endsWith(".ppk")) {
            return f;
        }
        else {
            return new File(s + ".ppk");
        }
    }

    protected boolean hasUserKeyFile() {
        File f = getUserKeyFile();
        return f.exists();
    }

    protected boolean hasUserPuttyKeyFile() {
        File f = getUserPuttyKeyFile();
        return f.exists();
    }

    protected String getUserPrivateKey()
    {
    	BufferedReader br = null;
    	StringBuffer   sb = null;

        try {
            if(hasUserKeyFile()) {
                File f = getUserKeyFile();
                br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
                sb = new StringBuffer();
                while(br.ready()) {
                    sb.append(br.readLine());
                    sb.append("\n");
                }

                return sb.toString();
            }
            else {
                throw new Error("Key file does not exist");
            }
        }
        catch(Exception e) {
            return null;
        }
        finally {
        	if(br != null) {
        		try { br.close(); } catch(Exception e) {}
        	}
        }
    }

    protected String getUserPuttyPrivateKey()
    {
    	BufferedReader br = null;
    	StringBuffer   sb = null;

        try {
            if(hasUserPuttyKeyFile()) {
                File f = getUserPuttyKeyFile();
                br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
                sb = new StringBuffer();
                while(br.ready()) {
                    sb.append(br.readLine());
                    sb.append("\n");
                }

                return sb.toString();
            }
            else {
                throw new Error("Key file does not exist");
            }
        }
        catch(Exception e) {
            return null;
        }
        finally {
        	if(br != null) {
        		try { br.close(); } catch(Exception e) {}
        	}
        }
    }
}


text:
package com.blazebit.weblink.server.weblinkgroup;

import javax.faces.application.FacesMessage;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import java.util.logging.Level;
import java.util.logging.Logger;

@Named
@ViewScoped
public class WeblinkGroupEditPage extends WeblinkGroupAddPage {

	private static final long serialVersionUID = 1L;
	private static final Logger LOG = Logger.getLogger(WeblinkGroupEditPage.class.getName());

	public String update() {
		try {
			put();
			return null;
		} catch (RuntimeException ex) {
			facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Could not put weblink group", null));
			LOG.log(Level.SEVERE, "Could not put weblink group " + name, ex);
			return null;
		}
	}

}


text:
'''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GL import _types as _cs
# End users want this...
from OpenGL.raw.GL._types import *
from OpenGL.raw.GL import _errors
from OpenGL.constant import Constant as _C

import ctypes
_EXTENSION_NAME = 'GL_AMD_depth_clamp_separate'
def _f( function ):
    return _p.createFunction( function,_p.PLATFORM.GL,'GL_AMD_depth_clamp_separate',error_checker=_errors._error_checker)
GL_DEPTH_CLAMP_FAR_AMD=_C('GL_DEPTH_CLAMP_FAR_AMD',0x901F)
GL_DEPTH_CLAMP_NEAR_AMD=_C('GL_DEPTH_CLAMP_NEAR_AMD',0x901E)


text:
package io.sarl.tests.api;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/** Annotation for indicating that a unit test is maunally mocked.
 *
 * <p>If not present, the @Mock and @InjectMocks will be considered.
 *
 * @author $Author: sgalland$
 * @version $FullVersion$
 * @mavengroupid $GroupId$
 * @mavenartifactid $ArtifactId$
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface ManualMocking {
	//
}


text:
AddCSLuaFile()

local PANEL = {}
local PlayerVoicePanels = {}

function PANEL:Init()

	self.LabelName = vgui.Create( "DLabel", self )
	self.LabelName:SetFont( "GModNotify" )
	self.LabelName:Dock( FILL )
	self.LabelName:DockMargin( 8, 0, 0, 0 )
	self.LabelName:SetTextColor( Color( 255, 255, 255, 255 ) )

	self.Avatar = vgui.Create( "AvatarImage", self )
	self.Avatar:Dock( LEFT )
	self.Avatar:SetSize( 32, 32 )

	self.Color = color_transparent

	self:SetSize( 250, 32 + 8 )
	self:DockPadding( 4, 4, 4, 4 )
	self:DockMargin( 2, 2, 2, 2 )
	self:Dock( BOTTOM )

end

function PANEL:Setup( ply )

	self.ply = ply
	self.LabelName:SetText( ply:Nick() )
	self.Avatar:SetPlayer( ply )

	self.Color = team.GetColor( ply:Team() )

	self:InvalidateLayout()

end

function PANEL:Paint( w, h )

	if ( !IsValid( self.ply ) ) then return end

	draw.RoundedBox( 4, 0, 0, w, h, self.Color )

end

function PANEL:Think()

	if ( IsValid( self.ply ) ) then
		self.LabelName:SetText( self.ply:Nick() )
	end

	if ( self.fadeAnim ) then
		self.fadeAnim:Run()
	end

end

function PANEL:FadeOut( anim, delta, data )

	if ( anim.Finished ) then

		if ( IsValid( PlayerVoicePanels[ self.ply ] ) ) then
			PlayerVoicePanels[ self.ply ]:Remove()
			PlayerVoicePanels[ self.ply ] = nil
			return
		end

	return end

	self:SetAlpha( 255 - (255 * delta) )

end

derma.DefineControl( "VoiceNotify", "", PANEL, "DPanel" )

function GM:PlayerStartVoice( ply )

	if ( !IsValid( g_VoicePanelList ) ) then return end

	-- There'd be an exta one if voice_loopback is on, so remove it.
	GAMEMODE:PlayerEndVoice( ply )

	if ( IsValid( PlayerVoicePanels[ ply ] ) ) then

		if ( PlayerVoicePanels[ ply ].fadeAnim ) then
			PlayerVoicePanels[ ply ].fadeAnim:Stop()
			PlayerVoicePanels[ ply ].fadeAnim = nil
		end

		PlayerVoicePanels[ ply ]:SetAlpha( 255 )

		return

	end

	if ( !IsValid( ply ) ) then return end

	local pnl = g_VoicePanelList:Add( "VoiceNotify" )
	pnl:Setup( ply )

	PlayerVoicePanels[ ply ] = pnl

end

local function VoiceClean()

	for k, v in pairs( PlayerVoicePanels ) do

		if ( !IsValid( k ) ) then
			GAMEMODE:PlayerEndVoice( k )
		end

	end

end
timer.Create( "VoiceClean", 10, 0, VoiceClean )

function GM:PlayerEndVoice( ply )

	if ( IsValid( PlayerVoicePanels[ ply ] ) ) then

		if ( PlayerVoicePanels[ ply ].fadeAnim ) then return end

		PlayerVoicePanels[ ply ].fadeAnim = Derma_Anim( "FadeOut", PlayerVoicePanels[ ply ], PlayerVoicePanels[ ply ].FadeOut )
		PlayerVoicePanels[ ply ].fadeAnim:Start( 2 )

	end

end

local function CreateVoiceVGUI()

	g_VoicePanelList = vgui.Create( "DPanel" )

	g_VoicePanelList:ParentToHUD()
	--g_VoicePanelList:SetPos( ScrW() - 300, 100 )
	g_VoicePanelList:SetPos( ScrW() - 300, 100 )
	g_VoicePanelList:SetSize( 250, ScrH() - 300 )
	g_VoicePanelList:SetDrawBackground( false )

end
hook.Add( "InitPostEntity", "CreateVoiceVGUI", CreateVoiceVGUI )


text:
import { APP_ID, APPLICATION_COMMON_PROVIDERS, AppViewManager, DirectiveResolver, DynamicComponentLoader, Injector, NgZone, Renderer, Provider, ViewResolver, provide } from 'angular2/core';
import { AnimationBuilder } from 'angular2/src/animate/animation_builder';
import { MockAnimationBuilder } from 'angular2/src/mock/animation_builder_mock';
import { ProtoViewFactory } from 'angular2/src/core/linker/proto_view_factory';
import { Reflector, reflector } from 'angular2/src/core/reflection/reflection';
import { IterableDiffers, defaultIterableDiffers, KeyValueDiffers, defaultKeyValueDiffers, ChangeDetectorGenConfig } from 'angular2/src/core/change_detection/change_detection';
import { ExceptionHandler } from 'angular2/src/facade/exceptions';
import { PipeResolver } from 'angular2/src/core/linker/pipe_resolver';
import { XHR } from 'angular2/src/compiler/xhr';
import { DOM } from 'angular2/src/platform/dom/dom_adapter';
import { MockDirectiveResolver } from 'angular2/src/mock/directive_resolver_mock';
import { MockViewResolver } from 'angular2/src/mock/view_resolver_mock';
import { MockLocationStrategy } from 'angular2/src/mock/mock_location_strategy';
import { LocationStrategy } from 'angular2/src/router/location_strategy';
import { MockNgZone } from 'angular2/src/mock/ng_zone_mock';
import { TestComponentBuilder } from './test_component_builder';
import { EventManager, EVENT_MANAGER_PLUGINS, ELEMENT_PROBE_PROVIDERS } from 'angular2/platform/common_dom';
import { ListWrapper } from 'angular2/src/facade/collection';
import { FunctionWrapper } from 'angular2/src/facade/lang';
import { AppViewPool, APP_VIEW_POOL_CAPACITY } from 'angular2/src/core/linker/view_pool';
import { AppViewManagerUtils } from 'angular2/src/core/linker/view_manager_utils';
import { DOCUMENT } from 'angular2/src/platform/dom/dom_tokens';
import { DomRenderer } from 'angular2/src/platform/dom/dom_renderer';
import { DomSharedStylesHost } from 'angular2/src/platform/dom/shared_styles_host';
import { SharedStylesHost } from 'angular2/src/platform/dom/shared_styles_host';
import { DomEventsPlugin } from 'angular2/src/platform/dom/events/dom_events';
import { Serializer } from "angular2/src/web_workers/shared/serializer";
import { Log } from './utils';
import { COMPILER_PROVIDERS } from 'angular2/src/compiler/compiler';
import { DomRenderer_ } from "angular2/src/platform/dom/dom_renderer";
import { DynamicComponentLoader_ } from "angular2/src/core/linker/dynamic_component_loader";
import { AppViewManager_ } from "angular2/src/core/linker/view_manager";
/**
 * Returns the root injector providers.
 *
 * This must be kept in sync with the _rootBindings in application.js
 *
 * @returns {any[]}
 */
function _getRootProviders() {
    return [provide(Reflector, { useValue: reflector })];
}
/**
 * Returns the application injector providers.
 *
 * This must be kept in sync with _injectorBindings() in application.js
 *
 * @returns {any[]}
 */
function _getAppBindings() {
    var appDoc;
    // The document is only available in browser environment
    try {
        appDoc = DOM.defaultDoc();
    }
    catch (e) {
        appDoc = null;
    }
    return [
        APPLICATION_COMMON_PROVIDERS,
        provide(ChangeDetectorGenConfig, { useValue: new ChangeDetectorGenConfig(true, false, true) }),
        provide(DOCUMENT, { useValue: appDoc }),
        provide(DomRenderer, { useClass: DomRenderer_ }),
        provide(Renderer, { useExisting: DomRenderer }),
        provide(APP_ID, { useValue: 'a' }),
        DomSharedStylesHost,
        provide(SharedStylesHost, { useExisting: DomSharedStylesHost }),
        AppViewPool,
        provide(AppViewManager, { useClass: AppViewManager_ }),
        AppViewManagerUtils,
        Serializer,
        ELEMENT_PROBE_PROVIDERS,
        provide(APP_VIEW_POOL_CAPACITY, { useValue: 500 }),
        ProtoViewFactory,
        provide(DirectiveResolver, { useClass: MockDirectiveResolver }),
        provide(ViewResolver, { useClass: MockViewResolver }),
        provide(IterableDiffers, { useValue: defaultIterableDiffers }),
        provide(KeyValueDiffers, { useValue: defaultKeyValueDiffers }),
        Log,
        provide(DynamicComponentLoader, { useClass: DynamicComponentLoader_ }),
        PipeResolver,
        provide(ExceptionHandler, { useValue: new ExceptionHandler(DOM) }),
        provide(LocationStrategy, { useClass: MockLocationStrategy }),
        provide(XHR, { useClass: DOM.getXHR() }),
        TestComponentBuilder,
        provide(NgZone, { useClass: MockNgZone }),
        provide(AnimationBuilder, { useClass: MockAnimationBuilder }),
        EventManager,
        new Provider(EVENT_MANAGER_PLUGINS, { useClass: DomEventsPlugin, multi: true })
    ];
}
function _runtimeCompilerBindings() {
    return [
        provide(XHR, { useClass: DOM.getXHR() }),
        COMPILER_PROVIDERS,
    ];
}
export function createTestInjector(providers) {
    var rootInjector = Injector.resolveAndCreate(_getRootProviders());
    return rootInjector.resolveAndCreateChild(ListWrapper.concat(_getAppBindings(), providers));
}
export function createTestInjectorWithRuntimeCompiler(providers) {
    return createTestInjector(ListWrapper.concat(_runtimeCompilerBindings(), providers));
}
/**
 * Allows injecting dependencies in `beforeEach()` and `it()`.
 *
 * Example:
 *
 * ```
 * beforeEach(inject([Dependency, AClass], (dep, object) => {
 *   // some code that uses `dep` and `object`
 *   // ...
 * }));
 *
 * it('...', inject([AClass], (object) => {
 *   object.doSomething();
 *   expect(...);
 * })
 * ```
 *
 * Notes:
 * - inject is currently a function because of some Traceur limitation the syntax should eventually
 *   becomes `it('...', @Inject (object: AClass, async: AsyncTestCompleter) => { ... });`
 *
 * @param {Array} tokens
 * @param {Function} fn
 * @return {FunctionWithParamTokens}
 */
export function inject(tokens, fn) {
    return new FunctionWithParamTokens(tokens, fn, false);
}
/**
 * Allows injecting dependencies in `beforeEach()` and `it()`. The test must return
 * a promise which will resolve when all asynchronous activity is complete.
 *
 * Example:
 *
 * ```
 * it('...', injectAsync([AClass], (object) => {
 *   return object.doSomething().then(() => {
 *     expect(...);
 *   });
 * })
 * ```
 *
 * @param {Array} tokens
 * @param {Function} fn
 * @return {FunctionWithParamTokens}
 */
export function injectAsync(tokens, fn) {
    return new FunctionWithParamTokens(tokens, fn, true);
}
export class FunctionWithParamTokens {
    constructor(_tokens, _fn, isAsync) {
        this._tokens = _tokens;
        this._fn = _fn;
        this.isAsync = isAsync;
    }
    /**
     * Returns the value of the executed function.
     */
    execute(injector) {
        var params = this._tokens.map(t => injector.get(t));
        return FunctionWrapper.apply(this._fn, params);
    }
    hasToken(token) { return this._tokens.indexOf(token) > -1; }
}


text:
package uk.gov.gchq.gaffer.rest.service.v1;

import uk.gov.gchq.gaffer.core.exception.GafferRuntimeException;
import uk.gov.gchq.gaffer.core.exception.Status;
import uk.gov.gchq.gaffer.rest.SystemStatus;
import uk.gov.gchq.gaffer.rest.factory.GraphFactory;
import uk.gov.gchq.gaffer.rest.factory.UserFactory;

import javax.inject.Inject;

/**
 * An implementation of {@link IStatusService}.
 * By default it will use a singleton {@link uk.gov.gchq.gaffer.graph.Graph} generated
 * using the {@link uk.gov.gchq.gaffer.rest.factory.GraphFactory}.
 * All operations are simply delegated to the graph.
 * Pre and post operation hooks are available by extending this class and implementing
 * preOperationHook and/or postOperationHook.
 * <p>
 * By default queries will be executed with an UNKNOWN user containing no auths.
 * The {@link UserFactory#createUser()} method should be overridden and a {@link uk.gov.gchq.gaffer.user.User}
 * object should be created from the http request.
 * </p>
 */
public class StatusService implements IStatusService {

    @Inject
    private GraphFactory graphFactory;

    @Inject
    private UserFactory userFactory;

    @Override
    public SystemStatus status() {
        try {
            if (null != graphFactory.getGraph()) {
                return SystemStatus.UP;
            }
        } catch (final Exception e) {
            throw new GafferRuntimeException("Unable to create graph.", e, Status.INTERNAL_SERVER_ERROR);
        }

        return SystemStatus.DOWN;
    }
}


text:
<link rel='import' href='../polymer/polymer.html'>
<link rel="stylesheet" href="vendor/prismjs/prism.css">

<dom-module id="code-example">

  <template>

      <content select=":not(code)"></content>

  </template>
</dom-module>


text:
namespace Nektar { template <typename Dim, typename DataType> class Array; }

namespace Nektar
{
    namespace LibUtilities
    {
      // Coefficient Space Interpolation methods

      // 1D Interpolation
      LIB_UTILITIES_EXPORT void InterpCoeff1D(const BasisKey &fbasis0,
			 const Array<OneD, const NekDouble>& from,
			 const BasisKey &tbasis0,
			 Array<OneD, NekDouble> &to);

    } // end of namespace
} // end of namespace
#endif


text:
from scripts import proj1_helpers, helpers, implementation, feature_processing, k_fold
import numpy as np

# Configuration
train_path = '../data/train.csv'
test_path  = '../data/test.csv'
output_path = 'logreg_1_submission.csv'
deg = 5
lambda_ = 2e-4
gamma = 0.1
max_iters = [50, 20]

# Loading data
print("Loading data")
y, X, idx = proj1_helpers.load_csv_data(train_path)
y_t, X_t, ids_t = proj1_helpers.load_csv_data(test_path)

print("Preprocessing data")
X_p, (x_mean, x_std) = feature_processing.process_X(X, deg)
X_t_p, _ = feature_processing.process_X(X_t, deg, (x_mean, x_std))

#Logistic regression

# Converting -1,1 to 0,1
y_01 = helpers.y_to_01(np.array([y]).T)

# starting point: zero vector
w0 = np.zeros((X_p.shape[1], 1))

# These phases can be merged into one. They are kept this way to make the resulting file same as for kaggle
print("Training 1")
np.random.seed(42)
w01, l = implementation.reg_logistic_regression_newton(y_01, X_p, lambda_ = lambda_,
                                                      initial_w = w0, max_iters = max_iters[0], gamma = gamma,
                                                      debug = False)

print("Training 2")
np.random.seed(42)
w010, l = implementation.reg_logistic_regression_newton(y_01, X_p, lambda_ = lambda_,
                                                      initial_w = w01, max_iters = max_iters[1], gamma = gamma,
                                                      debug = False)
# Saving results to submission file
y_pred = proj1_helpers.predict_labels(w010, X_t_p)
proj1_helpers.create_csv_submission(ids_t, y_pred, output_path)


text:
module Fume
  module Nav
    class NavTag
      attr_accessor :helper, :current, :active_class, :inactive_class, :hide_if_empty

      def initialize(attributes = {})
        attributes.each_pair do |name, value|
          send("#{name}=", value)
        end
        @empty = true
      end

      def hide?
        hide_if_empty && @empty
      end

      def li_tag(value, options = {}, &block)
        content_tag(value, :li, options, &block)
      end

      def link_to(value, *args, &block)
        options = args.extract_options!
        apply_active_options(value, options)
        helper.link_to(*args, options, &block)
      end

      def content_tag(value, tag_name, options = {}, &block)
        apply_active_options(value, options)
        helper.content_tag(tag_name, options, &block)
      end

      def apply_active_options(value, options)
        apply(value) do |cls|
          if options[:class]
            options[:class] += " #{cls}"
          else
            options[:class] = "#{cls}"
          end
        end

        @empty = false
      end

      def match?(source, target)
        case source
        when Array
          source.each_with_index.all? { |value, index| match?(value, target[index]) }
        when Regexp
          source.match(target)
        else
          source.to_s == target.to_s
        end
      end

      def apply(value, &block)
        result = match?(value, current)
        block.call(result ? active_class : inactive_class)
      end

      def apply_content(value, &block)
        @empty = false

        apply(value) do |cls|
          helper.capture(cls, &block)
        end
      end
    end
  end
end


text:
package org.apache.harmony.jndi.tests.javax.naming.spi;

import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.spi.ResolveResult;
import javax.naming.spi.Resolver;

public class MockResolver implements Resolver {

	/*
	 * (non-Javadoc)
	 *
	 * @see javax.naming.spi.Resolver#resolveToClass(javax.naming.Name,
	 *      java.lang.Class)
	 */
	public ResolveResult resolveToClass(Name n, Class<? extends Context> c) throws NamingException {
		return null;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see javax.naming.spi.Resolver#resolveToClass(java.lang.String,
	 *      java.lang.Class)
	 */
	public ResolveResult resolveToClass(String n, Class<? extends Context> c)
			throws NamingException {
		return null;
	}

}


text:
'use strict';

export type RNTesterBackAction = {
  type: 'RNTesterBackAction',
};

export type RNTesterListAction = {
  type: 'RNTesterListAction',
};

export type RNTesterExampleAction = {
  type: 'RNTesterExampleAction',
  openExample: string,
};

export type RNTesterAction = (
  RNTesterBackAction |
  RNTesterListAction |
  RNTesterExampleAction
);

function Back(): RNTesterBackAction {
  return {
    type: 'RNTesterBackAction',
  };
}

function ExampleList(): RNTesterListAction {
  return {
    type: 'RNTesterListAction',
  };
}

function ExampleAction(openExample: string): RNTesterExampleAction {
  return {
    type: 'RNTesterExampleAction',
    openExample,
  };
}

const RNTesterActions = {
  Back,
  ExampleList,
  ExampleAction,
};

module.exports = RNTesterActions;


text:
#include "ARDroneTypes.h"

/**
 * Define a protocol to make it possible for the game engine to callback the Parrot library
 */
@protocol ARDroneProtocolIn<NSObject>
/**
 * Change the state of the library.

 * Note: It is the library sole responsability to handle change of states and modify its behavior; basically, it should pause some of the threads when "paused" then resume everything back to normal when "running".
 *
 * @param inGame Boolean flag that indicates whether the library state shall change to "running" (YES) or "pause" (NO).
 */
- (void)changeState:(BOOL)inGame;

/**
 * Send a command informaton.
 *
 * @commandIn Command structure : identifier, parameters, callback. (each sender has to define its own identifiers; the receiver has to check which sender is calling and react accordingly).
 * @sender Pointer to the object that requests the change of state.
 * @refresh If the menu settings should be refreshed at the end of the command
 */
- (void)executeCommandIn:(ARDRONE_COMMAND_IN_WITH_PARAM)commandIn fromSender:(id)sender refreshSettings:(BOOL)refresh;

/**
 * Send a default configuration for the application (must be sent before the navdata thread is launched)
 *
 * @key Config key to set the default value
 * @value pointer to the application default value of the config key
 */
- (void)setDefaultConfigurationForKey:(ARDRONE_CONFIG_KEYS)key withValue:(void *)value;

/**
 * Send a command informaton.
 *
 * @commandId Command identification number (each sender has to define its own identifiers; the receiver has to check which sender is calling and react accordingly).
 * @parameter parameter for the command
 * @sender Pointer to the object that requests the change of state.
 */
- (void)executeCommandIn:(ARDRONE_COMMAND_IN)commandId withParameter:(void*)parameter fromSender:(id)sender __attribute__((deprecated));

/**
 * Check the state of the library.
 *
 * @return Boolean flag that indicates whether the library is running (YES) or paused (NO).
 */
- (BOOL)checkState;

@optional
/**
 * Get the latest drone's navigation data.
 *
 * @param data Pointer to a navigation data structure.
 */
- (void)navigationData:(ARDroneNavigationData*)data;

/**
 * Get the latest detection camera structure (rotation and translation).
 *
 * @param data Pointer to a detection camera structure.
 */
- (void)detectionCamera:(ARDroneDetectionCamera*)camera;

/**
 * Get the latest drone camera structure (rotation and translation).
 *
 * @param data Pointer to a drone camera structure.
 */
- (void)droneCamera:(ARDroneCamera*)camera;

/**
 * Exchange enemies data.

 * Note: basically, data should be provided by the Parrot library when in multiplayer mode (enemy type = "HUMAN"), and by the game controller when in single player mode (enemy type = "AI").
 *
 * @param data Pointer to an enemies data structure.
 */
- (void)humanEnemiesData:(ARDroneEnemiesData*)data;

@end

/**
 * Define a protocol to make it possible for the Parrot library to callback the game engine
 */
@protocol ARDroneProtocolOut<NSObject>

/**
 * Send a command informaton.
 *
 * @commandId Command identification number (each sender has to define its own identifiers; the receiver has to check which sender is calling and react accordingly).
 * @sender Pointer to the object that requests the change of state.
 */
- (void)executeCommandOut:(ARDRONE_COMMAND_OUT)commandId withParameter:(void*)parameter fromSender:(id)sender;

@optional
/**
 * Exchange AI enemies data.

 * Note: basically, data should be provided by the Parrot library when in multiplayer mode (enemy type = "HUMAN"), and by the game controller when in single player mode (enemy type = "AI").
 *
 * @param data Pointer to an enemies data structure.
 */
- (void)AIEnemiesData:(ARDroneEnemiesData*)data;

@end


text:
namespace StatTag.Controls
{
    partial class ValueProperties
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
            this.lblDefault = new System.Windows.Forms.Label();
            this.cboType = new System.Windows.Forms.ComboBox();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
            this.numericValueProperties1 = new StatTag.Controls.NumericValueProperties();
            this.percentageValueProperties1 = new StatTag.Controls.PercentageValueProperties();
            this.dateTimeValueProperties1 = new StatTag.Controls.DateTimeValueProperties();
            this.horizontalLine1 = new StatTag.Controls.HorizontalLine();
            flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
            flowLayoutPanel1.SuspendLayout();
            this.tableLayoutPanel1.SuspendLayout();
            this.SuspendLayout();
            //
            // flowLayoutPanel1
            //
            flowLayoutPanel1.AutoSize = true;
            flowLayoutPanel1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
            this.tableLayoutPanel1.SetColumnSpan(flowLayoutPanel1, 2);
            flowLayoutPanel1.Controls.Add(this.lblDefault);
            flowLayoutPanel1.Controls.Add(this.numericValueProperties1);
            flowLayoutPanel1.Controls.Add(this.percentageValueProperties1);
            flowLayoutPanel1.Controls.Add(this.dateTimeValueProperties1);
            flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
            flowLayoutPanel1.Location = new System.Drawing.Point(3, 93);
            flowLayoutPanel1.Name = "flowLayoutPanel1";
            flowLayoutPanel1.Size = new System.Drawing.Size(547, 190);
            flowLayoutPanel1.TabIndex = 13;
            //
            // lblDefault
            //
            this.lblDefault.AutoSize = true;
            this.lblDefault.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.lblDefault.Location = new System.Drawing.Point(3, 0);
            this.lblDefault.Name = "lblDefault";
            this.lblDefault.Size = new System.Drawing.Size(541, 28);
            this.lblDefault.TabIndex = 2;
            this.lblDefault.Text = "Default is the exact same output from the statistical package.";
            //
            // cboType
            //
            this.cboType.Dock = System.Windows.Forms.DockStyle.Fill;
            this.cboType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cboType.FormattingEnabled = true;
            this.cboType.Location = new System.Drawing.Point(84, 31);
            this.cboType.Name = "cboType";
            this.cboType.Size = new System.Drawing.Size(466, 36);
            this.cboType.TabIndex = 5;
            this.cboType.SelectedIndexChanged += new System.EventHandler(this.cboType_SelectedIndexChanged);
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.label1.Location = new System.Drawing.Point(3, 28);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(75, 42);
            this.label1.TabIndex = 6;
            this.label1.Text = "Format";
            this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.tableLayoutPanel1.SetColumnSpan(this.label2, 2);
            this.label2.Dock = System.Windows.Forms.DockStyle.Fill;
            this.label2.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label2.Location = new System.Drawing.Point(0, 0);
            this.label2.Margin = new System.Windows.Forms.Padding(0);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(553, 28);
            this.label2.TabIndex = 7;
            this.label2.Text = "Value Options";
            //
            // tableLayoutPanel1
            //
            this.tableLayoutPanel1.AutoSize = true;
            this.tableLayoutPanel1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
            this.tableLayoutPanel1.ColumnCount = 2;
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
            this.tableLayoutPanel1.Controls.Add(this.label2, 0, 0);
            this.tableLayoutPanel1.Controls.Add(this.horizontalLine1, 0, 2);
            this.tableLayoutPanel1.Controls.Add(this.label1, 0, 1);
            this.tableLayoutPanel1.Controls.Add(this.cboType, 1, 1);
            this.tableLayoutPanel1.Controls.Add(flowLayoutPanel1, 0, 3);
            this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0);
            this.tableLayoutPanel1.Name = "tableLayoutPanel1";
            this.tableLayoutPanel1.Padding = new System.Windows.Forms.Padding(0, 0, 5, 0);
            this.tableLayoutPanel1.RowCount = 4;
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F));
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
            this.tableLayoutPanel1.Size = new System.Drawing.Size(558, 286);
            this.tableLayoutPanel1.TabIndex = 12;
            //
            // numericValueProperties1
            //
            this.numericValueProperties1.AutoSize = true;
            this.numericValueProperties1.DecimalPlaces = 0;
            this.numericValueProperties1.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.numericValueProperties1.Location = new System.Drawing.Point(3, 28);
            this.numericValueProperties1.Margin = new System.Windows.Forms.Padding(3, 0, 3, 0);
            this.numericValueProperties1.Name = "numericValueProperties1";
            this.numericValueProperties1.Size = new System.Drawing.Size(259, 82);
            this.numericValueProperties1.TabIndex = 1;
            this.numericValueProperties1.UseThousands = false;
            //
            // percentageValueProperties1
            //
            this.percentageValueProperties1.AutoSize = true;
            this.percentageValueProperties1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
            this.percentageValueProperties1.DecimalPlaces = 0;
            this.percentageValueProperties1.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.percentageValueProperties1.Location = new System.Drawing.Point(268, 28);
            this.percentageValueProperties1.Margin = new System.Windows.Forms.Padding(3, 0, 3, 0);
            this.percentageValueProperties1.Name = "percentageValueProperties1";
            this.percentageValueProperties1.Size = new System.Drawing.Size(209, 39);
            this.percentageValueProperties1.TabIndex = 1;
            //
            // dateTimeValueProperties1
            //
            this.dateTimeValueProperties1.AutoSize = true;
            this.dateTimeValueProperties1.DateFormat = "";
            this.dateTimeValueProperties1.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.dateTimeValueProperties1.Location = new System.Drawing.Point(3, 110);
            this.dateTimeValueProperties1.Margin = new System.Windows.Forms.Padding(3, 0, 3, 0);
            this.dateTimeValueProperties1.Name = "dateTimeValueProperties1";
            this.dateTimeValueProperties1.Size = new System.Drawing.Size(259, 80);
            this.dateTimeValueProperties1.TabIndex = 1;
            this.dateTimeValueProperties1.TimeFormat = "";
            //
            // horizontalLine1
            //
            this.horizontalLine1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.horizontalLine1.AutoSize = true;
            this.horizontalLine1.AutoValidate = System.Windows.Forms.AutoValidate.Disable;
            this.tableLayoutPanel1.SetColumnSpan(this.horizontalLine1, 2);
            this.horizontalLine1.Location = new System.Drawing.Point(3, 73);
            this.horizontalLine1.Name = "horizontalLine1";
            this.horizontalLine1.Padding = new System.Windows.Forms.Padding(3);
            this.horizontalLine1.Size = new System.Drawing.Size(547, 6);
            this.horizontalLine1.TabIndex = 0;
            //
            // ValueProperties
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(11F, 28F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.AutoSize = true;
            this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
            this.Controls.Add(this.tableLayoutPanel1);
            this.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
            this.Name = "ValueProperties";
            this.Size = new System.Drawing.Size(558, 286);
            this.Load += new System.EventHandler(this.ValueProperties_Load);
            flowLayoutPanel1.ResumeLayout(false);
            flowLayoutPanel1.PerformLayout();
            this.tableLayoutPanel1.ResumeLayout(false);
            this.tableLayoutPanel1.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.ComboBox cboType;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private HorizontalLine horizontalLine1;
        private NumericValueProperties numericValueProperties1;
        private PercentageValueProperties percentageValueProperties1;
        private DateTimeValueProperties dateTimeValueProperties1;
        private System.Windows.Forms.Label lblDefault;
        private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;

    }
}


text:
module Newgistics
  module ResponseHandlers
    class PostErrors
      attr_reader :model

      def initialize(model)
        @model = model
      end

      def handle(response)
        if response.success?
          handle_successful_response(response)
        else
          handle_failed_response(response)
        end
      end

      private

      def handle_successful_response(response)
        xml = Nokogiri::XML(response.body)
        model.errors = error_nodes(xml).map(&:text)
        model.warnings = warning_nodes(xml).map(&:text)
      end

      def handle_failed_response(response)
        message = "API Error: #{response.status}"
        model.errors << message
      end

      def error_nodes(xml)
        xml.css('errors error') + xml.css('Errors Error')
      end

      def warning_nodes(xml)
        xml.css('warnings warning') + xml.css('Warnings warning')
      end
    end
  end
end


text:
'use strict';

import JSNetworkXAlgorithmError from './JSNetworkXAlgorithmError';

/**
 * Exception raised by algorithms trying to solve a problem
 * instance that has no feasible solution.
 * @constructor
 * @extends {JSNetworkXAlgorithmError}
 */
export default class JSNetworkXUnfeasible extends JSNetworkXAlgorithmError {
   constructor(message) {
     super(message);
     this.name = 'JSNetworkXUnfeasible';
   }
}


text:
using System;
using System.Linq;
using System.Net.Mail;

namespace Premotion.Mansion.Web.Mail
{
	/// <summary>
	/// Provides extensions for mail related classes.
	/// </summary>
	public static class Extensions
	{
		#region Constants
		private static readonly char[] AddressSeparators = new[] {',', ';'};
		#endregion
		#region MailAddressCollection Extensions
		/// <summary>
		/// Adds the <paramref name="addressString"/> to the <paramref name="collection"/>.
		/// </summary>
		/// <param name="collection">The <see cref="MailAddressCollection"/> to which to add the <paramref name="addressString"/>.</param>
		/// <param name="addressString">The addresses which to add.</param>
		/// <param name="displayNameString">The display names of the <paramref name="addressString"/>.</param>
		public static void Add(this MailAddressCollection collection, string addressString, string displayNameString)
		{
			// validate arguments
			if (collection == null)
				throw new ArgumentNullException("collection");
			if (addressString == null)
				throw new ArgumentNullException("addressString");
			if (displayNameString == null)
				throw new ArgumentNullException("displayNameString");

			// check if there are no addresses specified
			if (string.IsNullOrEmpty(addressString))
				return;

			// split the addresses and display names
			var addresses = addressString.Split(AddressSeparators).Select(x => x.Trim()).ToArray();
			var displayNames = displayNameString.Split(AddressSeparators).Select(x => x.Trim()).ToArray();

			// generate empty display names when no display names are provided
			if (displayNames.Length == 0 || addresses.Length > 0)
				displayNames = new string[addresses.Length];

			// check for mismatch between addresses and displayNames
			if (displayNames.Length != addresses.Length)
				throw new InvalidOperationException("Mismatch between number of display names and e-mail addresses");

			// loop through all the address to add them
			for (var index = 0; index < addresses.Length; index++)
				collection.Add(new MailAddress(addresses[index], displayNames[index]));
		}
		#endregion
	}
}


text:
class Admin::UsersController < Spree::BaseController
  resource_controller
end


text:
package goots

import (
	"math"
	"math/rand"
	"time"
)

// RetryPolicy 是重试策略的接口,包含2个未实现的方法和它们的参数列表。要实现一个重试策略,
// 继承这个类并实现它的2个方法。
type RetryPolicyInterface interface {
	GetRetryDelay(retry_times int, exception *OTSServiceError, api_name string) float64
	ShouldRetry(retry_times int, exception *OTSServiceError, api_name string) bool
}

// 默认重试策略
// 最大重试次数为3,最大重试间隔为2000毫秒,对流控类错误以及读操作相关的服务端内部错误进行了重试。
//
// Methods defined here:
//
// GetRetryDelay(retry_times int, exception *OTSServiceError, api_name string) float64
//
// ShouldRetry(retry_times int, exception *OTSServiceError, api_name string) bool
//
// ----------------------------------------------------------------------
// Data and other attributes defined here:
//
// MaxRetryDelay = 2
//
// MaxRetryTimes = 3
//
// ScaleFactor = 2
//
// ServerThrottlingExceptionDelayFactor = 0.5
//
// StabilityExceptionDelayFactor = 0.2
var OTSDefaultRetryPolicy DefaultRetryPolicy

// 不进行任何重试的重试策略
var OTSNoRetryPolicy NoRetryPolicy

// 没有延时的重试策略
// 最大重试次数为3
var OTSNoDelayRetryPolicy NoDelayRetryPolicy

func init() {
	OTSDefaultRetryPolicy.MaxRetryTimes = 3
	OTSDefaultRetryPolicy.MaxRetryDelay = 2
	OTSDefaultRetryPolicy.ScaleFactor = 2
	OTSDefaultRetryPolicy.ServerThrottlingExceptionDelayFactor = 0.5
	OTSDefaultRetryPolicy.StabilityExceptionDelayFactor = 0.2

	OTSNoDelayRetryPolicy.MaxRetryTimes = 3
}

func should_retry_no_matter_which_api(exception *OTSServiceError) bool {
	if exception != nil {
		error_code := exception.Code
		error_message := exception.Message

		if error_code == "OTSRowOperationConflict" ||
			error_code == "OTSNotEnoughCapacityUnit" ||
			error_code == "OTSTableNotReady" ||
			error_code == "OTSPartitionUnavailable" ||
			error_code == "OTSServerBusy" ||
			error_code == "OTSOperationThrottled" {
			return true
		}

		if error_code == "OTSQuotaExhausted" && error_message == "Too frequent table operations." {
			return true
		}
	}

	return false
}

func is_repeatable_api(api_name string) bool {
	if api_name == "ListTable" ||
		api_name == "DescribeTable" ||
		api_name == "GetRow" ||
		api_name == "BatchGetRow" ||
		api_name == "GetRange" ||
		api_name == "DescrieStream" ||
		api_name == "GetShardIterator" ||
		api_name == "GetStreamRecord" ||
		api_name == "ListStream" {
		return true
	}
	return false
}

func should_retry_when_api_repeatable(retry_times int, exception *OTSServiceError, api_name string) bool {
	if exception != nil {

		error_code := exception.Code
		//error_message := exception.Message
		http_status := exception.HttpStatus

		if error_code == "OTSTimeout" ||
			error_code == "OTSInternalServerError" ||
			error_code == "OTSServerUnavailable" {
			return true
		}

		if http_status == 500 || http_status == 502 || http_status == 503 {
			return true
		}
	}

	// TODO handle network error & timeout
	return false
}

func is_server_throttling_exception(exception *OTSServiceError) bool {
	if exception != nil {
		error_code := exception.Code
		error_message := exception.Message

		if error_code == "OTSServerBusy" ||
			error_code == "OTSNotEnoughCapacityUnit" ||
			error_code == "OTSOperationThrottled" {
			return true
		}

		if error_code == "OTSQuotaExhausted" && error_message == "Too frequent table operations." {
			return true
		}
	}

	return false
}

// 默认重试策略
// 最大重试次数为3,最大重试间隔为2000毫秒,对流控类错误以及读操作相关的服务端内部错误进行了重试。
type DefaultRetryPolicy struct {
	// 最大重试次数
	MaxRetryTimes int

	// 最大重试间隔,单位为秒
	MaxRetryDelay float64

	// 每次重试间隔的递增倍数
	ScaleFactor float64

	// 两种错误的起始重试间隔,单位为秒
	ServerThrottlingExceptionDelayFactor float64
	StabilityExceptionDelayFactor        float64
}

func (self DefaultRetryPolicy) _max_retry_time_reached(retry_times int, exception *OTSServiceError, api_name string) bool {
	return retry_times >= self.MaxRetryTimes
}

func (self DefaultRetryPolicy) _can_retry(retry_times int, exception *OTSServiceError, api_name string) bool {
	if should_retry_no_matter_which_api(exception) {
		return true
	}

	if is_repeatable_api(api_name) && should_retry_when_api_repeatable(retry_times, exception, api_name) {
		return true
	}

	return false
}

func (self DefaultRetryPolicy) GetRetryDelay(retry_times int, exception *OTSServiceError, api_name string) float64 {
	var delay_factor float64
	if is_server_throttling_exception(exception) {
		delay_factor = self.ServerThrottlingExceptionDelayFactor
	} else {
		delay_factor = self.StabilityExceptionDelayFactor
	}

	delay_limit := delay_factor * math.Pow(self.ScaleFactor, float64(retry_times))

	if delay_limit >= self.MaxRetryDelay {
		delay_limit = self.MaxRetryDelay
	}

	real_delay := delay_limit*0.5 + delay_limit*0.5*rand.New(rand.NewSource(time.Now().UnixNano())).Float64()
	return real_delay
}

func (self DefaultRetryPolicy) ShouldRetry(retry_times int, exception *OTSServiceError, api_name string) bool {
	if self._max_retry_time_reached(retry_times, exception, api_name) {
		return false
	}

	if self._can_retry(retry_times, exception, api_name) {
		return true
	}

	return false
}

// 不进行任何重试的重试策略
type NoRetryPolicy struct {
}

func (self NoRetryPolicy) GetRetryDelay(retry_times int, exception *OTSServiceError, api_name string) float64 {
	return 0
}

func (self NoRetryPolicy) ShouldRetry(retry_times int, exception *OTSServiceError, api_name string) bool {
	return false
}

// 没有延时的重试策略
type NoDelayRetryPolicy struct {
	// 最大重试次数
	MaxRetryTimes int
}

func (self NoDelayRetryPolicy) _max_retry_time_reached(retry_times int, exception *OTSServiceError, api_name string) bool {
	return retry_times >= self.MaxRetryTimes
}

func (self NoDelayRetryPolicy) _can_retry(retry_times int, exception *OTSServiceError, api_name string) bool {
	if should_retry_no_matter_which_api(exception) {
		return true
	}

	if is_repeatable_api(api_name) && should_retry_when_api_repeatable(retry_times, exception, api_name) {
		return true
	}

	return false
}

func (sels NoDelayRetryPolicy) GetRetryDelay(retry_times int, exception *OTSServiceError, api_name string) float64 {
	return 0
}

func (self NoDelayRetryPolicy) ShouldRetry(retry_times int, exception *OTSServiceError, api_name string) bool {
	if self._max_retry_time_reached(retry_times, exception, api_name) {
		return false
	}

	if self._can_retry(retry_times, exception, api_name) {
		return true
	}

	return false
}


text:
module DigitalObjectsHelper

  include ApplicationHelper
  include ActionView::Helpers::UrlHelper

  # def digital_object_link_single(digital_object, label=nil)
  #   url = get_digital_object_url(digital_object)
  #   if url
  #     # label ||= digital_object[:title]
  #     label ||= 'Digital content'
  #     link_to(label, url, class: 'external')
  #   else
  #     nil
  #   end
  # end

  def digital_object_link_single(digital_object, label=nil)
    output = nil
    if !digital_object[:digital_object_volumes].blank?

      filesystem_browse_link = Proc.new do |url|
        label = "View contents"
        link_to(label, url, class: 'filesystem-browse-link')
      end

      if digital_object[:digital_object_volumes].length > 1
        volume_links = []
        digital_object[:digital_object_volumes].each do |v|
          url = v[:filesystem_browse_url]
          volume_links << filesystem_browse_link.call(url)
        end
        output = volume_links.join("
\n")
      else
        url = digital_object[:digital_object_volumes].first[:filesystem_browse_url]
        output = filesystem_browse_link.call(url)
      end

    elsif digital_object[:files]
      file = digital_object[:files].first
      url = file[:file_uri]
      if !(url.match(/^http/))
        url = 'http://' + url
      end
      label ||= 'Digital content'
      output = link_to(label, url, class: 'external')
    end
    output
  end

  def digital_object_link_multi(digital_objects, label=nil)
    output = ''
    label ||= 'Digital content'
    # output << label
    # output << '
'
    digital_objects.each do |d|
      do_link = digital_object_link_single(d)
      if do_link
        output << digital_object_link_single(d)
        if !(d == digital_objects.last)
          output += '
'
        end
      end
    end
    output.html_safe
  end

  def get_digital_object_url(digital_object)
    if digital_object[:files]
      file = digital_object[:files].first
      url = file[:file_uri]
      if !(url.match(/^http/))
        url = 'http://' + url
      end
      url
    end
  end

  def archival_object_digital_object_link(presenter)
    output = ''
    if presenter.digital_objects
      if presenter.digital_objects.length == 1
        do_link = digital_object_link_single(presenter.digital_objects.first)
      elsif presenter.digital_objects.length > 1
        do_link = digital_object_link_multi(presenter.digital_objects)
      end
      if do_link
        output << do_link
      end
    end
    output.html_safe
  end

  def resource_digital_object_link
    output = ''
    standard_label = 'Portions of this collection have been digitized and made available online'
    if @presenter
      if @presenter.digital_objects
        if @presenter.digital_objects.length == 1
          output << digital_object_link_single(@presenter.digital_objects.first, standard_label)
        elsif @presenter.digital_objects.length > 1
          output << digital_object_link_multi(@presenter.digital_objects, standard_label)
        end
      elsif @presenter.has_descendant_digital_objects
        # output << link_to(standard_label, sal_collection_url(@presenter.collection_id), class: 'external')
        if @presenter.alt_digital_object_url
          output << link_to(standard_label, @presenter.alt_digital_object_url, class: 'external')
        else
          output << standard_label
        end
      end
    end
    output.html_safe
  end

  def resource_digital_object_output
    output = ''
    output << '
'
    output << "
#{resource_digital_object_link()}
"
    output << '
Additional materials, including those not available online,
      may be available for viewing in the Special Collections reading room in D.H. Hill Library.
      Certain formats may require the creation of an access copy and will require additional advanced notice.
'
    output << '
'
  end

  def resource_overview_digital_object_output
    output = ''
    output << '
'
    output << "
#{resource_digital_object_link()}
"
    output << '
'
  end

  # Load custom methods if they exist
  begin
    include DigitalObjectsHelperCustom
  rescue
  end

end


text:
const { Command } = require('discord.js-commando');
const _sdata = require('../../assets/_data/static_data.json');
const Tag = require('../../models/Tag');

module.exports = class TagCommand extends Command {
    constructor(client) {
        super(client, {
            name: 'tag',
            group: 'tags',
            memberName: 'tag',
            description: '`AL: low` Displays a tag.',
            guildOnly: true,
            throttling: {
                usages: 2,
                duration: 3
            },

            args: [
                {
                    key: 'name',
                    label: 'tagname',
                    prompt: 'what tag would you like to see?\n',
                    type: 'string',
                    parse: str => str.toLowerCase()
                }
            ]
        });
    }

    hasPermission(msg) {
        return this.client.provider.get(msg.author.id, 'userLevel') >= _sdata.aLevel.low;
    }

    async run(msg, { name }) {
        const tag = await Tag.findOne({ where: { name, guildID: msg.guild.id } });
        if (!tag) return null;
        tag.increment('uses');
        return msg.embed({ color: _sdata.colors.blue, description: tag.content });
    }
};


text:
var Constants = require('../../../common_classes/Constants');
var logger = require('mino-logger');

function CallbackObject(callback){
	var co = this;

	co.callback = callback;
	co.exists = false;
}

function FolderChecker(handler){
	var fc = this;

	fc.handler = handler;

	fc.paths = {};
	fc.callback_objects = [];

	fc.retrieved_existances = {};

	fc.immediate_mode = false;
}

FolderChecker.prototype.check_path_existance = function(path, callback){
	var fc = this;

	logger.debug("check_path_existance ",path);

	if(fc.immediate_mode){
		paths = {};
		callback_objects = [];
	} else {
		paths = fc.paths;
		callback_objects = fc.callback_objects;
	}

	var existance_path = path.toString();

	var callback_object = new CallbackObject(callback);
	callback_objects.push(callback_object);

	var existing_existance = fc.retrieved_existances[existance_path];
	if(existing_existance===undefined){

		var existing = fc.paths[existance_path];
	    if(existing===undefined){
	        existing = [];
	        fc.paths[existance_path] = existing;
	    }
	    existing.push(callback_object);

	} else {
		existing.push(callback_object);
		if(fc.immediate_mode){
			callback();
			return;
		}
	}

	if(fc.immediate_mode){
		fc.retrieve_existances(null,paths,callback_objects);
	}
};

FolderChecker.prototype.resolve_callbacks = function(callback_objects){
	var fc = this;

	if(!callback_objects){
		callback_objects = fc.callback_objects;
	}

	for(var i = 0; i < callback_objects.length; i++){
		var co = callback_objects[i];

		if(co.exists){
			co.callback(Constants.EXISTS);
		} else {
			co.callback(null);
		}
	}
};

FolderChecker.prototype.retrieve_existances = function(callback, paths, callback_objects){
	var fc = this;

	if(!paths){
		paths = fc.paths;
	}
	if(callback_objects===null){
		callback_objects = fc.callback_objects;
	}

	var keys = Object.keys(paths);

	if(keys.length===0){
		fc.resolve_callbacks(callback_objects);
		if(callback){
			callback();
		}
		return;
	}

	fc.handler.api.ds.object_collection.find({
		"full_path" : {"$in" : keys}
	}).toArray(function(array_err, array){

		for(var i = 0; i < array.length; i++){
			var object = array[i];

			logger.debug(object.full_path);
			var callbacks = paths[object.full_path];
			if(callbacks){
				for(var n = 0; n < callbacks.length; n++){
					callbacks[n].exists = true;
				}
			}
		}

		var root_path_callbacks = paths["/"];
		if(root_path_callbacks){
			for(var n = 0; n < root_path_callbacks.length; n++){
				root_path_callbacks[n].exists = true;
			}
		}

		fc.resolve_callbacks(callback_objects);

		if(callback){
			callback();
		}
	});
};

module.exports = FolderChecker;


text:
{-# LANGUAGE Rank2Types #-}

-- !!! Check that record selectors for polymorphic fields work right

module Main where

class Foo a where
  bar :: a -> [a]

instance Foo Int where
  bar x = replicate x x

instance Foo Bool where
  bar x = [x, not x]

data Record = R {
     blub :: forall a. Foo a => a -> [a]
    }

main = do { let r = R {blub = bar}
          ; print (blub r (3::Int))
          ; print (blub r True)
          }


text:
namespace QuickBooks.Net.Data.Models.Fields.Line_Items.Payment_Line
{
    public class PaymentLine : LineBase
    {

        public LineEx LineEx { get; set; }

    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>campy.stanford package — campy 0.0.1.dev6 documentation</title>

  <link rel="stylesheet" href="_static/css/theme.css" type="text/css" />
  <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />

<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/site.webmanifest">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5">
<meta name="msapplication-TileColor" content="#ffc40d">
<meta name="theme-color" content="#ffffff">

             campy

  <form id="rtd-search-form" class="wy-form" action="search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

campy.stanford package

Module contents

          campy

Docs »

campy.stanford package

             View page source

campy.stanford package¶

Module contents¶

Welcome to campy.stanford.

See:

https://www.stanforddaily.com/2011/04/26/one-time-at-camp-stanford/

        © Copyright 2019, Sam Redmond

  Built with Sphinx using a theme provided by Read the Docs.


text:
// Copyright 2016 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.analysis.config;

import static com.google.common.truth.Truth.assertThat;

import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.lib.analysis.ConfiguredTarget;
import com.google.devtools.build.lib.analysis.util.BuildViewTestCase;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.packages.Provider;
import com.google.devtools.build.lib.packages.StarlarkProvider;
import com.google.devtools.build.lib.packages.StructImpl;
import com.google.devtools.build.lib.syntax.Dict;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests for {@link BuildConfiguration}'s integration with Starlark. */
@RunWith(JUnit4.class)
public final class BuildConfigurationStarlarkTest extends BuildViewTestCase {

  @Test
  public void testStarlarkWithTestEnvOptions() throws Exception {
    useConfiguration("--test_env=TEST_ENV_VAR=my_value");
    scratch.file("examples/rule/BUILD");
    scratch.file(
        "examples/rule/config_test.bzl",
        "MyInfo = provider()",
        "def _test_rule_impl(ctx):",
        "   return MyInfo(test_env = ctx.configuration.test_env)",
        "test_rule = rule(implementation = _test_rule_impl,",
        "   attrs = {},",
        ")");

    scratch.file(
        "examples/config_starlark/BUILD",
        "package(default_visibility = ['//visibility:public'])",
        "load('//examples/rule:config_test.bzl', 'test_rule')",
        "test_rule(",
        "    name = 'my_target',",
        ")");

    ConfiguredTarget starlarkTarget = getConfiguredTarget("//examples/config_starlark:my_target");
    Provider.Key key =
        new StarlarkProvider.Key(
            Label.parseAbsolute("//examples/rule:config_test.bzl", ImmutableMap.of()), "MyInfo");
    StructImpl myInfo = (StructImpl) starlarkTarget.get(key);
    assertThat(((Dict) myInfo.getValue("test_env")).get("TEST_ENV_VAR")).isEqualTo("my_value");
  }
}


text:
using System.Reflection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http.Metadata;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace Microsoft.AspNetCore.Http.HttpResults;

/// <summary>
/// An <see cref="IResult"/> that on execution will write an object to the response
/// with status code Created (201) and Location header.
/// </summary>
public sealed class Created : IResult, IEndpointMetadataProvider, IStatusCodeHttpResult
{
    /// <summary>
    /// Initializes a new instance of the <see cref="Created"/> class with the values
    /// provided.
    /// </summary>
    /// <param name="location">The location at which the content has been created.</param>
    internal Created(string location)
    {
        Location = location;
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="Created"/> class with the values
    /// provided.
    /// </summary>
    /// <param name="locationUri">The location at which the content has been created.</param>
    internal Created(Uri locationUri)
    {
        if (locationUri == null)
        {
            throw new ArgumentNullException(nameof(locationUri));
        }

        if (locationUri.IsAbsoluteUri)
        {
            Location = locationUri.AbsoluteUri;
        }
        else
        {
            Location = locationUri.GetComponents(UriComponents.SerializationInfoString, UriFormat.UriEscaped);
        }
    }

    /// <summary>
    /// Gets the HTTP status code: <see cref="StatusCodes.Status201Created"/>
    /// </summary>
    public int StatusCode => StatusCodes.Status201Created;

    int? IStatusCodeHttpResult.StatusCode => StatusCode;

    /// <inheritdoc/>
    public string? Location { get; }

    /// <inheritdoc/>
    public Task ExecuteAsync(HttpContext httpContext)
    {
        ArgumentNullException.ThrowIfNull(httpContext);

        // Creating the logger with a string to preserve the category after the refactoring.
        var loggerFactory = httpContext.RequestServices.GetRequiredService<ILoggerFactory>();
        var logger = loggerFactory.CreateLogger("Microsoft.AspNetCore.Http.Result.CreatedResult");

        if (!string.IsNullOrEmpty(Location))
        {
            httpContext.Response.Headers.Location = Location;
        }

        HttpResultsHelper.Log.WritingResultAsStatusCode(logger, StatusCode);
        httpContext.Response.StatusCode = StatusCode;

        return Task.CompletedTask;
    }

    /// <inheritdoc/>
    static void IEndpointMetadataProvider.PopulateMetadata(MethodInfo method, EndpointBuilder builder)
    {
        ArgumentNullException.ThrowIfNull(method);
        ArgumentNullException.ThrowIfNull(builder);

        builder.Metadata.Add(new ProducesResponseTypeMetadata(StatusCodes.Status201Created));
    }
}


text:
.lbf-menu { position:absolute; z-index:10; display:none;}
.lbf-menu-panel { padding:5px 0; margin:0; list-style:none; background:#fff; font-size: 14px; outline: none; border: 1px solid #ccc;
    border:1px solid rgba(0, 0, 0, 0.15);
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
    -webkit-box-shadow: 0 6px 12px rgba(0,0,0,0.175);
    -moz-box-shadow: 0 6px 12px rgba(0,0,0,0.175);
    box-shadow: 0 6px 12px rgba(0,0,0,0.175);
    background-clip: padding-box;
    -webkit-transition: opacity 0.218s;
    -moz-transition: opacity 0.218s;
    -ms-transition: opacity 0.218s;
    -o-transition: opacity 0.218s;
    transition: opacity 0.218s;}
.lbf-menu .lbf-menu-item { position:relative; display:block;}
.lbf-menu .lbf-menu-label { display:block; min-width:160px; _width:160px; height:20px; padding:3px 12px; line-height: 20px; color:#333; font-size:12px; text-decoration:none; white-space:nowrap;}
.lbf-menu .lbf-menu-label:hover { background-color:#f5f5f5; color:#262626;}
.lbf-menu .lbf-menu-split { margin:3px 4px; border-bottom:1px solid #dbdbdb; line-height:0; font-size:0;}