text:
<!DOCTYPE html>

    <title>ng-curtain</title>

    <meta property="og:title" content="ngCurtain" />
    <meta property="og:type" content="website" />
    <meta property="og:url" content="http://bit.ly/ngCurtain" />
    <meta property="og:image" content="https://a248.e.akamai.net/assets.github.com/images/modules/logos_page/Octocat.png?1366128846" />
    <meta name="og:description" content="A set of pure AngularJS directives to create a wicked-cool 'rising curtain' effect to unroll the sections of your website. Trust me. It's epic.">

    <meta name="twitter:card" content="summary">
    <meta name="twitter:site" content="@joshdmiller">
    <meta name="twitter:creator" content="@joshdmiller">
    <meta name="twitter:title" content="ngCurtain">
    <meta name="twitter:image" content="https://a248.e.akamai.net/assets.github.com/images/modules/logos_page/Octocat.png?1366128846">
    <meta name="twitter:description" content="A set of pure AngularJS directives to create a wicked-cool 'rising curtain' effect to unroll the sections of your website. Trust me. It's epic.">

    <link rel="stylesheet" type="text/css" href="<%= grunt.config.get('pkg.name') %>-demo.css"/>

ngCurtain

                  <fb:like href="http://bit.ly/ngCurtain" send="true" layout="button_count" width="90" show_faces="true"></fb:like>

              A set of pure AngularJS directives to create a wicked-cool "rising
              curtain" effect to unroll the sections of your website.

              Trust me. It's epic.

What is it?

                      In a word: victory.

                      ngCurtain is a set of directives for AngularJS applications to
                      create the "rising curtain" scrolling effect you see on
                      this page.

                      This project is based, in part, on the no-longer-maintained
                      curtain.js
                      for jQuery, but contains some improvements that AngularJS
                      makes easy. Not all features have yet been ported. For an
                      up-to-date list, check out Issue
                      #1 on GitHub.

                      Bower installation instructions are in the next section,
                      but if you want the source code, visit the GitHub
                      project page.

                      This is alpha quality software and contributions are
                      welcomed. Please feel free to contact me, file an issue,
                      or send a pull request (well, aren't you thoughtful?).

Usage

1. Install It

                      ngCurtain is available through
                      Bower, so this is by far the easiest way to obtain
                      it. Just run:

$ bower install --save-dev ng-curtain

                      This will download the latest version of ngCurtain and
                      install it into your Bower directory (defaults to
                      components). Boom!

2. Incorporate It

                      Now you have to add the script file to your application.
                      You can, of course, just add a script tag.
                      If you're using ngBoilerplate
                      or any of its derivatives, simply add it to the
                      vendor.js array of your
                      Gruntfile.js:

vendor: {
  js: [
    // ...
    'vendor/ng-curtain/ng-curtain.min.js',
    // ...
  ]
},

                      However you get it there, as soon as it's in your build
                      path, you need to tell your app module to depend on it:

angular.module( 'myApp', [ 'ngCurtain', /* other deps */ ] );

                      Also be sure to include the stylesheet. In ngBoilerplate,
                      simply import ng-curtain.less into your
                      main.less file.

                      Now you're ready to go! Sweet.

3. Use It

                      The markup for ngCurtain is fairly straightforward. There
                      are two directives: ctnCurtains and
                      ctnCurtain. The former is the main directive
                      and wraps all content, accepting within it as many of the
                      latter as necessary, each representing a separate curtain
                      whose position to manage. Both can be used either as
                      elements or as attributes.

                      For example, the typical structure of ngCurtain therefore
                      looks something like this:

<ctn-curtains>

</ctn-curtains>

                      Check out
                      this demo's source code for a more detailed example.

How it Works

                      If you're just interesting in using ngCurtain, you
                      can ignore this section completely. But for those
                      curious, this section contains an overview of how the
                      code works.

                      The outer directive (ctnCurtains) contains the
                      vast majority of the logic as methods on its scope. The
                      inner directives (ctnCurtain) require the
                      outer directive and call a method during their linking
                      phase to register their presence.

                      After initialization of all the children, ctnCurtains
                      calculates the positions of all the individual
                      ctnCurtain elements that registered
                      themselves, calculates the total window height, and
                      determines which curtains to start where based on the
                      current value of $location.path(). This same
                      process is repeated every time the window is resized.

                      Technically, all cards start positioned at
                      0,0 and the window's height is manually
                      calculated and applied as the sum of the heights of the
                      individual curtains.

                      When the browser window scrolls, the
                      ctnCurtains directive determines whether we
                      are scrolling within a curtain, beyond a curtain, or
                      above a curtain and arranges the positions and stacks
                      appropriately and applies translateY
                      operations to change the current vertical position of the
                      curtain relative to the current (virtual) scroll
                      position. That probably sounds confusing, but if you look
                      at the code, it's pretty straightforward.

ngCurtain API

Attribute: ctnCover

                      While all curtains have a minimum height of the
                      window height, it is not always desirable to allow some
                      curtains to extend beyond the window height. For example,
                      covers (like the first curtain here) make sense to not
                      overflow the window as they are an "intro" whose display
                      we want to control responsively. Setting the
                      ctnCover attribute on a curtain to
                      true will ensure the curtain does not exceed
                      the current window height.

                      ctnCover takes an expression, but that
                      expression is never re-evaluated as it does not make
                      sense to convert something that once was a cover into no
                      longer a cover, and vice versa. The simplest use case is
                      just the value true:

Class: current

                      Whichever ctnCurtain is currently active is
                      given the class current (this can be
                      configured in the template).

                      No styles are by default associated with this class.

Class: hidden

                      When a ctnCurtain is not visible - either as
                      the current curtain or the following or preceding
                      curtain, if visible - it is assigned the
                      hidden class (this can be configured in the
                      template).

                      By default, this simply sets display: none
                      on the curtain.

ngCurtain

              Created by Josh David Miller


text:
#include <pthread.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include "posixtest.h"

static void *a_thread_func()
{

    pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);

    /* If the thread wasn't canceled in 10 seconds, time out */
    sleep(10);

    perror("Thread couldn't be canceled (at cleanup time), timing out\n");
    pthread_exit(0);
    return NULL;
}

static int posix_testcase(void)
{
    pthread_attr_t new_attr;
    pthread_t new_th;
    int ret;

    /* Initialize attribute */
    if (pthread_attr_init(&new_attr) != 0) {
        perror("Cannot initialize attribute object\n");
        return PTS_UNRESOLVED;
    }

    /* Set the attribute object to be joinable */
    if (pthread_attr_setdetachstate(&new_attr, PTHREAD_CREATE_JOINABLE) !=
        0) {
        perror("Error in pthread_attr_setdetachstate()\n");
        return PTS_UNRESOLVED;
    }

    /* Create the thread */
    if (pthread_create(&new_th, &new_attr, a_thread_func, NULL) != 0) {
        perror("Error creating thread\n");
        return PTS_UNRESOLVED;
    }

    /* Detach the thread. */
    if (pthread_detach(new_th) != 0) {
        printf("Error detaching thread\n");
        return PTS_FAIL;
    }

    /* Verify that it hasn't terminated the thread */
    ret = pthread_cancel(new_th);

    if (ret != 0) {
        if (ret == ESRCH) {
            printf("Test FAILED\n");
            return PTS_FAIL;
        }
        perror("Error canceling thread\n");
        return PTS_UNRESOLVED;
    }

    printf("Test PASSED\n");
    return PTS_PASS;
}
#include <rtt_utest_internal.h>
UTEST_TC_EXPORT(testcase, "posix.pthread_detach.2-1.c", RT_NULL, RT_NULL, 10);

redpajama_set_name: RedPajamaGithub


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.camunda.bpm.dmn.xlsx;

import static org.assertj.core.api.Assertions.assertThat;

import java.io.InputStream;
import java.util.Collection;

import org.camunda.bpm.model.dmn.DmnModelInstance;
import org.camunda.bpm.model.dmn.instance.Decision;
import org.camunda.bpm.model.dmn.instance.DecisionTable;

/**
 * @author Thorben Lindhauer
 *
 */
public class TestHelper {

  public static InputStream getClassPathResource(String path) {
    return TestHelper.class.getClassLoader().getResourceAsStream(path);
  }

  public static DecisionTable assertAndGetSingleDecisionTable(DmnModelInstance dmnModel) {
    assertThat(dmnModel.getDefinitions()).isNotNull();
    Collection<Decision> decisions = dmnModel.getDefinitions().getChildElementsByType(Decision.class);
    assertThat(decisions).hasSize(1);

    Decision decision = decisions.iterator().next();
    assertThat(decision).isNotNull();

    Collection<DecisionTable> decisionTables = decision.getChildElementsByType(DecisionTable.class);
    assertThat(decisionTables).hasSize(1);

    return decisionTables.iterator().next();
  }
}


text:
package com.skcraft.plume.module;

import com.google.common.collect.Lists;
import com.google.inject.Inject;
import com.skcraft.plume.common.UserId;
import com.skcraft.plume.common.util.event.EventBus;
import com.skcraft.plume.common.util.module.Module;
import com.skcraft.plume.event.Cause;
import com.skcraft.plume.event.DelegateEvent;
import com.skcraft.plume.event.block.BlockChange;
import com.skcraft.plume.event.block.BreakBlockEvent;
import com.skcraft.plume.event.block.PlaceBlockEvent;
import com.skcraft.plume.event.entity.DamageEntityEvent;
import com.skcraft.plume.util.BlockState;
import com.skcraft.plume.util.Events;
import com.skcraft.plume.util.Location3i;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import li.cil.oc.api.event.RobotAttackEntityEvent;
import li.cil.oc.api.event.RobotBreakBlockEvent;
import li.cil.oc.api.event.RobotMoveEvent;
import li.cil.oc.api.event.RobotPlaceBlockEvent;
import li.cil.oc.api.internal.Agent;
import net.minecraft.init.Blocks;

import java.util.List;

@Module(name = "robot-abstraction-listener", hidden = true)
public class RobotAbstractionListener {

    private final EventBus eventBus;
    private final BlockState STONE_STATE = BlockState.create(Blocks.stone);
    private final BlockState AIR_STATE = BlockState.create(Blocks.air);

    @Inject
    public RobotAbstractionListener(EventBus eventBus) {
        this.eventBus = eventBus;
    }

    private Cause createCause(Agent agent) {
        return Cause.create(new UserId(agent.ownerUUID(), agent.ownerName()), agent);
    }

    @SubscribeEvent
    public void onRobotBreak(RobotBreakBlockEvent.Pre event) {
        if (event.world.isRemote) return;

        Location3i location = new Location3i(event.world, event.x, event.y, event.z);
        BlockState current = BlockState.getBlockAndMeta(location);
        List<BlockChange> changes = Lists.newArrayList(new BlockChange(location, current, AIR_STATE));

        Events.postDelegate(eventBus, new BreakBlockEvent(createCause(event.agent), event.world, changes), event);
    }

