text:
"use strict";
import createRuleExample from "./create-textlint-rule-example.js";
import getRuleTest from "./get-rule-test.js";

export { createRuleExample };
export { getRuleTest };


text:
package com.aspose.tasks.examples.Projects;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import com.aspose.tasks.Duration;
import com.aspose.tasks.ParseErrorArgs;
import com.aspose.tasks.ParseErrorCallback;
import com.aspose.tasks.Project;
import com.aspose.tasks.SaveFileFormat;
import com.aspose.tasks.TimeUnitType;
import com.aspose.tasks.examples.Utils;

public class IgnoringInvalidCharactersDuringLoadingProject {
	// ExStart: IgnoringInvalidCharactersDuringLoadingProject
	public static void main(String[] args) throws IOException {
		// For complete examples and data files, please go to https://github.com/aspose-tasks/Aspose.Tasks-for-Java

		// The path to the documents directory.
		String dataDir = Utils.getDataDir(ReadingProjectDatafromMicrosoftProjectDatabase.class);

		InputStream stream = null;
	    try
	    {
	        stream = new ByteArrayInputStream(getModifiedXml().getBytes("utf-8"));
	    }
	    catch (UnsupportedEncodingException e)
	    {
	        e.printStackTrace();
	    }

	    Project project = new Project(stream, new ParseErrorCallback()
	    {
	    	public Object invoke(Object sender, ParseErrorArgs args)
	    	{
	    		return customDurationHandler(sender, args);
	    	}
	    });
	    project.save(dataDir + "Project1.xml", SaveFileFormat.XML);
	}

	private static String getModifiedXml()
	{
	    StringBuilder xml = new StringBuilder();

	    BufferedReader reader;
	    String line;
	    try
	    {
	        reader = new BufferedReader(new InputStreamReader(new FileInputStream("NewProductDev.xml"), "UTF8"));
	        while ((line = reader.readLine()) != null)
	        {
	            xml.append(line).append("\n");
	        }
	    }
	    catch (Exception e)
	    {
	        e.printStackTrace();
	    }

	    return xml.toString().replaceAll("PT(\\d+)H(\\d+)M(\\d+)S", "**$1Hrs$2Mins$3Secs**");
	}

	private static Object customDurationHandler(Object sender, ParseErrorArgs args)
	{
	    System.err.print(String.format("Object field : %s; Invalid value : %s; ", args.getFieldName(), args.getInvalidValue()));
	    String duration = args.getInvalidValue().replaceAll("[*]{2}(\\d+)Hrs(\\d+)Mins(\\d+)Secs[*]{2}", "PT$1H$2M$3S");
	    double newValue = Duration.parseTimeSpan(duration)*0.001/60/60;
	    System.err.println(String.format("New value : %s", duration));
	    Project project = new Project();
		return project.getDuration(newValue, TimeUnitType.Hour);
	}
	// ExEnd: IgnoringInvalidCharactersDuringLoadingProject
}

redpajama_set_name: RedPajamaGithub


text:
module Archimate
  module Svg
    module Entity
      class BusinessEvent < EventEntity
      end
    end
  end
end


