text:
package org.apache.catalina.valves;

import java.io.IOException;
import java.io.Writer;
import java.util.Scanner;

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

import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.util.RequestUtil;
import org.apache.catalina.util.ServerInfo;
import org.apache.catalina.util.TomcatCSS;
import org.apache.coyote.ActionCode;
import org.apache.tomcat.util.ExceptionUtils;
import org.apache.tomcat.util.res.StringManager;

/**
 *
Implementation of a Valve that outputs HTML error pages.

 *
 *
This Valve should be attached at the Host level, although it will work
 * if attached to a Context.

 *
 *
HTML code from the Cocoon 2 project.

 *
 * @author Remy Maucherat
 * @author Craig R. McClanahan
 * @author Nicola Ken Barozzi Aisa
 * @author Stefano Mazzocchi
 * @author Yoav Shapira
 */
public class ErrorReportValve extends ValveBase {

    private boolean showReport = true;

    private boolean showServerInfo = true;

    //------------------------------------------------------ Constructor
    public ErrorReportValve() {
        super(true);
    }

    // --------------------------------------------------------- Public Methods

    /**
     * Invoke the next Valve in the sequence. When the invoke returns, check
     * the response state. If the status code is greater than or equal to 400
     * or an uncaught exception was thrown then the error handling will be
     * triggered.
     *
     * @param request The servlet request to be processed
     * @param response The servlet response to be created
     *
     * @exception IOException if an input/output error occurs
     * @exception ServletException if a servlet error occurs
     */
    @Override
    public void invoke(Request request, Response response) throws IOException, ServletException {

        // Perform the request
        getNext().invoke(request, response);

        if (response.isCommitted()) {
            if (response.setErrorReported()) {
                // Error wasn't previously reported but we can't write an error
                // page because the response has already been committed. Attempt
                // to flush any data that is still to be written to the client.
                try {
                    response.flushBuffer();
                } catch (Throwable t) {
                    ExceptionUtils.handleThrowable(t);
                }
                // Close immediately to signal to the client that something went
                // wrong
                response.getCoyoteResponse().action(ActionCode.CLOSE_NOW, null);
            }
            return;
        }

        Throwable throwable = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);

        // If an async request is in progress and is not going to end once this
        // container thread finishes, do not process any error page here.
        if (request.isAsync() && !request.isAsyncCompleting()) {
            return;
        }

        if (throwable != null && !response.isError()) {
            // Make sure that the necessary methods have been called on the
            // response. (It is possible a component may just have set the
            // Throwable. Tomcat won't do that but other components might.)
            // These are safe to call at this point as we know that the response
            // has not been committed.
            response.reset();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }

        // One way or another, response.sendError() will have been called before
        // execution reaches this point and suspended the response. Need to
        // reverse that so this valve can write to the response.
        response.setSuspended(false);