    @SubscribeEvent
    public void onRobotMoveEvent(RobotMoveEvent.Pre event) {
        if (event.agent.world().isRemote) return;

        Agent agent = event.agent;

        Location3i location = new Location3i(event.agent.world(),
                (int) agent.xPosition() + event.direction.offsetX,
                (int) agent.yPosition() + event.direction.offsetY,
                (int) agent.zPosition() + event.direction.offsetZ);
        BlockState current = BlockState.getBlockAndMeta(location);
        List<BlockChange> changes = Lists.newArrayList(new BlockChange(location, current, STONE_STATE)); // Hack

        Events.postDelegate(eventBus, new PlaceBlockEvent(createCause(event.agent), event.agent.world(), changes), event);
    }

    @SubscribeEvent
    public void onRobotPlace(RobotPlaceBlockEvent.Pre event) {
        if (event.world.isRemote) return;

        Location3i location = new Location3i(event.world, event.x, event.y, event.z);
        BlockState current = BlockState.getBlockAndMeta(location);
        List<BlockChange> changes = Lists.newArrayList(new BlockChange(location, current, STONE_STATE)); // Hack until we get a block

        Events.postDelegate(eventBus, new PlaceBlockEvent(createCause(event.agent), event.world, changes), event);
    }

    @SubscribeEvent
    public void onRobotAttackEntity(RobotAttackEntityEvent event) {
        if (event.target.worldObj.isRemote) return;

        DelegateEvent delegateEvent = new DamageEntityEvent(createCause(event.agent), event.target.worldObj, Lists.newArrayList(event.target));

        Events.postDelegate(eventBus, delegateEvent, event);
    }

}


text:
package org.apache.jackrabbit.core.security.user;

import org.apache.jackrabbit.commons.iterator.NodeIteratorAdapter;
import org.apache.jackrabbit.core.NodeImpl;
import org.apache.jackrabbit.spi.Name;
import org.apache.jackrabbit.spi.Path;
import org.apache.jackrabbit.spi.commons.conversion.NamePathResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.PathNotFoundException;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Value;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.regex.PatternSyntaxException;

/**
 *
 */
class TraversingNodeResolver extends NodeResolver {

    private static final Logger log = LoggerFactory.getLogger(TraversingNodeResolver.class);

    /**
     * Additionally to the NodeType-Argument the resolvers searched is narrowed
     * by indicating a Path to an {@link javax.jcr.Item} as start for the search
     *
     * @param session to use for repository access
     * @param resolver The NamePathResolver used to convert {@link org.apache.jackrabbit.spi.Name}
     * and {@link org.apache.jackrabbit.spi.Path} to JCR names/path.
     */
    TraversingNodeResolver(Session session, NamePathResolver resolver) {
        super(session, resolver);
    }

    //-------------------------------------------------------< NodeResolver >---
    /**
     * @inheritDoc
     */
    @Override
    public Node findNode(Name nodeName, Name ntName) throws RepositoryException {
        String sr = getSearchRoot(ntName);
        if (getSession().nodeExists(sr)) {
            try {
                Node root = getSession().getNode(sr);
                return collectNode(nodeName, ntName, root.getNodes());
            } catch (PathNotFoundException e) {
                // should not get here
                log.warn("Error while retrieving node " + sr);
            }
        } // else: searchRoot does not exist yet -> omit the search
        return null;
    }

    /**
     * @inheritDoc
     */
    @Override
    public Node findNode(Name propertyName, String value, Name ntName) throws RepositoryException {
        String sr = getSearchRoot(ntName);
        if (getSession().nodeExists(sr)) {
            try {
                Node root = getSession().getNode(sr);
                Set<Node> matchSet = new HashSet<Node>();
                collectNodes(value, Collections.singleton(propertyName), ntName, root.getNodes(), matchSet, true, 1);

                NodeIterator it = new NodeIteratorAdapter(matchSet);
                if (it.hasNext()) {
                    return it.nextNode();
                }
            } catch (PathNotFoundException e) {
                // should not get here
                log.warn("Error while retrieving node " + sr);
            }
        } // else: searchRoot does not exist yet -> omit the search
        return null;
    }

    /**
     * @inheritDoc
     */
    @Override
    public NodeIterator findNodes(Set<Name> propertyNames, String value, Name ntName,
                                  boolean exact, long maxSize) throws RepositoryException {
        String sr = getSearchRoot(ntName);
        if (getSession().nodeExists(sr)) {
            try {
                Node root = getSession().getNode(sr);
                Set<Node> matchSet = new HashSet<Node>();
                collectNodes(value, propertyNames, ntName, root.getNodes(), matchSet, exact, maxSize);
                return new NodeIteratorAdapter(matchSet);
            } catch (PathNotFoundException e) {
                // should not get here
                log.warn("Error while retrieving node " + sr);
            }
        } // else: searchRoot does not exist yet -> omit the search
        return NodeIteratorAdapter.EMPTY;
    }

    /**
     * @inheritDoc
     */
    @Override
    public NodeIterator findNodes(Path relPath, String value, int authorizableType, boolean exact, long maxSize) throws RepositoryException {
        String sr = getSearchRoot(authorizableType);
        if (getSession().nodeExists(sr)) {
            try {
                String path = getNamePathResolver().getJCRPath(relPath);
                AuthorizableTypePredicate pred = getAuthorizableTypePredicate(authorizableType, relPath.getLength() > 1);

                Node root = getSession().getNode(sr);
                Map<String, Node> matchingNodes = new HashMap<String, Node>();
                collectNodes(value, path, pred, root.getNodes(), matchingNodes, exact, maxSize);

                return new NodeIteratorAdapter(matchingNodes.values());
            } catch (PathNotFoundException e) {
                // should not get here
                log.warn("Error while retrieving node " + sr);
            }
        } // else: searchRoot does not exist yet -> omit the search
        return NodeIteratorAdapter.EMPTY;
    }

    //--------------------------------------------------------------------------
    /**
     *
     * @param nodeName
     * @param ntName
     * @param nodes
     * @return The first matching node or null.
     */
    private Node collectNode(Name nodeName, Name ntName, NodeIterator nodes) {
        Node match = null;
        while (match == null && nodes.hasNext()) {
            NodeImpl node = (NodeImpl) nodes.nextNode();
            try {
                if (node.isNodeType(ntName) && nodeName.equals(node.getQName())) {
                    match = node;
                } else if (node.hasNodes()) {
                    match = collectNode(nodeName, ntName, node.getNodes());
                }
            } catch (RepositoryException e) {
                log.warn("Internal error while accessing node", e);
            }
        }
        return match;
    }

    /**
     * Searches the given value in the range of the given NodeIterator.
     * This method is called recursively to look within the complete tree
     * of authorizable nodes.
     *
     * @param value         the value to be found in the nodes
     * @param propertyNames property to be searched, or null if {@link javax.jcr.Item#getName()}
     * @param nodeTypeName  name of node types to search
     * @param itr           range of nodes and descendants to be searched
     * @param matchSet      Set of found matches to append results
     * @param exact         if set to true the value has to match exact
     * @param maxSize
     */
    private void collectNodes(String value, Set<Name> propertyNames,
                              Name nodeTypeName, NodeIterator itr,
                              Set<Node> matchSet, boolean exact, long maxSize) {
        while (itr.hasNext()) {
            NodeImpl node = (NodeImpl) itr.nextNode();
            try {
                if (matches(node, nodeTypeName, propertyNames, value, exact)) {
                    matchSet.add(node);
                    maxSize--;
                }
                if (node.hasNodes() && maxSize > 0) {
                    collectNodes(value, propertyNames, nodeTypeName,
                            node.getNodes(), matchSet, exact, maxSize);
                }
            } catch (RepositoryException e) {
                log.warn("Internal error while accessing node", e);
            }
        }
    }

    private void collectNodes(String value, String relPath,
                              AuthorizableTypePredicate predicate, NodeIterator itr,
                              Map<String, Node> matchingNodes, boolean exact, long maxSize) {
        while (itr.hasNext()) {
            NodeImpl node = (NodeImpl) itr.nextNode();
            try {
                Node authNode = getMatchingNode(node, predicate, relPath, value, exact);
                if (authNode != null) {
                    matchingNodes.put(authNode.getIdentifier(), authNode);
                    maxSize--;
                } else if (node.hasNodes() && maxSize > 0) {
                    collectNodes(value, relPath, predicate, node.getNodes(), matchingNodes, exact, maxSize);
                }
            } catch (RepositoryException e) {
                log.warn("Internal error while accessing node", e);
            }
        }
    }

    /**
     *
     * @param node
     * @param nodeTypeName
     * @param propertyNames
     * @param value
     * @param exact
     * @return
     * @throws RepositoryException
     */
    private static boolean matches(NodeImpl node, Name nodeTypeName,
                            Collection<Name> propertyNames, String value,
                            boolean exact) throws RepositoryException {

        boolean match = false;
        if (node.isNodeType(nodeTypeName)) {
            if (value == null) {
                match = true;
            } else {
                try {
                    if (propertyNames.isEmpty()) {
                        match = (exact) ? node.getName().equals(value) :
                                node.getName().matches(".*"+value+".*");
                    } else {
                        Iterator<Name> pItr = propertyNames.iterator();
                        while (!match && pItr.hasNext()) {
                            Name propertyName = pItr.next();
                            if (node.hasProperty(propertyName)) {
                                Property prop = node.getProperty(propertyName);
                                if (prop.isMultiple()) {
                                    Value[] values = prop.getValues();
                                    for (int i = 0; i < values.length && !match; i++) {
                                        match = matches(value, values[i].getString(), exact);
                                    }
                                } else {
                                    match = matches(value, prop.getString(), exact);
                                }
                            }
                        }
                    }
                } catch (PatternSyntaxException pe) {
                    log.debug("couldn't search for {}, pattern invalid: {}",
                            value, pe.getMessage());
                }
            }
        }
        return match;
    }

    /**
     *
     * @param node
     * @param predicate
     * @param relPath
     * @param value
     * @param exact
     * @return
     * @throws RepositoryException
     */
    private static Node getMatchingNode(NodeImpl node, AuthorizableTypePredicate predicate,
                                        String relPath, String value,
                                        boolean exact) throws RepositoryException {
        boolean match = false;
        Node authNode = predicate.getAuthorizableNode(node);
        if (authNode != null && node.hasProperty(relPath)) {
            try {
                Property prop = node.getProperty(relPath);
                if (prop.isMultiple()) {
                    Value[] values = prop.getValues();
                    for (int i = 0; i < values.length && !match; i++) {
                        match = matches(value, values[i].getString(), exact);
                    }
                } else {
                    match = matches(value, prop.getString(), exact);
                }
            } catch (PatternSyntaxException pe) {
                log.debug("couldn't search for {}, pattern invalid: {}", value, pe.getMessage());
            }
        }
        return (match) ? authNode : null;
    }

    private static boolean matches(String value, String toMatch, boolean exact) {
        return (exact) ? toMatch.equals(value) : toMatch.matches(".*"+value+".*");
    }
}


text:
package com.cody.live.event.bus.lib.exception;

/**
 * Created by xu.yi. on 2019/3/31.
 * 类型错误异常
 */
public class WrongTypeException extends RuntimeException {
    public WrongTypeException() {
        super("请使用自动生成的接口文件");
    }
}


text:
package edu.washington.escience.myria.operator.apply;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.io.IOException;

import org.junit.Test;

import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.google.common.collect.ImmutableList;