text:
[![Build Status](https://travis-ci.org/gmtprime/njord.svg?branch=master)](https://travis-ci.org/gmtprime/njord) [![Hex pm](http://img.shields.io/hexpm/v/njord.svg?style=flat)](https://hex.pm/packages/njord) [![hex.pm downloads](https://img.shields.io/hexpm/dt/njord.svg?style=flat)](https://hex.pm/packages/njord) [![Deps Status](https://beta.hexfaktor.org/badge/all/github/gmtprime/njord.svg)](https://beta.hexfaktor.org/github/gmtprime/njord) [![Inline docs](http://inch-ci.org/github/gmtprime/njord.svg?branch=master)](http://inch-ci.org/github/gmtprime/njord)

> Njörðr, god of the wind and the sea.

This library is a wrapper around `HTTPoison` to build client REST API libraries
as specifications.

```elixir
defmodule Github do
  use Njord

  @url "https://api.github.com"

  def valid_username(username) when is_binary(username), do: true
  def valid_username(_), do: false

  def process_url(%Njord{} = request, path, _state) do
    %Njord{request | url: @url <> path}
  end

  @doc """
  Calls the `GET https://api.github.com/users/:username` service. Requests the
  repositories from the `user`. Additionally, `HTTPoison` `options` can be
  provided.
  """
  defget :get_repos,
    [path: "/users/:user",
     arguments: [user: [type: :path_arg,
                        validation: fn user -> valid_username(user) end]]]
end
```

The previous example generates a module called `Github` with two functions:

  * `get_repos/1` that receives the user and returns the repositories from that
  user.

  * `get_repos/2` that receives the user and a list of options. This options
  are the same options passed to the functions in `HTTPoison` with the extra
  option `:state`. The state can be any Elixir term. This state is used in the
  functions that process the requests and the response.

The macro `defget` sends a `GET` request to the URL. For the other methods use
the macro that you need: `defget`, `defpost`, `defput`, `defdelete`, `defhead`,
`defpatch`, `defoptions`

```elixir
iex(1)> Github.get_repos("alexdesousa")
{:ok, %HTTPoison.Response{...}}
```

## Overriding functions

Like `HTTPoison`, `Njord` defines the following list of functions, all of
which can be overriden:

```elixir
alias HTTPoison.Response

# Processes the endpoint URL after the substitutions.
@spec process_url(Njord.t, String.t, term) :: Njord.t
def process_url(request, url, state)

# Processes the request headers.
@spec process_headers(Njord.t, [{binary, binary}], term) :: Njord.t
def process_headers(request, headers, state)

# Processes the request body.
@spec process_body(Njord.t, term, term) :: Njord.t
def process_body(request, body, state)

# Processes the response headers.
@spec process_response_headers(name, Response.t, [{binary, binary}], term)
  :: Response.t
    when name: {function_name, arity}, function_name: atom, arity: integer
def process_response_headers(name, response, headers, state)

# Processes the response body.
@spec process_response_body(name, Response.t, String.t, term)
  :: Response.t
    when name: {function_name, arity}, function_name: atom, arity: integer
def process_response_body(name, response, body, state)

# Processes the status code of the request.
@spec process_status_code(name, Response.t, integer, term)
  :: Response.t
    when name: {function_name, arity}, function_name: atom, arity: integer
def process_status_code(name, response, status_code, state)
```

## Installation

Just add it to your dependencies in your `mix.exs`:

```elixir
def deps do
  [{:njord, "~> 1.0.2"}]
end
```


text:
{% extends "templates/docs/layout.njk" %}
{% set page_title ="Collapsible" %}
{% set active_accordion ="components" %}
{% set active_page ="collapsible" %}

{% block main %}

    {% include "templates/docs/collapsible/collapsible.njk" %}

    {% include "templates/docs/collapsible/styles.njk" %}

{% endblock %}


text:
package com.helger.as4.config;

import javax.annotation.Nullable;

import com.helger.commons.annotation.IsSPIImplementation;
import com.helger.commons.thirdparty.ELicense;
import com.helger.commons.thirdparty.IThirdPartyModule;
import com.helger.commons.thirdparty.IThirdPartyModuleProviderSPI;
import com.helger.commons.thirdparty.ThirdPartyModule;
import com.helger.commons.version.Version;

/**
 * Implement this SPI interface if your JAR file contains external third party
 * modules.
 *
 * @author Philip Helger
 */
@IsSPIImplementation
public final class ThirdPartyModuleProvider_ph_as4_lib implements IThirdPartyModuleProviderSPI
{
  private static final IThirdPartyModule WSS4J = new ThirdPartyModule ("Apache WSS4J",
                                                                       "Apache",
                                                                       ELicense.APACHE2,
                                                                       new Version (2, 2, 4),
                                                                       "https://ws.apache.org/wss4j/");

  @Nullable
  public IThirdPartyModule [] getAllThirdPartyModules ()
  {
    return new IThirdPartyModule [] { WSS4J };
  }
}


text:
<form name="processForm" class="mt10">

Cluster

            Name
            <select ng-model="cluster.name" ng-required="true" class="form-control padding0" validation-message="{{validations.messages.cluster}}">
              <option value="" disabled selected style='display:none;'>-Select cluster-</option>
              <option ng-repeat="clusterItem in clusterList">{{clusterItem.name}}</option>
            </select>

Validity

Start

              <input type="text" class="form-control" placeholder="Start Date"
                     datepicker-popup="{{dateFormat}}"
                     ng-model="cluster.validity.start.date"
                     is-open="cluster.validity.start.opened"
                     ng-required="true">

End

              <input type="text" class="form-control" placeholder="End Date"
                     datepicker-popup="{{dateFormat}}"
                     ng-model="cluster.validity.end.date"
                     is-open="cluster.validity.end.opened"
                     ng-required="true">

              - delete

      + add cluster

        Previous

        Next

        Cancel

</form>


text:
namespace Poker.Deck
{
    internal static class DeckTablesHelper
    {
        internal static CardMask[] GenerateStandardDeckCardMaskTable()
        {
            var deck = new StandardDeck();
            var cardMaskTable = new CardMask[deck.NoOfCards];

            for (var cardIndex = 0; cardIndex != deck.NoOfCards; ++cardIndex)
            {
                var cardSuit = deck.ToSuit(deck.ToSuitIndex(cardIndex));
                var cardRankIndex = deck.ToRankIndex(cardIndex);
                CardMask cardMask;

                switch (cardSuit)
                {
                    case CardSuit.Hearts:
                        cardMask = (CardMask)((0x1L << cardRankIndex) << 48);
                        break;
                    case CardSuit.Diamonds:
                        cardMask = (CardMask)((0x1L << cardRankIndex) << 32);
                        break;
                    case CardSuit.Clubs:
                        cardMask = (CardMask)((0x1L << cardRankIndex) << 16);
                        break;
                    case CardSuit.Spades:
                        cardMask = (CardMask)(0x1L << cardRankIndex);
                        break;
                    case CardSuit.Undefined:
                        cardMask = CardMask.Empty;
                        break;
                    default:
                        cardMask = CardMask.Empty;
                        break;
                }

                cardMaskTable[cardIndex] = cardMask;
            }

            return cardMaskTable;
        }
    }
}


text:
import arrayLikeToArray from "./arrayLikeToArray.js";
export default function _unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return arrayLikeToArray(o, minLen);
  var n = Object.prototype.toString.call(o).slice(8, -1);
  if (n === "Object" && o.constructor) n = o.constructor.name;
  if (n === "Map" || n === "Set") return Array.from(o);
  if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen);
}


text:
package org.pimslims.servlet.spot;

import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;

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

import org.apache.commons.lang.StringEscapeUtils;
import org.pimslims.bioinf.newtarget.PIMSTarget;
import org.pimslims.dao.ReadableVersion;
import org.pimslims.dao.WritableVersion;
import org.pimslims.exception.AbortedException;
import org.pimslims.exception.AccessException;
import org.pimslims.exception.ConstraintException;
import org.pimslims.lab.primer.PimsStandardPrimerDesigner;
import org.pimslims.lab.primer.YorkPrimerBean;
import org.pimslims.lab.sequence.DnaSequence;
import org.pimslims.lab.sequence.SequenceUtility;
import org.pimslims.lab.sequence.ThreeLetterProteinSeq;
import org.pimslims.metamodel.ModelObject;
import org.pimslims.model.core.LabNotebook;
import org.pimslims.model.sample.Sample;
import org.pimslims.model.target.ResearchObjective;
import org.pimslims.model.target.Target;
import org.pimslims.presentation.ModelObjectBean;
import org.pimslims.presentation.ModelObjectShortBean;
import org.pimslims.presentation.TargetBean;
import org.pimslims.presentation.construct.ConstructBean;
import org.pimslims.presentation.construct.ConstructBeanWriter;
import org.pimslims.presentation.construct.ConstructResultBean;
import org.pimslims.presentation.construct.SyntheticGeneBean;
import org.pimslims.presentation.construct.SyntheticGeneManager;
import org.pimslims.servlet.PIMSServlet;
import org.pimslims.servlet.construct.AddPrimers;

/**
 *
 *
 *
 */
public class CreateExpressionObjective extends PIMSServlet {

    /**
     * SAVE_PRIMERLESS_CONSTRUCT String
     */
    public static final String SAVE_PRIMERLESS_CONSTRUCT = "Save Construct";

    /**
     * C_TAG String
     */
    public static final String C_TAG = "expressed_prot_c";

    /**
     * N_TAG String
     */
    public static final String N_TAG = "expressed_prot_n";

    /**
     * @see javax.servlet.Servlet#getServletInfo()
     * @return Description of Servlet
     */
    @Override
    public String getServletInfo() {
        return "Create a construct";
    }

    /**
     * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
     *      javax.servlet.http.HttpServletResponse)
     * @param request a request from a URL
     * @param response a response from a URL
     * @throws ServletException if no target found
     * @throws IOException if it cannot write to the user's browser
     */
    @Override
    protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {

        // Ensure that PIMS was able to connect to the database
        if (!this.checkStarted(request, response)) {
            return;
        }

        // Get a read transaction
        final ReadableVersion version = this.getReadableVersion(request, response);
        if (version == null) {
            return; // error message has already been sent
        }

        // always use a transaction in a try/catch block
        try {
            final ConstructBean cb;
            final String pathInfo = request.getPathInfo();
            String sampleHook = "";
            String sampleName = "";
            if (pathInfo.contains("sample.Sample")) {
                Sample sgSample;
                if (null == pathInfo || 2 > pathInfo.length()) {
                    throw new ServletException("No Sample specified");
                }
                final String hook = pathInfo.substring(1);
                //Attempt to distinguish synthetic gene from Target
                sampleHook = hook;
                request.setAttribute("sampleHook", sampleHook);
                sgSample = version.get(hook);
                if (null == sgSample || !(SyntheticGeneManager.isSynthGene(sgSample))) {
                    this.writeErrorHead(request, response, "Synthetic gene Sample not found",
                        HttpServletResponse.SC_NOT_FOUND);
                    return;
                }
                // Synthetic gene support was never used
                final SyntheticGeneBean sgb = new SyntheticGeneBean(sgSample);
                request.setAttribute("syntheticGeneBean", sgb);
                sampleName = sgb.getName();
                request.setAttribute("sampleName", sampleName);
                final TargetBean sgtb = sgb.getTargetBean(); //get the targeBean from the SyntheticGene bean
                final Target t = version.get(sgtb.getHook()); //get the Target from the Target bean
                final String dnaSeq = sgb.getDnaSeq().toUpperCase(); //Set the DNA sequence in the TargetBean to the SyntheticGene sequence
                sgtb.setDnaSeq(dnaSeq);

                cb = new ConstructBean(sgtb);
                //cb.setTargetProtSeq(sgb.getProteinSeq());
                //cb.setName(sgb.getSgeneName()); //??what is this for?
                cb.setAccess(sgb.getAccess());
                SpotNewTarget.setPeople(request, version);

                request.setAttribute("constructBean", cb);
                final Collection<ConstructResultBean> milestones =
                    org.pimslims.servlet.spot.SpotTarget.getMilestones(version, t);
                request.setAttribute("milestones", milestones);
                //To format the DNA sequence in JSP without using scriptlets
                final List<String> chunks = new DnaSequence(cb.getTargetDnaSeq()).chunkSeq();
                request.setAttribute("chunks", chunks);
                cb.setTargetProtSeq(ThreeLetterProteinSeq.translate(sgtb.getDnaSeq()));
                //final List<String> transSeqChunks = new ProteinSequence(cb.getTargetProtSeq()).chunkSeq();
                final List<String> transSeqChunks = SequenceUtility.chunkSeq(cb.getTargetProtSeq());
                request.setAttribute("transSeqChunks", transSeqChunks);
                request.setAttribute("accessObjects", PIMSServlet.getPossibleCreateOwners(version));

            } else {
                final Target t = SpotNewConstructWizard.getTarget(request, version);
                if (null == t) {
                    this.writeErrorHead(request, response, "Target not found",
                        HttpServletResponse.SC_NOT_FOUND);
                    return;
                }

                // Get a SPOTTarget
                final TargetBean tb = new TargetBean(t);

                //DNA Target doesn't have DNA MolComp
                if (!PIMSTarget.isDNATarget(t)) {
                    if (null == tb.getDnaSeq()) {
                        this.writeErrorHead(request, response, "No DNA sequence found",
                            HttpServletResponse.SC_BAD_REQUEST);
                        response
                            .getWriter()
                            .println(
                                "Please create a DNA sequence or associate a DNA sequence with this target
");
                        response.getWriter().println(

                            "Add new
"

                        );
                        response.getWriter().println(
                            "Search/Add
");

                        response.getWriter().println("");
                        return;
                    }
                }

                cb = new ConstructBean(tb);
                //cb.setTargetName(tb.getProtein_name());
                //DNA Target doesn't need protein sequence
                if (!PIMSTarget.isDNATarget(t)) {
                    try {
                        cb.setTargetProtSeq(ThreeLetterProteinSeq.translate(tb.getDnaSeq()));
                        //final List<String> transSeqChunks = new ProteinSequence(cb.getTargetProtSeq()).chunkSeq();
                        final List<String> transSeqChunks = SequenceUtility.chunkSeq(cb.getTargetProtSeq());
                        request.setAttribute("transSeqChunks", transSeqChunks);

                    } catch (final IllegalArgumentException e) {
                        if (e.getMessage().contains("Protein sequence is not all IUB symbols")) {
                            this.writeErrorHead(request, response, "Invalid DNA sequence",
                                HttpServletResponse.SC_BAD_REQUEST);
                            response.getWriter().println(
                                "Please correct the DNA sequence: " + tb.getDnaSeq() + "
"
                                    + e.getMessage());
                            response.getWriter().println("");
                            return;
                        } else if (e.getMessage().contains(
                            "The source length must be divisible by the window width")) {
                            this.writeErrorHead(request, response, "Invalid DNA sequence",
                                HttpServletResponse.SC_BAD_REQUEST);
                            response.getWriter().println(
                                "Please correct the DNA sequence: "
                                    + StringEscapeUtils.escapeXml(tb.getDnaSeq()) + "
"
                                    + e.getMessage());
                            response.getWriter().println("");
                            return;
                        }
                        throw e;
                    }
                    cb.setTargetDnaSeq(tb.getDnaSeq().toUpperCase());
                }
                //DNA Target saves DNA sequence in protein sequence
                else {
                    cb.setTargetName(tb.getName());
                    cb.setTargetDnaSeq(tb.getProtSeq().toUpperCase().replaceAll(" ", ""));
                    cb.setDnaTarget("dnaTarget");
                    //nonProtConstruct =true;
                }

                SpotNewTarget.setPeople(request, version);
                request.setAttribute("constructBean", cb);
                final Collection<ConstructResultBean> milestones =
                    org.pimslims.servlet.spot.SpotTarget.getMilestones(version, t);
                request.setAttribute("milestones", milestones);
                //To format the DNA sequence in JSP without using scriptlets
                final List<String> chunks = new DnaSequence(cb.getTargetDnaSeq()).chunkSeq();
                request.setAttribute("chunks", chunks);
                request.setAttribute("accessObjects", PIMSServlet.getPossibleCreateOwners(version));
            }
            final RequestDispatcher dispatcher = request.getRequestDispatcher(this.getJspPath());
            dispatcher.forward(request, response);
            version.commit();
        } catch (final AbortedException ex) {
            throw new ServletException(ex);
        } catch (final ConstraintException ex) {
            throw new ServletException(ex);
        } finally {
            if (!version.isCompleted()) {
                version.abort();
            }
        }

    }

    /**
     * @return String path to the calling JSP
     */
    protected String getJspPath() {
        return "/JSP/spot/CreateExpressionObjective.jsp";
    }

    //needed to pass value of checkbox if using non-standard start codon
    //TODO no, don't use mutable static fields. Value goes into hidden field in SpotNewConstructWizardStep2c.jsp.
    private static String fixNonstandardStartCodon = "";

    /**
     * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest,
     *      javax.servlet.http.HttpServletResponse)
     * @param request a request from a URL
     * @param response a response from a URL
     * @throws ServletException if no target found
     * @throws IOException if it cannot write to the user's browser
     */
    @Override
    protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {

        final WritableVersion version = this.getWritableVersion(request, response);
        if (version == null) {
            return; // error message has already been sent
        }
        try {
            //TODO if its a polycistronic construct, there will be several targets
            //String insert = "";
            final String targetHook = request.getParameter("pims_target_hook");
            TargetBean tb = new TargetBean();
            if (null != targetHook) {
                final Target target = (Target) version.get(targetHook);
                tb = new TargetBean(target);
                /* if (1 == target.getNucleicAcids().size()) {
                    // TODO accept a parameter
                    //insert = target.getNucleicAcids().iterator().next().getSeqString();
                } */
            }
            /* TODO For synthetic gene, need different DNA sequence
            final String sampleHook = request.getParameter("sampleHook");
            if (null != sampleHook && "" != sampleHook) {
                final Sample sgSample = version.get(sampleHook);
                if (null == sgSample || !(SyntheticGeneManager.isSynthGene(sgSample))) {
                    this.writeErrorHead(request, response, "Synthetic gene Sample not found",
                        HttpServletResponse.SC_NOT_FOUND);
                    return;
                }
                final SyntheticGeneBean sgb = new SyntheticGeneBean(sgSample);
                request.setAttribute("syntheticGeneBean", sgb);
                final String dnaSeq = sgb.getDnaSeq().toUpperCase();
                tb.setDnaSeq(dnaSeq);
            }
            request.setAttribute("sampleHook", sampleHook);
            */

            final String name = request.getParameter("construct_id");

            final ConstructBean cb = new ConstructBean(tb);

            if (null != request.getParameter("sampleName") && "" != request.getParameter("sampleName")) {
                cb.setName(request.getParameter("sampleName") + "." + request.getParameter("construct_id"));
            } else {
                cb.setName(cb.getTargetName() + "." + request.getParameter("construct_id"));
            }

            //For synthetic gene construct
            if (null != request.getParameter("sampleHook") && "" != request.getParameter("sampleHook")) {
                final String shook = request.getParameter("sampleHook");
                cb.setSgSampleHook(shook);
                String sampleName;
                final ModelObject sample = version.get(shook);
                sampleName = sample.get_Name();
                cb.setSgSampleName(sampleName);
            }

            this.setConstructBean(version, request, cb, tb);
            cb.setPcrProductSeq(cb.getDnaSeq());
            cb.setExpressedProt(ThreeLetterProteinSeq.translate(cb.getDnaSeq()));
            final ResearchObjective ro = ConstructBeanWriter.createNewConstruct(version, cb);
            final String roHook = ro.get_Hook();
            final String roeHook = ro.getResearchObjectiveElements().iterator().next().get_Hook();
            version.commit();
            if (CreateExpressionObjective.SAVE_PRIMERLESS_CONSTRUCT.equals(request.getParameter("Submit"))) {
                PIMSServlet.redirectPost(response, request.getContextPath() + "/View/" + roHook);
                return;
            } else {
                PIMSServlet
                    .redirectPost(response, request.getContextPath() + "/update/AddPrimers/" + roeHook);
                //TODO ?desired_tm=
            }

            /* this part is obsolete
            final ConstructBean cb =
                new ConstructBean(tb, new PrimerBean(PrimerBean.FORWARD), new PrimerBean(PrimerBean.REVERSE));
            cb.setConstructId(name);
            this.setConstructBean(version, request, cb, tb);
            final Map<String, String> parameterMap = PIMSServlet.getParameterMap(request);

            final List<YorkPrimerBean> primerBeans = new ArrayList<YorkPrimerBean>();
            final List<YorkPrimerBean> rprimerBeans = new ArrayList<YorkPrimerBean>();
            final String nextPage =
                CreateExpressionObjective.designPrimers(parameterMap, cb, primerBeans, rprimerBeans);
            // not saved, need to show another form
            SpotNewTarget.setPeople(request, version);
            request.setAttribute("constructBean", cb);
            request.setAttribute("primerBeans", primerBeans);
            request.setAttribute("rprimerBeans", rprimerBeans);
            request.setAttribute("forward_tags", Extensions.getExtensions(version, "Forward Extension"));
            request.setAttribute("reverse_tags", Extensions.getExtensions(version, "Reverse Extension"));
            request.setAttribute("fixNonstandardStartCodon",
                CreateExpressionObjective.fixNonstandardStartCodon); //for non-standard start codon

            response.setStatus(HttpServletResponse.SC_OK);
            final RequestDispatcher dispatcher = request.getRequestDispatcher(nextPage);
            dispatcher.forward(request, response);
            version.abort(); // nothing created yet */
            return;
        } catch (final AbortedException e) {
            throw new ServletException(e);
        } catch (final ConstraintException e) {
            e.printStackTrace();
            throw new ServletException(e);
        } catch (final AccessException e) {
            throw new ServletException(e);
        } catch (final NumberFormatException e1) {
            this.writeErrorHead(request, response, "bad number: " + e1.getMessage(),
                HttpServletResponse.SC_BAD_REQUEST);
        } finally {
            if (!version.isCompleted()) {
                version.abort();
            }
        }
    }

    @Deprecated
    // tested but not used
    static String designPrimers(final Map<String, String> parms, final ConstructBean cb,
        final List<YorkPrimerBean> primerBeans, final List<YorkPrimerBean> rprimerBeans) {

        //final String NONSTANDARD = "Non-standard letters in DNA Sequence";
        final String wizardStep = parms.get("wizard_step");

        if (wizardStep.equals("1")) {
            if (null != parms.get("sampleName") && "" != parms.get("sampleName")) {
                // for synthetic gene
                cb.setConstructId(parms.get("sampleName") + "." + parms.get("construct_id"));
            } else {
                cb.setConstructId(cb.getTargetName() + "." + parms.get("construct_id"));
            }

            final String desiredTm = parms.get("desired_tm");
            float tm = AddPrimers.DEFAULT_TM;
            if (null != desiredTm) {
                tm = Float.parseFloat(desiredTm);
            }
            cb.setDesiredTm(tm);
            // }
            //06-02-09 processing non-standard start codons
            if ("on".equals(parms.get("fixNonstandardStartCodon"))) {
                final String newStart = "A";
                cb.setDnaSeq(newStart + cb.getDnaSeq().substring(1));
                CreateExpressionObjective.fixNonstandardStartCodon = "on";
            } else {
                CreateExpressionObjective.fixNonstandardStartCodon = "off";
            }
            PimsStandardPrimerDesigner.makeFandRPrimerBeanLists(primerBeans, rprimerBeans, cb.getDesiredTm(),
                cb.getDnaSeq());

            // }
            return "/JSP/spot/SpotNewConstructWizardStep2c.jsp"; //TODO /JSP/construct/DesignOverlaps.jsp

        } else if (wizardStep.equals("1dna")) {

            //cb.setDesignType(parms.get("design_type"));
            cb.setConstructId(parms.get("target_name") //TODO get this some other way
                + "." + parms.get("construct_id"));
            final String desiredTm = parms.get("desired_tm");
            float tm = AddPrimers.DEFAULT_TM;
            if (null != desiredTm) {
                tm = Float.parseFloat(desiredTm);
            }
            cb.setDesiredTm(tm);
            // }
            PimsStandardPrimerDesigner.makeFandRPrimerBeanLists(primerBeans, rprimerBeans, cb.getDesiredTm(),
                cb.getDnaSeq());
            return "/JSP/dnaTarget/DNAConstructWizardStep2.jsp";
        } else {
            throw new java.lang.AssertionError("Use AddPrimers");
        }

    }

    /**
     * @param request a request from a URL
     * @return org.pimslims.presentation.construct.ConstructBean -presenation layer construct bean
     */
    private ModelObjectShortBean setConstructBean(final ReadableVersion version,
        final HttpServletRequest request, final ConstructBean cb, final TargetBean tb) {
        if (null != request.getParameter(PIMSServlet.LAB_NOTEBOOK_ID)) {
            cb.setDnaTarget(request.getParameter("dna_target"));

            final LabNotebook project = version.get(request.getParameter(PIMSServlet.LAB_NOTEBOOK_ID));
            if (project != null) {
                cb.setAccess(new ModelObjectBean(project));
            }
        }

        //this.setDnaAndProtProperties(request, cb);
        //DNA Sequence formatted for JSPs
        final List<String> chunks = SequenceUtility.chunkSeq(cb.getTargetDnaSeq());
        request.setAttribute("chunks", chunks);
        //Oct 08 after re-design
        //Susy 23-62010 for version 4.1 -displaying target protein sequence NOT translated sequence

        if (null == cb.getDnaTarget() || "".equals(cb.getDnaTarget())) {
            cb.setTargetProtSeq(ThreeLetterProteinSeq.translate(tb.getDnaSeq()));
            this.setSeqStartAndEnd(request, cb);
            final List<String> transSeqChunks =
                SequenceUtility.chunkSeq(ThreeLetterProteinSeq.translate(cb.getTargetDnaSeq()));
            //final List<String> transSeqChunks = SequenceUtility.chunkSeq(cb.getTargetProtSeq());
            request.setAttribute("transSeqChunks", transSeqChunks);
        } else {
            this.setDNASeqStartAndEnd(request, cb);
        }

        final String final_n = request.getParameter("final_prot_n");
        cb.setFinalProtN(final_n == null ? "" : final_n);

        if (null == cb.getDnaTarget() || "".equals(cb.getDnaTarget())) {
            //22-11-07 Code to process Start codon ATG addition to tag, if checkbox is checked
            if ("on".equals(request.getParameter("check1"))) {
                final String ftag = request.getParameter("forward_extension") + "ATG";
                cb.setForwardTag(ftag);
                //220708 Also have to add 'M' to N-term of protein
                final String expM = request.getParameter(CreateExpressionObjective.N_TAG) + "M";
                cb.setForwardTag(expM);
                final String finM = final_n + "M";
                cb.setFinalProtN(finM);
            }

            //not set anywhere
            cb.setDescription(request.getParameter("description"));
            cb.setComments(request.getParameter("comments"));
            cb.setUserHook(request.getParameter("personHook"));
        }

        return cb;
    }

    /* Mapping for Primer design type obsolete
    private static java.util.Map<String, String> radioMap = new LinkedHashMap<String, String>();
    static {
        CreateExpressionObjective.radioMap.put("StAndrews", "User-defined primer length");
        CreateExpressionObjective.radioMap.put("PrimersProvided", "User-provided primer sequences");
        CreateExpressionObjective.radioMap.put("York", "User-defined Tm");
    } */

    /**
     * @param request a request from a URL
     * @param cb an instance of org.pimslims.presentation.construct.ConstructBean
     */
    private void setDNASeqStartAndEnd(final HttpServletRequest request, final ConstructBean cb) {
        String startDT = "";
        String endDT = "";

        if (null != request.getParameter("target_dna_start")) {
            startDT = request.getParameter("target_dna_start").trim();
            final int startInt = Integer.parseInt(startDT);
            cb.setTargetDnaStart(new Integer(startInt));
        }
        if (null != request.getParameter("target_dna_end")) {
            endDT = request.getParameter("target_dna_end").trim();
            final int endInt = Integer.parseInt(endDT);
            cb.setTargetDnaEnd(new Integer(endInt));
        }
        cb.setDnaSeq(cb.getTargetDnaSeq().substring((cb.getTargetDnaStart()) - 1, cb.getTargetDnaEnd()));
        final List<String> constructChunks = new DnaSequence(cb.getDnaSeq()).chunkSeq();
        request.setAttribute("constructChunks", constructChunks);

    }

    /**
     * @param request a request from a URL
     * @param cb an instance of org.pimslims.presentation.construct.ConstructBean
     */
    protected void setSeqStartAndEnd(final HttpServletRequest request, final ConstructBean cb) {
        final int THREE = 3;
        cb.setTargetProtStart(new Integer(request.getParameter("target_prot_start")));
        cb.setTargetProtEnd(new Integer(request.getParameter("target_prot_end")));
        cb.setDnaSeq(cb.getTargetDnaSeq().substring(((cb.getTargetProtStart()) * THREE) - THREE,
            cb.getTargetProtEnd() * THREE));

        //06-02-09 processing non-standard start codons
        if ("on".equals(request.getParameter("fixNonstandardStartCodon"))
            || "on".equals(request.getParameter("fixNonstandardStartCodon"))) {
            cb.setDnaSeq("A" + cb.getDnaSeq().substring(1));
        }
        cb.setProtSeq(ThreeLetterProteinSeq.translate(cb.getDnaSeq()));
        //Oct 08 after re-design
        final List<String> protConDNAChunks = SequenceUtility.chunkSeq(cb.getDnaSeq());
        request.setAttribute("protConDNAChunks", protConDNAChunks);
        final List<String> protConChunks = SequenceUtility.chunkSeq(cb.getProtSeq());
        request.setAttribute("protConChunks", protConChunks);
        cb.suggestPrimerNames();
    }

}


text:
namespace ConfigServer.Server
{
    internal static class PropertyNameParser
    {
        public static string SplitCamelCase(string input)
        {
            return System.Text.RegularExpressions.Regex.Replace(input, "(?<=[a-z])([A-Z])", " $1", System.Text.RegularExpressions.RegexOptions.Compiled);
        }

        public static string ToLowerCamelCase(this string input)
        {
            if (string.IsNullOrWhiteSpace(input))
                return input;
            var firstChar = char.ToLower(input[0]);
            return input.Length >1? firstChar + input.Substring(1): firstChar.ToString();
        }
    }
}


text:
.lm-video-capture-video-section {
  text-align: center;
  position: relative;
}
.lm-video-capture-processing {
  position: absolute;
  z-index: 99;
  width: 100%;
  height: 100%;
  background-color: white;
  opacity: 0.9;
  padding-top: 20px;
}
.lm-video-capture-message {
  text-align: center;
}
.lm-video-capture-record-start-btn-style, .lm-video-capture-record-stop-btn-style {
  display: inline-block;
  cursor: pointer;
}
.lm-video-capture-record-stop-btn-style {
  margin-left: 10px;
}


text:
"use strict";

var last = require('lodash/array/last');

function _walk(parents, obj, ast) {
  var enter = obj.enter || function() {};
  var exit = obj.exit || function() {};
  var recur = _walk.bind(null, parents, obj);
  var handlers = {
    Module: function(node) {
      node.statements.forEach(recur);
      node.exports.forEach(recur);
    },
    GetProperty: function(node) {
      recur(node.obj);
      recur(node.prop);
    },
    GetIndex: function(node) {
      recur(node.array);
      recur(node.arrayIndex);
    },
    GetMethod: function(node) {
      recur(node.obj);
      recur(node.prop);
    },
    CallMethod: function(node) {
      recur(node.obj);
      recur(node.prop);
      node.args.forEach(recur);
    },
    Call: function(node) {
      recur(node.f);
      node.args.forEach(recur);
    },
    ExprStmt: function(node) {
      recur(node.expression);
    },
    Function: function(node) {
      recur(node.parameters);
      recur(node.body);
    },
    Declaration: function(node) {
      recur(node.identifier);
    },
    Parameters: function(node) {
      if (node.context) {
        recur(node.context);
      }
      node.positional.forEach(recur);
      if (node.slurpy) {
        recur(node.slurpy);
      }
    },
    Block: function(node) {
      node.statements.forEach(recur);
      recur(node.expression);
    },
    If: function(node) {
      recur(node.condition);
      recur(node.ifBranch);
      node.elseIfs.forEach(recur);
      recur(node.elseBranch);
    },
    ElseIf: function(node) {
      recur(node.condition);
      recur(node.branch);
    },
    Let: function(node) {
      recur(node.binding);
    },
    Binding: function(node) {
      recur(node.pattern);
      recur(node.value);
    },
    Array: function(node) {
      node.data.forEach(recur);
    },
    Object: function(node) {
      node.data.forEach(recur);
    },
    BinOp: function(node) {
      recur(node.operator);
      recur(node.left);
      recur(node.right);
    },
    Parameter: function(node) {
      recur(node.identifier);
    },
    Pair: function(node) {
      recur(node.key);
      recur(node.value);
    },
    IdentifierExpression: function(node) {
      recur(node.data);
    },
    ReplExpression: function(node) {
      recur(node.expression);
    },
    ReplBinding: function(node) {
      recur(node.binding);
    },
    Match: function(node) {
      recur(node.expression);
      node.clauses.forEach(recur);
    },
    MatchClause: function(node) {
      recur(node.pattern);
      recur(node.expression);
    },
    PatternSimple: function(node) {
      recur(node.identifier);
    },
    PatternParenExpr: function(node) {
      recur(node.expr);
    },
    PatternLiteral: function(node) {
      recur(node.data);
    },
    PatternArray: function(node) {
      node.patterns.forEach(recur);
    },
    PatternArraySlurpy: function(node) {
      node.patterns.forEach(recur);
      recur(node.slurp);
    },
    PatternObject: function(node) {
      node.pairs.forEach(recur);
    },
    PatternObjectPair: function(node) {
      recur(node.key);
      recur(node.value);
    },
    Error: function(node) {
      recur(node.message);
    },
    Throw: function(node) {
      recur(node.exception);
    },
    Try: function(node) {
      recur(node.expr);
    },
    Require: function(node) {
      recur(node.expr);
    },
    Not: function(node) {
      recur(node.expr);
    },
    Negate: function(node) {
      recur(node.expr);
    },
    Debugger: function(node) {},
    Global: function(node) {},
    True: function(node) {},
    False: function(node) {},
    Null: function(node) {},
    Undefined: function(node) {},
    Operator: function(node) {},
    Identifier: function(node) {},
    Number: function(node) {},
    String: function(node) {},
  };
  enter(ast, last(parents));
  if (!(ast.type in handlers)) {
    throw new Error('unknown AST node type ' + JSON.stringify(ast));
  }
  parents.push(ast);
  handlers[ast.type](ast);
  parents.pop();
  exit(ast, last(parents));
}

function walk(obj, ast) {
  return _walk([], obj, ast);
}

module.exports = {
  walk: walk
};


text:
"use strict";
var fs = require('fs');
var path = require('path');
var util = require('util');

var opInfo;
var filename;
var functionBody = null;
var finalCallback;
var session; // MMS session
var doDeploy;

exports.deployVirtualOp = function deployVirtualOp(mmsSession,callback)
{
    doVirtualOp(mmsSession,true,callback);
}
exports.undeployVirtualOp = function undeployVirtualOp(mmsSession,callback)
{
    doVirtualOp(mmsSession,false,callback);
}

function doVirtualOp(mmsSession,_deDeploy,callback)
{
    doDeploy = _deDeploy;
    finalCallback = callback;
    session = mmsSession;

    opInfo = JSON.parse(fs.readFileSync('operation.json','utf-8'));
    functionBody = null;

    var ls = fs.readdirSync('.');
    ls.forEach(function(name) {
        var end = name.substring(name.length - 3);
        if(end === '.js') {
            if(functionBody) {
                console.log('More than one .js file in operation is not allowed: ' + opInfo.name);
                process.exit(1);
            } else {
                filename = name;
                functionBody = fs.readFileSync(name, "utf-8");
            }
        }
    });

    //
    //  Delete the existing operation, if any
    //
    var obj = new Object();
    obj.op = "INVOKE";
    obj.targetType = "CdmOperation";
    obj.name = "deleteOperation";
    obj.params = new Object();
        obj.params.typeName = opInfo.type;
        obj.params.name = opInfo.name;

    session.directive(obj,'rest.operation.does.not.exist',onDeleteOperationComplete);
}

function onDeleteOperationComplete(err,restResponse)
{
    if (restResponse.status == "SUCCESS")
    {
        console.log('Operation "' + opInfo.name + '" deleted');
    }
    else if (    restResponse.errors
            &&     (restResponse.errors.length == 1)
            &&    (restResponse.errors[0].code == 'rest.operation.does.not.exist'))
    {
        if (!doDeploy)
        {
            console.log("Operation " + opInfo.name + " was not found");
        }
    }
    else
    {
        console.log('Error deleting operation "' + opInfo.name + '": ' + processRestResponse(restResponse));
    }

    //
    //  If we are deploying the operation just try to create it and ignore errors if it already exists
    //
    if (doDeploy)
    {
        onDeleteTypeComplete(null,null);
        return
    }

    //
    //  Delete the virtual CdmType, if any
    //
    var obj = new Object();
    obj.op = "INVOKE";
    obj.targetType = "CdmType";
    obj.name = "deleteCdmType";
    obj.params = new Object();
        obj.params.typeName = opInfo.type;
    obj.options = new Object();

    //console.log('Deleting type "' + opInfo.type + '...');
    session.directive(obj,'rest.target.type.does.not.exist',onDeleteTypeComplete);

}
function onDeleteTypeComplete(err,restResponse)
{
    if (restResponse)
    {

        if (restResponse.status == "SUCCESS")
        {
            console.log('CdmType "' + opInfo.type + '" deleted');
        }
        else if (    restResponse.errors
                &&   (restResponse.errors.length == 1)
                &&   (restResponse.errors[0].code == 'rest.target.type.does.not.exist'))
        {
            if (!doDeploy)
            {
                console.log("CdmType " + opInfo.type + " was not found");
            }
        }
        else
        {
            console.log('Error deleting Type "' + opInfo.type + '": ' +  processRestResponse(restResponse));
        }
    }

    if (!doDeploy)
    {
        finalCallback();
        return;
    }
    var returns;

    if (opInfo.returns && opInfo.returns.splice)
    {
        returns = opInfo.returns;
    }
    else
    {
        returns = new Array();
    }

    var ary = new Array();
    var obj;

    //
    //  Create the Virtual CdmType
    //
    obj = new Object();
    obj.op = "INVOKE";

    obj.targetType = "CdmType";
    obj.name = "createCdmType";
    obj.params = new Object();
    obj.params.typeName = opInfo.type;
    obj.params.storage = "virtual";
    obj.params.externallySourced = false;
    obj.params.sourceStrategy = "sync";
    obj.params.uniqueExternalId = true;
    obj.params.overrideAllowed = true;
    obj.params.multiTypes = returns;
    obj.params.virtualOpNames = {targetType : "CdmVirtualTypeOperations", select : [opInfo.name]};

    session.directive(obj,'cdm.type.exists',createOperation);

}

function createOperation(err,result) {
    if (result.status == "SUCCESS")
    {
        console.log('CdmType "' + opInfo.type + '" created');
    }
    else
    {
        if (doDeploy && (result.errors.length == 1) &&  (result.errors[0].code == 'cdm.type.exists'))
        {
            console.log('CdmType "' + opInfo.type + '" already exists');
        }
        else
        {

            console.log('Creation of CdmType "' + opInfo.type + '" failed: ' + processRestResponse(result));
            process.exit(1);
        }
    }

    var parameters = new Array();

    var parmsToAddString = opInfo.parameters;

    if (parmsToAddString)
    {
        var parmPairsToAdd = parmsToAddString.split(",");

        for (var i=0; i<parmPairsToAdd.length; i++)
        {
            var parmPair = parmPairsToAdd[i];
            var nv = parmPair.split(":");

            if (nv.length == 2)
            {
                var parmName = nv[0];
                var parmType = nv[1];

                parameters.push({name: parmName, typeName: parmType});
            }
            else
            {
                console.error("Parameter pair '" + parmPair + "' is invalid");
            }
        }
    }

    //
    //  Create the operation
    //
    var obj = new Object();
    obj.op = "INVOKE";

    obj.targetType = "CdmOperation";
    obj.name = "createOperation";
    obj.params = new Object();
        obj.params.objectType = opInfo.type;
        obj.params.name = opInfo.name;
        obj.params.scriptType = 'javascript';
        obj.params.body = functionBody;
        obj.params.parameters = parameters;
        obj.params.returnType = opInfo.type;

    session.directive(obj,onRegisterComplete);
}

function onRegisterComplete(err,result)
{
    if (result.status == "SUCCESS")
    {
        console.log("Created Virtual Type '" + opInfo.type + "' with Javascript operation '" + opInfo.name + "' from file " + filename);
    }
    else
    {
        console.log('Create operation "' + opInfo.name + '" failed: ' + processRestResponse(result));
    }
    console.log('');

    finalCallback();
}

function processRestResponse(restResponse)
{
    var errorMessage = null;

    if (restResponse.errors)
    {
        for (var i=0; i<restResponse.errors.length; i++)
        {
            var cdmStatus = restResponse.errors[i];

            if (errorMessage)
            {
                errorMessage += "\n" + cdmStatus.message;
            }
            else
            {
                errorMessage = cdmStatus.message;
            }

            if (restResponse.errorCode)
            {
                errorMessage += " (" + restResponse.errorCode + ")";
            }
        }
    }
    else
    {
        errorMessage = "Return value was not RestResponse: '" + JSON.stringify(restResponse) + "'";
    }

    return errorMessage;
}


text:
require File.expand_path('../application', __FILE__)

# Initialize the rails application
Coshx::Application.initialize!


text:
#region License

#endregion

using NUnit.Framework;

using Spring.Context;
using Spring.Context.Support;
using Spring.Objects;
using Spring.Objects.Factory.Xml;

namespace Spring.Aop.Framework.Adapter
{
	/// <summary>
	/// TestCase for AdvisorAdapterRegistrationManager mechanism.
	/// </summary>
	/// <author>Dmitriy Kopylenko</author>
	/// <author>Simon White (.NET)</author>
	[Platform("Win")]
	public class AdvisorAdapterRegistrationTests
	{
		[Test]
		public void AdvisorAdapterRegistrationManagerNotPresentInContext()
		{
			string configLocation = ReadOnlyXmlTestResource.GetFilePath("withoutBPPContext.xml", typeof(AdvisorAdapterRegistrationTests));
			IApplicationContext ctx = new XmlApplicationContext(configLocation);
			ITestObject to = (ITestObject) ctx.GetObject("testObject");
			// just invoke any method to see if advice fired
			try
			{
				to.ReturnsThis();
				Assert.Fail("Should throw UnknownAdviceTypeException");
			}
			catch (UnknownAdviceTypeException)
			{
				// expected
				Assert.AreEqual(0, GetAdviceImpl(to).InvocationCounter);
			}
		}

		[Test]
		public void AdvisorAdapterRegistrationManagerPresentInContext()
		{
			string configLocation = ReadOnlyXmlTestResource.GetFilePath("withBPPContext.xml", typeof(AdvisorAdapterRegistrationTests));
			IApplicationContext ctx = new XmlApplicationContext(configLocation);
			ITestObject to = (ITestObject) ctx.GetObject("testObject");
			// just invoke any method to see if advice fired
			try
			{
				to.ReturnsThis();
				Assert.AreEqual(1, GetAdviceImpl(to).InvocationCounter);
			}
			catch (UnknownAdviceTypeException)
			{
				Assert.Fail("Should not throw UnknownAdviceTypeException");
			}
		}

		private SimpleBeforeAdviceImpl GetAdviceImpl(ITestObject to)
		{
			IAdvised advised = (IAdvised) to;
			IAdvisor advisor = advised.Advisors[0];
			return (SimpleBeforeAdviceImpl) advisor.Advice;
		}
	}
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>edu.pjatk.inn.coffeemaker.impl (coffeemaker 5.3.25 API)</title>
<meta name="date" content="2016-01-22">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

edu.pjatk.inn.coffeemaker.impl

Classes

CoffeeMaker

DeliveryImpl

Inventory

Recipe


text:
import os
from os.path import join, exists
import hashlib
import requests
from flask import Flask
from flask import request, redirect, url_for, abort
from flask import render_template
from landmark import detectLandmarks

app = Flask(__name__)
app.config.from_object('config')

headers = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Encoding': 'gzip, deflate, sdch',
    'Host': 'image.baidu.com',
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.65 Safari/537.36',
}

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'GET':
        return render_template('index.html')
    # check url first
    url = request.form.get('url', None)
    if url != '':
        md5 = hashlib.md5(url+app.config['MD5_SALT']).hexdigest()
        fpath = join(join(app.config['MEDIA_ROOT'], 'upload'), md5+'.jpg')
        try:
            response = requests.get(url)
            with open(fpath, 'wb') as fout:
                fout.write(response.content)
        except Exception:
            abort(403)
        return redirect(url_for('landmark', hash=md5))

    # save file first
    f = request.files['file']
    if f.filename == '': abort(403)
    md5 = hashlib.md5(f.filename + app.config['MD5_SALT']).hexdigest()
    fpath = join(join(app.config['MEDIA_ROOT'], 'upload'), md5+'.jpg')
    f.save(fpath)
    return redirect(url_for('landmark', hash=md5))

@app.route('/landmark/<hash>')
def landmark(hash):
    RES_ROOT = join(app.config['MEDIA_ROOT'], 'result')
    UPL_ROOT = join(app.config['MEDIA_ROOT'], 'upload')
    src = join(UPL_ROOT, hash+'.jpg')
    dst = join(RES_ROOT, hash+'.jpg')
    if not exists(src):
        abort(404)
    #if not exists(dst):
    #    detectLandmarks(src, dst)
    detectLandmarks(src, dst)
    return render_template('index.html', image=os.path.basename(dst))

@app.route('/media/result/<path>')
def serve_media(path):
    """
        Serve Media File, **this function is only used for Debug**
    """
    from flask import send_from_directory
    return send_from_directory(join(app.config['MEDIA_ROOT'], 'result'), path, \
                               as_attachment=True)

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)


text:
var keypress = require('keypress'),
  five = require('johnny-five'),
  board = five.Board(),
  configs = five.Motor.SHIELD_CONFIGS.ADAFRUIT_V1;

board.on('ready', function() {
  console.log('International NodeBots Day - El Salvador');
  console.log('Controlar motor desde teclado con Node.js');
  var m1 = new five.Motor(configs.M1);
  //hacer que `process.stdin` emita eventos "mousepress" (y "keypress")
  keypress(process.stdin);
  process.stdin.resume();
  process.stdin.setEncoding('utf8');
  process.stdin.setRawMode(true);

  process.stdin.on('keypress', function (ch, key) {
    if (!key) return ;

    switch (key.name) {
      case 'q':
        console.log('Saliendo');
        process.exit();
        break;
      case 'up':
        console.log('Adelante');
        m1.forward(255);
        break;
      case 'down':
        console.log('Atras');
        m1.reverse(255);
        break;
      case 'space':
        console.log('Detener');
        m1.stop();
        break;
      default:
        break;
    }

  });
});


text:
module Damage
  class Response
    attr_reader :schema, :message

    def initialize(message, options = {})
      @message = message
      @schema = options[:schema] || Damage::Schema.new(Damage::Schema::DEFAULT_SCHEMA)
    end

    def cast_field_value(type, value)
      case type.to_s
      when "INT"
        value.to_i
      when "PRICE"
        BigDecimal.new("#{value}e-2")
      when "UTCTIMESTAMP"
        tz = ActiveSupport::TimeZone["UTC"]
        tz.parse(value)
      when "BOOLEAN"
        value == "Y" ? true : false
      else
        value
      end
    end

    def message_components
      message.split(SOH)
    end

    def message_hash
      @message_hash ||= message_hash_from_components
    end

    def message_tuples_from_components
      message_components.map do |comp|
        numeric_key, raw_value = comp.split(/=/)
        keyword = schema.field_name(numeric_key)
        field_type = schema.field_type(numeric_key)
        cast_value = cast_field_value(field_type, raw_value)
        [keyword, cast_value]
      end
    end

    def message_hash_from_components
      message_tuples_from_components.inject(Hash.new) do |memo, tuple|
        key, value = tuple
        if memo.has_key?(key)
          memo[key] = [memo[key]].flatten + [value]
        else
          memo[key] = value
        end
        memo
      end
    end

    def message_type
      %r{35=([A-Z0-9]+)}i.match(message)[1]
    end

    def message_name
      type_code = %r{35=([A-Z0-9]+)}i.match(message)[1]
      schema.msg_name(type_code)
    end

    def original_message
      message
    end

    def underscored_keys
      Hash[*message_hash.map do |k,v|
        [k.underscore, v]
      end.flatten(1)]
    end

    #easy access to properties
    def respond_to?(meth)
      has_property?(method_to_property_key(meth)) || super
    end

    def method_to_property_key(meth)
      meth.to_s.camelize
    end

    def has_property?(key)
      message_hash.has_key?(key) || schema.field_names_for_message(schema.msg_name(msg_type)).include?(key)
    end

    def method_missing(meth, *args, &block)
      key = method_to_property_key(meth)
      if has_property?(key)
        message_hash[key]
      else
        super
      end
    end
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>S3Downloader</title>
<meta name="date" content="2014-04-05">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.deeplearning4j.aws.s3.reader

Class S3Downloader

java.lang.Object

org.deeplearning4j.aws.s3.BaseS3

org.deeplearning4j.aws.s3.reader.S3Downloader

public class S3Downloader
extends BaseS3

Downloads files from S3

Field Summary

Fields inherited from class org.deeplearning4j.aws.s3.BaseS3

ACCESS_KEY, ACCESS_SECRET, accessKey, AWS_ACCESS_KEY, AWS_SECRET_KEY, creds, secretKey, serialVersionUID

Constructor Summary

Constructors

Constructor and Description

S3Downloader()

Method Summary

Methods

Modifier and Type
Method and Description

java.util.List<java.lang.String>
buckets()

Returns the list of buckets in s3

void
download(java.lang.String bucket,
        java.lang.String key,
        java.io.File to)

void
download(java.lang.String bucket,
        java.lang.String key,
        java.io.OutputStream to)

java.util.Iterator<java.io.InputStream>
iterateBucket(java.lang.String bucket)

Iterate over individual buckets.

com.amazonaws.services.s3.model.ObjectListing
listObjects(java.lang.String bucket)

Simple way of retrieving the listings for a bucket

com.amazonaws.services.s3.model.ObjectListing
nextList(com.amazonaws.services.s3.model.ObjectListing list)

Iterator style one list at a time

java.io.InputStream
objectForKey(java.lang.String bucket,
            java.lang.String key)

Returns an input stream for the given bucket and key

void
paginate(java.lang.String bucket,
        BucketKeyListener listener)

Paginates through a bucket's keys invoking the listener
 at each key

Methods inherited from class org.deeplearning4j.aws.s3.BaseS3

findCreds, getClient, getCreds, getEc2, setCreds

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

S3Downloader

public S3Downloader()

Method Detail

buckets

public java.util.List<java.lang.String> buckets()

Returns the list of buckets in s3

Returns:

the list of buckets

iterateBucket

public java.util.Iterator<java.io.InputStream> iterateBucket(java.lang.String bucket)

Iterate over individual buckets.
 Returns input streams to each object.
 It is your responsibility to close the input streams

Parameters:

bucket - the bucket to iterate over

Returns:

an iterator over the objects in an s3 bucket

nextList

public com.amazonaws.services.s3.model.ObjectListing nextList(com.amazonaws.services.s3.model.ObjectListing list)

Iterator style one list at a time

Parameters:

list - the list to get the next batch for

Returns:

the next batch of objects or null if
 none are left

listObjects

public com.amazonaws.services.s3.model.ObjectListing listObjects(java.lang.String bucket)

Simple way of retrieving the listings for a bucket

Parameters:

bucket - the bucket to retrieve listings for

Returns:

the object listing for this bucket

paginate

public void paginate(java.lang.String bucket,
            BucketKeyListener listener)

Paginates through a bucket's keys invoking the listener
 at each key

Parameters:

bucket - the bucket to iterate

listener - the listener

objectForKey

public java.io.InputStream objectForKey(java.lang.String bucket,
                               java.lang.String key)

Returns an input stream for the given bucket and key

Parameters:

bucket - the bucket to retrieve from

key - the key of the objec  t

Returns:

an input stream to the object

download

public void download(java.lang.String bucket,
            java.lang.String key,
            java.io.File to)
              throws java.io.IOException

Throws:

java.io.IOException

download

public void download(java.lang.String bucket,
            java.lang.String key,
            java.io.OutputStream to)
              throws java.io.IOException

Throws:

java.io.IOException

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
class AgilentMixin:
    id_query = "*TST?"

    def id_response(self, response):
        if response.strip() == "0":
            return True

    def initialize(self, *args, **kw):
        ret = super(AgilentMixin, self).initialize(*args, **kw)
        if ret:
            self.communicator.write_terminator = chr(10)
            cmds = self._get_initialization_commands()
            if cmds:
                for c in cmds:
                    self.tell(c)

            self._clear_and_report_errors()
        return ret

    def _get_initialization_commands(self):
        pass

    def _clear_and_report_errors(self):
        self.info("Clear and Report Errors. simulation:{}".format(self.simulation))

        es = self._get_errors()
        self.info("------------------------ Errors ------------------------")
        if es:
            for ei in es:
                self.warning(ei)
        else:
            self.info("No Errors")
        self.info("--------------------------------------------------------")

    def _get_errors(self):
        # maximum of 10 errors so no reason to use a while loop
        def gen_error():
            for _i in range(10):
                error = self._get_error()
                if error is None:
                    break
                else:
                    yield error

        return list(gen_error())

    def _get_error(self):
        error = None
        cmd = "SYST:ERR?"
        if not self.simulation:
            s = self.ask(cmd)
            if s is not None:
                s = s.strip()
                if s != '+0,"No error"':
                    error = s

        return error

# ============= EOF =============================================


text:
import PropTypes from 'prop-types';
import { createActionsFromDefinitions } from '../../actions/lib/actions';

export const planSelectionActions = createActionsFromDefinitions({
  downgradeAccount: {},
  hideOverlay: {},
}, PropTypes.checkPropTypes);

export default planSelectionActions;


text:
<?php
namespace App\Form;

use Cake\Form\Form;
use Cake\Form\Schema;
use Cake\ORM\TableRegistry;
use Cake\Utility\Inflector;

class ImportForm extends Form
{
	public $results = array();

	protected function _buildSchema(Schema $schema)
	{
		return $schema->addField('json_data', 'string');
	}

	protected function _execute(array $data)
	{
		$json = json_decode($data['json_data']);

		$this->results = array();

		$this->parse($json);
		return true;
	}

	private function parse($json)
	{
		if (is_array($json)) {
			foreach ($json as $item) {
				$this->parse($item);
			}
		} else {
			$json = (array)$json;
		}

		foreach ($json as $tablename => $data) {
			if (!is_array($data)) {
				$this->parse($data);
			} else {
				$table = Inflector::tableize($tablename);
				$table = $table == 'armours' ? 'armour' : $table; // Hack for non-standard table names

				$table = TableRegistry::get($table);
				foreach ($data as $record) {
					$record = (array)$record;
					$new = $table->import($record);
					$result = ['table' => Inflector::humanize($tablename), 'record' => $new->import_name, 'status' => $new->import_action, 'errors' => $new->import_errors];
					$this->results[] = $result;
				}
			}
		}
	}
}


text:
{% load staticfiles %}
{% if object.required_courses.all %}

    {% for course in object.required_courses.all %}
    Required Course: {{ course.name }}

    {% endfor %}

{% endif %}

    <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#save_changes_modal">
        Share Your Work
    </button>

    <button type="button" class="btn btn-primary btn-lg">
        View Job Statistics
    </button>
    <a href="{{ object.get_export_url }}" <button type="button" class="btn btn-default btn-lg" > Export Job </button>

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            ×
        </button>

Save Your Work:

            Continuous KML

            Direct KML Link

            Shape Workcells

            Shape Points

            Shape Lines

            Shape Polygons

            Job and Features

            Workcell Grid

            Detailed Features

            Simple Features

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

Export to New Job

        <form class="exportJobForm">
          <fieldset class="form-group">
            Job Name
            <input type="text" class="form-control" id="newJobName" placeholder="Enter new job name">
        </fieldset>

         Select a Destination Project
        <select class="selectpicker" title="Select Project">
          <option>Project 1</option>
          <option>Project 2</option>
          <option>Project 3</option>
        </select>

        Select Attributes to be Exported

              <input id="exportWorkCell" type="checkbox" value="">Workcells

              <input id="exportFeature" type="checkbox" value="">Features

              <input id="exportLayer" type="checkbox" value="">Layers

              <input id="exportAnalysts" type="checkbox" value="">Analysts

            <button type="button" class="btn btn-primary" data-dismiss="modal">Export</button>
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>


text:
#pragma once
#include <aws/chime/Chime_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace Chime
{
namespace Model
{
  enum class RegistrationStatus
  {
    NOT_SET,
    Unregistered,
    Registered,
    Suspended
  };

namespace RegistrationStatusMapper
{
AWS_CHIME_API RegistrationStatus GetRegistrationStatusForName(const Aws::String& name);

AWS_CHIME_API Aws::String GetNameForRegistrationStatus(RegistrationStatus value);
} // namespace RegistrationStatusMapper
} // namespace Model
} // namespace Chime
} // namespace Aws


text:
layout: pattern
title: Serverless
folder: serverless
permalink: /patterns/serverless/
categories: Architectural
tags:
 - Cloud distributed
---

## Serverless

Serverless eliminates the need to plan for infrastructure and let's you focus on your
application.

Following are optimization katas you should be aware of while building a serverless
applications

* The Lean function
    * Concise logic - Use functions to transform, not transport (utilize some of the
    integration available from the provider to transport), and make sure you read only
     what you need
    * Efficient/single purpose code - avoid conditional/routing logic and break down
    into individual functions, avoid "fat"/monolithic functions and control the
    dependencies in the function deployment package to reduce the load time for your
    function
    * ephemeral environment - Utilize container start for expensive initializations
* Eventful Invocations
    * Succinct payloads - Scrutinize the event as much as possible, and watch for
    payload constraints (async - 128K)
    * resilient routing - Understand retry policies and leverage dead letter queues
    (SQS or SNS for replays) and remember retries count as invocations
    * concurrent execution - lambda thinks of it's scale in terms of concurrency and
    its not request based/duration based. Lambda will spin up the number of instances
    based on the request.
* Coordinated calls
    * Decoupled via APIs - best practice to setup your application is to have API's as
     contracts that ensures separation of concerns
    * scale-matched downstream - make sure when Lambda is calling downstream
    components, you are matching scale configuration to it (by specifying max
    concurrency based on downstream services)
    * secured - Always ask a question, do I need a VPC?
* Serviceful operations
    * Automated - use automated tools to manage and maintain the stack
    * monitored applications - use monitoring services to get holistic view of your
    serverless applications

## Intent

Whether to reduce your infrastructure costs, shrink the time you spend on ops tasks,
simplify your deployment processes, reach infinite scalability, serverless cuts time
to market in half.

## Explanation

Serverless computing is a cloud computing execution model in which the cloud provider
dynamically manages the allocation of machine resources. Pricing is based on the
actual amount of resources consumed by an application, rather than on pre-purchased
units of capacity.

## Class diagram
![alt text](./etc/serverless.urm.png "Serverless pattern class diagram")

## Serverless framework

[Serverless](https://serverless.com/) is a toolkit for deploying and operating serverless architectures.

## (Function as a Service or "FaaS")

The term 'Serverless' is confusing since with such applications there are both server
hardware and server processes running somewhere, but the difference to normal
approaches is that the organization building and supporting a 'Serverless' application
 is not looking after the hardware or the processes - they are outsourcing this to a vendor.

Some of the Serverless Cloud Providers are

![https://serverless.com/framework/docs/providers/aws/](./etc/aws-black.png "aws")
![https://serverless.com/framework/docs/providers/azure/](./etc/azure-black.png "azure")
![https://serverless.com/framework/docs/providers/openwhisk/](./etc/openwhisk-black.png "openwhisk")
![https://serverless.com/framework/docs/providers/google/](./etc/gcf-black.png "google")
![https://serverless.com/framework/docs/providers/kubeless/](./etc/kubeless-logos-black.png "kubeless")
![https://serverless.com/framework/docs/providers/spotinst/](./etc/spotinst-logos-black-small.png "spotinst")
![https://serverless.com/framework/docs/providers/webtasks/](./etc/webtask-small-grayscale.png "webtask")
...

Anything that triggers an Lambda Function to execute is regarded by the Framework as
an Event. Most of the Serverless Cloud Providers support following Events
- Http
- PubSub Events
- scheduled

AWS supports processing event generated from AWS Services (S3/Cloudwatch/etc) and
using aws as a compute engine is our first choice.

## (Backend as a Service or "BaaS")
This example creates a backend for 'persons' collection which uses DynamoDB NoSQL
database service also provided by Amazon.

## AWS lambda function implementation

[AWS Lambda SDK](https://aws.amazon.com/sdk-for-java/) provides pre-defined interface
`com.amazonaws.services.lambda.runtime
.RequestHandler` to implement our lambda function.

```java
public class LambdaInfoApiHandler implements RequestHandler<Map<String, Object>, ApiGatewayResponse> {

  private static final Logger LOG = Logger.getLogger(LambdaInfoApiHandler.class);
  private static final Integer SUCCESS_STATUS_CODE = 200;

  @Override
  public ApiGatewayResponse handleRequest(Map<String, Object> input, Context context) {

  }
}
```
handleRequest method is where the function code is implemented. Context provides
useful information about Lambda execution environment. AWS Lambda function needs a
deployment package. This package is either a .zip or .jar file that contains all the
dependencies of the function.

`serverless.yml` contains configuration to manage deployments for your functions.

## Run example in local

# Pre-requisites

* Node.js v6.5.0 or later.
* Serverless CLI v1.9.0 or later. You can run npm install -g serverless to install it.
* An AWS account. If you don't already have one, you can sign up for a free trial that includes 1 million free Lambda requests per month.
* [Set-up](https://serverless.com/framework/docs/providers/aws/guide/credentials/) your Provider Credentials. Watch the video on setting up credentials

# build and deploy

* `cd serverless`
* `mvn clean package`
* `serverless deploy --stage=dev --verbose`

Based on the configuration in `serverless.yml` serverless framework creates following
resources

* CloudFormation stack for S3 (ServerlessDeploymentBucket)
* IAM Role (IamRoleLambdaExecution)
* CloudWatch (log groups)
* API Gateway (ApiGatewayRestApi)
* Lambda function
* DynamoDB collection

The command will print out Stack Outputs which looks something like this

```yaml
endpoints:
  GET - https://xxxxxxxxx.execute-api.us-east-1.amazonaws.com/dev/info
  POST - https://xxxxxxxxx.execute-api.us-east-1.amazonaws.com/dev/api/person
  GET - https://xxxxxxxxx.execute-api.us-east-1.amazonaws.com/dev/api/person/{id}

```

```yaml
CurrentTimeLambdaFunctionQualifiedArn: arn:aws:lambda:us-east-1:xxxxxxxxxxx:function:lambda-info-http-endpoint-dev-currentTime:4
ServiceEndpoint: https://xxxxxxxxx.execute-api.us-east-1.amazonaws.com/dev
ServerlessDeploymentBucketName: lambda-info-http-endpoin-serverlessdeploymentbuck-2u8uz2i7cap2
```
access the endpoint to invoke the function.

Use the following cURL commands to test the endpoints

```cURL
curl -X GET \
  https://xxxxxxxxx.execute-api.us-east-1.amazonaws.com/dev/info \
  -H 'cache-control: no-cache'
```

```cURL
curl -X POST \
  https://xxxxxxxxx.execute-api.us-east-1.amazonaws.com/dev/api/person \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/json' \
  -d '{
	"firstName": "Thor",
	"lastName": "Odinson",
	"address": {
		"addressLineOne": "1 Odin ln",
		"addressLineTwo": "100",
		"city": "Asgard",
		"state": "country of the Gods",
		"zipCode": "00001"
	}
}'
```

```cURL
curl -X GET \
  https://xxxxxxxxx.execute-api.us-east-1.amazonaws.com/dev/api/person/{id} \
  -H 'cache-control: no-cache'
```

## Credits

* [serverless docs](https://serverless.com/framework/docs/)
* [Serverless Architectures](https://martinfowler.com/articles/serverless.html)
* [Serverless Black Belt](https://youtu.be/oQFORsso2go)


text:
#ifndef SRC_MAIN_DMDMAIN_H
#define SRC_MAIN_DMDMAIN_H

namespace opendmd {

// extern int DmdClientMain(int argc, char *argv[]);
extern int DmdServerMain(int argc, char *argv[]);

}  // namespace opendmd

#endif  // SRC_MAIN_DMDMAIN_H


text:
<?php

namespace Doctrine\Tests\DBAL\Platforms;

use Doctrine\DBAL\Platforms\SQLServer2012Platform;
use Doctrine\DBAL\Schema\Sequence;

class SQLServer2012PlatformTest extends AbstractSQLServerPlatformTestCase
{
    public function createPlatform()
    {
        return new SQLServer2012Platform;
    }

    public function testSupportsSequences()
    {
        $this->assertTrue($this->_platform->supportsSequences());
    }

    public function testDoesNotPreferSequences()
    {
        $this->assertFalse($this->_platform->prefersSequences());
    }

    public function testGeneratesSequenceSqlCommands()
    {
        $sequence = new Sequence('myseq', 20, 1);
        $this->assertEquals(
            'CREATE SEQUENCE myseq START WITH 1 INCREMENT BY 20 MINVALUE 1',
            $this->_platform->getCreateSequenceSQL($sequence)
        );
        $this->assertEquals(
            'ALTER SEQUENCE myseq INCREMENT BY 20',
            $this->_platform->getAlterSequenceSQL($sequence)
        );
        $this->assertEquals(
            'DROP SEQUENCE myseq',
            $this->_platform->getDropSequenceSQL('myseq')
        );
        $this->assertEquals(
            "SELECT NEXT VALUE FOR myseq",
            $this->_platform->getSequenceNextValSQL('myseq')
        );
    }
}


text:
import unittest

class TestSuperOpanGrad(unittest.TestCase):

    def test_SuperOpanGradIsAbstract(self):
        from opan.grad import SuperOpanGrad

        self.assertRaises(NotImplementedError, SuperOpanGrad)

## end class TestSuperOpanGrad

class TestSuperOpanHess(unittest.TestCase):

    def test_SuperOpanHessIsAbstract(self):
        from opan.hess import SuperOpanHess

        self.assertRaises(NotImplementedError, SuperOpanHess)

## end class TestSuperOpanHess

class SuperOrca(unittest.TestCase):
    # Superclass for all ORCA test case superclasses

    # Imports
    import os

    # Constants
    testdir = 'orca_test_dir'
    resourcedir = os.path.join('test','resource','orca')

## end class SuperOrca

def suite():
    s = unittest.TestSuite()
    tl = unittest.TestLoader()
    s.addTests([tl.loadTestsFromTestCase(TestSuperOpanGrad),
                tl.loadTestsFromTestCase(TestSuperOpanHess)
                ])
    return s

if __name__ == '__main__':  # pragma: no cover
    print("Module not executable.")


text:
<!DOCTYPE html>

  <meta charset="utf-8">

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

  <title>Index — loan-status version fd65d3a</title>

    <link rel="stylesheet" href="_static/css/theme.css" type="text/css" />

    <link rel="stylesheet" href="_static/css/bootstrap.css" type="text/css" />

    <link rel="stylesheet" href="_static/css/rtd-style.css" type="text/css" />

        <link rel="index" title="Index"
              href="genindex.html"/>
        <link rel="search" title="Search" href="search.html"/>
    <link rel="top" title="loan-status version fd65d3a" href="index.html"/>

             loan-status

  <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>

Project Contents:

Classifying Risky P2P Loans

Abstract

Project Overview

Objective

About P2P Lending

Project Setup

Import Libraries & Modules

Notebook Config

Data Preprocessing

Load Dataset

Exploration

Summary

Missing Data

Data Munging

Cleaning

Feature Engineering

New Features

Drop Features

Load & Prepare Function

Exploratory Data Analysis (EDA)

Helper Functions

Overview

Missing Data

Factor Analysis

Target: loan_status

Summary Statistics

Predictive Modeling

Initializing Train/Test Sets

Shuffle and Split Data

Classification Models

Naive Predictor (Baseline)

Decision Tree Classifier

Random Forest Classifier

Blagging Classifier

Evaluating Model Performance

Feature Importance (via RandomForestClassifier)

Model Selection

Comparative Analysis

Optimal Model

Optimizing Hyperparameters

Conclusion *Pending

References

          loan-status

Docs »

Index

Index

        © Copyright 2017, Victor Naidu.
      Last updated on Aug 23, 2017.


text:
package com.tyrfing.games.tyrlib3.test;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

import com.tyrfing.games.tyrlib3.test.network.NetworkTest;

@RunWith(Suite.class)
@SuiteClasses({
	NetworkTest.class
})
public class AllTests {

}


text:
public class Gittest{

  public static void main (String[] args){
    System.out.println("Hello AS");
    System.out.println("good evening");
  }
}


text:
<!doctype html>

    <meta charset="utf-8">

<title>Search - Garrett Chung</title>
<meta name="description" content="Experience Blog">

  <meta name="author" content="Garrett Chung">

<meta property="og:type" content="website">
<meta property="og:locale" content="en_US">
<meta property="og:site_name" content="Garrett Chung">
<meta property="og:title" content="Search">
<meta property="og:url" content="http://localhost:4000/search/">

  <meta property="og:description" content="Experience Blog">

  <meta property="og:image" content="http://localhost:4000/assets/images/bio-photo.jpg">

  <meta name="twitter:site" content="@GarrettChungAU">
  <meta name="twitter:title" content="Search">
  <meta name="twitter:description" content="Experience Blog">
  <meta name="twitter:url" content="http://localhost:4000/search/">

    <meta name="twitter:card" content="summary">

      <meta name="twitter:image" content="http://localhost:4000/assets/images/bio-photo.jpg">

<link rel="canonical" href="http://localhost:4000/search/">

  <meta name="google-site-verification" content="Zju3OZrm4CblACj7RHUNhC0NAiXt_IzFSwb0mUA3WDs" />

<link href="/feed.xml" type="application/atom+xml" rel="alternate" title="Garrett Chung Feed">

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

<link rel="stylesheet" href="/assets/css/main.css">

Skip links

Skip to primary navigation

Skip to content

Skip to footer

          Garrett Chung
          Martech, Adtech & CXM

              About

              Posts

        <button class="search__toggle" type="button">
          Toggle search
          <svg class="icon" width="16" height="16" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 15.99 16">
            <path d="M15.5,13.12L13.19,10.8a1.69,1.69,0,0,0-1.28-.55l-0.06-.06A6.5,6.5,0,0,0,5.77,0,6.5,6.5,0,0,0,2.46,11.59a6.47,6.47,0,0,0,7.74.26l0.05,0.05a1.65,1.65,0,0,0,.5,1.24l2.38,2.38A1.68,1.68,0,0,0,15.5,13.12ZM6.4,2A4.41,4.41,0,1,1,2,6.4,4.43,4.43,0,0,1,6.4,2Z" transform="translate(-.01)"></path>
          </svg>
        </button>

        <button class="greedy-nav__toggle hidden" type="button">
          Toggle menu

        </button>

          Home
          <meta itemprop="position" content="1" />

        /

Search

Garrett Chung

Consultant

    <button class="btn btn--inverse">Follow</button>

           Sydney, Australia

 LinkedIn

 Website

 Twitter

 Instagram

Search

<input type="text" id="search" class="search-input" tabindex="-1" placeholder="Enter your search term..." />

<form class="search-content__form" onkeydown="return event.key != 'Enter';">

      Enter your search term...

    <input type="search" id="search" class="search-input" tabindex="-1" placeholder="Enter your search term..." />
  </form>

Follow:

 LinkedIn

 Twitter

 Instagram

 Feed

© 2021 Garrett Chung. Powered by Jekyll & Minimal Mistakes.


text:
#include "tensorflow/core/kernels/mfcc_mel_filterbank.h"

#include <vector>

#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/types.h"

namespace tensorflow {

TEST(MfccMelFilterbankTest, AgreesWithPythonGoldenValues) {
  // This test verifies the Mel filterbank against "golden values".
  // Golden values are from an independent Python Mel implementation.
  MfccMelFilterbank filterbank;

  std::vector<double> input;
  const int kSampleCount = 513;
  input.reserve(kSampleCount);
  for (int i = 0; i < kSampleCount; ++i) {
    input.push_back(i + 1);
  }
  const int kChannelCount = 20;
  filterbank.Initialize(input.size(),
                        22050 /* sample rate */,
                        kChannelCount /* channels */,
                        20.0 /*  lower frequency limit */,
                        4000.0 /* upper frequency limit */);

  std::vector<double> output;
  filterbank.Compute(input, &output);

  std::vector<double> expected = {
      7.38894574,   10.30330648, 13.72703292,  17.24158686,  21.35253118,
      25.77781089,  31.30624108, 37.05877236,  43.9436536,   51.80306637,
      60.79867148,  71.14363376, 82.90910141,  96.50069158,  112.08428368,
      129.96721968, 150.4277597, 173.74997634, 200.86037462, 231.59802942};

  ASSERT_EQ(output.size(), kChannelCount);

  for (int i = 0; i < kChannelCount; ++i) {
    EXPECT_NEAR(output[i], expected[i], 1e-04);
  }
}

TEST(MfccMelFilterbankTest, IgnoresExistingContentOfOutputVector) {
  // Test for bug where the output vector was not cleared before
  // accumulating next frame's weighted spectral values.
  MfccMelFilterbank filterbank;

  const int kSampleCount = 513;
  std::vector<double> input;
  std::vector<double> output;

  filterbank.Initialize(kSampleCount,
                        22050 /* sample rate */,
                        20 /* channels */,
                        20.0 /*  lower frequency limit */,
                        4000.0 /* upper frequency limit */);

  // First call with nonzero input value, and an empty output vector,
  // will resize the output and fill it with the correct, nonzero outputs.
  input.assign(kSampleCount, 1.0);
  filterbank.Compute(input, &output);
  for (const double value : output) {
    EXPECT_LE(0.0, value);
  }

  // Second call with zero input should also generate zero output.  However,
  // the output vector now is already the correct size, but full of nonzero
  // values.  Make sure these don't affect the output.
  input.assign(kSampleCount, 0.0);
  filterbank.Compute(input, &output);
  for (const double value : output) {
    EXPECT_EQ(0.0, value);
  }
}

}  // namespace tensorflow


text:
@implementation OMIModelArray
{
    NSMutableArray* _storage;
    Class _targetClass;
}

-(id)initWithArray:(NSArray *)array modelClass:(Class)cls
{
    self = [super init];

    if (self) {
        _storage = [NSMutableArray arrayWithArray:array];
        _targetClass = cls;
    }
    return self;
}

-(id)firstObject
{
    return [self objectAtIndex:0];
}

-(id)lastObject
{
    return [self objectAtIndex:_storage.count - 1];
}

-(id)objectAtIndex:(NSUInteger)index
{
    return [self objectAtIndexedSubscript:index];
}

-(id)objectAtIndexedSubscript:(NSUInteger)index
{
    id object = _storage[index];
    if (![object isMemberOfClass:_targetClass]) {
        NSError* err = nil;
        object = [[_targetClass alloc] initWithDictionary:object error:&err];
        if (object) {
            _storage[index] = object;
        }
    }
    return object;
}

-(void)forwardInvocation:(NSInvocation *)anInvocation
{
    [anInvocation invokeWithTarget:_storage];
}

-(id)forwardingTargetForSelector:(SEL)selector
{
    static NSArray *overriddenMethods = nil;
    if (!overriddenMethods) overriddenMethods = @[@"initWithArray:modelClass:", @"objectAtIndex:", @"objectAtIndexedSubscript:", @"count", @"modelWithIndexValue:", @"description", @"mutableCopy", @"firstObject", @"lastObject", @"countByEnumeratingWithState:objects:count:"];
    if ([overriddenMethods containsObject:NSStringFromSelector(selector)]) {
        return self;
    }
    return _storage;
}

-(NSUInteger)count
{
    return _storage.count;
}

-(id)modelWithIndexValue:(id)indexValue
{
    if (self.count==0) return nil;
    if (![_storage[0] indexPropertyName]) return nil;

    for (OMIModel* model in _storage) {
        if ([[model valueForKey:model.indexPropertyName] isEqual:indexValue]) {
            return model;
        }
    }

    return nil;
}

-(id)mutableCopy
{
    //it's already mutable
    return self;
}

#pragma mark - description
-(NSString*)description
{
    NSMutableString* res = [NSMutableString stringWithFormat:@"<OMIModelArray[%@]>\n", [_targetClass description]];
    for (id m in _storage) {
        [res appendString: [m description]];
        [res appendString: @",\n"];
    }
    [res appendFormat:@"\n</OMIModelArray>"];
    return res;
}

-(NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state
                                 objects:(id __unsafe_unretained [])stackbuf
                                   count:(NSUInteger)stackbufLength
{
    NSUInteger count = 0;

    unsigned long countOfItemsAlreadyEnumerated = state->state;

    if (countOfItemsAlreadyEnumerated == 0) {
        state->mutationsPtr = &state->extra[0];
    }

    if (countOfItemsAlreadyEnumerated < [self count]) {
        state->itemsPtr = stackbuf;
        while ((countOfItemsAlreadyEnumerated < [self count]) && (count < stackbufLength)) {
            stackbuf[count] = [self objectAtIndex:countOfItemsAlreadyEnumerated];
            countOfItemsAlreadyEnumerated++;
            count++;
        }
    } else {
        count = 0;
    }

    state->state = countOfItemsAlreadyEnumerated;

    return count;
}

@end


text:
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'i18n'
require 'buspirate'

DEFAULT_BAUDRATE = 115200
DEFAULT_DATABITS = 8
DEFAULT_STOPBITS = 1
DEFAULT_PARITY = SerialPort::NONE
DEFAULT_DEVICE = Dir.glob('/dev/ttyACM*').first

begin
  buspirate = BusPirate.new(DEFAULT_DEVICE, DEFAULT_BAUDRATE, DEFAULT_DATABITS, DEFAULT_STOPBITS, DEFAULT_PARITY)

  buspirate.reset_console
  puts "Start on #{DEFAULT_DEVICE}"

  print "entering bitbang mode..\t\t"
  if buspirate.enter_bitbang
    puts "done"
  else
    puts "failed"
    exit
  end

  print "entering binary UART mode...\t"
  if buspirate.switch_mode(BusPirate::Mode::UART)
    puts "done"
  else
    puts "failed"
    exit
  end

  print "setting baud rate...\t\t"
  if buspirate.uart_set_baudrate(9600)
    puts "done"
  else
    puts "failed"
    exit
  end

  print "setting configuration...\t"
  if buspirate.uart_set_config(BusPirate::UART::PIN_OUTPUT_HIZ, BusPirate::UART::FORMAT_8N, BusPirate::UART::STOPBITS_1, BusPirate::UART::IDLE_POLARITY_1)
    puts "done"
  else
    puts "failed"
    exit
  end

  print "configuring peripherals...\t"
  if buspirate.config_peripherals(true, true, false, false)
    puts "done"
  else
    puts "failed"
    exit
  end

  print "starting RX echo...\t\t"
  if buspirate.uart_rx_echo(true)
    puts "done"
  else
    puts "failed"
  end

  while !buspirate.port.eof?
    puts buspirate.port.readline
  end

  print "press enter to exit"
  STDIN.getc

rescue => e
  puts "Error: #{e}"
ensure
  buspirate.close unless buspirate.nil?
end


text:
Single source file function call interceptor for OpenGL. This project provides
a basic skeleton for building more sophisticated OpenGL interceptors and detours.

The template project, `opengl_proxy.cpp` provides wrapper functions for the
"classic OpenGL", AKA fixed function OpenGL, plus WGL on Windows and a few log utilities.
As is stands, it can be used for basic interception of old OpenGL applications and GL-based games.

Currently only building for Windows. Tested on Windows 7, Visual Studio 2015.

## How it works

The default DLL search strategy on Windows is:

- Application directory
- System directories

So we can take advantage of that and override system libraries, like `opengl32.dll`,
by simply placing a new DLL with the same name and interface into the application directory.

GLProxy provides a template DLL project that defines a thin wrapper over OpenGL functions
that in itself just forwards the calls to the actual OpenGL library. When compiled, it will
output a proxy `opengl32.dll` that you can place in the install directory of an application
and the app will reference it instead of the "real" OpenGL when run.

This opens the door for a lot of interesting things, from just logging every GL call
made by an application, to saving draw calls to a file for later playback.

This project is just a base skeleton for anyone interested in writing their own interceptors,
hence why it is small and entirely contained inside a single source file (`opengl_proxy.cpp`).
It provides wrappers for most of the old fixed function OpenGL + WGL. The wrapper just forwards
each call to the real OpenGL DLL, but it will also keep a global call count for each function
and attempt to write a log file when the process terminates with the counts for each function.

For more robust uses and more mature projects, I suggest checking:

- [GLIntercept](https://github.com/dtrebilco/glintercept)
- [APITrace](https://github.com/apitrace/apitrace)
- [RenderDoc](https://github.com/baldurk/renderdoc)

## License

This project's source code is released under the [MIT License](http://opensource.org/licenses/MIT).


text:
package clang

// #include "./clang-c/Index.h"
// #include "go-clang.h"
import "C"
import "fmt"

/*
	Flags that control how translation units are saved.

	The enumerators in this enumeration type are meant to be bitwise
	ORed together to specify which options should be used when
	saving the translation unit.
*/
type SaveTranslationUnit_Flags uint32

const (
	// Used to indicate that no special saving options are needed.
	SaveTranslationUnit_None SaveTranslationUnit_Flags = C.CXSaveTranslationUnit_None
)

func (stuf SaveTranslationUnit_Flags) Spelling() string {
	switch stuf {
	case SaveTranslationUnit_None:
		return "SaveTranslationUnit=None"
	}

	return fmt.Sprintf("SaveTranslationUnit_Flags unkown %d", int(stuf))
}

func (stuf SaveTranslationUnit_Flags) String() string {
	return stuf.Spelling()
}


text:
var isIndex = require('./isIndex'),
    isLength = require('./isLength'),
    isObject = require('../lang/isObject');

/**
 * Checks if the provided arguments are from an iteratee call.
 *
 * @private
 * @param {*} value The potential iteratee value argument.
 * @param {*} index The potential iteratee index or key argument.
 * @param {*} object The potential iteratee object argument.
 * @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`.
 */
function isIterateeCall(value, index, object) {
  if (!isObject(object)) {
    return false;
  }
  var type = typeof index;
  if (type == 'number') {
    var length = object.length,
        prereq = isLength(length) && isIndex(index, length);
  } else {
    prereq = type == 'string' && index in value;
  }
  return prereq && object[index] === value;
}

module.exports = isIterateeCall;


text:
import re

import pytest

from faker import Factory
from faker.config import AVAILABLE_LOCALES, DEFAULT_LOCALE, PROVIDERS

locales = AVAILABLE_LOCALES

# searches {{group}} and capture the _group_
find_group = re.compile(r"\{\{(\w+)\}\}")

@pytest.mark.parametrize("locale", locales)
def test_no_invalid_formats(locale):
    """
    For each locale, for each provider, search all the definitions of "formats"
    and make sure that all the providers in there (e.g. {{group}}) are valid
    and do not emit empty strings. Empty strings are allowed only if the group
    is not surrounded by spaces. This is a quick way to make sure that no
    string is generated with "double spaces", starting spaces or ending spaces.
    """
    faker = Factory.create(locale)
    errors = []

    for provider in PROVIDERS:
        if provider == "faker.providers":
            continue
        prov_cls, lang, default_lang = Factory._find_provider_class(provider, locale)
        if default_lang is None:
            # for non-localized providers, the discovered language will be None
            assert lang is None
        else:
            # for localized providers, the discovered language will either be
            # the requested one
            # or the default language of the provider
            # or the fallback locale
            assert lang in (locale, default_lang or DEFAULT_LOCALE)

        attributes = set(dir(prov_cls))

        for attribute in attributes:
            # consider only the format attributes
            if not attribute.endswith("formats"):
                continue
            formats = getattr(prov_cls, attribute)
            # may be a function or some other bizarre types
            if not isinstance(formats, (list, tuple)):
                continue
            for format in formats:
                # search all the {{groups}} in the format
                for match in find_group.finditer(format):
                    group = match.group(1)
                    try:
                        attr = faker.format(group)
                    except AttributeError as e:
                        errors.append(str(e))
                        continue
                    # touching = True if the group is touching sometime on at
                    # least one side, i.e. it's not surrounded by spaces
                    touching = False
                    if match.start() != 0 and format[match.start() - 1] != " ":
                        touching = True
                    if match.end() != len(format) and format[match.end()] != " ":
                        touching = True

                    if not attr and not touching:
                        errors.append(
                            "Attribute {{%s}} provided an invalid value in format '%s' from %s.%s.%s"
                            % (group, format, provider, locale, attribute),
                        )
    # group errors reporting all the ones from the same locale
    assert not errors, "Errors:\n - " + "\n - ".join(errors)


text:
package com.jiabangou.ninja.vertx.standalone.guice;

import com.google.inject.Injector;
import io.vertx.core.Verticle;
import io.vertx.core.impl.JavaVerticleFactory;
import io.vertx.core.spi.VerticleFactory;
import ninja.Bootstrap;

import java.lang.reflect.Constructor;

/**
 * Extends the default vert.x {@link JavaVerticleFactory} using Guice for dependency injection.
 */
public class GuiceVerticleFactory implements VerticleFactory {

    public static final String PREFIX = "java-guice";

    private static Bootstrap bootstrap;

    /**
     * Returns the current parent injector
     * @return
     */
    public Injector getInjector() {

        return bootstrap.getInjector();
    }

    public static void setBootstrap(Bootstrap bootstrap) {
        GuiceVerticleFactory.bootstrap = bootstrap;
    }

    @Override
    public String prefix() {
        return PREFIX;
    }

    @Override
    public Verticle createVerticle(String verticleName, ClassLoader classLoader) throws Exception {
        verticleName = VerticleFactory.removePrefix(verticleName);

        // Use the provided class loader to create an instance of GuiceVerticleLoader.  This is necessary when working with vert.x IsolatingClassLoader
        @SuppressWarnings("unchecked")
        Class<Verticle> loader = (Class<Verticle>) classLoader.loadClass(GuiceVerticleLoader.class.getName());
        Constructor<Verticle> ctor = loader.getConstructor(String.class, ClassLoader.class, Injector.class);

        if (ctor == null) {
            throw new IllegalStateException("Could not find GuiceVerticleLoader constructor");
        }

        return ctor.newInstance(verticleName, classLoader, getInjector());
    }

}