        try {
            report(request, response, throwable);
        } catch (Throwable tt) {
            ExceptionUtils.handleThrowable(tt);
        }
    }

    // ------------------------------------------------------ Protected Methods

    /**
     * Prints out an error report.
     *
     * @param request The request being processed
     * @param response The response being generated
     * @param throwable The exception that occurred (which possibly wraps
     *  a root cause exception
     */
    protected void report(Request request, Response response, Throwable throwable) {

        int statusCode = response.getStatus();

        // Do nothing on a 1xx, 2xx and 3xx status
        // Do nothing if anything has been written already
        // Do nothing if the response hasn't been explicitly marked as in error
        //    and that error has not been reported.
        if (statusCode < 400 || response.getContentWritten() > 0 || !response.setErrorReported()) {
            return;
        }
        String message = RequestUtil.filter(response.getMessage());
        if (message == null) {
            if (throwable != null) {
                String exceptionMessage = throwable.getMessage();
                if (exceptionMessage != null && exceptionMessage.length() > 0) {
                    message = RequestUtil.filter((new Scanner(exceptionMessage)).nextLine());
                }
            }
            if (message == null) {
                message = "";
            }
        }

        // Do nothing if there is no reason phrase for the specified status code and
        // no error message provided
        String reason = null;
        String description = null;
        StringManager smClient = StringManager.getManager(
                Constants.Package, request.getLocales());
        response.setLocale(smClient.getLocale());
        try {
            reason = smClient.getString("http." + statusCode + ".reason");
            description = smClient.getString("http." + statusCode + ".desc");
        } catch (Throwable t) {
            ExceptionUtils.handleThrowable(t);
        }
        if (reason == null || description == null) {
            if (message.isEmpty()) {
                return;
            } else {
                reason = smClient.getString("errorReportValve.unknownReason");
                description = smClient.getString("errorReportValve.noDescription");
            }
        }

        StringBuilder sb = new StringBuilder();

        sb.append("<!doctype html>");
        sb.append("");
        sb.append("<title>");
        sb.append(smClient.getString("errorReportValve.statusHeader",
                String.valueOf(statusCode), reason));
        sb.append("</title>");
        sb.append("");
        sb.append("");
        sb.append("
");
        sb.append(smClient.getString("errorReportValve.statusHeader",
                String.valueOf(statusCode), reason)).append("
");
        if (isShowReport()) {
            sb.append("
");
            sb.append("
");
            sb.append(smClient.getString("errorReportValve.type"));
            sb.append(" ");
            if (throwable != null) {
                sb.append(smClient.getString("errorReportValve.exceptionReport"));
            } else {
                sb.append(smClient.getString("errorReportValve.statusReport"));
            }
            sb.append("
");
            if (!message.isEmpty()) {
                sb.append("
");
                sb.append(smClient.getString("errorReportValve.message"));
                sb.append(" ");
                sb.append(message).append("
");
            }
            sb.append("
");
            sb.append(smClient.getString("errorReportValve.description"));
            sb.append(" ");
            sb.append(description);
            sb.append("
");
            if (throwable != null) {
                String stackTrace = getPartialServletStackTrace(throwable);
                sb.append("
");
                sb.append(smClient.getString("errorReportValve.exception"));
                sb.append("

");
                sb.append(RequestUtil.filter(stackTrace));
                sb.append("
");

                int loops = 0;
                Throwable rootCause = throwable.getCause();
                while (rootCause != null && (loops < 10)) {
                    stackTrace = getPartialServletStackTrace(rootCause);
                    sb.append("
");
                    sb.append(smClient.getString("errorReportValve.rootCause"));
                    sb.append("

");
                    sb.append(RequestUtil.filter(stackTrace));
                    sb.append("
");
                    // In case root cause is somehow heavily nested
                    rootCause = rootCause.getCause();
                    loops++;
                }

                sb.append("
");
                sb.append(smClient.getString("errorReportValve.note"));
                sb.append(" ");
                sb.append(smClient.getString("errorReportValve.rootCauseInLogs"));
                sb.append("
");

            }
            sb.append("
");
        }
        if (isShowServerInfo()) {
            sb.append("
").append(ServerInfo.getServerInfo()).append("
");
        }
        sb.append("");

        try {
            try {
                response.setContentType("text/html");
                response.setCharacterEncoding("utf-8");
            } catch (Throwable t) {
                ExceptionUtils.handleThrowable(t);
                if (container.getLogger().isDebugEnabled()) {
                    container.getLogger().debug("status.setContentType", t);
                }
            }
            Writer writer = response.getReporter();
            if (writer != null) {
                // If writer is null, it's an indication that the response has
                // been hard committed already, which should never happen
                writer.write(sb.toString());
                response.finishResponse();
            }
        } catch (IOException e) {
            // Ignore
        } catch (IllegalStateException e) {
            // Ignore
        }

    }

    /**
     * Print out a partial servlet stack trace (truncating at the last
     * occurrence of javax.servlet.).
     * @param t The stack trace to process
     * @return the stack trace relative to the application layer
     */
    protected String getPartialServletStackTrace(Throwable t) {
        StringBuilder trace = new StringBuilder();
        trace.append(t.toString()).append(System.lineSeparator());
        StackTraceElement[] elements = t.getStackTrace();
        int pos = elements.length;
        for (int i = elements.length - 1; i >= 0; i--) {
            if ((elements[i].getClassName().startsWith
                 ("org.apache.catalina.core.ApplicationFilterChain"))
                && (elements[i].getMethodName().equals("internalDoFilter"))) {
                pos = i;
                break;
            }
        }
        for (int i = 0; i < pos; i++) {
            if (!(elements[i].getClassName().startsWith
                  ("org.apache.catalina.core."))) {
                trace.append('\t').append(elements[i].toString()).append(System.lineSeparator());
            }
        }
        return trace.toString();
    }

    /**
     * Enables/Disables full error reports
     *
     * @param showReport true to show full error data
     */
    public void setShowReport(boolean showReport) {
        this.showReport = showReport;
    }

    public boolean isShowReport() {
        return showReport;
    }

    /**
     * Enables/Disables server info on error pages
     *
     * @param showServerInfo true to show server info
     */
    public void setShowServerInfo(boolean showServerInfo) {
        this.showServerInfo = showServerInfo;
    }

    public boolean isShowServerInfo() {
        return showServerInfo;
    }
}


text:
package com.hevelian.identity.users.repository;

import com.hevelian.identity.users.model.Role;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;

import java.util.Set;

public interface RoleRepository extends PagingAndSortingRepository<Role, Long>, JpaSpecificationExecutor<Role> {

  int deleteByName(String roleName);

  Role findOneByName(String roleName);

  // Need to use the custom Query instead. See:
  // https://bugs.eclipse.org/bugs/show_bug.cgi?id=349477
  @Query("select r from Role r  where r.name in ?1")
  Set<Role> findByNameIsIn(Set<String> roleNames);

  @Modifying
  @Query("update Role r set r.name = ?2 where r.name = ?1")
  int updateName(String name, String newName);

  // TODO replace with JPA query
  @Modifying
  @Query(value = "DELETE FROM USER_ROLE WHERE ROLES_ID = ?1", nativeQuery = true)
  void deleteAllUsers(Long roleId);

}

redpajama_set_name: RedPajamaGithub


text:
require 'cases/helper'
require 'models/topic'
require 'models/car'
require 'models/wheel'
require 'models/engine'
require 'models/reply'
require 'models/category'
require 'models/categorization'
require 'models/dog'
require 'models/dog_lover'
require 'models/person'
require 'models/friendship'
require 'models/subscriber'
require 'models/subscription'
require 'models/book'

class CounterCacheTest < ActiveRecord::TestCase
  fixtures :topics, :categories, :categorizations, :cars, :dogs, :dog_lovers, :people, :friendships, :subscribers, :subscriptions, :books

  class ::SpecialTopic < ::Topic
    has_many :special_replies, :foreign_key => 'parent_id'
  end

  class ::SpecialReply < ::Reply
    belongs_to :special_topic, :foreign_key => 'parent_id', :counter_cache => 'replies_count'
  end

  setup do
    @topic = Topic.find(1)
  end

  test "increment counter" do
    assert_difference '@topic.reload.replies_count' do
      Topic.increment_counter(:replies_count, @topic.id)
    end
  end

  test "decrement counter" do
    assert_difference '@topic.reload.replies_count', -1 do
      Topic.decrement_counter(:replies_count, @topic.id)
    end
  end

  test "reset counters" do
    # throw the count off by 1
    Topic.increment_counter(:replies_count, @topic.id)

    # check that it gets reset
    assert_difference '@topic.reload.replies_count', -1 do
      Topic.reset_counters(@topic.id, :replies)
    end
  end

  test "reset counters with string argument" do
    Topic.increment_counter('replies_count', @topic.id)

    assert_difference '@topic.reload.replies_count', -1 do
      Topic.reset_counters(@topic.id, 'replies')
    end
  end

  test "reset counters with modularized and camelized classnames" do
    special = SpecialTopic.create!(:title => 'Special')
    SpecialTopic.increment_counter(:replies_count, special.id)

    assert_difference 'special.reload.replies_count', -1 do
      SpecialTopic.reset_counters(special.id, :special_replies)
    end
  end

  test "reset counter with belongs_to which has class_name" do
    car = cars(:honda)
    assert_nothing_raised do
      Car.reset_counters(car.id, :engines)
    end
    assert_nothing_raised do
      Car.reset_counters(car.id, :wheels)
    end
  end

  test "reset the right counter if two have the same class_name" do
    david = dog_lovers(:david)

    DogLover.increment_counter(:bred_dogs_count, david.id)
    DogLover.increment_counter(:trained_dogs_count, david.id)

    assert_difference 'david.reload.bred_dogs_count', -1 do
      DogLover.reset_counters(david.id, :bred_dogs)
    end
    assert_difference 'david.reload.trained_dogs_count', -1 do
      DogLover.reset_counters(david.id, :trained_dogs)
    end
  end

  test "update counter with initial null value" do
    category = categories(:general)
    assert_equal 2, category.categorizations.count
    assert_nil category.categorizations_count

    Category.update_counters(category.id, :categorizations_count => category.categorizations.count)
    assert_equal 2, category.reload.categorizations_count
  end

  test "update counter for decrement" do
    assert_difference '@topic.reload.replies_count', -3 do
      Topic.update_counters(@topic.id, :replies_count => -3)
    end
  end

  test "update counters of multiple records" do
    t1, t2 = topics(:first, :second)

    assert_difference ['t1.reload.replies_count', 't2.reload.replies_count'], 2 do
      Topic.update_counters([t1.id, t2.id], :replies_count => 2)
    end
  end

  test "reset the right counter if two have the same foreign key" do
    michael = people(:michael)
    assert_nothing_raised(ActiveRecord::StatementInvalid) do
      Person.reset_counters(michael.id, :followers)
    end
  end

  test "reset counter of has_many :through association" do
    subscriber = subscribers('second')
    Subscriber.reset_counters(subscriber.id, 'books')
    Subscriber.increment_counter('books_count', subscriber.id)

    assert_difference 'subscriber.reload.books_count', -1 do
      Subscriber.reset_counters(subscriber.id, 'books')
    end
  end
end


text:
[![CircleCI](https://circleci.com/gh/cschiewek/mandrag.svg?style=svg)](https://circleci.com/gh/cschiewek/mandrag)

Zero Confing Elixir Deployments to [Kubernetes](https://kubernetes.io/) via [Helm](https://helm.sh/)

## Requirements
- Elixir 1.9 (See the older v0.7.x tags for versions that support > 1.9 via Distillery)
- Mandrag expects that you have docker, kubectl and helm binaries installed and configured.
- Currently, It also expects that you have a helm chart in the `chart` directory.

## Installation

If [available in Hex](https://hex.pm/docs/publish), the package can be installed
by adding `mandrag` to your list of dependencies in `mix.exs`:

```elixir
def deps do
  [
    {:mandrag, "~> 0.8.0"}
  ]
end
```

## Configure

Mandrag doesn't require configuation, it'll introspect the parent mix config to derive configuration, and use it's own built-in [Dockerfile](https://github.com/cschiewek/mandrag/blob/master/priv/Dockerfile), but you can override those values as seen below.

```elixir
config :mandrag,
  # The name of the app and release. Defaults to the :app key in the parent mix project.
  app: :app_name,
  # The docker repo to push to. Defaults to `app_name`.
  docker_repo: "docker_user_name/app_name",
  # The path to the Dockerfile to be used.  Defaults to the Dockerfile inside this package.
  dockerfile_path: "Dockerfile",
  # A map of values that are translated to `--build-arg` arguments.
  docker_build_args: %{key: "value"}
  # The kubernetes context, defaults to your current context
  k8s_context: "docker-for-desktop"
```

TODO for 1.0:
- Add default Helm chart for zero conifg standup.

TODO for 1.x:
- Enable clustering for deploys with multiple replicas via [libcluster](https://github.com/bitwalker/libcluster)
- Remove dependency docker, kubectl, and helm binaries by leveraging their respective APIs

Documentation can be generated with [ExDoc](https://github.com/elixir-lang/ex_doc)
and published on [HexDocs](https://hexdocs.pm). Once published, the docs can
be found at [https://hexdocs.pm/mandrag](https://hexdocs.pm/mandrag).


text:
from ebooks.auth import is_safe_url, load_saml_settings, prepare_flask_request
from unittest.mock import patch

import os

from flask import request

def test_is_safe_url_is_safe(app):
    with app.test_request_context():
        x = is_safe_url('http://localhost/?safe')
        assert x is True

def test_is_safe_url_is_not_safe(app):
    with app.test_request_context():
        x = is_safe_url('//unsafe-site.com')
        assert x is False

@patch.dict(os.environ, {
    'SP_ENTITY_ID': 'http://ebooks.test/shibboleth/',
    'SP_ACS_URL': 'http://ebooks.test/shibboleth/?acs',
    'SP_SLS_URL': 'http://ebooks.test/shibboleth/?sls',
    'IDP_ENTITY_ID': 'https://test-idp.com/saml2/metadata/',
    'IDP_SSO_URL': 'https://test-idp.com/saml2/http-post/sso/',
    'IDP_SLS_URL': 'http://test-idp.com/saml2/http-post/slo/',
    'SP_CERT': 'iamacert',
    'SP_KEY': 'iamasecretkey',
    'IDP_CERT': 'iamacert'})
def test_load_saml_settings_returns_json(app):
    with app.test_request_context():
        x = load_saml_settings()
        assert x['sp']['entityId'] == 'http://ebooks.test/shibboleth/'

@patch.dict(os.environ, {'SP_ENTITY_ID': ''})
def test_load_saml_settings_missing_env_variable_raises_exception(app):
    # TODO: raise an exception if there is a missing SAML env variable. We know
    # that this will break auth, so the app shouldn't run without it.
    pass

def test_prepare_flask_request(app):
    with app.test_request_context():
        x = prepare_flask_request(request)
        assert x['http_host'] == 'localhost'


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>ezbake.data</groupId>
        <artifactId>ezbake-data-access-ezelastic-parent</artifactId>
        <version>2.1</version>
    </parent>

    <artifactId>elastic-common</artifactId>

    <dependencies>
        <!-- Third-Party dependencies -->
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
        </dependency>

        <!-- EzBake dependencies -->
        <dependency>
            <groupId>ezbake.data</groupId>
            <artifactId>ezelastic-thrift</artifactId>
        </dependency>
        <dependency>
            <groupId>ezbake.data</groupId>
            <artifactId>common-utils</artifactId>
            <version>2.1</version>
        </dependency>
    </dependencies>
</project>


text:
<resources>

    <style name="AppTheme.BottomSheet">
        <item name="android:windowDrawsSystemBarBackgrounds">true</item>
        <item name="android:windowTranslucentStatus">true</item>
        <item name="android:windowAllowEnterTransitionOverlap">true</item>
        <item name="android:windowAllowReturnTransitionOverlap">true</item>
        <item name="android:windowTransitionBackgroundFadeDuration">200</item>
    </style>

    <style name="NormalTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/trans_blue</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:windowActionBar">false</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:statusBarColor">@color/black_overlay</item>
        <item name="android:windowDrawsSystemBarBackgrounds">true</item>
        <item name="android:windowActionBarOverlay">true</item>
        <item name="android:windowActionModeOverlay">true</item>
        <item name="android:windowContentOverlay">@null</item>
        <!--<item name="android:windowBackground">@color/cardview_light_background</item>-->
        <!--<item name="android:windowTranslucentStatus">true</item>-->
        <!--<item name="android:statusBarColor">#cc555555</item>-->
        <!--<item name="android:statusBarColor">@android:color/transparent</item>-->
        <!--<item name="android:statusBarColor">@android:color/transparent</item>-->
    </style>

    <style name="NormalTheme.Translate">
        <item name="android:windowDrawsSystemBarBackgrounds">true</item>
        <item name="android:statusBarColor">@android:color/transparent</item>
    </style>
</resources>


text:
package com.intellij.psi.impl.source.tree.java;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.psi.PsiKeyword;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.ChildRoleBase;
import com.intellij.psi.impl.source.tree.ChildRole;
import com.intellij.lang.ASTNode;

/**
 *  @author dsl
 */
public class ImplementsListElement extends ReferenceListElement {
  private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.tree.java.ImplementsListElement");

  public ImplementsListElement() {
    super(IMPLEMENTS_LIST);
  }

  protected String getKeywordText() {
    return PsiKeyword.IMPLEMENTS;
  }

  protected IElementType getKeywordType() {
    return IMPLEMENTS_KEYWORD;
  }

  public ASTNode findChildByRole(int role) {
    LOG.assertTrue(ChildRole.isUnique(role));
    switch(role){
      default:
        return null;

      case ChildRole.EXTENDS_KEYWORD:
        return findChildByType(EXTENDS_KEYWORD);
    }
  }

  public int getChildRole(ASTNode child) {
    LOG.assertTrue(child.getTreeParent() == this);
    IElementType i = child.getElementType();
    if (i == IMPLEMENTS_KEYWORD) {
      return ChildRole.IMPLEMENTS_KEYWORD;
    }
    else if (i == COMMA) {
      return ChildRole.COMMA;
    }
    else if (i == JAVA_CODE_REFERENCE) {
      return ChildRole.REFERENCE_IN_LIST;
    }
    else {
      return ChildRoleBase.NONE;
    }
  }
}


text:
package com.wesley009.opensource.rt_podcast_unofficial.utilities;

import android.graphics.Rect;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
    private int space;
    private int spanCount;
    private int lastItemInFirstLane = -1;
    public SpacesItemDecoration(int space) {
        this(space, 1);
    }

    public SpacesItemDecoration(int space, int spanCount) {
        this.space = space;
        this.spanCount = spanCount;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) view.getLayoutParams();
        final int position = params.getViewPosition();
        final int spanSize;
        final int index;
        if (params instanceof GridLayoutManager.LayoutParams) {
            GridLayoutManager.LayoutParams gridParams = (GridLayoutManager.LayoutParams) params;
            spanSize = gridParams.getSpanSize();
            index = gridParams.getSpanIndex();
        }else{
            spanSize = 1;
            index = position % spanCount;
        }
        // invalid value
        if (spanSize < 1 || index < 0) return;

        if (spanSize == spanCount) { // full span
            outRect.left = space;
            outRect.right = space;
        } else {
            if (index == 0) {  // left one
                outRect.left = space;
            }
            // spanCount >= 1
            if (index == spanCount - 1) { // right one
                outRect.right = space;
            }
            if (outRect.left == 0) {
                outRect.left = space / 2;
            }
            if (outRect.right == 0) {
                outRect.right = space / 2;
            }
        }
        // set top to all in first lane
        if (position < spanCount && spanSize <= spanCount) {
            if (lastItemInFirstLane < 0) { // lay out at first time
                lastItemInFirstLane = position + spanSize == spanCount ? position : lastItemInFirstLane;
                outRect.top = space;
            } else if (position <= lastItemInFirstLane) { // scroll to first lane again
                outRect.top = space;
            }
        }
        outRect.bottom = space;

    }
}


text:
package org.kuali.kfs.sec.document.authorization;

import java.util.List;
import java.util.Set;

import org.kuali.kfs.sec.service.AccessSecurityService;
import org.kuali.kfs.sys.businessobject.AccountingLine;
import org.kuali.kfs.sys.context.SpringContext;
import org.kuali.kfs.sys.document.AccountingDocument;
import org.kuali.kfs.sys.document.authorization.AccountingLineAuthorizer;
import org.kuali.kfs.sys.document.web.AccountingLineRenderingContext;
import org.kuali.kfs.sys.document.web.AccountingLineViewAction;
import org.kuali.rice.kim.api.identity.Person;

/**
 * AccountingLineAuthorizer that wraps access security checks around another AccountingLineAuthorizer configured for the document type
 */
public class SecAccountingLineAuthorizer implements AccountingLineAuthorizer {
    protected AccountingLineAuthorizer lineAuthorizer;

    public List<AccountingLineViewAction> getActions(AccountingDocument accountingDocument, AccountingLineRenderingContext accountingLineRenderingContext, String accountingLinePropertyName, Integer lineIndex, Person currentUser, String groupTitle) {
        return lineAuthorizer.getActions(accountingDocument, accountingLineRenderingContext, accountingLinePropertyName, lineIndex, currentUser, groupTitle);
    }

    public Set<String> getUnviewableBlocks(AccountingDocument accountingDocument, AccountingLine accountingLine, boolean newLine, Person currentUser) {
        return lineAuthorizer.getUnviewableBlocks(accountingDocument, accountingLine, newLine, currentUser);
    }

    /**
     * Makes call to check edit access security on accounting line
     *
     * @see org.kuali.kfs.sys.document.authorization.AccountingLineAuthorizer#hasEditPermissionOnAccountingLine
     */
    public boolean hasEditPermissionOnAccountingLine(AccountingDocument accountingDocument, AccountingLine accountingLine, String accountingLineCollectionProperty, Person currentUser, boolean pageIsEditable) {
        boolean hasEditPermission = lineAuthorizer.hasEditPermissionOnAccountingLine(accountingDocument, accountingLine, accountingLineCollectionProperty, currentUser, pageIsEditable);

        if (hasEditPermission) {
            hasEditPermission = SpringContext.getBean(AccessSecurityService.class).canEditDocumentAccountingLine(accountingDocument, accountingLine, currentUser);
        }

        return hasEditPermission;
    }

    /**
     * If access was granted to line and line authorizer allows field modify then allow field modify
     *
     * @see org.kuali.kfs.sys.document.authorization.AccountingLineAuthorizer#hasEditPermissionOnField
     */
    public boolean hasEditPermissionOnField(AccountingDocument accountingDocument, AccountingLine accountingLine, String accountingLineCollectionProperty, String fieldName, boolean editableLine, boolean editablePage, Person currentUser) {
        boolean hasEditPermission = lineAuthorizer.hasEditPermissionOnField(accountingDocument, accountingLine, accountingLineCollectionProperty, fieldName, editableLine, editablePage, currentUser);

        return hasEditPermission;
    }

    public boolean isGroupEditable(AccountingDocument accountingDocument, List<? extends AccountingLineRenderingContext> accountingLineRenderingContexts, Person currentUser) {
        return lineAuthorizer.isGroupEditable(accountingDocument, accountingLineRenderingContexts, currentUser);
    }

    public boolean renderNewLine(AccountingDocument accountingDocument, String accountingGroupProperty) {
        return lineAuthorizer.renderNewLine(accountingDocument, accountingGroupProperty);
    }

    /**
     * Sets the lineAuthorizer attribute value.
     *
     * @param lineAuthorizer The lineAuthorizer to set.
     */
    public void setLineAuthorizer(AccountingLineAuthorizer lineAuthorizer) {
        this.lineAuthorizer = lineAuthorizer;
    }

}


text:
'use strict';

const expect = require('chai').expect;
const func = require('./addtwonumbers').addTwoNumbers;
const ListNode = require('./listnode').ListNode

describe('*2. Add Two Numbers*', function () {
    it('[2,4,3], [5,6,4] = [7,0,8]', function () {
        const input1 = JSON.parse('{"val": 2, "next": {"val": 4, "next": {"val": 3, "next": null}}}');
        const input2 = JSON.parse('{"val": 5, "next": {"val": 6, "next": {"val": 4, "next": null}}}');
        const expected = JSON.parse('{"val": 7, "next": {"val": 0, "next": {"val": 8, "next": null}}}');

        expect(JSON.stringify(func(input1, input2))).to.be.eql(JSON.stringify(expected));
    })
});


text:
package ar.com.javacuriosities.hibernate.model.bidirectional_map;

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

@Entity
@Table(name = "parameters")
public class Parameters {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private String value;

    @ManyToOne
    private Execution execution;

    public Parameters() {
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public Execution getExecution() {
        return execution;
    }

    public void setExecution(Execution execution) {
        this.execution = execution;
    }
}


text:
from elements import ELEMENTS

# holds important information associated with data file
FILE_INFO = {'Element':'', 'Source':'', 'Supply':'', 'TiltDeg':[],
             'Z_mm':[]}

""" gets information for FILE_INFO from name of data file """
def parseFilename(filename):
    global FILE_INFO
    # ignore '.csv' at end of filename
    if filename.endswith('.csv'):
        filename = filename[:-4]
    # experiment parameters should be separated with underscores
    rawFileInfo = filename.split('_')
    # keys: keywords in filename; values: corresponding keys in FILE_INFO
    tagsDict = {'Source': 'Source', 'Src': 'Source', 'SRC': 'Source',
            'src': 'Source', 't': 'TiltDeg', 'tilt': 'TiltDeg', 'z': 'Z_mm',
            'Z': 'Z_mm', 'Supply': 'Supply', 'Sup': 'Supply', 'sup': 'Supply'}
    for tag in rawFileInfo:
        # strippedTag is the keyword
        strippedTag = filter(str.isalpha, tag)
        # tagVal is the numerical value attached to the keyword
        tagVal = filter(lambda x: not x.isalpha(), tag)
        if strippedTag in tagsDict:
            stdName = tagsDict.get(strippedTag)
            # multiple z-values can be listed in filename
            if (stdName == 'Z_mm' and stdName in FILE_INFO):
                FILE_INFO[stdName] += [float(tagVal)]
            # z and t values should be stored in a list (used in
            #   data processing)
            elif (stdName == 'Z_mm' or stdName == 'TiltDeg'):
                FILE_INFO[stdName] = [float(tagVal)]
            # all other values can be saved as string
            else:
                FILE_INFO[stdName] = tagVal
        elif tag in ELEMENTS:
            FILE_INFO['Element'] = tag

    # keep track of any parameters that were not found in filename
    invalidTags = []
    for tag in FILE_INFO:
        if not FILE_INFO.get(tag):
            invalidTags.append(tag)

    # existence of invalidTags will be checked by MainMenu
    return invalidTags


text:
typedef NS_ENUM(NSInteger, RotateState){
    RotateStateStop = 0,
    RotateStateRun
};

@interface FirstViewController () {
    //旋转角度
    CGFloat imageAngel;
    //旋转图片
    UIImageView *rotateImage;
    //旋转状态
    RotateState rotateState;
}

//音乐播放器
@property(nonatomic,strong)AVAudioPlayer *audioPlayer;

@end

@implementation FirstViewController

#pragma mark - viewDidLoad

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor redColor];
    self.title = @"微信";
    [self setupRightBarButtonItem];
    NSString *dateStr = [self currentDateWithFormatter:@"EEEE"];
    NSLog(@"dateStr is :%@", dateStr);

}

#pragma mark - setupRightBarButtonItem

- (void)setupRightBarButtonItem {
    rotateImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"rightBarButtonImg"]];
    rotateImage.autoresizingMask = UIViewAutoresizingNone;
    rotateImage.contentMode = UIViewContentModeScaleToFill;
    rotateImage.bounds = CGRectMake(0, 0, 30, 30);
    rotateImage.layer.cornerRadius = 15;
    rotateImage.layer.masksToBounds = YES;

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, 30, 30);
    [button addSubview:rotateImage];
    rotateImage.center = button.center;
    [button addTarget:self action:@selector(runAnimation) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button];
}

#pragma mark - button target

- (void)runAnimation {
    if (rotateState == RotateStateStop) {
        rotateState = RotateStateRun;
        [self rotateAnimate];
        [self playMusic];
    } else {
        rotateState = RotateStateStop;
        [self stopMusic];
    }
}

#pragma mark - 旋转动画

- (void)rotateAnimate {
    imageAngel += 60;
    [UIView animateWithDuration:0.5 delay:0.0 options:UIViewAnimationOptionCurveLinear animations:^{
        rotateImage.transform = CGAffineTransformMakeRotation(kDEGRE_TO_RADIANS(imageAngel));
    } completion:^(BOOL finished) {
        if (rotateState == RotateStateRun) {
            [self rotateAnimate];
        }
    }];
}

#pragma mark - 开始播放音乐

- (void)playMusic {
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"电音之王" ofType:@"mp3"];
    NSURL *musicUrl = [[NSURL alloc]initFileURLWithPath:filePath];
    _audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:musicUrl error:nil];
    [_audioPlayer prepareToPlay];
    //循环次数,-1为无限循环
    _audioPlayer.numberOfLoops = -1;
    [_audioPlayer play];
}

#pragma mark - 关闭音乐

- (void)stopMusic {
    [_audioPlayer stop];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.navigationController pushViewController:[MusicViewController new] animated:YES];

}

#pragma mark - 判读当前是周几

- (NSString *)currentDateWithFormatter:(NSString *)formatter {
    NSDate *date = [NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:formatter];
    NSString *weekString = [dateformatter stringFromDate:date];
    return weekString;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

@end


text:
package com.android.server;

import com.francetelecom.rd.stubs.annotation.Code;

@com.francetelecom.rd.stubs.annotation.ClassDone(0)
public class InputMethodManagerService
  extends com.android.internal.view.IInputMethodManager.Stub  implements android.content.ServiceConnection, android.os.Handler.Callback
{
  // Constructors
  @com.francetelecom.rd.stubs.annotation.CallBackRegister("onCreate")
  public InputMethodManagerService(android.content.Context arg1){
    super();
  }
  // Methods

  @com.francetelecom.rd.stubs.annotation.CallBack("onCreate")
  public boolean onTransact(int arg1, android.os.Parcel arg2, android.os.Parcel arg3, int arg4) throws android.os.RemoteException{
    return false;
  }
  protected void dump(java.io.FileDescriptor arg1, java.io.PrintWriter arg2, java.lang.String [] arg3){
  }
  @com.francetelecom.rd.stubs.annotation.CallBack("onCreate")
  public boolean handleMessage(android.os.Message arg1){
    return false;
  }
  @com.francetelecom.rd.stubs.annotation.CallBack("onCreate")
  public void onServiceConnected(android.content.ComponentName arg1, android.os.IBinder arg2){
  }
  @com.francetelecom.rd.stubs.annotation.CallBack("onCreate")
  public void onServiceDisconnected(android.content.ComponentName arg1){
  }
  public boolean showSoftInput(@com.francetelecom.rd.stubs.annotation.CallBackRegister("IInputMethodClient") com.android.internal.view.IInputMethodClient arg1, int arg2, android.os.ResultReceiver arg3){
    return false;
  }
  public com.android.internal.view.InputBindResult startInput(@com.francetelecom.rd.stubs.annotation.CallBackRegister("IInputMethodClient") com.android.internal.view.IInputMethodClient arg1, com.android.internal.view.IInputContext arg2, android.view.inputmethod.EditorInfo arg3, boolean arg4, boolean arg5){
    return (com.android.internal.view.InputBindResult) null;
  }
  public boolean hideSoftInput(@com.francetelecom.rd.stubs.annotation.CallBackRegister("IInputMethodClient") com.android.internal.view.IInputMethodClient arg1, int arg2, android.os.ResultReceiver arg3){
    return false;
  }
  public void setImeWindowStatus(android.os.IBinder arg1, int arg2, int arg3){
  }
  public void systemReady(StatusBarManagerService arg1){
  }
  public void addClient(@com.francetelecom.rd.stubs.annotation.CallBackRegister("IInputMethodClient") com.android.internal.view.IInputMethodClient arg1, com.android.internal.view.IInputContext arg2, int arg3, int arg4){
  }
  public void finishInput(@com.francetelecom.rd.stubs.annotation.CallBackRegister("IInputMethodClient") com.android.internal.view.IInputMethodClient arg1){
  }
  public void removeClient(@com.francetelecom.rd.stubs.annotation.CallBackRegister("IInputMethodClient") com.android.internal.view.IInputMethodClient arg1){
  }
  public java.util.List<android.view.inputmethod.InputMethodInfo> getEnabledInputMethodList(){
    return (java.util.List) null;
  }
  @com.francetelecom.rd.stubs.annotation.Code("return java.util.Collections.singletonList(inputMethodSubtype);")
  public java.util.List<android.view.inputmethod.InputMethodSubtype> getEnabledInputMethodSubtypeList(android.view.inputmethod.InputMethodInfo arg1, boolean arg2){
    return (java.util.List) null;
  }
  public void registerSuggestionSpansForNotification(android.text.style.SuggestionSpan [] arg1){
  }
  public java.util.List<android.view.inputmethod.InputMethodInfo> getInputMethodList(){
    return (java.util.List) null;
  }
  @com.francetelecom.rd.stubs.annotation.FieldGet("inputMethodSubtype")
  public android.view.inputmethod.InputMethodSubtype getLastInputMethodSubtype(){
    return (android.view.inputmethod.InputMethodSubtype) null;
  }
  public java.util.List getShortcutInputMethodsAndSubtypes(){
    return (java.util.List) null;
  }
  public void windowGainedFocus(@com.francetelecom.rd.stubs.annotation.CallBackRegister("IInputMethodClient") com.android.internal.view.IInputMethodClient arg1, android.os.IBinder arg2, boolean arg3, boolean arg4, int arg5, boolean arg6, int arg7){
  }
  public void showInputMethodPickerFromClient(@com.francetelecom.rd.stubs.annotation.CallBackRegister("IInputMethodClient") com.android.internal.view.IInputMethodClient arg1){
  }
  public void showInputMethodAndSubtypeEnablerFromClient(@com.francetelecom.rd.stubs.annotation.CallBackRegister("IInputMethodClient") com.android.internal.view.IInputMethodClient arg1, java.lang.String arg2){
  }
  public void setInputMethod(android.os.IBinder arg1, @com.francetelecom.rd.stubs.annotation.FieldSet("inputMethod") java.lang.String arg2){
  }
  public void setInputMethodAndSubtype(android.os.IBinder arg1, @com.francetelecom.rd.stubs.annotation.FieldSet("inputMethod") java.lang.String arg2, @com.francetelecom.rd.stubs.annotation.FieldSet("inputMethodSubtype") android.view.inputmethod.InputMethodSubtype arg3){
  }
  public void hideMySoftInput(android.os.IBinder arg1, int arg2){
  }
  public void showMySoftInput(android.os.IBinder arg1, int arg2){
  }
  public void updateStatusIcon(android.os.IBinder arg1, java.lang.String arg2, int arg3){
  }
  public boolean notifySuggestionPicked(android.text.style.SuggestionSpan arg1, java.lang.String arg2, int arg3){
    return false;
  }
  @com.francetelecom.rd.stubs.annotation.FieldGet("inputMethodSubtype")
  public android.view.inputmethod.InputMethodSubtype getCurrentInputMethodSubtype(){
    return (android.view.inputmethod.InputMethodSubtype) null;
  }
  public boolean setCurrentInputMethodSubtype(@com.francetelecom.rd.stubs.annotation.FieldSet("inputMethodSubtype") android.view.inputmethod.InputMethodSubtype arg1){
    return false;
  }
  public boolean switchToLastInputMethod(android.os.IBinder arg1){
    return false;
  }
  public boolean setInputMethodEnabled(@com.francetelecom.rd.stubs.annotation.FieldSet("inputMethod") java.lang.String arg1, boolean arg2){
    return false;
  }
  @Code("inputMethodSubtype = arg2[0];")
  public void setAdditionalInputMethodSubtypes(java.lang.String arg1, android.view.inputmethod.InputMethodSubtype [] arg2){
  }
  @com.francetelecom.rd.stubs.annotation.Code("return java.util.Collections.singletonList(inputMethodSubtype);")
  public java.util.List<android.view.inputmethod.InputMethodSubtype> getEnabledInputMethodSubtypeListLocked(android.view.inputmethod.InputMethodInfo arg1, boolean arg2){
	return (java.util.List) null;
  }
}


text:
<?php

namespace Symfony\Component\Security\Core\User;

use Symfony\Component\Security\Core\Exception\AccountExpiredException;
use Symfony\Component\Security\Core\Exception\CredentialsExpiredException;
use Symfony\Component\Security\Core\Exception\DisabledException;
use Symfony\Component\Security\Core\Exception\LockedException;

/**
 * Checks the state of the in-memory user account.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class InMemoryUserChecker implements UserCheckerInterface
{
    public function checkPreAuth(UserInterface $user)
    {
        // @deprecated since Symfony 5.3, in 6.0 change to:
        // if (!$user instanceof InMemoryUser) {
        if (!$user instanceof InMemoryUser && !$user instanceof User) {
            return;
        }

        if (!$user->isEnabled()) {
            $ex = new DisabledException('User account is disabled.');
            $ex->setUser($user);
            throw $ex;
        }

        // @deprecated since Symfony 5.3
        if (User::class === \get_class($user)) {
            if (!$user->isAccountNonLocked()) {
                $ex = new LockedException('User account is locked.');
                $ex->setUser($user);
                throw $ex;
            }

            if (!$user->isAccountNonExpired()) {
                $ex = new AccountExpiredException('User account has expired.');
                $ex->setUser($user);
                throw $ex;
            }
        }
    }

    public function checkPostAuth(UserInterface $user)
    {
        // @deprecated since Symfony 5.3, noop in 6.0
        if (User::class !== \get_class($user)) {
            return;
        }

        if (!$user->isCredentialsNonExpired()) {
            $ex = new CredentialsExpiredException('User credentials have expired.');
            $ex->setUser($user);
            throw $ex;
        }
    }
}

if (!class_exists(UserChecker::class, false)) {
    class_alias(InMemoryUserChecker::class, UserChecker::class);
}


text:
package ua.com.fielden.platform.sample.domain.validators;

import java.lang.annotation.Annotation;
import java.util.Date;
import java.util.Set;

import org.joda.time.DateTime;

import com.google.inject.Inject;

import ua.com.fielden.platform.entity.AbstractEntity;
import ua.com.fielden.platform.entity.meta.MetaProperty;
import ua.com.fielden.platform.entity.validation.IBeforeChangeEventHandler;
import ua.com.fielden.platform.error.Result;

public class DateValidator implements IBeforeChangeEventHandler<Date> {

    @Inject
    public DateValidator() {
        super();
    }

    @Override
    public Result handle(final MetaProperty<Date> property, final Date newValue, final Set<Annotation> mutatorAnnotations) {
        final AbstractEntity<?> entity = property.getEntity();
        if (!entity.isPersisted()) {
            if (newValue != null && new DateTime(2003, 2, 1, 6, 19).equals(new DateTime(newValue))) {
                return Result.failure(newValue, "[1/2/3 6:19] is not acceptable.");
            }
        } else {
            if (newValue != null && new DateTime(2003, 2, 1, 6, 22).equals(new DateTime(newValue))) {
                return Result.failure(newValue, "[1/2/3 6:22] is not acceptable for persisted entity.");
            }
        }
        return Result.successful(newValue);
    }

}


text:
#pragma once

#include <string>
#include <mraa/i2c.hpp>
#include "lcd.h"
#include "ssd.h"

namespace upm
{
const uint8_t DISPLAY_CMD_SET_NORMAL_1308 = 0xA6;

/**
 * @library i2clcd
 * @sensor ssd1308
 * @comname SSD1308 OLED Display
 * @altname Grove OLED Display 0.96"
 * @type display
 * @man seeed adafruit
 * @web http://garden.seeedstudio.com/images/4/46/SSD1308_1.0.pdf
 * @web http://www.seeedstudio.com/wiki/Grove_-_OLED_Display_0.96%22
 * @con i2c
 *
 * @brief API for SSD1308 i2c controlled OLED displays
 *
 * The SSD1308 is a 128x64 Dot matrix OLED/PLED segment driver with
 * controller. This implementation was tested using the Grove LED 128×64
 * Display module which is an OLED monochrome display.
 *
 * @image html ssd1308.jpeg
 * @snippet ssd1308-oled.cxx Interesting
 */
class SSD1308 : public LCD
{
  public:
    /**
     * SSD1308 Constructor, calls libmraa initialisation functions
     *
     * @param bus i2c bus to use
     * @param address the slave address the lcd is registered on
     */
    SSD1308(int bus, int address = 0x3C);
    /**
     * SSD1308 Destructor
     */
    ~SSD1308();
    /**
     * Draw an image, see examples/python/make_oled_pic.py for an
     * explanation on how the pixels are mapped to bytes
     *
     * @param data the buffer to read
     * @param bytes the amount of bytes to read from the pointer
     * @return Result of operation
     */
    mraa_result_t draw(uint8_t* data, int bytes);
    /**
     * Write a string to LCD
     *
     * @param msg The std::string to write to display, note only ascii
     *     chars are supported
     * @return Result of operation
     */
    mraa_result_t write(std::string msg);
    /**
     * Set cursor to a coordinate
     *
     * @param row The row to set cursor to
     * @param column The column to set cursor to
     * @return Result of operation
     */
    mraa_result_t setCursor(int row, int column);
    /**
     * Clear display from characters
     *
     * @return Result of operatio
     */
    mraa_result_t clear();
    /**
     * Return to coordinate 0,0
     *
     * @return Result of operation
     */
    mraa_result_t home();

  private:
    mraa_result_t writeChar(uint8_t value);
    mraa_result_t setNormalDisplay();
    mraa_result_t setAddressingMode(displayAddressingMode mode);

    int m_lcd_control_address;
    mraa::I2c m_i2c_lcd_control;
};
}


text:
package com.gopivotal.manager;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;

import org.apache.catalina.Context;
import org.apache.catalina.Globals;
import org.apache.catalina.Manager;
import org.apache.catalina.Session;
import org.apache.catalina.session.StandardSession;

/**
 * Utilities for serializing and deserializing {@link Session}s
 */
public final class SessionSerializationUtils {

    private final Manager manager;

    /**
     * Creates a new instance
     *
     * @param manager the manager to use when recreating sessions
     */
    public SessionSerializationUtils(Manager manager) {
        this.manager = manager;
    }

    /**
     * Deserialize a {@link Session}
     *
     * @param session a {@code byte[]} representing the serialized {@link Session}
     * @return the deserialized {@link Session} or {@code null} if the session data is {@code null}
     * @throws ClassNotFoundException
     * @throws IOException
     */
    public Session deserialize(byte[] session) throws ClassNotFoundException, IOException {
        if (session == null) {
            return null;
        }

        ByteArrayInputStream bytes = null;
        ObjectInputStream in = null;
        Context context = this.manager.getContext();
        ClassLoader oldThreadContextCL = context.bind(Globals.IS_SECURITY_ENABLED, null);

        try {
            bytes = new ByteArrayInputStream(session);
            in = new ObjectInputStream(bytes) {
                @Override
                protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
                    try {
                        return Class.forName(desc.getName(), false, Thread.currentThread().getContextClassLoader());
                    } catch (ClassNotFoundException cnfe) {
                        return super.resolveClass(desc);
                    }
                }
            };

            StandardSession standardSession = (StandardSession) this.manager.createEmptySession();
            standardSession.readObjectData(in);

            return standardSession;
        } finally {
            closeQuietly(in, bytes);
            context.unbind(Globals.IS_SECURITY_ENABLED, oldThreadContextCL);
        }
    }

    /**
     * Serialize a {@link Session}
     *
     * @param session the {@link Session} to serialize
     * @return a {@code byte[]} representing the serialized {@link Session}
     * @throws IOException
     */
    public byte[] serialize(Session session) throws IOException {
        ByteArrayOutputStream bytes = null;
        ObjectOutputStream out = null;

        try {
            bytes = new ByteArrayOutputStream();
            out = new ObjectOutputStream(bytes);

            StandardSession standardSession = (StandardSession) session;
            standardSession.writeObjectData(out);

            out.flush();
            bytes.flush();

            return bytes.toByteArray();
        } finally {
            closeQuietly(out, bytes);
        }

    }

    private void closeQuietly(Closeable... closeables) {
        for (Closeable closeable : closeables) {
            try {
                closeable.close();
            } catch (Exception e) {
                // Nothing to do
            }
        }
    }
}


text:
from tests import settings
from .resources import BankAccount, BankWirePayOut
from .test_base import BaseTest

from mangopay.utils import Money, Address

import responses

class PayOutsTest(BaseTest):
    @responses.activate
    def test_create_bank_wire_payout(self):
        self.mock_legal_user()
        self.mock_user_wallet()

        self.register_mock([
            {
                'method': responses.POST,
                'url': settings.MANGOPAY_API_SANDBOX_URL+settings.MANGOPAY_CLIENT_ID+'/users/1169420/bankaccounts/IBAN',
                'body': {
                    "UserId": "1169420",
                    "Type": "IBAN",
                    "OwnerName": "MangoPay",
                    "OwnerAddress": {
                        "AddressLine1": "AddressLine1",
                        "AddressLine2": "AddressLine2",
                        "City": "City",
                        "Region": "Region",
                        "PostalCode": "11222",
                        "Country": "FR"
                    },
                    "IBAN": "FR3020041010124530725S03383",
                    "BIC": "CRLYFRPP",
                    "Id": "1169675",
                    "Tag": "custom tag",
                    "CreationDate": 1383561267
                },
                'status': 200
            },
            {
                'method': responses.POST,
                'url': settings.MANGOPAY_API_SANDBOX_URL+settings.MANGOPAY_CLIENT_ID+'/payouts/bankwire',
                'body': {
                    "Id": 30047,
                    "CreditedFunds": None,
                    "BankWireRef": "John Doe's trousers",
                    "DebitedFunds": {"Currency": "EUR", "Amount": 1000},
                    "BankAccountId": 6784645,
                    "AuthorId": 6784642,
                    "Tag": "Custom data",
                    "Fees": {"Currency": "EUR", "Amount": 100},
                    "DebitedWalletId": 6784644
                },
                'status': 200
            },
            {
                'method': responses.GET,
                'url': settings.MANGOPAY_API_SANDBOX_URL+settings.MANGOPAY_CLIENT_ID+'/payouts/30047',
                'body': {
                    "Id": 30047,
                    "Tag": "custom tag",
                    "CreationDate": 1374232891,
                    "AuthorId": "20164",
                    "CreditedUserId": None,
                    "DebitedFunds": {
                        "Currency": "EUR",
                        "Amount": 100
                    },
                    "CreditedFunds": {
                        "Currency": "EUR",
                        "Amount": "1000"
                    },
                    "Fees": {
                        "Currency": "EUR",
                        "Amount": "100"
                    },
                    "Status": "SUCCEEDED",
                    "ResultCode": "00000",
                    "ExecutionDate": 1374233532,
                    "Type": "PAY_OUT",
                    "Nature": "NORMAL",
                    "DebitedWalletId": "30025",
                    "BankAccountId": "30027",
                    "BankWireRef": "John Doe's trousers"
                },
                'status': 200
            }])

        params = {
            "owner_name": "Victor Hugo",
            "user": self.legal_user,
            "type": "IBAN",
            "owner_address": Address(address_line_1='AddressLine1', address_line_2='AddressLine2',
                                     city='City', region='Region',
                                     postal_code='11222', country='FR'),
            "iban": "FR3020041010124530725S03383",
            "bic": "CRLYFRPP",
            "tag": "custom tag"
        }
        bankaccount = BankAccount(**params)
        bankaccount.save()

        bank_wire_payout_params = {
            "tag": "Custom data",
            "author": self.legal_user,
            "debited_funds": Money(amount=1000, currency='EUR'),
            "fees": Money(amount=100, currency='EUR'),
            "debited_wallet": self.legal_user_wallet,
            "bank_account": bankaccount,
            "bank_wire_ref": "John Doe's trousers"
        }
        bank_wire_payout = BankWirePayOut(**bank_wire_payout_params)

        self.assertIsNone(bank_wire_payout.get_pk())
        bank_wire_payout.save()
        self.assertIsInstance(bank_wire_payout, BankWirePayOut)

        self.assertEqual(bank_wire_payout.debited_funds.amount, 1000)
        bank_wire_payout_params.pop('debited_funds')

        self.assertEqual(bank_wire_payout.fees.amount, 100)
        bank_wire_payout_params.pop('fees')

        for key, value in bank_wire_payout_params.items():
            self.assertEqual(getattr(bank_wire_payout, key), value)

        self.assertIsNotNone(bank_wire_payout.get_pk())

        # test_retrieve_payouts
        retrieved_payout = BankWirePayOut.get(bank_wire_payout.get_pk())

        self.assertIsNotNone(retrieved_payout.get_pk())
        self.assertIsInstance(retrieved_payout, BankWirePayOut)

        self.assertEqual(getattr(retrieved_payout, 'id'), bank_wire_payout.get_pk())


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>error_code::unspecified_bool_type_t</title>
<link rel="stylesheet" href="../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.75.2">
<link rel="home" href="../../index.html" title="Asio">
<link rel="up" href="../reference.html" title="Reference">
<link rel="prev" href="error_code/value.html" title="error_code::value">
<link rel="next" href="generic__basic_endpoint.html" title="generic::basic_endpoint">

error_code::unspecified_bool_type_t

struct unspecified_bool_type_t

        Requirements

        Header: asio/error_code.hpp

        Convenience header: asio.hpp

Copyright © 2003-2016 Christopher
      M. Kohlhoff

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Threading;
using System.Threading.Tasks;
using LanguageExt;
using SJP.Schematic.Core;
using SJP.Schematic.Core.Extensions;
using SJP.Schematic.PostgreSql.Query;

namespace SJP.Schematic.PostgreSql.Versions.V10
{
    public class PostgreSqlRelationalDatabaseTableProvider : V9_4.PostgreSqlRelationalDatabaseTableProvider
    {
        public PostgreSqlRelationalDatabaseTableProvider(IDbConnection connection, IIdentifierDefaults identifierDefaults, IIdentifierResolutionStrategy identifierResolver, IDbTypeProvider typeProvider)
            : base(connection, identifierDefaults, identifierResolver, typeProvider)
        {
        }

        protected override Task<IReadOnlyList<IDatabaseColumn>> LoadColumnsAsync(Identifier tableName, CancellationToken cancellationToken)
        {
            if (tableName == null)
                throw new ArgumentNullException(nameof(tableName));

            return LoadColumnsAsyncCore(tableName, cancellationToken);
        }

        private async Task<IReadOnlyList<IDatabaseColumn>> LoadColumnsAsyncCore(Identifier tableName, CancellationToken cancellationToken)
        {
            var query = await Connection.QueryAsync<ColumnDataWithIdentity>(
                ColumnsQuery,
                new { SchemaName = tableName.Schema, TableName = tableName.LocalName },
                cancellationToken
            ).ConfigureAwait(false);

            var result = new List<IDatabaseColumn>();

            foreach (var row in query)
            {
                var typeMetadata = new ColumnTypeMetadata
                {
                    TypeName = Identifier.CreateQualifiedIdentifier(Constants.PgCatalog, row.data_type),
                    Collation = !row.collation_name.IsNullOrWhiteSpace()
                        ? Option<Identifier>.Some(Identifier.CreateQualifiedIdentifier(row.collation_catalog, row.collation_schema, row.collation_name))
                        : Option<Identifier>.None,
                    MaxLength = row.character_maximum_length > 0
                        ? row.character_maximum_length
                        : CreatePrecisionFromBase(row.numeric_precision, row.numeric_precision_radix),
                    NumericPrecision = row.numeric_precision_radix > 0
                        ? Option<INumericPrecision>.Some(CreatePrecisionWithScaleFromBase(row.numeric_precision, row.numeric_scale, row.numeric_precision_radix))
                        : Option<INumericPrecision>.None
                };

                var columnType = TypeProvider.CreateColumnType(typeMetadata);
                var columnName = Identifier.CreateQualifiedIdentifier(row.column_name);

                var isAutoIncrement = row.is_identity == Constants.Yes;
                var autoIncrement = isAutoIncrement
                    && decimal.TryParse(row.identity_start, out var seqStart)
                    && decimal.TryParse(row.identity_increment, out var seqIncr)
                    ? Option<IAutoIncrement>.Some(new AutoIncrement(seqStart, seqIncr))
                    : Option<IAutoIncrement>.None;

                var isSerialAutoIncrement = !isAutoIncrement && !row.serial_sequence_schema_name.IsNullOrWhiteSpace() && !row.serial_sequence_local_name.IsNullOrWhiteSpace();
                if (isSerialAutoIncrement)
                    autoIncrement = Option<IAutoIncrement>.Some(new AutoIncrement(1, 1));

                var defaultValue = !row.column_default.IsNullOrWhiteSpace()
                    ? Option<string>.Some(row.column_default)
                    : Option<string>.None;
                var isNullable = row.is_nullable == Constants.Yes;

                var column = new DatabaseColumn(columnName, columnType, isNullable, defaultValue, autoIncrement);
                result.Add(column);
            }

            return result;
        }

        protected override string ColumnsQuery => ColumnsQuerySql;

        // a little bit convoluted due to the quote_ident() being required.
        // when missing, case folding will occur (we should have guaranteed that this is already done)
        // additionally the default behaviour misses the schema which may be necessary
        private const string ColumnsQuerySql = @"
select
    column_name,
    ordinal_position,
    column_default,
    is_nullable,
    data_type,
    character_maximum_length,
    character_octet_length,
    numeric_precision,
    numeric_precision_radix,
    numeric_scale,
    datetime_precision,
    interval_type,
    collation_catalog,
    collation_schema,
    collation_name,
    domain_catalog,
    domain_schema,
    domain_name,
    udt_catalog,
    udt_schema,
    udt_name,
    dtd_identifier,
    (pg_catalog.parse_ident(pg_catalog.pg_get_serial_sequence(quote_ident(table_schema) || '.' || quote_ident(table_name), column_name)))[1] as serial_sequence_schema_name,
    (pg_catalog.parse_ident(pg_catalog.pg_get_serial_sequence(quote_ident(table_schema) || '.' || quote_ident(table_name), column_name)))[2] as serial_sequence_local_name,
    is_identity,
    identity_generation,
    identity_start,
    identity_increment,
    identity_maximum,
    identity_minimum,
    identity_cycle
from information_schema.columns
where table_schema = @SchemaName and table_name = @TableName
order by ordinal_position";
    }
}


text:
<?php

namespace Common\Mapper;

use Zend\EventManager\EventManagerAwareInterface,
	Common\EventManager\EventsProviderTrait,
	Common\Mapper\Exception\NoEntityException,
	Doctrine\ORM\EntityManager;

abstract class AbstractMapper implements EventManagerAwareInterface {

	use EventsProviderTrait;

	protected $entityClass;
	protected $entityManager;
	protected $eventManager;

	public function __construct(EntityManager $entityManager) {
		if (!$this->entityClass) {
			throw new NoEntityException('You must set an entity class');
		}
		$this->entityManager = $entityManager;
	}

	public function setEntityManager(EntityManager $entityManager) {
		$this->entityManager = $entityManager;
		return $this;
	}

	public function getEntityManager() {
		return $this->entityManager;
	}

	public function getEntityClass() {
		return $this->entityClass;
	}

	public function setEntityClass($entityClass) {
		$this->entityClass = $entityClass;
		return $this;
	}

	protected function getRepository() {
		return $this->getEntityManager()->getRepository($this->entityClass);
	}

	public function fetchOne($id) {
		return $this->getRepository()->find($id);
	}

	public function fetchAll() {
		return $this->getRepository()->fetchAll();
	}

	public function fetchBy(array $criteria) {
		return $this->getRepository()->findBy($criteria);
	}

	public function persist($entity) {
		$manager = $this->getEntityManager();
		$manager->persist($entity);
		$manager->flush();
		return $entity;
	}

}


text:
package som.interpreter;

import com.oracle.truffle.api.nodes.ControlFlowException;

import som.vmobjects.SAbstractObject;

public final class SomException extends ControlFlowException {

  private static final long     serialVersionUID = -639789248178270606L;
  private final SAbstractObject somObj;

  public SomException(final SAbstractObject somObj) {
    this.somObj = somObj;
  }

  public SAbstractObject getSomObject() {
    return somObj;
  }

  @Override
  public String toString() {
    return "SomException[" + somObj.toString() + "]";
  }
}


text:
Learning-ajax
=============

Simple examples with Ajax


text:
package au.com.centrumsystems.hudson.plugin.buildpipeline.testsupport;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

import java.net.URL;
import java.net.URLEncoder;

import static au.com.centrumsystems.hudson.plugin.buildpipeline.testsupport.TestUtils.waitForElement;

public class LoginLogoutPage implements Page {

    private final URL baseUrl;
    private final WebDriver driver;

    public LoginLogoutPage(WebDriver driver, URL baseUrl) {
        this.driver = driver;
        this.baseUrl = baseUrl;
    }

    public <T extends Page> void login(String username) {
        driver.get(baseUrl + "login");

        usernameField().sendKeys(username);
        passwordField().sendKeys(username);
        passwordField().submit();
    }

    private WebElement usernameField() {
        return waitForElement(By.name("j_username"), driver);
    }

    private WebElement passwordField() {
        return waitForElement(By.name("j_password"), driver);
    }

    public void logout() {
        driver.get(baseUrl + "logout");
    }

    public String getRelativeUrl() {
        return "login";
    }

    public <T extends Page> String getUrl(T nextPage) {
        return baseUrl + "login?from=" + encodeSafely(nextPage.getRelativeUrl());
    }

    private String encodeSafely(String s) {
        try {
            return URLEncoder.encode(s, "utf-8");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}


text:
typedef void(^uploadResultBlock)(NSDictionary *dic);

@class THRead;
@class THReadProgress;

@interface THReadList : NSObject

+(NSArray<THRead*> *)books;

+(BOOL)AddData:(THRead*)read;
+(BOOL)DelDataWithID:(NSString*)rID;
+(BOOL)DelData:(THRead *)read;
+(BOOL)EditPage:(NSUInteger)page Read:(THRead*)read;
+(void)storageData;
+(BOOL)DelReadProgressDataForLast:(THRead*)read;
+(void)SortBooksAsReadProgress;
-(void)UploadDataWithHost:(NSString*)host resultBlock:(uploadResultBlock)block;

+(NSUInteger)lastDayProgressForReadID:(NSString*)rID;
+(NSUInteger)lastPageProgressForReadID:(NSString*)rID;
+(NSArray<THReadProgress*>*)getReadProgressFromReadID:(NSString*)rID;
@end


text:
namespace net {

class BoundNetLog;
class DnsResponse;
class DnsSession;

// DnsTransaction implements a stub DNS resolver as defined in RFC 1034.
// The DnsTransaction takes care of retransmissions, name server fallback (or
// round-robin), suffix search, and simple response validation ("does it match
// the query") to fight poisoning.
//
// Destroying DnsTransaction cancels the underlying network effort.
class NET_EXPORT_PRIVATE DnsTransaction {
 public:
  virtual ~DnsTransaction() {}

  // Returns the original |hostname|.
  virtual const std::string& GetHostname() const = 0;

  // Returns the |qtype|.
  virtual uint16_t GetType() const = 0;

  // Starts the transaction.  Always completes asynchronously.
  virtual void Start() = 0;
};

// Creates DnsTransaction which performs asynchronous DNS search.
// It does NOT perform caching, aggregation or prioritization of transactions.
//
// Destroying the factory does NOT affect any already created DnsTransactions.
class NET_EXPORT_PRIVATE DnsTransactionFactory {
 public:
  // Called with the response or NULL if no matching response was received.
  // Note that the |GetDottedName()| of the response may be different than the
  // original |hostname| as a result of suffix search.
  typedef base::Callback<void(DnsTransaction* transaction,
                              int neterror,
                              const DnsResponse* response)> CallbackType;

  virtual ~DnsTransactionFactory() {}

  // Creates DnsTransaction for the given |hostname| and |qtype| (assuming
  // QCLASS is IN). |hostname| should be in the dotted form. A dot at the end
  // implies the domain name is fully-qualified and will be exempt from suffix
  // search. |hostname| should not be an IP literal.
  //
  // The transaction will run |callback| upon asynchronous completion.
  // The |net_log| is used as the parent log.
  virtual scoped_ptr<DnsTransaction> CreateTransaction(
      const std::string& hostname,
      uint16_t qtype,
      const CallbackType& callback,
      const BoundNetLog& net_log) WARN_UNUSED_RESULT = 0;

  // Creates a DnsTransactionFactory which creates DnsTransactionImpl using the
  // |session|.
  static scoped_ptr<DnsTransactionFactory> CreateFactory(
      DnsSession* session) WARN_UNUSED_RESULT;
};

}  // namespace net

#endif  // NET_DNS_DNS_TRANSACTION_H_


text:
/**
 * THIS FILE IS AUTO-GENERATED
 * DON'T MAKE CHANGES HERE
 */
import { typedDependencies } from './dependenciesTyped.generated'
import { createSplitUnit } from '../../factoriesAny.js'

export const splitUnitDependencies = {
  typedDependencies,
  createSplitUnit
}


text:
<?
/*
abstract class dbDriver {
	abstract function getField($id);
	abstract function getNumFields();
	abstract function gettingRows();
	abstract function getFieldCount();
	abstract function getFieldTable($id);
	abstract function getLastInsert();

	abstract function query($sql);
	abstract function getErrors();
	abstract function escape($value);
}
*/

class Query extends App {

	private $_mode = 'select';
	private $_whereData = array();
	private $_selectData;
	private $_joinData;
	private $_setData;
	private $_joins;
	private $_joinOns;
	static public $_fromValue;
	static public $_fromLimit;

	private $_whereValue;
	private $_limit;
	private $_orderBy;
	private $_groupBy;
	private $_updateValue;
	private	$_insert;
	private $_selectFunction;

	static protected $_driver;
	static $last = '';

	public function __construct() {
		$this->helper('misc');
		self::$_driver = $this->lib('databases/Databases')->getCurrentDb();
	}

	function insert($values) {
		$this->_insert = $values;
		//D::show($this->_insert, 'Incert');
		return $this;
	}

	function into($tableName) {
		$this->_mode='insert';
		return $this->from($tableName);
	}

	public function reset() {
		$this->_mode = 'select';
		//@todo turn the following properties into one array.
		self::$_fromValue = null;
		$this->_whereData = array();
		$this->_selectData = null;
		$this->_joinData = null;
		$this->_setData = null;
		$this->_joins = null;
		$this->_joinOns = null;
		$this->_whereValue = null;
		$this->_limit = null;
		$this->_orderBy = null;
		$this->_groupBy = null;
		$this->_updateValue = null;
		$this->_insert = null;
		$this->_selectFunction = null;
		self::$_fromLimit = null;
		return $this;
	}

	public function select($cols='*') {
		if(is_string($cols)) {
			$this->_selectData = func_get_args();
		} else {
			$this->_selectData = (array)$cols;
		}
		return $this;
	}

	function from($val, $limit=null) {
		if(is_array($val)) {
			Query::$_fromValue = f_keyMap(
				function($v, $k) {
					if(is_string($k)) {
						return $v . ' AS ' . $k;
					}
					return $v;
				},
				$val
			);
		} else {
			Query::$_fromValue = $val;
		}
		if(isset($limit)) {
			Query::$_fromLimit = array_map('intval', (array)$limit);
		}
		return $this;
	}
	public function where() {
		$this->_whereValue = func_get_args();
//		D::log($this->_whereValue, 'where val');
		return $this;
	}

	public function update($value) {
		$this->_mode = 'update';
		Query::$_fromValue = f_flatten(func_get_args());
		return $this;
	}
	function delete() {
		$this->_mode = 'delete';
		return $this;
	}

	function set($value) {
		$this->_setValue = $value;
		return $this;

	}

	function count() {
		$this->_selectFunction = 'COUNT';
		return $this;
	}

	function join($values) {
//		D::log($values, 'Join Values');
		if(!array_key_exists(0, $values)) {
			$values = array($values);
		}
		$this->_joins = $values;
		return $this;
	}

	public function orderBy($value=null) {
		$this->_orderBy = $value;
		return $this;
	}

	public function groupBy($value=null) {
		$this->_groupBy = $value;
		return $this;
	}

	public function limit() {
		$this->_limit = array_filter(f_flatten(func_get_args()));
		//D::log($this->_limit, 'limit');
		//D::log(array_filter($this->_limit), 'limit filtered');
		if(empty($this->_limit)) {
			$this->_limit = null;
		}
		return $this;
	}

	function _buildSelect() {
		if(isset($this->_selectFunction)) {
			return $this->_selectFunction .'(*)';
		}

		//'total' => array('COUNT' => 'ft_style.feature_value'),
				//COUNT(`ft_style.feature_value`) AS 'total',

			//array('COUNT' => 'ft_style.feature_value')
/*
		'total_count' => array('COUNT' => 'ft_style.feature_value'),
		array('COUNT' => 'ft_style.feature_value')
		'total' => 'va_items.item_id',
		'color_finish' => 'ft_color_finish.feature_value',
		'regularField',
		'style' => 'ft_style.feature_value',
*/

		return join(', ', f_keyMap(
			function($v, $k) {
 				if(is_array($v)) {
					$v = join(', ', f_keyMap(
						function($vV, $vK) {
							return Query::escape($vK) . '(' . join(',', array_map('Query::escape', (array) $vV)) . ')';
						},
						$v
					));
				} else {
					$v = Query::escape($v);
				}
				if(is_string($k)) {
					return $v . ' AS ' . Query::escape($k, '\'');
				} else {
					return $v;
				}
				/*
				//old:
				if(is_string($k)) {
					if(is_array($v)) {
						return Query::escape($k) . '(' . join(',', array_map('Query::escape', $v)) . ')';
					}
					return Query::escape($k) . ' AS \'' . Query::escape($v) . '\'';
				}
				return $v;
				*/
			},
			$this->_selectData
		));
	}
/*
Array (
    [slug] => articles
    [0] => Array (
        [children.published_on] => 1251788400
        [0] => >
    )
    [1] => Array (
        [children.published_on] => 1254380400
        [0] => <
    )
)

WHERE (
	(
		(
			children.published_on < 1254380400
		)
		AND articles.slug < 'articles'
		AND articles.id < 1254380400
	)
)
*/
	static function _buildWhere($group, $groupOperator='AND', $escape=true) {
		//"Bitch I'll pick the world up and I'ma drop it on your f*ckin' head" - Lil Wayne.
		$keys = array_keys($group);
		if(is_int(f_last($keys)) && is_string(f_last($group))) {
			$operator = f_last($group);
			$group = f_chop($group);
		} else {
			$operator = '=';
		}
		if(is_int(f_first($keys)) && is_string(f_first($group))) {
			$groupOperator = f_first($group);
			$group = f_rest($group);
		}
		$builtArray = f_keyMap(
			function($value, $key) use($groupOperator, $operator, $escape) {
				if(is_int($key) && is_array($value)) {
					$bWhere = Query::_buildWhere($value, $groupOperator, $escape);
					if(!empty($bWhere)) {
						return '(' . "\n\t" . $bWhere . "\n" .')';
					} else {
						return null;
					}
				}
				if(is_string($key)) {
					static $escapeFunc = array('Query' , 'nullEscape');
					if(!$escape) {
						$escapeFunc = 'nothing';
					} else {
						$escapeFunc = f_callable($escapeFunc);
					}
					if(is_array($value)) {
						$key = $escapeFunc($key, '');
						if(f_first(array_keys($value)) !== 0) {
							return join(' ' . $groupOperator . ' ', f_keyMap(function($v, $k) use($key, $escapeFunc) {
								return $key . ' BETWEEN ' . $escapeFunc($k) . ' AND ' . $escapeFunc($v);
							}, $value));
						}
						return $key . ' IN (' . join(', ', array_map($escapeFunc, $value)) . ')';
					} else {
						$value = call_user_func($escapeFunc, $value);
						if($value === 'null') {
							if($operator == '=') {
								$operator = 'IS';
							} else {
								$operator = 'IS NOT';
							}
						}
						return Query::escape($key) . ' ' . $operator . ' ' . $value;
					}
				}
			},
			$group
		);
		if(!empty($builtArray)) {
			return join(' ' . $groupOperator . ' ', array_filter($builtArray));
		}
	}

	function _buildOrderBy() {
		if(!empty($this->_orderBy)) {
			return "\n" . ' ORDER BY ' . join(' , ', f_keyMap(
				function($v, $k) {
					return Query::escape($k) . ' ' . Query::escape($v);
				},
				$this->_orderBy
			));
		}
	}

	function _buildGroupBy() {
		if(!empty($this->_groupBy)) {
			return "\n" . ' GROUP BY ' . join(' , ', array_map('Query::escape', $this->_groupBy));
		}
	}

	function _buildJoins() {
	 	if(!empty($this->_joins)) {
		 	return "\n" . join(' ', f_map(
		 		function($join) {
		 	 	 	return join(' ', f_keyMap(
						function($joinSets, $jTable) {
							//$jTableName = f_last(explode(' ', $jTable));
							return "\n" . ' LEFT JOIN ' . $jTable . "\n\t" . 'ON ' . Query::_buildWhere($joinSets, 'AND', false);
						},
						$join
					));
				},
				$this->_joins
			));
	 	}
	}

	function _buildLimit($limit=null) {
		//D::show($limit );
		if(!empty($limit)) {
			return "\n" . ' LIMIT ' . join(', ', array_reverse($limit));
		}
	}

	function _buildSet($values, $separator='=') {
		return join(
			', ',
			f_keyMap(
				function($v, $k) use ($separator) {
					return Query::escape($k) . ' ' . $separator . Query::nullEscape($v);
				},
				$values
			)
		);
	}

	function _buildWhereString($values) {
		if(empty($values)) {
			return '';
		}
		$whereContent = $this->_buildWhere($values);
		if(!empty($whereContent)) {
//			D::log($whereContent, 'where content');
			return "\n" . ' WHERE ' . $whereContent;
		}
	}

	function _build() {
		//puts all the stuff together in a magic happy fashion.
		$sqlString = '';
		switch ($this->_mode) {
			case 'select':
				//adds in our select values
				//@todo Make the second parameter in `form()` actaully be a real "sub query"
					//$this->
				if(isset(self::$_fromLimit)) {
					self::$_fromValue = '(SELECT * FROM ' . Query::$_fromValue . $this->_buildLimit(Query::$_fromLimit) . ') AS ' . Query::$_fromValue;
				}

				$sqlString = 'SELECT ' . $this->_buildSelect() . "\n" . ' FROM ' . join(', ', (array)Query::$_fromValue) . $this->_buildJoins() .  $this->_buildWhereString($this->_whereValue) . $this->_buildGroupBy() . $this->_buildOrderBy() . $this->_buildLimit($this->_limit);
				break;
			case 'update':
				$sqlString = 'UPDATE ' . f_first(Query::$_fromValue) . "\n" . ' SET ' . $this->_buildSet($this->_setValue) . $this->_buildWhereString($this->_whereValue);
				break;
			case 'insert':
				/*
				f_reduce(
					function($a, $b) {
						return array_merge(array_keys((array)$b), array_keys((array)$a));
					},
					$this->_insert
				);
				*/
				if(!is_array(f_first($this->_insert) )) {
					$this->_insert = array($this->_insert);
				};
				$cols = array_map(function($v) { return Query::nullEscape($v, '`');}, array_keys(array_reduce($this->_insert, 'array_merge_recursive', array())));

				$sqlString = 'INSERT INTO ' . f_first((array) Query::$_fromValue) . ' (' . join(', ', $cols) . ') VALUES ' . join(', ', f_map(
					function($v) use($cols) {
						return '(' . join(',', f_map(
							function ($i) use ($v) {
								$i = substr($i, 1, -1);
								if(isset($v[$i])) {
									return Query::nullEscape($v[$i]);
								} else {
									return 'null';
								}
							},
							$cols
						)) . ')';
					},
					D::log($this->_insert, 'Insert Data')
				));
				break;
			case 'delete':
				$sqlString = 'DELETE FROM ' . join(', ', (array)Query::$_fromValue) . $this->_buildWhereString($this->_whereValue);
				break;
		}
		$this->sql = $sqlString;
		return $this->sql;
	}

	public function go($query=null) {

		if(!isset($query)) {
			self::$last = $this->_build();
		} else {
			self::$last = $query;
		}
		$this->reset();
		if(!self::$_driver->query(self::$last)) {
			D::warn('Query Failed: ' . self::$last);
			return false;
		}

		return $this;
	}

	public function results($type='object', $query=null) {
		if(!isset($query)) {
			self::$last = $this->_build();
		} else {
			self::$last = $query;
		}
		$this->reset();
		return self::$_driver->query(self::$last, $type);
	}

	public function getDriver() {
		return self::$_driver;
	}

	public function getLastInsert() {
		return self::$_driver->lastInsert();
	}

	public static function nullEscape($var, $sep="'") {
		if(!isset($var)) {
			return 'null';
		}
		if(is_bool($var) || is_int($var)) {
			return intval($var);
		}
        if(is_float($var)) {
            return floatval($var);
        }
		return self::escape($var, $sep);
	}

	public static function escape($var, $sep='') {
		//Databases::f('query', array($sql, $type));
		//@todo change this.
		if(is_bool($var) || is_int($var)) {
			return intval($var);
		}
        if(is_float($var)) {
            return floatval($var);
        }
		return $sep . mysql_escape_string($var)  . $sep;
	}

	/*
	###`select()`

	`$this->select('*')`
	:	SELECT *

	`$this->select('colName', 'otherCol')`
	:	SELECT colName, otherCol

	`$this->select(array('colName', 'otherCol'))`
	:	SELECT colName, otherCol

	###`where()`

	`$this->select('*')->where(array('item' => 5))->from('table')`
	:	SELECT * FROM table WHERE item = '5'

	`$this->select('*')->where(array('item' => 5, 'thing' => 'what'))->from('table')`
	:	SELECT * FROM table WHERE item = '5' AND thing = 'what'

	`$this->select('*')->where(array(
		'OR',
		'item' => 5,
		'thing' => 'what'
	))->from('table')`
	:	SELECT * FROM table WHERE item = '5' OR thing = 'what'

	`$this->select('*')->where(array('item' => 5, 'thing' => 'what', '!='))->from('table')`
	:	SELECT * FROM table WHERE item != '5' OR thing != 'what'

	`$this->select('*')->where(array('item' => array('what', 'who'))->from('table')`
	:	SELECT * FROM table WHERE item IN ('what', 'who')

	`$this->select('*')->where(array('item' => array(10 => 30))->from('table')`
	:	SELECT * FROM table WHERE item BETWEEN (10 AND 30)

	###`join()`

	`$this->select('*')->from('Club_RnD.dbo.Posts')->join('Club_RnD.dbo.Comments', array('Club_RnD.dbo.Posts.comments' => 'Club_RnD.dbo.Comments.id'))`
	:	SELECT * FROM Club_RnD.dbo.Posts LEFT JOIN Club_RnD.dbo.Comments ON Club_RnD.dbo.Posts.comments = Club_RnD.dbo.Comments.id

	###`delete()`

	`$this->delete()->from('tableName')`
	:	DELETE FROM tableName

	###`set()`

	`$this->set(array('key' => 'value')`
	:	SET key = 'value'
	*/
}


text:
require File.expand_path("../spec_helper", __FILE__)

describe Ambry::Adapter do

  before { Ambry.adapters.clear }
  after  { Ambry.adapters.clear }

  describe "#initialize" do

    it "should register itself" do
      Ambry::Adapter.new :name => :an_adapter
      assert_equal :an_adapter,  Ambry.adapters.keys.first
    end

    it "should use a default name if none given" do
      assert_equal Ambry.default_adapter_name, Ambry::Adapter.new.name
    end

    it "should raise error if a duplicate name is used" do
      assert_raises Ambry::AmbryError do
        2.times {Ambry::Adapter.new(:name => :test_adapter)}
      end
    end

    it "should set an empty hash as the db" do
      assert_equal Hash.new, Ambry::Adapter.new.db
    end
  end

  describe "#db_for" do

    before { load_fixtures }

    it "should return a instance of Hash" do
      adapter = Ambry.adapters[:main]
      assert_kind_of Hash, adapter.db_for(Person)
    end
  end

  describe "stubbed io operations" do
    it "should return true" do
      adapter = Ambry::Adapter.new
      [:export_data, :import_data, :save_database].each do |method|
        assert adapter.send method
      end
    end
  end
end


text:
var codeEditor = {

    requestedEditors: new Array(),

    loadedEditors: new Array(),

    loadEditor: function(divId, mode) {

        var editor = new ace.edit(divId);

        editor.setShowPrintMargin(false);
        editor.setTheme("ace/theme/twilight");
        editor.setReadOnly(true);

        var editorSession = editor.getSession();

        editorSession.setUseWrapMode(true);
        editorSession.setMode(mode);

        editorSession.on('change', function(){
            codeEditor.resizeEditor(editor);
        });

        this.resizeEditor(editor);

        this.loadedEditors[divId] = editor;

    },

    resizeEditor: function(editor) {

        var size = editor.getSession().getValue().split("\n").length * 20 + 15;

        $("#"+editor.container.id).height(size);
        $("#"+editor.container.id+"-placeholder").height(size);

        editor.resize();
    },

    wakeEditor: function(event) {
        var $btn, editorId, editor, data, html;

        event.preventDefault();

        codeEditor.sleepAllEditors();

        $btn     = $(event.currentTarget);
        editorId = $btn.attr('rel');
        editor   = codeEditor.loadedEditors[editorId];
        data     = { nodeId: editorId+'-form', formAction: $btn.attr('href') };

        //get template
        html = $.tmpl( "editCodeForm", data );

        //append form
        $('#'+editorId+'-placeholder').after(html);

        //Populate and hide code field
        $('#ftc_bundle_codebundle_contributetype_code').parents(".control-group:first").hide();
        $('#ftc_bundle_codebundle_contributetype_code').val( editor.getSession().getValue() );
        $('.btn-reset').on('click', codeEditor.sleepAllEditors);

        editor.setReadOnly(false);
        editor.getSession().on('change', function(x){
            $('#ftc_bundle_codebundle_contributetype_code').val( editor.getSession().getValue() );
        });

        editor.focus();
    },

    sleepAllEditors: function() {
        $('.code-comment-form-row').remove();
    },

    sleepEditor: function(event) {

    },

    loadPageEditors: function() {
        $.each(this.requestedEditors, function(index, editorDiv) {
            codeEditor.loadEditor(editorDiv.id, editorDiv.mode)
        })
    }
};


text:
package org.kie.remote.services.jaxb;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;

import org.codehaus.jackson.annotate.JsonAutoDetect;
import org.codehaus.jackson.annotate.JsonTypeInfo;
import org.codehaus.jackson.annotate.JsonTypeInfo.Id;
import org.jbpm.services.task.impl.model.xml.JaxbComment;
import org.kie.api.command.Command;
import org.kie.api.task.model.Comment;
import org.kie.services.client.serialization.jaxb.impl.AbstractJaxbCommandResponse;
import org.kie.services.client.serialization.jaxb.impl.JaxbPaginatedList;

@XmlRootElement(name="task-comment-list-response")
@XmlAccessorType(XmlAccessType.FIELD)
@JsonAutoDetect(getterVisibility=JsonAutoDetect.Visibility.NONE, fieldVisibility=JsonAutoDetect.Visibility.ANY)
public class JaxbTaskCommentListResponse extends AbstractJaxbCommandResponse<List<Comment>> implements JaxbPaginatedList<Comment> {

    @XmlElements({
        @XmlElement(name="task-comment",type=JaxbComment.class)
    })
    @JsonTypeInfo(defaultImpl=JaxbComment.class, use=Id.CLASS)
    private List<Comment> commentList;

    @XmlElement(name="page-number")
    @XmlSchemaType(name="int")
    private Integer pageNumber;

    @XmlElement(name="page-size")
    @XmlSchemaType(name="int")
    private Integer pageSize;

    public JaxbTaskCommentListResponse() {
        this.commentList = new ArrayList<Comment>();
    }

    public JaxbTaskCommentListResponse(Collection<Comment> commentCollection) {
       this.commentList = convertToJaxbComment(commentCollection);
    }

    public JaxbTaskCommentListResponse(List<Comment> commentCollection, int i, Command<?> cmd ) {
        super(i, cmd);
       this.commentList = convertToJaxbComment(commentCollection);
    }

    private List<Comment> convertToJaxbComment(Collection<Comment> list) {
        if( list == null || list.isEmpty() ) {
            return new ArrayList<Comment>();
        }
        List<Comment> newList = new ArrayList<Comment>(list.size());
        Iterator<Comment> iter = list.iterator();
        while(iter.hasNext()) {
            Comment comment = iter.next();
            if( comment instanceof JaxbComment ) {
                newList.add(comment);
            } else {
                newList.add(new JaxbComment(comment));
            }
        }
        return newList;
    }

    @Override
    public List<Comment> getResult() {
        return commentList;
    }

    @Override
    public void setResult(List<Comment> result) {
        this.commentList = convertToJaxbComment(result);
    }

    @Override
    public void addContents(List<Comment> contentList) {
        this.commentList = convertToJaxbComment(contentList);
    }

    @JsonTypeInfo(defaultImpl=JaxbComment.class, use=Id.CLASS)
    public List<Comment> getList() {
        return commentList;
    }

    @JsonTypeInfo(defaultImpl=JaxbComment.class, use=Id.CLASS)
    public void setList(List<Comment> result) {
        this.commentList = result;
    }

    @Override
    public Integer getPageNumber() {
        return this.pageNumber;
    }

    @Override
    public void setPageNumber(Integer page) {
        this.pageNumber = page;
    }

    @Override
    public Integer getPageSize() {
        return this.pageSize;
    }

    @Override
    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

}


text:
using System;
using Microsoft.Xna.Framework;

namespace Warcraft.Util
{
    abstract class Base
    {
		public Animation animations;

		public Vector2 position;
		public Vector2 Position
		{
            get; set;
		}

		public Information information;
		public static Information Information;

		public Base()
        {
	    }
    }
}