import edu.washington.escience.myria.Type;
import edu.washington.escience.myria.api.MyriaJsonMapperProvider;
import edu.washington.escience.myria.expression.AbsExpression;
import edu.washington.escience.myria.expression.AndExpression;
import edu.washington.escience.myria.expression.CastExpression;
import edu.washington.escience.myria.expression.CeilExpression;
import edu.washington.escience.myria.expression.ConditionalExpression;
import edu.washington.escience.myria.expression.ConstantExpression;
import edu.washington.escience.myria.expression.CosExpression;
import edu.washington.escience.myria.expression.DivideExpression;
import edu.washington.escience.myria.expression.EqualsExpression;
import edu.washington.escience.myria.expression.ExpressionOperator;
import edu.washington.escience.myria.expression.FloorExpression;
import edu.washington.escience.myria.expression.GreaterExpression;
import edu.washington.escience.myria.expression.GreaterThanExpression;
import edu.washington.escience.myria.expression.GreaterThanOrEqualsExpression;
import edu.washington.escience.myria.expression.HashMd5Expression;
import edu.washington.escience.myria.expression.IntDivideExpression;
import edu.washington.escience.myria.expression.LenExpression;
import edu.washington.escience.myria.expression.LessThanExpression;
import edu.washington.escience.myria.expression.LessThanOrEqualsExpression;
import edu.washington.escience.myria.expression.LesserExpression;
import edu.washington.escience.myria.expression.LogExpression;
import edu.washington.escience.myria.expression.MinusExpression;
import edu.washington.escience.myria.expression.ModuloExpression;
import edu.washington.escience.myria.expression.NegateExpression;
import edu.washington.escience.myria.expression.NotEqualsExpression;
import edu.washington.escience.myria.expression.NotExpression;
import edu.washington.escience.myria.expression.OrExpression;
import edu.washington.escience.myria.expression.PlusExpression;
import edu.washington.escience.myria.expression.PowExpression;
import edu.washington.escience.myria.expression.RandomExpression;
import edu.washington.escience.myria.expression.SinExpression;
import edu.washington.escience.myria.expression.SqrtExpression;
import edu.washington.escience.myria.expression.StateExpression;
import edu.washington.escience.myria.expression.SubstrExpression;
import edu.washington.escience.myria.expression.TanExpression;
import edu.washington.escience.myria.expression.TimesExpression;
import edu.washington.escience.myria.expression.ToUpperCaseExpression;
import edu.washington.escience.myria.expression.TypeExpression;
import edu.washington.escience.myria.expression.TypeOfExpression;
import edu.washington.escience.myria.expression.VariableExpression;
import edu.washington.escience.myria.expression.WorkerIdExpression;

public class ApplySerializationTest {

  @Test
  public void testJsonMapping() throws IOException {
    ObjectReader reader = MyriaJsonMapperProvider.getReader().withType(ExpressionOperator.class);
    ObjectWriter writer = MyriaJsonMapperProvider.getWriter();

    ImmutableList.Builder<ExpressionOperator> expressions = ImmutableList.builder();

    /* Zeroary */
    ConstantExpression constant = new ConstantExpression(Type.INT_TYPE, "5");
    RandomExpression random = new RandomExpression();
    StateExpression state = new StateExpression(3);
    TypeExpression type = new TypeExpression(Type.INT_TYPE);
    TypeOfExpression typeof = new TypeOfExpression(2);
    VariableExpression variable = new VariableExpression(1);
    WorkerIdExpression worker = new WorkerIdExpression();
    expressions.add(constant).add(random).add(state).add(type).add(typeof).add(variable).add(worker);

    /* Unary */
    AbsExpression abs = new AbsExpression(constant);
    CeilExpression ceil = new CeilExpression(constant);
    FloorExpression floor = new FloorExpression(constant);
    LogExpression log = new LogExpression(constant);
    HashMd5Expression md5 = new HashMd5Expression(constant);
    NegateExpression negate = new NegateExpression(constant);
    CosExpression cos = new CosExpression(constant);
    SinExpression sin = new SinExpression(constant);
    SqrtExpression sqrt = new SqrtExpression(constant);
    TanExpression tan = new TanExpression(constant);
    ToUpperCaseExpression upper = new ToUpperCaseExpression(constant);
    NotExpression not = new NotExpression(constant);
    LenExpression len = new LenExpression(constant);
    expressions.add(abs).add(ceil).add(cos).add(floor).add(log).add(md5).add(negate).add(not).add(sin).add(sqrt).add(
        tan).add(upper).add(len);

    /* Binary */
    DivideExpression divide = new DivideExpression(constant, variable);
    IntDivideExpression idivide = new IntDivideExpression(constant, variable);
    MinusExpression minus = new MinusExpression(constant, variable);
    PlusExpression plus = new PlusExpression(constant, variable);
    PowExpression pow = new PowExpression(constant, variable);
    TimesExpression times = new TimesExpression(constant, variable);
    AndExpression and = new AndExpression(constant, variable);
    OrExpression or = new OrExpression(constant, variable);
    EqualsExpression eq = new EqualsExpression(constant, variable);
    NotEqualsExpression ne = new NotEqualsExpression(constant, variable);
    GreaterThanExpression gt = new GreaterThanExpression(constant, variable);
    LessThanExpression lt = new LessThanExpression(constant, variable);
    GreaterThanOrEqualsExpression gte = new GreaterThanOrEqualsExpression(constant, variable);
    LessThanOrEqualsExpression lte = new LessThanOrEqualsExpression(constant, variable);
    CastExpression cast = new CastExpression(constant, typeof);
    ModuloExpression modulo = new ModuloExpression(constant, variable);
    LesserExpression min = new LesserExpression(constant, variable);
    GreaterExpression max = new GreaterExpression(constant, variable);
    expressions.add(and).add(divide).add(idivide).add(eq).add(gt).add(gte).add(lt).add(lte).add(minus).add(ne).add(or)
        .add(plus).add(pow).add(times).add(cast).add(modulo).add(min).add(max);

    /* NAry */
    VariableExpression variable2 = new VariableExpression(2);
    ConditionalExpression conditional = new ConditionalExpression(variable, constant, variable2);
    SubstrExpression substr = new SubstrExpression(constant, constant, constant);
    expressions.add(conditional).add(substr);

    /* Test serializing and deserializing all of them. */
    for (ExpressionOperator op : expressions.build()) {
      assertTrue(writer.canSerialize(op.getClass()));
      String serialized = writer.writeValueAsString(op);
      ExpressionOperator op2 = reader.readValue(serialized);
      assertEquals(op2, op);
    }
  }
}


text:
///
/// anax
/// An open source C++ entity system.
///
/// Copyright (C) 2013-2014 Miguel Martin (miguel@miguel-martin.com)
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
///

#ifndef ANAX_DETAIL_CONFIG_HPP
#define ANAX_DETAIL_CONFIG_HPP

#include <cstddef>

/* #undef ANAX_32_BIT_ENTITY_IDS */
#define ANAX_VIRTUAL_DTORS_IN_COMPONENT ON
/* #undef ANAX_COMPONENTS_ALIGNED */

#ifdef ANAX_32_BIT_ENTITY_IDS
#	define ANAX_ENTITY_ID_INDEX_BIT_COUNT 20
#	define ANAX_ENTITY_ID_COUNTER_BIT_COUNT 12
#else
#	define ANAX_ENTITY_ID_INDEX_BIT_COUNT 48
#	define ANAX_ENTITY_ID_COUNTER_BIT_COUNT 16
#endif

namespace anax
{
    /// The default size of a pool within a world
    constexpr const std::size_t DEFAULT_ENTITY_POOL_SIZE = 1000;

    /// The maximum amount of components an entity can
    /// contain. Try to make this number even, or preferably
    /// a power of 2.
    constexpr const std::size_t MAX_AMOUNT_OF_COMPONENTS = 64;
}

#endif // ANAX_DETAIL_CONFIG_HPP


text:
package samples.junit48.rules;

import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import samples.junit48.rules.impl.SimpleEasyMockJUnitRule;
import samples.rule.SimpleThingCreator;
import samples.rule.SimpleThingImpl;
import samples.rule.ThingToTest;

import static org.easymock.EasyMock.expect;
import static org.junit.Assert.assertEquals;
import static org.powermock.api.easymock.PowerMock.*;

@RunWith(PowerMockRunner.class)
@PrepareForTest(SimpleThingCreator.class)
public class ExceptionHandlingRuleTest {

    @Rule
    public SimpleEasyMockJUnitRule mocks = new SimpleEasyMockJUnitRule();

    private SimpleThingImpl simpleThingMock = mocks.createMock(SimpleThingImpl.class);

    // object under test
    private ThingToTest testThing;

    @Before
    public void setUp() throws Exception {
        mockStatic(SimpleThingCreator.class);
        expect(SimpleThingCreator.createSimpleThing()).andReturn(simpleThingMock);
        replay(SimpleThingCreator.class);

        verify(SimpleThingCreator.class);
    }

    @Test
    @Ignore("This test SHOULD fail but how do we expect it when verification happens in the rule?")
    public void exceptionThrownByRuleFailsTheTest() throws Exception {
        final String expectedName = "Smith";
        expect(simpleThingMock.getThingName()).andReturn(expectedName);
        mocks.replay();

        assertEquals("wrong name", expectedName, testThing.getName());
        // verify will be called by rule
    }
}


text:
import { EventEmitter } from 'events';
import * as Utils from './utils';

let loadPromise = null;
let googleGPTScriptLoadPromise = null;
let singleRequestEnabled = true;
let disableInitialLoadEnabled = false;
let lazyLoadEnabled = false;
let lazyLoadConfig = null;
let servePersonalizedAds = true;
let serveCookies = true;
const registeredSlots = {};
let managerAlreadyInitialized = false;
const globalTargetingArguments = {};
const globalAdSenseAttributes = {};
let limitedAds = false;

const DFPManager = Object.assign(new EventEmitter().setMaxListeners(0), {

  singleRequestIsEnabled() {
    return singleRequestEnabled;
  },

  configureSingleRequest(value) {
    singleRequestEnabled = !!value;
  },

  disableInitialLoadIsEnabled() {
    return disableInitialLoadEnabled;
  },

  configureDisableInitialLoad(value) {
    disableInitialLoadEnabled = !!value;
  },

  configureLazyLoad(enable = true, config = null) {
    let conf = null;
    if (config !== null && typeof config === 'object') {
      conf = { ...config };
    }
    lazyLoadEnabled = !!enable;
    lazyLoadConfig = conf;
  },

  lazyLoadIsEnabled() {
    return lazyLoadEnabled;
  },

  limitedAdsIsEnabled() {
    return limitedAds;
  },

  configureLimitedAds(value) {
    limitedAds = !!value;
  },

  getLazyLoadConfig() {
    return lazyLoadConfig;
  },

  getAdSenseAttribute(key) {
    return globalAdSenseAttributes[key];
  },

  configurePersonalizedAds(value) {
    servePersonalizedAds = value;
  },

  configureCookieOption(value) {
    serveCookies = value;
  },

  personalizedAdsEnabled() {
    return servePersonalizedAds;
  },

  cookiesEnabled() {
    return serveCookies;
  },

  setAdSenseAttribute(key, value) {
    this.setAdSenseAttributes({ [key]: value });
  },

  getAdSenseAttributes() {
    return { ...globalAdSenseAttributes };
  },

  setAdSenseAttributes(attrs) {
    Object.assign(globalAdSenseAttributes, attrs);
    if (managerAlreadyInitialized === true) {
      this.getGoogletag().then((googletag) => {
        googletag.cmd.push(() => {
          const pubadsService = googletag.pubads();
          Object.keys(globalAdSenseAttributes).forEach(
            (key) => {
              pubadsService.set(key, globalTargetingArguments[key]);
            },
          );
        });
      });
    }
  },

  setTargetingArguments(data) {
    Object.assign(globalTargetingArguments, data);
    const availableKeys = Object.keys(registeredSlots);
    availableKeys.forEach((slotId) => {
      registeredSlots[slotId].targetingArguments = data;
    });
    if (managerAlreadyInitialized === true) {
      this.getGoogletag().then((googletag) => {
        googletag.cmd.push(() => {
          const pubadsService = googletag.pubads();
          Object.keys(globalTargetingArguments).forEach((varName) => {
            if (pubadsService) {
              pubadsService.setTargeting(varName, globalTargetingArguments[varName]);
            }
          });
        });
      });
    }
  },

  getTargetingArguments() {
    return { ...globalTargetingArguments };
  },

  getSlotProperty(slotId, propName) {
    const slot = this.getRegisteredSlots()[slotId];
    let ret = null;
    if (slot !== undefined) {
      ret = slot[propName] || ret;
    }
    return ret;
  },

  getSlotTargetingArguments(slotId) {
    const propValue = this.getSlotProperty(slotId, 'targetingArguments');
    return propValue ? { ...propValue } : null;
  },

  getSlotAdSenseAttributes(slotId) {
    const propValue = this.getSlotProperty(slotId, 'adSenseAttributes');
    return propValue ? { ...propValue } : null;
  },

  init() {
    if (managerAlreadyInitialized === false) {
      managerAlreadyInitialized = true;
      this.getGoogletag().then((googletag) => {
        googletag.cmd.push(() => {
          const pubadsService = googletag.pubads();
          pubadsService.addEventListener('slotRenderEnded', (event) => {
            const slotId = event.slot.getSlotElementId();
            this.emit('slotRenderEnded', { slotId, event });
          });
          pubadsService.addEventListener('impressionViewable', (event) => {
            const slotId = event.slot.getSlotElementId();
            this.emit('impressionViewable', { slotId, event });
          });
          pubadsService.addEventListener('slotVisibilityChanged', (event) => {
            const slotId = event.slot.getSlotElementId();
            this.emit('slotVisibilityChanged', { slotId, event });
          });
          pubadsService.setRequestNonPersonalizedAds(
            this.personalizedAdsEnabled() ? 0 : 1,
          );
          pubadsService.setCookieOptions(
            this.cookiesEnabled() ? 0 : 1,
          );
        });
      });
    }
  },

  getGoogletag() {
    if (googleGPTScriptLoadPromise === null) {
      googleGPTScriptLoadPromise = Utils.loadGPTScript(limitedAds);
    }
    return googleGPTScriptLoadPromise;
  },

  setCollapseEmptyDivs(collapse) {
    this.collapseEmptyDivs = collapse;
  },

  load(...slots) {
    if (loadPromise === null) {
      loadPromise = this.doLoad(...slots);
    } else {
      loadPromise = loadPromise.then(
        () => this.doLoad(...slots),
      );
    }
  },

  doLoad(...slots) {
    this.init();
    let availableSlots = {};

    if (slots.length > 0) {
      availableSlots = slots.filter(
        slotId => Object.prototype.hasOwnProperty.call(registeredSlots, slotId),
      );
    } else {
      availableSlots = Object.keys(registeredSlots);
    }
    availableSlots = availableSlots.filter(
      id => !registeredSlots[id].loading && !registeredSlots[id].gptSlot,
    );
    availableSlots.forEach((slotId) => {
      registeredSlots[slotId].loading = true;
    });
    return this.gptLoadAds(availableSlots);
  },

  gptLoadAds(slotsToInitialize) {
    return new Promise((resolve) => {
      this.getGoogletag().then((googletag) => {
        this.configureInitialOptions(googletag);
        slotsToInitialize.forEach((currentSlotId) => {
          registeredSlots[currentSlotId].loading = false;

          googletag.cmd.push(() => {
            const slot = registeredSlots[currentSlotId];
            let gptSlot;
            const adUnit = `${slot.dfpNetworkId}/${slot.adUnit}`;
            if (slot.renderOutOfThePage === true) {
              gptSlot = googletag.defineOutOfPageSlot(adUnit, currentSlotId);
            } else {
              gptSlot = googletag.defineSlot(adUnit, slot.sizes, currentSlotId);
            }
            if (gptSlot !== null) {
              slot.gptSlot = gptSlot;
              const slotTargetingArguments = this.getSlotTargetingArguments(currentSlotId);
              if (slotTargetingArguments !== null) {
                Object.keys(slotTargetingArguments).forEach((varName) => {
                  if (slot && slot.gptSlot) {
                    slot.gptSlot.setTargeting(varName, slotTargetingArguments[varName]);
                  }
                });
              }
              const slotAdSenseAttributes = this.getSlotAdSenseAttributes(currentSlotId);
              if (slotAdSenseAttributes !== null) {
                Object.keys(slotAdSenseAttributes).forEach((varName) => {
                  slot.gptSlot.set(varName, slotAdSenseAttributes[varName]);
                });
              }
              slot.gptSlot.addService(googletag.pubads());
              if (slot.sizeMapping) {
                let smbuilder = googletag.sizeMapping();
                slot.sizeMapping.forEach((mapping) => {
                  smbuilder = smbuilder.addSize(mapping.viewport, mapping.sizes);
                });
                slot.gptSlot.defineSizeMapping(smbuilder.build());
              }
            }
          });
        });
        this.configureOptions(googletag);
        googletag.cmd.push(() => {
          googletag.enableServices();
          slotsToInitialize.forEach((theSlotId) => {
            googletag.display(theSlotId);
          });
          resolve();
        });
      });
    });
  },

  // configure those gpt parameters that need to be set before pubsads service
  // initialization.
  configureInitialOptions(googletag) {
    googletag.cmd.push(() => {
      if (this.disableInitialLoadIsEnabled()) {
        googletag.pubads().disableInitialLoad();
      }
    });
  },

  configureOptions(googletag) {
    googletag.cmd.push(() => {
      const pubadsService = googletag.pubads();
      pubadsService.setRequestNonPersonalizedAds(
        this.personalizedAdsEnabled() ? 0 : 1,
      );
      pubadsService.setCookieOptions(
        this.cookiesEnabled() ? 0 : 1,
      );
      const targetingArguments = this.getTargetingArguments();
      // set global targetting arguments
      Object.keys(targetingArguments).forEach((varName) => {
        if (pubadsService) {
          pubadsService.setTargeting(varName, targetingArguments[varName]);
        }
      });
      // set global adSense attributes
      const adSenseAttributes = this.getAdSenseAttributes();
      Object.keys(adSenseAttributes).forEach((key) => {
        pubadsService.set(key, adSenseAttributes[key]);
      });
      if (this.lazyLoadIsEnabled()) {
        const config = this.getLazyLoadConfig();
        if (config) {
          pubadsService.enableLazyLoad(config);
        } else {
          pubadsService.enableLazyLoad();
        }
      }
      if (this.singleRequestIsEnabled()) {
        pubadsService.enableSingleRequest();
      }
      if (this.collapseEmptyDivs === true || this.collapseEmptyDivs === false) {
        pubadsService.collapseEmptyDivs(this.collapseEmptyDivs);
      }
    });
  },

  getRefreshableSlots(...slotsArray) {
    const slots = {};
    if (slotsArray.length === 0) {
      const slotsToRefresh = Object.keys(registeredSlots)
        .map(k => registeredSlots[k]);
      return slotsToRefresh.reduce((last, slot) => {
        if (slot.slotShouldRefresh() === true) {
          slots[slot.slotId] = slot;
        }
        return slots;
      }, slots);
    }
    return slotsArray.reduce((last, slotId) => {
      const slot = registeredSlots[slotId];
      if (typeof slot !== 'undefined') {
        slots[slotId] = slot;
      }
      return slots;
    }, slots);
  },

  refresh(...slots) {
    if (loadPromise === null) {
      this.load();
    } else {
      loadPromise.then(() => {
        this.gptRefreshAds(
          Object.keys(
            this.getRefreshableSlots(...slots),
          ),
        );
      });
    }
  },

  gptRefreshAds(slots) {
    return this.getGoogletag().then((googletag) => {
      this.configureOptions(googletag);
      googletag.cmd.push(() => {
        const pubadsService = googletag.pubads();
        const slotsToRefreshArray = slots.map(slotId => registeredSlots[slotId].slotId);
        pubadsService.refresh(slotsToRefreshArray);
      });
    });
  },

  reload(...slots) {
    return this.destroyGPTSlots(...slots).then(() => this.load());
  },

  destroyGPTSlots(...slotsToDestroy) {
    if (slotsToDestroy.length === 0) {
      // eslint-disable-next-line no-param-reassign
      slotsToDestroy = Object.keys(registeredSlots);
    }
    return new Promise((resolve) => {
      const slots = [];
      // eslint-disable-next-line guard-for-in,no-restricted-syntax
      for (const idx in slotsToDestroy) {
        const slotId = slotsToDestroy[idx];
        const slot = registeredSlots[slotId];
        slots.push(slot);
      }
      this.getGoogletag()
        .then((googletag) => {
          googletag.cmd.push(() => {
            if (managerAlreadyInitialized === true) {
              if (slotsToDestroy.length > 0) {
                // eslint-disable-next-line guard-for-in,no-restricted-syntax
                for (const idx in slots) {
                  const slot = slots[idx];
                  slots.push(slot.gptSlot);
                  delete slot.gptSlot;
                }
                googletag.destroySlots(slots);
              } else {
                googletag.destroySlots();
              }
            }
            resolve(slotsToDestroy);
          });
        });
    });
  },

  registerSlot({
    slotId,
    dfpNetworkId,
    adUnit,
    sizes,
    renderOutOfThePage,
    sizeMapping,
    adSenseAttributes,
    targetingArguments,
    slotShouldRefresh,
  }, autoLoad = true) {
    if (!Object.prototype.hasOwnProperty.call(registeredSlots, slotId)) {
      registeredSlots[slotId] = {
        slotId,
        sizes,
        renderOutOfThePage,
        dfpNetworkId,
        adUnit,
        adSenseAttributes,
        targetingArguments,
        sizeMapping,
        slotShouldRefresh,
        loading: false,
      };
      this.emit('slotRegistered', { slotId });
      if (autoLoad === true && loadPromise !== null) {
        loadPromise = loadPromise.catch().then(() => {
          const slot = registeredSlots[slotId];
          if (typeof slot !== 'undefined') {
            const { loading, gptSlot } = slot;
            if (loading === false && !gptSlot) {
              this.load(slotId);
            }
          }
        });
      }
    }
  },

  unregisterSlot({ slotId }) {
    this.destroyGPTSlots(slotId);
    delete registeredSlots[slotId];
  },

  getRegisteredSlots() {
    return registeredSlots;
  },

  attachSlotRenderEnded(cb) {
    this.on('slotRenderEnded', cb);
  },

  detachSlotRenderEnded(cb) {
    this.removeListener('slotRenderEnded', cb);
  },

  attachSlotVisibilityChanged(cb) {
    this.on('slotVisibilityChanged', cb);
  },

  detachSlotVisibilityChanged(cb) {
    this.removeListener('slotVisibilityChanged', cb);
  },

  attachSlotIsViewable(cb) {
    this.on('impressionViewable', cb);
  },

  detachSlotIsViewable(cb) {
    this.removeListener('impressionViewable', cb);
  },

});

export default DFPManager;


text:
@interface IconActionSheet : UIView <UICollectionViewDelegate, UICollectionViewDataSource> {
@private
    CGFloat _height;
}

@property (nonatomic, strong) NSMutableArray *blocks;
@property (nonatomic, strong) UICollectionView *collectionView;

+ (id)sheetWithTitle:(NSString *)title;

- (id)initWithTitle:(NSString *)title;

- (void)addIconWithTitle:(NSString *)title image:(UIImage*)image block:(void (^)())block atIndex:(NSInteger)index;
- (void)showInView:(UIView *)view;
- (void)dismissView;

@end


text:
<?php if (!defined('APPLICATION')) exit();
$Definition['Plugins.CookieConsent.MessageText'] = 'Testo del Messaggio';
$Definition['Plugins.CookieConsent.DismissText'] = 'Testo per accettare';
$Definition['Plugins.CookieConsent.LearnMoreText'] = 'Testo per ulteriori informazioni';
$Definition['Plugins.CookieConsent.Theme'] = 'Tema Banner';
$Definition['Plugins.CookieConsent.Message'] = 'Questo sito utilizza i cookie in modo da garantirvi l\'esperienza migliore sul nostro sito web';
$Definition['Plugins.CookieConsent.Dismiss'] = 'Ho capito!';
$Definition['Plugins.CookieConsent.LearnMore'] = 'Scopri di più!';


text:
Expression::Expression() : Algebra<SymbolicTerm, scalar_t>() {}

void Expression::add(const Term &sterm) {
  SymbolicTerm symterm = sterm.symterm();
  auto search = terms_.find(symterm);

  if (search != terms_.end()) {
    /// Found, then just add the factor to the existing term
    search->second += sterm.coefficient();
    if (search->second == 0) {
      terms_.erase(search);
    }
  } else {
    terms_[symterm] = sterm.coefficient();
  }
}

void Expression::add(const std::pair<SymbolicTerm, scalar_t> &term_factor,
                     scalar_t scale) {

  const SymbolicTerm &term = term_factor.first;
  scalar_t factor = term_factor.second;

  auto search = terms_.find(term);

  if (search != terms_.end()) {
    /// Found, then just add the factor to the existing term
    search->second += scale * factor;
    if (search->second == 0) {
      terms_.erase(search);
    }
  } else {
    terms_[term] = scale * factor;
  }
}

void Expression::add(const Expression &expr, scalar_t scale) {
  for (const auto &kv : expr.terms()) {
    add(kv, scale);
  }
}

Expression &Expression::canonicalize() {
  std::map<SymbolicTerm, scalar_t> canonical_terms;
  for (const auto &[k, v] : terms_) {
    SymbolicTerm term = k;
    scalar_t factor = term.canonicalize();
    factor *= v;
    add_to_map(canonical_terms, term, factor);
  }
  terms_ = canonical_terms;
  return *this;
}

Expression &Expression::reindex(index_map_t &idx_map) {
  std::map<SymbolicTerm, scalar_t> reindexed_terms;
  for (auto &kv : terms_) {
    SymbolicTerm term = kv.first;
    term.reindex(idx_map);
    add_to_map(reindexed_terms, term, kv.second);
  }
  return *this;
}

bool Expression::operator==(const Expression &other) {
  return (terms_.size() == other.terms_.size()) and
         std::equal(terms_.begin(), terms_.end(), other.terms_.begin());
}

std::string Expression::str() const {
  std::vector<std::string> str_vec;
  int n = 0;
  for (auto &kv : terms_) {
    std::string symterm_str = kv.first.str();
    std::string factor_str;
    if (n == 0) { // don't show the first element sign unless it's negative
      factor_str += kv.second.str(false);
    } else {
      factor_str += kv.second.str(true);
    }
    // rational(1,1).str() returns "", so we need to handle the case of
    // a pure scalar term with no operator
    if ((factor_str.size() > 1) and (factor_str != "-")) {
      factor_str += " ";
    }
    if (factor_str.size() + symterm_str.size() == 0) {
      factor_str = (n == 0) ? "1" : "+1";
    }
    str_vec.push_back(factor_str + symterm_str);
    n++;
  }
  return join(str_vec, "\n");
}

std::string Expression::latex(const std::string &sep) const {
  std::vector<std::string> str_vec;
  for (auto &kv : terms_) {
    str_vec.push_back(kv.second.latex() + ' ' + kv.first.latex());
  }
  return join(str_vec, sep);
}

std::map<std::string, std::vector<Equation>>
Expression::to_manybody_equation(const std::string &label) const {
  std::map<std::string, std::vector<Equation>> result;
  for (const auto &term_factor : terms_) {
    std::vector<Index> lower;
    std::vector<Index> upper;
    const SymbolicTerm &term = term_factor.first;
    scalar_t factor = term_factor.second;
    for (const auto &op : term.ops()) {
      if (op.type() == SQOperatorType::Creation) {
        lower.push_back(op.index());
      } else {
        // upper indices are read in reverse order
        upper.insert(upper.begin(), op.index());
      }
    }
    SymbolicTerm lhs;
    Tensor lhs_tensor(label, lower, upper, SymmetryType::Antisymmetric);
    auto signature = lhs_tensor.signature();
    // convert the signature to a string (to bypass limitations of pybind11)
    std::string signature_str_upper;
    std::string signature_str_lower;
    int pos = 0;
    for (const auto &[u, l] : signature) {
      signature_str_upper += std::string(u, orbital_subspaces->label(pos));
      signature_str_lower += std::string(l, orbital_subspaces->label(pos));
      pos += 1;
    }
    reverse(signature_str_lower.begin(), signature_str_lower.end());
    auto signature_str = signature_str_upper + "|" + signature_str_lower;
    lhs.add(lhs_tensor);

    SymbolicTerm rhs;
    for (const auto &tensor : term.tensors()) {
      rhs.add(tensor);
    }
    result[signature_str].push_back(Equation(lhs, rhs, factor));
  }
  return result;
}

std::ostream &operator<<(std::ostream &os, const Expression &sum) {
  os << sum.str();
  return os;
}

Expression make_operator_expr(const std::string &label,
                              const std::vector<std::string> &components,
                              bool normal_ordered, SymmetryType symmetry,
                              scalar_t coefficient) {
  Expression result;
  for (const std::string &s : components) {
    auto s_vec = split(s);

    std::vector<int> cre_count(orbital_subspaces->num_spaces(), 0);
    std::vector<int> ann_count(orbital_subspaces->num_spaces(), 0);
    for (const auto &s : s_vec) {
      int space = orbital_subspaces->label_to_space(s[0]);
      ann_count[space] += 1;
    }

    std::vector<Index> cre;
    std::vector<Index> ann;

    // parse "v+ o"
    for (const auto &s : s_vec) {
      int space = orbital_subspaces->label_to_space(s[0]);
      if (s.size() == 2) {
        auto idx = Index(space, cre_count[space]);
        cre.push_back(idx);
        cre_count[space] += 1;
      } else {
        ann_count[space] -= 1;
        auto idx = Index(space, ann_count[space]);
        ann.push_back(idx);
      }
    }
    Term term;
    term.set_normal_ordered(normal_ordered);
    term.set(coefficient);
    for (const auto &c : cre) {
      term.add(SQOperator(SQOperatorType::Creation, c));
    }
    for (const auto &a : ann) {
      term.add(SQOperator(SQOperatorType::Annihilation, a));
    }
    std::reverse(std::begin(ann), std::end(ann));
    Tensor tensor(label, cre, ann, symmetry);
    term.add(tensor);
    result.add(term);
  }
  return result;
}

Expression string_to_expr(const std::string &s, SymmetryType symmetry) {

  TensorSyntax syntax = TensorSyntax::Wicked;
  Expression sum;

  // if we have an empty string, do not parse it (the code below would interpret
  // it as the term 1)
  if (s.size() == 0)
    return sum;

  //"f^{v0}_{o0} t^{o0}_{v0}"
  std::string factor_re;
  std::string tensor_re;
  std::string operator_re;
  if (syntax == TensorSyntax::Wicked) {
    tensor_re = "([a-zA-Z0-9]+\\^\\{[\\w,\\s]*\\}_\\{[\\w,\\s]*\\})";
    operator_re = "a([+-]{1,1})\\(([\\w,\\d]*)\\)";
    factor_re = "^\\s*([+-]?\\d*\\/?\\d*)\\s*";
  }

  auto tensors = findall(s, tensor_re);

  SymbolicTerm term;
  for (const auto &t : tensors) {
    term.add(make_tensor_from_str(t, symmetry));
  }

  auto operators = findall(s, operator_re);

  for (size_t n = 0; n < operators.size(); n += 2) {
    SQOperatorType type = operators[n] == "+" ? SQOperatorType::Creation
                                              : SQOperatorType::Annihilation;
    Index index = make_index_from_str(operators[n + 1]);
    term.add(SQOperator(type, index));
  }

  auto factor_vec = findall(s, factor_re);
  scalar_t factor = make_rational_from_str(factor_vec[0]);

  sum.add(term, factor);

  return sum;
}


text:
AuthDialog::AuthDialog(const std::shared_ptr<twitpp::oauth::account> a, QWidget* parent)
    : QDialog(parent), pin(new QLineEdit), account(a) {
  if (account->get_authorize_url()) {
    emit failure();
    this->close();
  }

  QString authorize_url = QString::fromStdString(account->authorize_url());

  auto button = new QPushButton("Auth");
  auto description = new QLabel("PIN:");
  auto info = new QLabel();
  info->setTextInteractionFlags(Qt::TextBrowserInteraction);
  info->setOpenExternalLinks(true);
  info->setText(
      "Open the following URL and Enter the PIN.
"
      "" + authorize_url + "");

  auto layout = new QGridLayout();
  layout->addWidget(info, 0, 0, 1, 0);
  layout->addWidget(description, 1, 0);
  layout->addWidget(pin, 1, 1);
  layout->addWidget(button, 1, 2);

  connect(button, SIGNAL(clicked()), this, SLOT(authorize()));

  this->setWindowTitle("Twitter Authorization");
  this->setLayout(layout);
}

void AuthDialog::authorize() {
  if (account->get_oauth_token(this->pin->text().toStdString())) {
    emit failure();
  } else {
    emit success();
  }

  this->close();
}


text:
RSpec.describe Types::VoteType do
  set_graphql_type

  it "has an :id field of ID! type" do
    expect(subject.fields['id'].type.to_type_signature).to eq('ID!')
  end

  it "has a :votedOn field of !PostType type" do
    expect(subject.fields['votedOn'].type.to_type_signature).to eq('Post!')
  end

  it "has a :voter field of !UserType type" do
    expect(subject.fields['voter'].type.to_type_signature).to eq('User!')
  end

  it "has a :voteWeight field of !Int type" do
    expect(subject.fields['voteWeight'].type.to_type_signature).to eq('Int!')
  end
end


text:
const expect = require('chai').expect;
const proxyquire = require('proxyquire');

const {
  errors,
} = require('../../../../../packages/workbox-cli/build/lib/errors');

const MODULE_PATH =
  '../../../../../packages/workbox-cli/build/lib/questions/ask-sw-dest';
// This is the hardcoded name of the question that's passed to inquirer.
// It's used as the key to read the response from the answer.
const QUESTION_NAME = 'swDest';

describe(`[workbox-cli] lib/questions/ask-sw-dest.js`, function () {
  it(`should reject with a 'invalid-sw-dest' error when the answer is empty`, async function () {
    const {askSWDest} = proxyquire(MODULE_PATH, {
      inquirer: {
        prompt: () => Promise.resolve({[QUESTION_NAME]: ''}),
      },
    });

    try {
      await askSWDest();
      throw new Error('Unexpected success.');
    } catch (error) {
      expect(error.message).to.eql(errors['invalid-sw-dest']);
    }
  });

  it(`should reject with a valid answer to the question`, async function () {
    const expectedAnswer = 'expected answer';
    const {askSWDest} = proxyquire(MODULE_PATH, {
      inquirer: {
        prompt: () => Promise.resolve({[QUESTION_NAME]: expectedAnswer}),
      },
    });

    const answer = await askSWDest();
    expect(answer).to.eql(expectedAnswer);
  });
});


text:
typedef NS_ENUM(NSInteger, LWRCSwitchServerState) {
    LWRCSwitchServerState_Connected,
    LWRCSwitchServerState_NotConnected,
    LWRCSwitchServerState_Browsing
};

@protocol LWRCSwitchServerDelegate <NSObject>
- (void)RCSwitchServer:(id)theServer stateChanged:(LWRCSwitchServerState) theState;
- (void)RCSwitchServer:(id)theServer didReceivedMessage:(NSString*)message widthData:(id)data;
@end

@interface LWRCSwitchServerConnection : NSObject
@property  NSString* hostName;
@property  NSInteger port;
@property NSString* serviceName;
@end

@interface LWRCSwitchServer : NSObject <LWServiceBrowserDelegate, SocketIODelegate>
@property LWRCSwitchServerState state;
@property LWRCSwitchServerConnection* connection;
@property (assign) id<LWRCSwitchServerDelegate> delegate;

- (id)initWithDelegate:(id<LWRCSwitchServerDelegate>)theDelegate;
- (void)connect;
- (void)sendMessage:(NSString*)message withData:(id) data;

+ (id)createAndConnectWithDelegate:(id<LWRCSwitchServerDelegate>)theDelegate;

@end


text:
package com.lanmo.canary.demo.server;

import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Created by Administrator on 2017/2/19.
 */
public class ServerBySpring {

    public static void main(String[] args){

        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContextPP.xml");

    }

}


text:
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using Ionic.Zip;
using NUnit.Framework;
using SIL.DblBundle.Tests.Properties;
using SIL.DblBundle.Text;
using SIL.DblBundle.Usx;
using SIL.IO;
using SIL.WritingSystems;

namespace SIL.DblBundle.Tests.Text
{
	/// <summary>
	/// Tests methods in the TextBundle class.
	/// </summary>
	[TestFixture]
	public class TextBundleTests
	{
		private TextBundle<DblTextMetadata<DblMetadataLanguage>, DblMetadataLanguage> _legacyBundle;
		private TextBundle<DblTextMetadata<DblMetadataLanguage>, DblMetadataLanguage> _legacyBundleWithoutLdml;
		private TextBundle<DblTextMetadata<DblMetadataLanguage>, DblMetadataLanguage> _bundle;
		private TextBundle<DblTextMetadata<DblMetadataLanguage>, DblMetadataLanguage> _bundleWithoutLdml;

		/// <summary>
		/// Setup test fixture.
		/// </summary>
		[OneTimeSetUp]
		public void TestFixtureSetup()
		{
			using (var zippedBundle = CreateZippedTextBundleFromResources(true, false, true))
				_legacyBundle = new TextBundle<DblTextMetadata<DblMetadataLanguage>, DblMetadataLanguage>(zippedBundle.Path);
			using (var zippedBundle = CreateZippedTextBundleFromResources(false, false, true))
				_legacyBundleWithoutLdml = new TextBundle<DblTextMetadata<DblMetadataLanguage>, DblMetadataLanguage>(zippedBundle.Path);
			using (var zippedBundle = CreateZippedTextBundleFromResources())
				_bundle = new TextBundle<DblTextMetadata<DblMetadataLanguage>, DblMetadataLanguage>(zippedBundle.Path);
			using (var zippedBundle = CreateZippedTextBundleFromResources(false))
				_bundleWithoutLdml = new TextBundle<DblTextMetadata<DblMetadataLanguage>, DblMetadataLanguage>(zippedBundle.Path);
		}

		/// <summary>
		/// Tear down test fixture.
		/// </summary>
		[OneTimeTearDown]
		public void TestFixtureTearDown()
		{
			_legacyBundle.Dispose();
			_legacyBundleWithoutLdml.Dispose();
			_bundle.Dispose();
			_bundleWithoutLdml.Dispose();
		}

		/// <summary>
		/// Tests that properties are correctly created in a bundle.
		/// </summary>
		[TestCase(true)]
		[TestCase(false)]
		public void CreateBundle_PropertiesReadCorrectly(bool legacy)
		{
			var bundle = legacy ? _legacyBundle : _bundle;
			Assert.AreEqual("7881095a69332502", bundle.Id);
			Assert.AreEqual("Ri utzilaj tzij re ri kanimajawal Jesucristo", bundle.Name);
			Assert.AreEqual("acr", bundle.LanguageIso);
		}

		/// <summary>
		/// Tests that the stylesheet is loaded correctly from a bundle.
		/// </summary>
		[TestCase(true)]
		[TestCase(false)]
		public void CreateBundle_ProperlyLoadsStylesheet(bool legacy)
		{
			var bundle = legacy ? _legacyBundle : _bundle;
			var stylesheet = bundle.Stylesheet;
			IStyle style = stylesheet.GetStyle("mt1");
			Assert.IsNotNull(style);
			Assert.AreEqual("Cambria", stylesheet.FontFamily);
			Assert.AreEqual(14, stylesheet.FontSizeInPoints);
		}

		/// <summary>
		/// Tests that writing system for a bundle is created correctly.
		/// </summary>
		[TestCase(true)]
		[TestCase(false)]
		public void CreateBundle_ProperlyLoadsWritingSystemDefinition(bool legacy)
		{
			var bundle = legacy ? _legacyBundle : _bundle;
			var ws = bundle.WritingSystemDefinition;
			Assert.IsNotNull(ws);

			Assert.AreEqual(WellKnownSubtags.UnlistedLanguage, ws.LanguageTag);

			// Quotation Marks
			Assert.AreEqual(4, ws.QuotationMarks.Count);
			Assert.AreEqual(""", ws.QuotationMarks[0].Open);
			Assert.AreEqual(""", ws.QuotationMarks[0].Close);
			Assert.AreEqual("―", ws.QuotationMarks[3].Open);
			Assert.AreEqual(QuotationMarkingSystemType.Narrative, ws.QuotationMarks[3].Type);

			Assert.AreEqual("Cambria", ws.DefaultFont.Name);
			Assert.IsFalse(ws.RightToLeftScript);
		}

		/// <summary>
		/// Tests that a book is obtained from a bundle.
		/// </summary>
		[TestCase(true)]
		[TestCase(false)]
		public void TryGetBook(bool legacy)
		{
			var bundle = legacy ? _legacyBundle : _bundle;
			UsxDocument book;
			Assert.IsTrue(bundle.TryGetBook("MAT", out book));
			Assert.AreEqual("MAT", book.BookId);
		}

		[Test]
		public void GetVersification_ValidBundle_ReturnsValidReader()
		{
			using (var reader = _bundle.GetVersification())
			{
				Assert.IsTrue(reader.ReadLine().StartsWith("#"));
			}
		}

		[Test]
		public void GetFonts_BundleWithFont_ReturnsEnumerationWithFont()
		{
			using (var zippedBundle = CreateZippedTextBundleFromResources(false, false, false, true))
				using (var bundle = new TextBundle<DblTextMetadata<DblMetadataLanguage>, DblMetadataLanguage>(zippedBundle.Path))
				{
					var fontInfo = bundle.GetFonts().Single();
					Assert.AreEqual("AppSILI.ttf", fontInfo.Item1);
					Assert.IsTrue(fontInfo.Item2.ReadByte() >= 0);
			}
		}

		[Test]
		public void GetFonts_BundleWithNoFonts_ReturnsEmptyEnumeration()
		{
			Assert.IsFalse(_bundle.GetFonts().Any());
		}

		/// <summary>
		/// Tests that a bundle with an LDML file correctly reports that.
		/// </summary>
		[TestCase(true)]
		[TestCase(false)]
		public void ContainsLdmlFile_FileExists_ReturnsTrue(bool legacy)
		{
			var bundle = legacy ? _legacyBundle : _bundle;
			Assert.IsTrue(bundle.ContainsLdmlFile());
		}

		[Test]
		public void GetLdml_BundleContainsLdmlFile_ReturnsValidReader()
		{
			using (var reader = _bundle.GetLdml())
			{
				reader.ReadLine(); // Skip past ?xml element
				Assert.IsTrue(reader.ReadLine().StartsWith("<ldml"));
			}
		}

		[Test]
		public void GetLdml_BundleDoesNotContainsLdmlFile_ReturnsNull()
		{
			Assert.IsNull(_bundleWithoutLdml.GetLdml());
		}

		/// <summary>
		/// Tests that a bundle without an LDML file correctly reports that.
		/// </summary>
		[TestCase(true)]
		[TestCase(false)]
		public void ContainsLdmlFile_FileDoesNotExist_ReturnsFalse(bool legacy)
		{
			var bundleWithoutLdml = legacy ? _legacyBundleWithoutLdml : _bundleWithoutLdml;
			Assert.IsFalse(bundleWithoutLdml.ContainsLdmlFile());
		}

		/// <summary>
		/// Tests that a bundle with an invalid USX path throws an exception.
		/// </summary>
		[Test]
		public void ContainsInvalidUsxPath_ThrowsApplicationException()
		{
			Assert.Throws<ApplicationException>(() =>
			{
				using (var zippedBundle = CreateZippedTextBundleFromResources(false, true))
				{
					// ReSharper disable once ObjectCreationAsStatement
					new TextBundle<DblTextMetadata<DblMetadataLanguage>, DblMetadataLanguage>(zippedBundle.Path);
				}
			});
		}

		/// <summary>
		/// Helper method for tests to create a zipped text bundle.
		/// </summary>
		public static TempFile CreateZippedTextBundleFromResources(bool includeLdml = true, bool invalidUsxDirectory = false, bool legacyFormat = false, bool includeFont = false)
		{
			TempFile bundle = TempFile.WithExtension(DblBundleFileUtils.kDblBundleExtension);

			using (var englishLds = TempFile.WithFilename("English.lds"))
			using (var metadataXml = TempFile.WithFilename("metadata.xml"))
			using (var stylesXml = TempFile.WithFilename("styles.xml"))
			using (var versificationVrs = TempFile.WithFilename(DblBundleFileUtils.kVersificationFileName))
			using (var ldmlXml = TempFile.WithFilename(DblBundleFileUtils.kLegacyLdmlFileName))
			using (var ttf = TempFile.WithFilename("AppSILI.ttf"))
			using (var matUsx = TempFile.WithFilename("MAT.usx"))
			using (var zip = new ZipFile())
			{
				File.WriteAllText(metadataXml.Path, legacyFormat ? Resources.metadata_xml : Resources.metadataVersion2_1_xml);
				zip.AddFile(metadataXml.Path, string.Empty);

				var subdirectory = legacyFormat ? string.Empty : "release";

				File.WriteAllBytes(englishLds.Path, Resources.English_lds);
				zip.AddFile(englishLds.Path, subdirectory);
				File.WriteAllText(stylesXml.Path, Resources.styles_xml);
				zip.AddFile(stylesXml.Path, subdirectory);
				File.WriteAllBytes(versificationVrs.Path, Resources.versification_vrs);
				zip.AddFile(versificationVrs.Path, subdirectory);
				if (includeLdml)
				{
					File.WriteAllText(ldmlXml.Path, Resources.ldml_xml);
					zip.AddFile(ldmlXml.Path, subdirectory);
				}
				if (includeFont)
				{
					File.WriteAllBytes(ttf.Path,
						(byte[])Resources.ResourceManager.GetObject("AppSILI", CultureInfo.InvariantCulture));
					zip.AddFile(ttf.Path, subdirectory);
				}
				File.WriteAllBytes(matUsx.Path, Resources.MAT_usx);
				zip.AddFile(matUsx.Path, (legacyFormat ? "" : "release/") + (invalidUsxDirectory ? "USX_999" : "USX_1"));
				zip.Save(bundle.Path);
			}

			return bundle;
		}
	}
}


text:
from __future__ import unicode_literals

import datetime
import importlib
import logging
import traceback
import os
import json
import inspect
import collections
import zipfile
import base64

import boto3
import sys
from werkzeug.wrappers import Response

# This file may be copied into a project's root,
# so handle both scenarios.
try:
    from zappa.cli import ZappaCLI
    from zappa.middleware import ZappaWSGIMiddleware
    from zappa.wsgi import create_wsgi_request, common_log
    from zappa.util import parse_s3_url
except ImportError as e:  # pragma: no cover
    from .cli import ZappaCLI
    from .middleware import ZappaWSGIMiddleware
    from .wsgi import create_wsgi_request, common_log
    from .util import parse_s3_url

# Set up logging
logging.basicConfig()
logger = logging.getLogger()
logger.setLevel(logging.INFO)

class WSGIException(Exception):
    """
    This exception is used by the handler to indicate that underlying WSGI app has returned a non-2xx(3xx) code.
    """

    pass

class UncaughtWSGIException(Exception):
    """
    Indicates a problem that happened outside of WSGI app context (and thus wasn't handled by the WSGI app itself)
    while processing a request from API Gateway.
    """

    def __init__(self, message, original=None):
        super(UncaughtWSGIException, self).__init__(message)
        self.original = original

class LambdaHandler(object):
    """
    Singleton for avoiding duplicate setup.

    Pattern provided by @benbangert.
    """

    __instance = None
    settings = None
    settings_name = None
    session = None

    # Application
    app_module = None
    wsgi_app = None
    trailing_slash = False

    def __new__(cls, settings_name="zappa_settings", session=None):
        """Singleton instance to avoid repeat setup"""
        if LambdaHandler.__instance is None:
            LambdaHandler.__instance = object.__new__(cls, settings_name, session)
        return LambdaHandler.__instance

    def __init__(self, settings_name="zappa_settings", session=None):

        # We haven't cached our settings yet, load the settings and app.
        if not self.settings:
            # Loading settings from a python module
            self.settings = importlib.import_module(settings_name)
            self.settings_name = settings_name
            self.session = session

            # Custom log level
            if self.settings.LOG_LEVEL:
                level = logging.getLevelName(self.settings.LOG_LEVEL)
                logger.setLevel(level)

            remote_env = getattr(self.settings, 'REMOTE_ENV', None)
            remote_bucket, remote_file = parse_s3_url(remote_env)

            if remote_bucket and remote_file:
                self.load_remote_settings(remote_bucket, remote_file)

            # Let the system know that this will be a Lambda/Zappa/Stack
            os.environ["SERVERTYPE"] = "AWS Lambda"
            os.environ["FRAMEWORK"] = "Zappa"
            try:
                os.environ["PROJECT"] = self.settings.PROJECT_NAME
                os.environ["STAGE"] = self.settings.API_STAGE
            except Exception:  # pragma: no cover
                pass

            # Set any locally defined env vars
            # Environement variable keys can't be Unicode
            # https://github.com/Miserlou/Zappa/issues/604
            for key in self.settings.ENVIRONMENT_VARIABLES.keys():
                os.environ[str(key)] = self.settings.ENVIRONMENT_VARIABLES[key]

            # Pulling from S3 if given a zip path
            project_zip_path = getattr(self.settings, 'ZIP_PATH', None)
            if project_zip_path:
                self.load_remote_project_zip(project_zip_path)

            # This is a non-WSGI application
            # https://github.com/Miserlou/Zappa/pull/748
            if not hasattr(self.settings, 'APP_MODULE') and not self.settings.DJANGO_SETTINGS:
                self.app_module = None
                wsgi_app_function = None
            # This is probably a normal WSGI app
            elif not self.settings.DJANGO_SETTINGS:
                # The app module
                self.app_module = importlib.import_module(self.settings.APP_MODULE)

                # The application
                wsgi_app_function = getattr(self.app_module, self.settings.APP_FUNCTION)
                self.trailing_slash = False
            # Django gets special treatment.
            else:

                try:  # Support both for tests
                    from zappa.ext.django import get_django_wsgi
                except ImportError:  # pragma: no cover
                    from django_zappa_app import get_django_wsgi

                # Get the Django WSGI app from our extension
                wsgi_app_function = get_django_wsgi(self.settings.DJANGO_SETTINGS)
                self.trailing_slash = True

            self.wsgi_app = ZappaWSGIMiddleware(wsgi_app_function)

    def load_remote_project_zip(self, project_zip_path):
        """
        Puts the project files from S3 in /tmp and adds to path
        """
        project_folder = '/tmp/{0!s}'.format(self.settings.PROJECT_NAME)
        if not os.path.isdir(project_folder):
            # The project folder doesn't exist in this cold lambda, get it from S3
            if not self.session:
                boto_session = boto3.Session()
            else:
                boto_session = self.session

            # Download the zip
            remote_bucket, remote_file = project_zip_path.lstrip('s3://').split('/', 1)
            s3 = boto_session.resource('s3')

            zip_path = '/tmp/{0!s}'.format(remote_file)
            s3.Object(remote_bucket, remote_file).download_file(zip_path)

            # Unzip contents to project folder
            with zipfile.ZipFile(zip_path, 'r') as z:
                z.extractall(path=project_folder)

        # Add to project path
        sys.path.insert(0, project_folder)

        # Change working directory to project folder
        # Related: https://github.com/Miserlou/Zappa/issues/702
        os.chdir(project_folder)
        return True

    def load_remote_settings(self, remote_bucket, remote_file):
        """
        Attempt to read a file from s3 containing a flat json object. Adds each
        key->value pair as environment variables. Helpful for keeping
        sensitiZve or stage-specific configuration variables in s3 instead of
        version control.
        """
        if not self.session:
            boto_session = boto3.Session()
        else:
            boto_session = self.session

        s3 = boto_session.resource('s3')
        try:
            remote_env_object = s3.Object(remote_bucket, remote_file).get()
        except Exception as e:  # pragma: no cover
            # catch everything aws might decide to raise
            print('Could not load remote settings file.', e)
            return

        try:
            content = remote_env_object['Body'].read().decode('utf-8')
        except Exception as e:  # pragma: no cover
            # catch everything aws might decide to raise
            print('Exception while reading remote settings file.', e)
            return

        try:
            settings_dict = json.loads(content)
        except (ValueError, TypeError):  # pragma: no cover
            print('Failed to parse remote settings!')
            return

        # add each key-value to environment - overwrites existing keys!
        for key, value in settings_dict.items():
            if self.settings.LOG_LEVEL == "DEBUG":
                print('Adding {} -> {} to environment'.format(
                    key,
                    value
                ))
            # Environement variable keys can't be Unicode
            # https://github.com/Miserlou/Zappa/issues/604
            try:
                os.environ[str(key)] = value
            except Exception:
                if self.settings.LOG_LEVEL == "DEBUG":
                    print("Environment variable keys must be non-unicode!")

    @staticmethod
    def import_module_and_get_function(whole_function):
        """
        Given a modular path to a function, import that module
        and return the function.
        """
        module, function = whole_function.rsplit('.', 1)
        app_module = importlib.import_module(module)
        app_function = getattr(app_module, function)
        return app_function

    @classmethod
    def lambda_handler(cls, event, context):  # pragma: no cover
        handler = cls()
        exception_handler = handler.settings.EXCEPTION_HANDLER
        try:
            return handler.handler(event, context)
        except WSGIException as wsgi_ex:
            # do nothing about LambdaExceptions since those are already handled (or should be handled by the WSGI app).
            raise wsgi_ex
        except UncaughtWSGIException as u_wsgi_ex:
            # hand over original error to exception handler, since the exception happened outside of WSGI app context
            # (it wasn't propertly processed by the app itself)
            cls._process_exception(exception_handler=exception_handler,
                                   event=event, context=context, exception=u_wsgi_ex.original)
            # raise unconditionally since it's an API gateway error (i.e. client expects to see a 500 and execution
            # won't be retried).
            raise u_wsgi_ex
        except Exception as ex:
            exception_processed = cls._process_exception(exception_handler=exception_handler,
                                                         event=event, context=context, exception=ex)
            if not exception_processed:
                # Only re-raise exception if handler directed so. Allows handler to control if lambda has to retry
                # an event execution in case of failure.
                raise

    @classmethod
    def _process_exception(cls, exception_handler, event, context, exception):
        exception_processed = False
        if exception_handler:
            try:
                handler_function = cls.import_module_and_get_function(exception_handler)
                exception_processed = handler_function(exception, event, context)
            except Exception as cex:
                logger.error(msg='Failed to process exception via custom handler.')
                print(cex)
        return exception_processed

    @staticmethod
    def run_function(app_function, event, context):
        """
        Given a function and event context,
        detect signature and execute, returning any result.
        """
        args, varargs, keywords, defaults = inspect.getargspec(app_function)
        num_args = len(args)
        if num_args == 0:
            result = app_function(event, context) if varargs else app_function()
        elif num_args == 1:
            result = app_function(event, context) if varargs else app_function(event)
        elif num_args == 2:
            result = app_function(event, context)
        else:
            raise RuntimeError("Function signature is invalid. Expected a function that accepts at most "
                               "2 arguments or varargs.")
        return result

    def update_certificate(self):
        """
        Call 'certify' locally.
        """
        import boto3
        session = boto3.Session()

        z_cli = ZappaCLI()
        z_cli.api_stage = self.settings.API_STAGE
        z_cli.load_settings(session=session)
        z_cli.certify()

        return

    def get_function_for_aws_event(self, record):
        """
        Get the associated function to execute for a triggered AWS event

        Support S3, SNS, DynamoDB and kinesis events
        """
        if 's3' in record:
            return record['s3']['configurationId'].split(':')[-1]

        arn = None
        if 'Sns' in record:
            arn = record['Sns'].get('TopicArn')
        elif 'dynamodb' in record or 'kinesis' in record:
            arn = record.get('eventSourceARN')

        if arn:
            return self.settings.AWS_EVENT_MAPPING.get(arn)

        return None

    def handler(self, event, context):
        """
        An AWS Lambda function which parses specific API Gateway input into a
        WSGI request, feeds it to our WSGI app, procceses the response, and returns
        that back to the API Gateway.

        """
        settings = self.settings

        # If in DEBUG mode, log all raw incoming events.
        if settings.DEBUG:
            logger.debug('Zappa Event: {}'.format(event))

        # This is the result of a keep alive, recertify
        # or scheduled event.
        if event.get('detail-type') == u'Scheduled Event':

            whole_function = event['resources'][0].split('/')[-1].split('-')[-1]

            # This is a scheduled function.
            if '.' in whole_function:
                app_function = self.import_module_and_get_function(whole_function)

                # Execute the function!
                return self.run_function(app_function, event, context)

            # Else, let this execute as it were.

        # This is a direct command invocation.
        elif event.get('command', None):

            whole_function = event['command']
            app_function = self.import_module_and_get_function(whole_function)
            result = self.run_function(app_function, event, context)
            print("Result of %s:" % whole_function)
            print(result)
            return result

        # This is a direct, raw python invocation.
        # It's _extremely_ important we don't allow this event source
        # to be overriden by unsanitized, non-admin user input.
        elif event.get('raw_command', None):

            raw_command = event['raw_command']
            exec(raw_command)
            return

        # This is a Django management command invocation.
        elif event.get('manage', None):

            from django.core import management

            try:  # Support both for tests
                from zappa.ext.django_zappa import get_django_wsgi
            except ImportError as e:  # pragma: no cover
                from django_zappa_app import get_django_wsgi

            # Get the Django WSGI app from our extension
            # We don't actually need the function,
            # but we do need to do all of the required setup for it.
            app_function = get_django_wsgi(self.settings.DJANGO_SETTINGS)

            # Couldn't figure out how to get the value into stdout with StringIO..
            # Read the log for now. :[]
            management.call_command(*event['manage'].split(' '))
            return {}

        # This is an AWS-event triggered invokation.
        elif event.get('Records', None):

            records = event.get('Records')
            result = None
            whole_function = self.get_function_for_aws_event(records[0])
            if whole_function:
                app_function = self.import_module_and_get_function(whole_function)
                result = self.run_function(app_function, event, context)
                logger.debug(result)
            else:
                logger.error("Cannot find a function to process the triggered event.")
            return result

        # This is an API Gateway authorizer event
        elif event.get('type') == u'TOKEN':
            whole_function = self.settings.AUTHORIZER_FUNCTION
            if whole_function:
                app_function = self.import_module_and_get_function(whole_function)
                policy = self.run_function(app_function, event, context)
                return policy
            else:
                logger.error("Cannot find a function to process the authorization request.")
                raise Exception('Unauthorized')

        # Normal web app flow
        try:
            # Timing
            time_start = datetime.datetime.now()

            # This is a normal HTTP request
            if event.get('httpMethod', None):

                if settings.DOMAIN:
                    # If we're on a domain, we operate normally
                    script_name = ''
                else:
                    # But if we're not, then our base URL
                    # will be something like
                    # https://blahblahblah.execute-api.us-east-1.amazonaws.com/dev
                    # So, we need to make sure the WSGI app knows this.
                    script_name = '/' + settings.API_STAGE

                # Create the environment for WSGI and handle the request
                environ = create_wsgi_request(
                    event,
                    script_name=script_name,
                    trailing_slash=self.trailing_slash,
                    binary_support=settings.BINARY_SUPPORT
                )

                # We are always on https on Lambda, so tell our wsgi app that.
                environ['HTTPS'] = 'on'
                environ['wsgi.url_scheme'] = 'https'
                environ['lambda.context'] = context

                # Execute the application
                response = Response.from_app(self.wsgi_app, environ)

                # This is the object we're going to return.
                # Pack the WSGI response into our special dictionary.
                zappa_returndict = dict()

                if response.data:
                    if settings.BINARY_SUPPORT:
                        if not response.mimetype.startswith("text/") \
                            or response.mimetype != "application/json":
                                zappa_returndict['body'] = base64.b64encode(response.data)
                                zappa_returndict["isBase64Encoded"] = "true"
                        else:
                            zappa_returndict['body'] = response.data
                    else:
                        zappa_returndict['body'] = response.data

                zappa_returndict['statusCode'] = response.status_code
                zappa_returndict['headers'] = {}
                for key, value in response.headers:
                    zappa_returndict['headers'][key] = value

                # Calculate the total response time,
                # and log it in the Common Log format.
                time_end = datetime.datetime.now()
                delta = time_end - time_start
                response_time_ms = delta.total_seconds() * 1000
                response.content = response.data
                common_log(environ, response, response_time=response_time_ms)

                return zappa_returndict
        except Exception as e:  # pragma: no cover

            # Print statements are visible in the logs either way
            print(e)
            exc_info = sys.exc_info()
            message = ('An uncaught exception happened while servicing this request. '
                       'You can investigate this with the `zappa tail` command.')

            # If we didn't even build an app_module, just raise.
            if not settings.DJANGO_SETTINGS:
                try:
                    self.app_module
                except NameError as ne:
                    message = 'Failed to import module: {}'.format(ne.message)

            # Return this unspecified exception as a 500, using template that API Gateway expects.
            content = collections.OrderedDict()
            content['statusCode'] = 500
            body = {'message': message}
            if settings.DEBUG:  # only include traceback if debug is on.
                body['traceback'] = traceback.format_exception(*exc_info)  # traceback as a list for readability.
            content['body'] = json.dumps(body, sort_keys=True, indent=4).encode('utf-8')
            return content

def lambda_handler(event, context):  # pragma: no cover
    return LambdaHandler.lambda_handler(event, context)

def keep_warm_callback(event, context):
    """Method is triggered by the CloudWatch event scheduled when keep_warm setting is set to true."""
    lambda_handler(event={}, context=context)  # overriding event with an empty one so that web app initialization will
    # be triggered.

def certify_callback(event, context):
    """
    Load our LH settings and update our cert.
    """
    lh = LambdaHandler()
    return lh.update_certificate()


text:
from importlib import import_module
import os
import tempfile

from django import conf
from django.contrib import admin
from django.test import TestCase, override_settings
from django.utils.autoreload import gen_filenames
from django.utils._os import upath

LOCALE_PATH = os.path.join(os.path.dirname(__file__), 'locale')

class TestFilenameGenerator(TestCase):
    def setUp(self):
        # Empty cached variables
        from django.utils import autoreload
        autoreload._cached_modules = set()
        autoreload._cached_filenames = []

    def test_django_locales(self):
        """
        Test that gen_filenames() also yields the built-in django locale files.
        """
        filenames = list(gen_filenames())
        self.assertIn(os.path.join(os.path.dirname(conf.__file__), 'locale',
                                   'nl', 'LC_MESSAGES', 'django.mo'),
                      filenames)

    @override_settings(LOCALE_PATHS=(LOCALE_PATH,))
    def test_locale_paths_setting(self):
        """
        Test that gen_filenames also yields from LOCALE_PATHS locales.
        """
        filenames = list(gen_filenames())
        self.assertIn(os.path.join(LOCALE_PATH, 'nl', 'LC_MESSAGES', 'django.mo'),
                      filenames)

    @override_settings(INSTALLED_APPS=[])
    def test_project_root_locale(self):
        """
        Test that gen_filenames also yields from the current directory (project
        root).
        """
        old_cwd = os.getcwd()
        os.chdir(os.path.dirname(__file__))
        try:
            filenames = list(gen_filenames())
            self.assertIn(
                os.path.join(LOCALE_PATH, 'nl', 'LC_MESSAGES', 'django.mo'),
                filenames)
        finally:
            os.chdir(old_cwd)

    @override_settings(INSTALLED_APPS=['django.contrib.admin'])
    def test_app_locales(self):
        """
        Test that gen_filenames also yields from locale dirs in installed apps.
        """
        filenames = list(gen_filenames())
        self.assertIn(os.path.join(os.path.dirname(admin.__file__), 'locale',
                                   'nl', 'LC_MESSAGES', 'django.mo'),
                      filenames)

    @override_settings(USE_I18N=False)
    def test_no_i18n(self):
        """
        If i18n machinery is disabled, there is no need for watching the
        locale files.
        """
        filenames = list(gen_filenames())
        self.assertNotIn(
            os.path.join(os.path.dirname(conf.__file__), 'locale', 'nl',
                         'LC_MESSAGES', 'django.mo'),
            filenames)

    def test_only_new_files(self):
        """
        When calling a second time gen_filenames with only_new = True, only
        files from newly loaded modules should be given.
        """
        list(gen_filenames())
        from fractions import Fraction  # NOQA
        filenames2 = list(gen_filenames(only_new=True))
        self.assertEqual(len(filenames2), 1)
        self.assertTrue(filenames2[0].endswith('fractions.py'))
        self.assertFalse(any(f.endswith('.pyc') for f in gen_filenames()))

    def test_deleted_removed(self):
        fd, filepath = tempfile.mkstemp(dir=os.path.dirname(upath(__file__)), suffix='.py')
        try:
            _, filename = os.path.split(filepath)
            import_module('.%s' % filename.replace('.py', ''), package='utils_tests')
            self.assertIn(filepath, gen_filenames())
        finally:
            os.close(fd)
            os.remove(filepath)
        self.assertNotIn(filepath, gen_filenames())


text:
namespace oless {
	namespace excel {
		namespace records {

			class CrErrRecord : public Record {
			public:
				CrErrRecord(unsigned short type, std::vector<uint8_t> data) : Record(type, data) {

				}
			};
		}
	}
}


text:
<?php

namespace Torine\WorkflowBundle\Service\Run;

/**
 * @author Rémi Alvado <remi.alvado@gmail.com>
 */
class RiakDao implements DaoInterface
{

    /**
     * {@inheritDoc}
     */
    public function save($run)
    {
        return $this->runBucket->put(array($run->getId() => $run));
    }

    /**
     * {@inheritDoc}
     */
    public function get($runId) {
        return $this->runBucket->uniq($runId)->getContent();
    }

    /**
     * {@inheritDoc}
     */
    public function delete($runId) {
        return $this->runBucket->delete($runId);
    }

    public function __construct($riakCluster)
    {
        $this->runBucket = $riakCluster->getBucket("workflow_run");
    }

    /**
     * @var \Kbrw\RiakBundle\Model\Bucket\Bucket
     */
    public $runBucket;
}