text:
#include "HCI557Common.h"

CameraTypes _cam_type = TRACKBALL;

/* A trackball to move and rotate the camera view */
Trackball trackball( WINDOW_WIDTH, WINDOW_HEIGHT, 0.4f, true, true );

/*!
 A new camera manipulator object
 */
CameraManipulator cam_manipulator(WINDOW_WIDTH, WINDOW_HEIGHT, 0.4f);

// variable too keep the glsl version.
int glsl_major = 0 , glsl_minor = 0;

// this is a helper variable to allow us to change the texture blend model
int g_change_texture_blend;

/*!
 Return the glsl major / minor version.
 */
int GLSLMajor(void)
{
    return glsl_major;
}

int GLSLMinor(void)
{
    return glsl_minor;
}

/*!
 Returns the camera matrix of the current active camera object
 */
glm::mat4 GetCurrentCameraMatrix(void)
{
    switch (_cam_type) {
        case CAMERA_MANIPULATOR:
            return cam_manipulator.getRotationMatrix();
            break;
        case TRACKBALL:
            return trackball.getRotationMatrix();
        default:
            break;
    }
}

/**
 Returns the translation matrix of the current camera
 */
glm::vec3 GetCurrentCameraTranslation(void)
{
    switch (_cam_type) {
    case CAMERA_MANIPULATOR:
        return cam_manipulator.getTranslationVec();
        break;
    case TRACKBALL: // constant distance
            return glm::vec3(0.0f,0.0f,65.0f);

    }
}

/**
 @brief Change the camera manipulator type
 @param m - the camera type.
 */
void SetCameraManipulator(CameraTypes m)
{
    _cam_type = m;
}

/* In GLFW mouse callback */
void mouseButtonCallback( GLFWwindow * window, int button, int action, int mods ){

    trackball.mouseButtonCallback( window, button, action, mods );

    cam_manipulator.camera_MouseButton_Callback(window, button, action, mods);
}

/* In GLFW curser callback */
void cursorCallback( GLFWwindow *window, double x, double y ) {

    trackball.cursorCallback( window, x, y );

    cam_manipulator.camera_MouseCursor_Callack(window, x, y );

}

// This is the callback we'll be registering with GLFW for errors.
// It'll just print out the error to the STDERR stream.
void error_callback(int error, const char* description) {
    fputs(description, stderr);
}

// This is the callback we'll be registering with GLFW for keyboard handling.
// The only thing we're doing here is setting up the window to close when we press ESC
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
    if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
    {
        glfwSetWindowShouldClose(window, GL_TRUE);
    }
    else if(key == 84 && action == GLFW_PRESS) // key t
    {
        g_change_texture_blend++;
        g_change_texture_blend = g_change_texture_blend%3;

    }
}

/*!
 This function initializes the GLFW window
 */
// The handle to the window object
GLFWwindow* initWindow(void)
{
    // The handle to the window object
    GLFWwindow*         window = NULL;

    // Initialize GLFW, and if it fails to initialize for any reason, print it out to STDERR.
    if (!glfwInit()) {
        fprintf(stderr, "Failed initialize GLFW.");
        exit(EXIT_FAILURE);
    }

    // Set the error callback, as mentioned above.
    glfwSetErrorCallback(error_callback);

    // Set up OpenGL options.
    // Use GLFW verion 3.3,
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    // Create a window to put our stuff in.
    window = glfwCreateWindow(800, 600, "OpenGL Window for 557", NULL, NULL);

    // If the window fails to be created, print out the error, clean up GLFW and exit the program.
    if( window == NULL ){
        cout <<  "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible." << endl;
        glfwTerminate();
        system("pause");
        exit(-1);
    }

    // Use the window as the current context (everything that's drawn will be place in this window).
    glfwMakeContextCurrent(window);

    // Set the keyboard callback so that when we press ESC, it knows what to do.
    glfwSetKeyCallback(window, key_callback);

    // set the cursor callback
    glfwSetCursorPosCallback(window, cursorCallback);
    glfwSetMouseButtonCallback(window, mouseButtonCallback);

    return window;
}

/*!
 This function initializes glew
 */
bool initGlew(void)
{

    // Makes sure all extensions will be exposed in GLEW and initialize GLEW.
    glewExperimental = GL_TRUE;

    // Initialize GLEW
    if (glewInit() != GLEW_OK) {
        cout <<  "Failed to initialize GLEW\n" << endl;
        system("pause");
        return -1;
    }

    cout <<  "OpenGL version supported by this platform " << glGetString(GL_VERSION) <<  endl;

    // Check the GLSL version
    const char *verstr = (const char *) glGetString(GL_SHADING_LANGUAGE_VERSION);
    cout << "GLSL version supported by this platform " << string (verstr) << endl;
    sscanf(verstr, "%d.%d", &glsl_major, &glsl_minor);

    return true;
}


text:
package org.jbpm.simulation;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import org.eclipse.bpmn2.FlowElement;
import org.eclipse.bpmn2.SequenceFlow;

public class PathContext {

    public enum Type {
        ROOT,
        ACTIVE,
        COMPLETED,
        TEMP;
    }

    private Set<FlowElement> pathElements = new HashSet<FlowElement>();
    private Type type;
    private boolean canBeFinished = true;
    private boolean locked = false;
    private String id;
    private int canBeFinishedCounter = 0;
    private String pathId;

    protected int getCanBeFinishedCounter() {
        return canBeFinishedCounter;
    }

    protected void setCanBeFinishedCounter(int canBeFinishedCounter) {
        this.canBeFinishedCounter = canBeFinishedCounter;
    }

    public PathContext() {
    	this.id = String.valueOf(UUID.randomUUID());
    	this.setType(Type.ROOT);
    }

    public PathContext(Type type) {
    	this.id = String.valueOf(UUID.randomUUID());
        this.setType(type);
    }

    public void addPathElement(FlowElement element) {
        if (!locked) {
            this.pathElements.add(element);
        }
    }

    public void removePathElement(FlowElement element) {
        if (!locked) {
            this.pathElements.remove(element);
        }
    }

    public void addAllPathElement(List<SequenceFlow> elements) {
        if (!locked) {
            this.pathElements.addAll(elements);
        }
    }

    public Set<FlowElement> getPathElements() {
        return this.pathElements;
    }

    public void setPathElements(Set<FlowElement> pathElements) {
        this.pathElements = pathElements;
    }

    public boolean isCanBeFinished() {
        return canBeFinished;
    }

    public void setCanBeFinishedNoIncrement(boolean canBeFinished) {
        this.canBeFinished = canBeFinished;
    }

    public void setCanBeFinished(boolean canBeFinished) {
        if (canBeFinished) {

            if (canBeFinishedCounter == 1) {
                this.canBeFinished = true;
            }
            canBeFinishedCounter--;
        } else {

            if (canBeFinishedCounter == 0) {
                this.canBeFinished = false;
            }
            canBeFinishedCounter++;

        }
    }

    public Type getType() {
        return type;
    }

    public void setType(Type type) {
        this.type = type;
    }

    public boolean isLocked() {
        return locked;
    }

    public void setLocked(boolean locked) {
        this.locked = locked;
    }

    public String getId() {
    	return this.id;
    }

    public String getPathId() {
        return pathId;
    }

    public void setPathId(String pathId) {
        this.pathId = pathId;
    }
}

redpajama_set_name: RedPajamaGithub


text:
// SampSharp
// Copyright 2022 Tim Potze
//
// 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.

namespace SampSharp.Core.Hosting;

/// Contains error codes used by Pawn AMX.
public enum AmxError
{
    /// No error.
    None,

    /// Exit code: forced exit.
    Exit,

    /// Exit code: assertion failed.
    Assert,

    /// Exit code: stack/heap collision.
    Stackerr,

    /// Exit code: index out of bounds.
    Bounds,

    /// Exit code: invalid memory access.
    Memaccess,

    /// Exit code: invalid instruction.
    Invinstr,

    /// Exit code: stack underflow.
    Stacklow,

    /// Exit code: heap underflow.
    Heaplow,

    /// Exit code: no callback, or invalid callback.
    Callback,

    /// Exit code: native function failed
    Native,

    /// Exit code: divide by zero
    Divide,

    /// Exit code: go into sleep mode - code can be restarted
    Sleep,

    /// Exit code: invalid state for this access
    Invstate,

    /// Out of memory.
    Memory = 16,

    /// Invalid file format.
    Format,

    /// File is for a newer version of the AMX.
    Version,

    /// Function not found.
    Notfound,

    /// Invalid index parameter (bad entry point).
    Index,

    /// Debugger cannot run.
    Debug,

    /// AMX not initialized (or doubly initialized).
    Init,

    /// Unable to set user data field (table full)
    Userdata,

    /// Cannot initialize the JIT.
    InitJit,

    /// Parameter error.
    Params,

    /// Domain error, expression result does not fit in range.
    Domain,

    /// General error (unknown or unspecific error).
    General,
}


text:
package parquet.filter2.compat;

import java.util.ArrayList;
import java.util.List;

import parquet.filter2.compat.FilterCompat.Filter;
import parquet.filter2.compat.FilterCompat.NoOpFilter;
import parquet.filter2.compat.FilterCompat.Visitor;
import parquet.filter2.predicate.FilterPredicate;
import parquet.filter2.predicate.SchemaCompatibilityValidator;
import parquet.filter2.statisticslevel.StatisticsFilter;
import parquet.hadoop.metadata.BlockMetaData;
import parquet.schema.MessageType;

import static parquet.Preconditions.checkNotNull;

/**
 * Given a {@link Filter} applies it to a list of BlockMetaData (row groups)
 * If the Filter is an {@link parquet.filter.UnboundRecordFilter} or the no op filter,
 * no filtering will be performed.
 */
public class RowGroupFilter implements Visitor<List<BlockMetaData>> {
  private final List<BlockMetaData> blocks;
  private final MessageType schema;

  public static List<BlockMetaData> filterRowGroups(Filter filter, List<BlockMetaData> blocks, MessageType schema) {
    checkNotNull(filter, "filter");
    return filter.accept(new RowGroupFilter(blocks, schema));
  }

  private RowGroupFilter(List<BlockMetaData> blocks, MessageType schema) {
    this.blocks = checkNotNull(blocks, "blocks");
    this.schema = checkNotNull(schema, "schema");
  }

  @Override
  public List<BlockMetaData> visit(FilterCompat.FilterPredicateCompat filterPredicateCompat) {
    FilterPredicate filterPredicate = filterPredicateCompat.getFilterPredicate();

    // check that the schema of the filter matches the schema of the file
    SchemaCompatibilityValidator.validate(filterPredicate, schema);

    List<BlockMetaData> filteredBlocks = new ArrayList<BlockMetaData>();

    for (BlockMetaData block : blocks) {
      if (!StatisticsFilter.canDrop(filterPredicate, block.getColumns())) {
        filteredBlocks.add(block);
      }
    }

    return filteredBlocks;
  }

  @Override
  public List<BlockMetaData> visit(FilterCompat.UnboundRecordFilterCompat unboundRecordFilterCompat) {
    return blocks;
  }

  @Override
  public List<BlockMetaData> visit(NoOpFilter noOpFilter) {
    return blocks;
  }
}


text:
class ShippingLine < ActiveRecord::Base
  belongs_to :invoice, touch: true
  has_many :discount_applications, class_name: "ShippingLineDiscountApplication"
end

class ShippingLineDiscountApplication < ActiveRecord::Base
  belongs_to :shipping_line
  belongs_to :discount
end


text:
<?php

namespace MattJanssen\ApiResponseBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\Config\Definition\Builder\NodeBuilder;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * API Response Bundle Configuration
 *
 * @author Matt Janssen <matt@mattjanssen.com>
 */
class Configuration implements ConfigurationInterface
{
    const SERIALIZER_ARRAY = 'array';
    const SERIALIZER_JSON_ENCODE = 'json_encode';
    const SERIALIZER_JSON_GROUP_ENCODE = 'json_group_encode';
    const SERIALIZER_JMS_SERIALIZER = 'jms_serializer';

    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('api_response');

        $this->buildConfigNode(
            $rootNode->children()
                ->arrayNode('defaults')
                    ->children()
        );

        $this->buildConfigNode(
            $rootNode->children()
                ->arrayNode('paths')
                    ->useAttributeAsKey('name')
                    ->prototype('array')
                        ->children()
                            ->scalarNode('pattern')->end()
                            ->scalarNode('prefix')->end()
        );

        return $treeBuilder;
    }

    /**
     * @param NodeBuilder $nodeBuilder
     *
     * @return ArrayNodeDefinition
     */
    private function buildConfigNode(NodeBuilder $nodeBuilder)
    {
        return $nodeBuilder
            ->scalarNode('serializer')->end()
            ->variableNode('serialize_groups')->end()
            ->scalarNode('cors_allow_origin_regex')->end()
            ->arrayNode('cors_allow_headers')
                ->prototype('scalar')->end()
            ->end()
            ->integerNode('cors_max_age')->end()
        ;
    }
}


text:
//
//  BackgroundArtworkDisplayView.h
//  Pinna
//
//  Created by Kevin MacWhinnie on 12/27/11.
//  Copyright (c) 2011 Roundabout Software, LLC. All rights reserved.
//

#import <Cocoa/Cocoa.h>

@interface BackgroundArtworkDisplayView : NSView
{
	BOOL mIsMouseInView;

	/** Properties **/

	///The storage for `mImage`
	NSImage *mImage;
}

#pragma mark Properties

@property (nonatomic, copy) NSImage *image;

@property (nonatomic, readonly) BOOL isMouseInView;

@end


text:
// KeyEventArgs.cs

#region Using Statements

using System;
using Microsoft.Xna.Framework.Input;

#endregion

namespace Sandbox.Events
{
    public class KeyEventArgs : InputEventArgs
    {
        public Keys Key { get; set; }

        public KeyEventArgs(TimeSpan p_Timestamp) : base(p_Timestamp) { }
    }
}


text:
package com.newsblur.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.newsblur.R;
import com.newsblur.activity.Profile;
import com.newsblur.domain.Feed;
import com.newsblur.domain.SocialFeed;
import com.newsblur.domain.UserDetails;
import com.newsblur.domain.ActivityDetails;
import com.newsblur.domain.ActivityDetails.Category;
import com.newsblur.network.APIManager;
import com.newsblur.util.FeedSet;
import com.newsblur.util.FeedUtils;
import com.newsblur.util.UIUtils;
import com.newsblur.view.ActivityDetailsAdapter;
import com.newsblur.view.ProgressThrobber;

public abstract class ProfileActivityDetailsFragment extends Fragment implements AdapterView.OnItemClickListener {

    private ListView activityList;
    private ActivityDetailsAdapter adapter;
    protected APIManager apiManager;
    private UserDetails user;
    private ProgressThrobber footerProgressView;
    private ProgressThrobber loadingProgressView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        apiManager = new APIManager(getActivity());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View v = inflater.inflate(R.layout.fragment_profileactivity, null);
        activityList = (ListView) v.findViewById(R.id.profile_details_activitylist);

        loadingProgressView = (ProgressThrobber) v.findViewById(R.id.empty_view_loading_throb);
        loadingProgressView.setColors(UIUtils.getColor(getActivity(), R.color.refresh_1),
                                      UIUtils.getColor(getActivity(), R.color.refresh_2),
                                      UIUtils.getColor(getActivity(), R.color.refresh_3),
                                      UIUtils.getColor(getActivity(), R.color.refresh_4));
        activityList.setFooterDividersEnabled(false);
        activityList.setEmptyView(v.findViewById(R.id.empty_view));

        View footerView = inflater.inflate(R.layout.row_loading_throbber, null);
        footerProgressView = (ProgressThrobber) footerView.findViewById(R.id.itemlist_loading_throb);
        footerProgressView.setColors(UIUtils.getColor(getActivity(), R.color.refresh_1),
                                     UIUtils.getColor(getActivity(), R.color.refresh_2),
                                     UIUtils.getColor(getActivity(), R.color.refresh_3),
                                     UIUtils.getColor(getActivity(), R.color.refresh_4));
        activityList.addFooterView(footerView, null, false);

        if (adapter != null) {
            displayActivities();
        }
        activityList.setOnScrollListener(new EndlessScrollListener());
        activityList.setOnItemClickListener(this);
        return v;
    }

    public void setUser(Context context, UserDetails user) {
        this.user = user;
        adapter = createAdapter(context, user);
        displayActivities();
    }

    protected abstract ActivityDetailsAdapter createAdapter(Context context, UserDetails user);

    private void displayActivities() {
        activityList.setAdapter(adapter);
        loadPage(1);
    }

    private void loadPage(final int pageNumber) {
        new AsyncTask<Void, Void, ActivityDetails[]>() {

            @Override
            protected void onPreExecute() {
                loadingProgressView.setVisibility(View.VISIBLE);
                footerProgressView.setVisibility(View.VISIBLE);
            }

            @Override
            protected ActivityDetails[] doInBackground(Void... voids) {
                // For the logged in user user.userId is null.
                // From the user intent user.userId is the number while user.id is prefixed with social:
                String id = user.userId;
                if (id == null) {
                    id = user.id;
                }
                if (id == null) {
                    return null;
                }
                return loadActivityDetails(id, pageNumber);
            }

            @Override
            protected void onPostExecute(ActivityDetails[] result) {
                if (result == null) {
                    com.newsblur.util.Log.w(getClass().getName(), "couldn't load page from API");
                    return;
                }
                if (pageNumber == 1 && result.length == 0) {
                    View emptyView = activityList.getEmptyView();
                    TextView textView = (TextView) emptyView.findViewById(R.id.empty_view_text);
                    textView.setText(R.string.profile_no_interactions);
                }
                for (ActivityDetails activity : result) {
                    adapter.add(activity);
                }
                adapter.notifyDataSetChanged();
                loadingProgressView.setVisibility(View.GONE);
                footerProgressView.setVisibility(View.GONE);
            }
        }.execute();
    }

    protected abstract ActivityDetails[] loadActivityDetails(String id, int pageNumber);

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        ActivityDetails activity = adapter.getItem(position);
        Context context = getActivity();
        if (activity.category == Category.FOLLOW) {
            Intent i = new Intent(context, Profile.class);
            i.putExtra(Profile.USER_ID, activity.withUserId);
            context.startActivity(i);
        } else if (activity.category == Category.FEED_SUBSCRIPTION) {
            Feed feed = FeedUtils.getFeed(activity.feedId);
            if (feed == null) {
                Toast.makeText(context, R.string.profile_feed_not_available, Toast.LENGTH_SHORT).show();
            } else {
                /* TODO: starting the feed view activity also requires both a feedset and a folder name
                   in order to properly function.  the latter, in particular, we could only guess at from
                   the info we have here.  at best, we would launch a feed view with somewhat unpredictable
                   delete behaviour. */
                //Intent intent = new Intent(context, FeedItemsList.class);
                //intent.putExtra(FeedItemsList.EXTRA_FEED, feed);
                //context.startActivity(intent);
            }
        } else if (activity.category == Category.STAR) {
            UIUtils.startReadingActivity(FeedSet.allSaved(), activity.storyHash, context);
        } else if (isSocialFeedCategory(activity)) {
            // Strip the social: prefix from feedId
            String socialFeedId = activity.feedId.substring(7);
            SocialFeed feed = FeedUtils.getSocialFeed(socialFeedId);
            if (feed == null) {
                Toast.makeText(context, R.string.profile_do_not_follow, Toast.LENGTH_SHORT).show();
            } else {
                UIUtils.startReadingActivity(FeedSet.singleSocialFeed(feed.userId, feed.username), activity.storyHash, context);
            }
        }
    }

    private boolean isSocialFeedCategory(ActivityDetails activity) {
        return activity.storyHash != null && (activity.category == Category.COMMENT_LIKE ||
                                              activity.category == Category.COMMENT_REPLY ||
                                              activity.category == Category.REPLY_REPLY ||
                                              activity.category == Category.SHARED_STORY);
    }

    /**
     * Detects when user is close to the end of the current page and starts loading the next page
     * so the user will not have to wait (that much) for the next entries.
     *
     * @author Ognyan Bankov
     *         <p/>
     *         https://github.com/ogrebgr/android_volley_examples/blob/master/src/com/github/volley_examples/Act_NetworkListView.java
     */
    public class EndlessScrollListener implements AbsListView.OnScrollListener {
        // how many entries earlier to start loading next page
        private int visibleThreshold = 5;
        private int currentPage = 1;
        private int previousTotal = 0;
        private boolean loading = true;

        public EndlessScrollListener() {
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem,
                             int visibleItemCount, int totalItemCount) {
            if (loading) {
                if (totalItemCount > previousTotal) {
                    loading = false;
                    previousTotal = totalItemCount;
                    currentPage++;
                }
            }
            if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
                // I load the next page of gigs using a background task,
                // but you can call any function here.
                loadPage(currentPage);
                loading = true;
            }
        }

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {

        }
    }
}


text:
import _ from 'lodash';
import { combineReducers } from 'redux';
import { APP_LAYOUT_CHANGE, APP_LAYOUT_INIT } from './constants';

const initState = 'SHCF';

const layout = (state = initState, action = {}) => {
  switch (action.type) {
  case APP_LAYOUT_INIT: {
    return _.get(action, ['payload'], state);
  }
  case APP_LAYOUT_CHANGE: {
    return _.get(action, ['payload'], state);
  }
  default:
    return state;
  }
};

const setting = combineReducers({
  layout
});
export default setting;


text:
/*
 * File:   NewProjectPage_1.h
 * Module: NewProject
 * Author: James Kuczynski
 * Email: jkuczyns@cs.uml.edu
 * File Description:
 *
 * Created on April 22, 2015, 12:25 AM
 */

#ifndef NEW_PROJECT_H
#define	NEW_PROJECT_H

#include <QWidget>
#include <QListWidget>
#include <QPushButton>
#include <QStringList>
#include <QByteArray>
#include <QFile>
#include <QIcon>
#include <QProcess>
#include <QString>
#include <QGridLayout>
#include <QHBoxLayout>

#include <iostream>

#include "RosEnv.h"
#include "NewProjectPage_1.h"
#include "NewProjectPage_2.h"
#include "NewProjectPage_3.h"
#include "NewProjectPage_4.h"
#include "RFile.h"
#include "FileTreeGui.h"
#include "WindowsConsoleText.h"
#include "UnixConsoleText.h"

#ifdef _WIN32
namespace cct = WindowsConsoleText;
#elif __APPLE
namespace cct = UnixConsoleText;
#elif __linux
namespace cct = UnixConsoleText;
#endif

using namespace std;

class NewProjectGui : public QWidget
{
    Q_OBJECT

    private:
        enum Page
        {
            PAGE_ONE,
            PAGE_TWO,
            PAGE_THREE,
            PAGE_FOUR
        };

        Page currentPage;

        QPushButton* backBtn;
        QPushButton* nextBtn;
        QPushButton* finishBtn;
        QPushButton* helpBtn;
        QPushButton* cancelBtn;

        QGridLayout* outerLayout;
        QHBoxLayout* buttonLayout;

        NewProjectPage_1* newProjectPage_1Ptr;
        NewProjectPage_2* newProjectPage_2Ptr;
        NewProjectPage_3* newProjectPage_3Ptr;
        NewProjectPage_4* newProjectPage_4Ptr;

        QString* absPathToProjBuildFileStrPtr;
        QString* absPathToProjRunFileStrPtr;
        QString* absPathToProjLaunchFileStrPtr;
        QString* absPathToProjCreateFileStrPtr;

    private slots:
        /**
         *
         */
        void handleBackBtnSlot();

        /**
         *
         */
        void handleNextBtnSlot();

        /**
         *
         */
        void handleFinishBtnSlot();

        /**
         *
         */
        void handleHelpBntSlot();

        /**
         *
         */
        void handleCancelBtnSlot();

    public:
        /**
         * Constructor.
         *
         * @param parent reference to parent type.
         */
        NewProjectGui(QWidget* parent = 0);

        /**
         *
         */
        void initBtns();

        /**
         *
         */
        void swapNextPage();

        /**
         *
         */
        void swapBackPage();

        /**
         *
         */
        void loadPage_1();

        /**
         *
         */
        void unloadPage_1();

        /**
         *
         */
        void loadPage_2();

        /**
         *
         */
        void unloadPage_2();

        /**
         *
         */
        void loadPage_3();

        /**
         *
         */
        void unloadPage_3();

        /**
         *
         */
        void loadPage_4();

        /**
         *
         */
        void unloadPage_4();

        /**
         *
         *
         * @param process
         * @param projectRootStrPtr
         */
        void genRideProjDepends(QProcess* process, QString* projectRootStrPtr);

        /**
         *
         *
         * @param absPathToProjBuildFileStrPtr
         */
        void setAbsPathToProjBuildFileStrPtr(QString* absPathToProjBuildFileStrPtr);

        /**
         *
         *
         * @return
         */
        QString* getAbsPathToProjBuildFileStrPtr();

        /**
         *
         *
         * @param absPathToProjRunFileStrPtr
         */
        void setAbsPathToProjRunFileStrPtr(QString* absPathToProjRunFileStrPtr);

        /**
         *
         *
         * @return
         */
        QString* getAbsPathToProjRunFileStrPtr();

        /**
         *
         *
         * @param absPathToProjLaunchFileStrPtr
         */
        void setAbsPathToProjLaunchFileStrPtr(QString* absPathToProjLaunchFileStrPtr);

        /**
         *
         *
         * @return
         */
        QString* getAbsPathToProjLaunchFileStrPtr();

        /**
         * Classic toString method.
         *
         * @return class data.
         */
        QString* toString();

        /**
         * Destructor.
         */
        ~NewProjectGui();

};

#endif	/* NEW_PROJECT_H */


text:
var generator = require('../helpers/generator');
var controllers = require('../api/controllers');
var planks = require('../config.json').planks;
var pconf = require('../config.json').APIVARS.PLANKS;
var planksDir = __dirname.replace('/helpers', pconf.DIR);

var apiParams = function (defRoute) {
  var defParams = '/' + defRoute.route;

  if(defRoute.params) {
    for(var param in defRoute.params) {
      if (param) { defParams += '/:'+ param; }
    }
  }
  return defParams;
};

var addPlanksApi = function(api){
  for(var idx in planks){
    if(planks.hasOwnProperty(idx)){
      var name = planks[idx];
      var prefix = '/' + name;
      var plank = require(planksDir + prefix + pconf.MAIN);
      var _cfg_ = require(planksDir + prefix + pconf.CONFIG);

      for(var g in plank.api.GET) {
        if (plank.api.GET.hasOwnProperty(g)) {
          var defGET = plank.api.GET[g];
          api.get(prefix + apiParams(defGET), defGET.fn);
        }
      }

      for(var p in plank.api.POST) {
        if (plank.api.POST.hasOwnProperty(p)) {
          var defPOST = plank.api.POST[p];
          api.post(prefix + apiParams(defPOST), defPOST.fn);
        }
      }

      addResourceRoutes(_cfg_.resources, api);
    }
  }
};

var addResourceRoutes = function(resources, api){
  for(var route in resources){
    if (resources.hasOwnProperty(route)) {
      if(resources[route].exclude){ continue; }

      generator.addRoutes({
        api: api,
        route: route,
        admin: resources[route].admin,
        controller: controllers[route],
        schema: resources[route].schema,
        clean:  resources[route].clean
      });
    }
  }
};

var getViewPath = function(name) {
  var dirname = __dirname.replace('/helpers', '');
  return dirname + pconf.DIR + '/' + name + pconf.VIEWS;
};

var addPlanksWeb = function(web){
  var views = [];
  for(var idx in planks){
    if(planks.hasOwnProperty(idx)){
      var name = planks[idx];
      var prefix = '/' + name;
      var plank = require(planksDir + prefix + pconf.CONFIG);

      for(var idy in plank.pages) {
        var page = plank.pages[idy];
        views.push(getViewPath(page));
        generator.addPage(web, page);
      }

      for(var route in plank.resources){
        if(plank.resources.hasOwnProperty(route)){
          generator.addView(web, route);
        }
      }
    }
  }

  return views;
};

//module.exports.apiParams = apiParams;
module.exports.addPlanksApi = addPlanksApi;
module.exports.addPlanksWeb = addPlanksWeb;


text:
require "spec_helper"

describe Chef::Mixin::ShellOut do
  include Chef::Mixin::ShellOut

  describe "shell_out_with_systems_locale" do
    describe "when environment['LC_ALL'] is not set" do
      it "should use the default shell_out setting" do
        cmd = if windows?
                shell_out_with_systems_locale("echo %LC_ALL%")
              else
                shell_out_with_systems_locale("echo $LC_ALL")
              end

        expect(cmd.stdout.chomp).to match_environment_variable("LC_ALL")
      end
    end

    describe "when environment['LC_ALL'] is set" do
      it "should use the option's setting" do
        cmd = if windows?
                shell_out_with_systems_locale("echo %LC_ALL%", :environment => { "LC_ALL" => "POSIX" })
              else
                shell_out_with_systems_locale("echo $LC_ALL", :environment => { "LC_ALL" => "POSIX" })
              end

        expect(cmd.stdout.chomp).to eq "POSIX"
      end
    end
  end

  describe "shell_out default_env: false" do
    describe "when environment['LC_ALL'] is not set" do
      it "should use the default shell_out setting" do
        cmd = if windows?
                shell_out("echo %LC_ALL%", default_env: false)
              else
                shell_out("echo $LC_ALL", default_env: false)
              end

        expect(cmd.stdout.chomp).to match_environment_variable("LC_ALL")
      end
    end

    describe "when environment['LC_ALL'] is set" do
      it "should use the option's setting" do
        cmd = if windows?
                shell_out("echo %LC_ALL%", :environment => { "LC_ALL" => "POSIX" }, default_env: false)
              else
                shell_out("echo $LC_ALL", :environment => { "LC_ALL" => "POSIX" }, default_env: false)
              end

        expect(cmd.stdout.chomp).to eq "POSIX"
      end
    end
  end
end


text:
hs.find = {
    Panel: Ext.extend (Ext.Panel, {
	constructor: function (config) {
	    if (!config)
		config = {};

	    var Filter = Ext.extend (Ext.Button, {
		constructor: function (name, g) {
		    var text = hs.data.fields [name].text;
		    Filter.superclass.constructor.call (this, {
			text: text,
			enableToggle: true,
			toggleGroup: 'filter',
			handler: function () {
			    g.reload (name);
			},
		    });
		},
	    });

	    var dataGrid = new hs.grid.Panel ({
		region: 'center',
		datatype: 'maps',
		load_public: true,
		selModel: new Ext.grid.RowSelectionModel({
		    singleSelect:true
		}),
		viewConfig: {
		    forceFit: true,
		},
	    });

	    var rec = new Ext.form.Checkbox ({
		boxLabel: 'Detector',
		listeners: {
		    check: function (box, event) {
			dataGrid.recommend (box.getValue ());
			dataGrid.reload (null);
		    }
		},
	    });

	    var keywordFilter = function (g, det, config) {
		if (!config)
		    config = {};
		Ext.apply (config, {
		    listeners: {
			specialkey: function (field, e) {
			    console.log ("EVENT");
			    if (e.getKey () == e.ENTER) {
				g.recommend (det.getValue ());
				g.keyword (field.getValue ());
			    }
			},
		    },
		});
		return new Ext.form.TextField (config);
	    };

            var text_box = keywordFilter (dataGrid, rec);

	    var top_menu = new Ext.Toolbar ({
		height: 30,
		items: [
		    text_box,
		    rec,
		],
	    });

	    var sub_menu = new Ext.Toolbar ({
		height: 'autoHeight',
		items: [
		    new Filter ('maps', dataGrid),
		    new Filter ('tools', dataGrid),
		    new Filter ('results', dataGrid),
		    new Filter ('analyses', dataGrid),
		],
	    });

	    var menus = new Ext.Panel ({
		region: 'north',
		height: 'autoHeight',
		items: [
		    top_menu,
		    sub_menu,
		],
	    });

	    this.search = function (term) {
		text_box.setValue (term);
		dataGrid.keyword (term);
            };

	    Ext.apply (config, {
		region: 'center',
		layout: 'border',
		items: [
		    menus,
		    dataGrid,
		],
	    });
	    hs.find.Panel.superclass.constructor.call (this, config);
	},
    }),
};


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using YnabApi.Files;
using YnabApi.Helpers;

namespace YnabApi
{
    public class YnabApi
    {
        private readonly YnabApiSettings _settings;

        private Lazy<Task<IList<Budget>>> _cachedBudgets;

        public YnabApi(YnabApiSettings settings)
        {
            this._settings = settings;
        }

        public Task<IList<Budget>> GetBudgetsAsync()
        {
            if (this._cachedBudgets == null || this._settings.CacheBudgets == false)
            {
                this._cachedBudgets = new Lazy<Task<IList<Budget>>>(async () =>
                {
                    try
                    {
                        string ynabSettingsFilePath = YnabPaths.YnabSettingsFile();

                        var ynabSettingsJson = await this._settings.FileSystem.ReadFileAsync(ynabSettingsFilePath);

                        if (ynabSettingsJson == null)
                            return new List<Budget>();

                        var ynabSettings = JObject.Parse(ynabSettingsJson);

                        string relativeBudgetsFolder = ynabSettings.Value<string>("relativeDefaultBudgetsFolder");

                        return ynabSettings
                            .Value<JArray>("relativeKnownBudgets")
                            .Values()
                            .Select(f => f.Value<string>())
                            .Select(f => new Budget(this._settings, this.ExtractBudgetName(f, relativeBudgetsFolder), f))
                            .ToArray();
                    }
                    catch (Exception exception) when (exception is YnabApiException == false)
                    {
                        throw new YnabApiException("Error while loading the budgets.", exception);
                    }
                });
            }

            return this._cachedBudgets.Value;
        }

        private string ExtractBudgetName(string budgetPath, string budgetsFolderPath)
        {
            var regex = new Regex(budgetsFolderPath + "/(.*)~.*");

            if (regex.IsMatch(budgetPath))
                return regex.Match(budgetPath).Groups[1].Value;

            return budgetPath;
        }
    }
}


text:
import os

from onadata.apps.main.tests.test_base import TestBase
from onadata.apps.logger.models.instance import Instance
from onadata.apps.logger.xform_instance_parser import get_uuid_from_xml
from onadata.libs.utils.logger_tools import inject_instanceid

class TestWebforms(TestBase):
    def setUp(self):
        super().setUp()
        self._publish_transportation_form_and_submit_instance()

    def __load_fixture(self, *path):
        with open(os.path.join(os.path.dirname(__file__), *path), 'r') as f:
            return f.read()

    def test_inject_instanceid(self):
        """
        Test that 1 and only 1 instance id exists or is injected
        """
        instance = Instance.objects.all().reverse()[0]
        xml_str = self.__load_fixture("..", "fixtures", "tutorial",
                                      "instances",
                                      "tutorial_2012-06-27_11-27-53.xml")
        # test that we dont have an instance id
        uuid = get_uuid_from_xml(xml_str)
        self.assertIsNone(uuid)
        injected_xml_str = inject_instanceid(xml_str, instance.uuid)
        # check that xml has the instanceid tag
        uuid = get_uuid_from_xml(injected_xml_str)
        self.assertEqual(uuid, instance.uuid)

    def test_dont_inject_instanceid_if_exists(self):
        xls_file_path = os.path.join(
            os.path.dirname(__file__),
            '..',
            'fixtures',
            'tutorial',
            'tutorial.xls')
        self._publish_xls_file_and_set_xform(xls_file_path)
        xml_file_path = os.path.join(
            os.path.dirname(__file__),
            '..',
            'fixtures',
            'tutorial',
            'instances',
            'tutorial_2012-06-27_11-27-53_w_uuid.xml')
        self._make_submission(xml_file_path)
        instance = Instance.objects.order_by('id').reverse()[0]
        injected_xml_str = inject_instanceid(instance.xml, instance.uuid)
        # check that the xml is unmodified
        self.assertEqual(instance.xml, injected_xml_str)


text:
#include "state_map.hpp"

using namespace engine;

/**
 * @brief Set a state to the game or characters.
 *
 * 	This method was implemented to set an state to the game or the
 * characters that have an animation, where can be on attack, attacking
 * dying, normal, looking left, looking right, falling, jumping, refuted,
 * on ground, vulnerable, and others.
 *
 * @param state_name Description's name of state defined by other classes
 * method.
 * @param state_value Description's value type represented by a string and
 * defined by other classes method.
 * @return void.
 */

void StateMap::set_state (std::string state_name, std::string state_value) {
  	states[state_name] = state_value;
}

/**
 * @brief Get state of the game and characters.
 *
 * 	This method was implemented to get an actual state of the game or the
 * characters that have an animation.
 *
 * @param state_name Description's name of the actual state.
 * @return string The return is a string of a determined state.
 */

std::string StateMap::get_state (std::string state_name) {
  	return states[state_name];
}


text:
package com.google.common.collect;

import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.client.rpc.SerializationStreamReader;
import com.google.gwt.user.client.rpc.SerializationStreamWriter;
import com.google.gwt.user.client.rpc.core.java.util.Map_CustomFieldSerializerBase;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * This class implements the GWT serialization of {@link RegularImmutableMap}.
 *
 * @author Hayward Chan
 */
public class RegularImmutableMap_CustomFieldSerializer {

  public static void deserialize(
      SerializationStreamReader reader, RegularImmutableMap<?, ?> instance) {}

  public static RegularImmutableMap<Object, Object> instantiate(SerializationStreamReader reader)
      throws SerializationException {
    Map<Object, Object> entries = new LinkedHashMap<>();
    Map_CustomFieldSerializerBase.deserialize(reader, entries);
    /*
     * For this custom field serializer to be invoked, the map must have been
     * RegularImmutableMap before it's serialized.  Since RegularImmutableMap
     * always have two or more elements, ImmutableMap.copyOf always return
     * a RegularImmutableMap back.
     */
    return (RegularImmutableMap<Object, Object>) ImmutableMap.copyOf(entries);
  }

  public static void serialize(SerializationStreamWriter writer, RegularImmutableMap<?, ?> instance)
      throws SerializationException {
    Map_CustomFieldSerializerBase.serialize(writer, instance);
  }
}


text:
Allows you to create QR Codes for MAC and IOS. It's based on libqrencode C library.

Usage
-----
```objc
QRCode * qrcode = [[QRCode alloc] initWithString:@"encode this string"];
UIImage * qrImage = qrcode.image;
```

you can also use static method to generate qr image:
```objc
NSImage * qrImage = [QRCode encode:@"encode this string, using static methode"];
```

License
-------

QRCode source is released under the terms of the MIT license. See [LICENSE](LICENSE) for more
information or see http://opensource.org/licenses/MIT.

The Demo App is released under terms of the GPLv3 license. See [LICENCE-GPLv3](demo/LICENCE-GPLv3) for more
information or see http://opensource.org/licenses/GPL-3.0.


text:
#ifndef RPG_TURN_HPP
#define RPG_TURN_HPP

#include <rpg-engine/Action.hpp>
#include <rpg-engine/EntityTurn.hpp>

#include <list>

namespace rpg
{
    class Entity;
    class TurnGameBased;

    /**
     * \brief Class to manage a turn of multiple entity
     */
    class Turn
    {
        public:
            Turn(const Turn&) = delete;
            Turn& operator=(const Turn&) = delete;

            Turn(const std::list<Entity*>& entitys);

            EntityTurn& getCurrentTurn()const;

        private:
            friend class TurnGameBased;

            void start();

            std::list<EntityTurn> turns;
            std::list<Action> actions;

            std::list<EntityTurn>::iterator current;

    };
}
#endif


text:
FROM python:3.6

RUN apt-get -y update && apt-get install -y redis-server cmake git

RUN export LD_LIBRARY_PATH=$HOME/.local/lib/:$LD_LIBRARY_PATH
RUN git clone --depth=1 https://github.com/lloyd/yajl.git
WORKDIR /yajl/
RUN ./configure --prefix=$HOME/.local/
RUN cmake -DCMAKE_INSTALL_PREFIX=$HOME/.local/ && make && make install
RUN ln -s /yajl/yajl-2.1.1/lib/libyajl.so.2.1.1 /usr/lib/x86_64-linux-gnu/libyajl.so

EXPOSE 4500

RUN pip install trellio
CMD ["python","-m","trellio.registry"]


text:
module RainforestRubyRuntime
  class DSL
    include RSpec::Matchers
    include Capybara::DSL

    def initialize(callback: )
      @callback = callback
    end

    def test(id: , title: , &block)
      RainforestRubyRuntime::Test.new(id: id, title: title, callback: @callback, &block)
    end

    def step(options, &block)
      RainforestRubyRuntime::Step.new(options.merge(callback: @callback), &block).tap(&:run)
    end

    def define_variable_scope(name, &block)
      scope = Variables::Scope.new(name, &block)
      Variables.scope_registry.register(scope)
    end

    def run_code(code)
      eval(code)
    end

    def method_missing(name, *args, &block)
      if Variables.scope_registry.has_variable?(name)
        Variables.scope_registry[name]
      else
        super
      end
    end
  end
end


text:
package com.maddyhome.idea.copyright.actions;

import com.intellij.codeInsight.FileModificationService;
import com.intellij.copyright.CopyrightManager;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ContentIterator;
import com.intellij.openapi.roots.ModuleFileIndex;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.vfs.ReadonlyStatusHandler;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.util.IncorrectOperationException;
import com.maddyhome.idea.copyright.CopyrightProfile;
import com.maddyhome.idea.copyright.util.FileTypeUtil;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public abstract class AbstractFileProcessor {
  private final Project myProject;
  private final Module myModule;
  private PsiDirectory directory = null;
  private PsiFile file = null;
  private PsiFile[] files = null;
  private final String message;
  private final String title;

  protected abstract Runnable preprocessFile(PsiFile file, boolean allowReplacement) throws IncorrectOperationException;

  protected AbstractFileProcessor(Project project, PsiFile file, String title, String message) {
    myProject = project;
    myModule = null;
    this.file = file;
    this.message = message;
    this.title = title;
  }

  protected AbstractFileProcessor(Project project, PsiFile[] files, String title, String message) {
    myProject = project;
    myModule = null;
    this.files = files;
    this.message = message;
    this.title = title;
  }

  public void run() {
    if (directory != null) {
      process(directory, false);
    }
    else if (files != null) {
      process(files);
    }
    else if (file != null) {
      process(file);
    }
    else if (myModule != null) {
      process(myModule);
    }
    else if (myProject != null) {
      process(myProject);
    }
  }

  private void process(final PsiFile file) {
    if (!FileModificationService.getInstance().preparePsiElementForWrite(file)) return;
    final Runnable[] resultRunnable = new Runnable[1];

    execute(() -> {
      try {
        resultRunnable[0] = preprocessFile(file, true);
      }
      catch (IncorrectOperationException incorrectoperationexception) {
        logger.error(incorrectoperationexception);
      }
    }, () -> {
      if (resultRunnable[0] != null) {
        resultRunnable[0].run();
      }
    });
  }

  private Runnable prepareFiles(List<PsiFile> files) {
    ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
    String msg = null;
    double fraction = 0.0D;
    if (indicator != null) {
      msg = indicator.getText();
      fraction = indicator.getFraction();
      indicator.setText(message);
    }

    final Runnable[] runnables = new Runnable[files.size()];
    for (int i = 0; i < files.size(); i++) {
      PsiFile pfile = files.get(i);
      if (pfile == null) {
        logger.debug("Unexpected null file at " + i);
        continue;
      }
      if (indicator != null) {
        if (indicator.isCanceled()) {
          return null;
        }

        indicator.setFraction((double)i / (double)files.size());
      }

      if (pfile.isWritable()) {
        try {
          runnables[i] = preprocessFile(pfile, true);
        }
        catch (IncorrectOperationException incorrectoperationexception) {
          logger.error(incorrectoperationexception);
        }
      }

      files.set(i, null);
    }

    if (indicator != null) {
      indicator.setText(msg);
      indicator.setFraction(fraction);
    }

    return () -> {
      ProgressIndicator indicator1 = ProgressManager.getInstance().getProgressIndicator();
      String msg1 = null;
      double fraction1 = 0.0D;
      if (indicator1 != null) {
        msg1 = indicator1.getText();
        fraction1 = indicator1.getFraction();
        indicator1.setText(message);
      }

      for (int j = 0; j < runnables.length; j++) {
        if (indicator1 != null) {
          if (indicator1.isCanceled()) {
            return;
          }

          indicator1.setFraction((double)j / (double)runnables.length);
        }

        Runnable runnable = runnables[j];
        if (runnable != null) {
          runnable.run();
        }
        runnables[j] = null;
      }

      if (indicator1 != null) {
        indicator1.setText(msg1);
        indicator1.setFraction(fraction1);
      }
    };
  }

  private void process(final PsiFile[] files) {
    final Runnable[] resultRunnable = new Runnable[1];
    execute(() -> resultRunnable[0] = prepareFiles(new ArrayList<>(Arrays.asList(files))), () -> {
      if (resultRunnable[0] != null) {
        resultRunnable[0].run();
      }
    });
  }

  private void process(final PsiDirectory dir, final boolean subdirs) {
    final List<PsiFile> pfiles = new ArrayList<>();
    ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> findFiles(pfiles, dir, subdirs), title, true, myProject);
    handleFiles(pfiles);
  }

  private void process(final Project project) {
    final List<PsiFile> pfiles = new ArrayList<>();
    ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> findFiles(project, pfiles), title, true, project);
    handleFiles(pfiles);
  }

  private void process(final Module module) {
    final List<PsiFile> pfiles = new ArrayList<>();
    ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> findFiles(module, pfiles), title, true, myProject);
    handleFiles(pfiles);
  }

  private static void findFiles(Project project, List<PsiFile> files) {
    Module[] modules = ModuleManager.getInstance(project).getModules();
    for (Module module : modules) {
      findFiles(module, files);
    }

  }

  protected static void findFiles(final Module module, final List<PsiFile> files) {
    final ModuleFileIndex idx = ModuleRootManager.getInstance(module).getFileIndex();

    final VirtualFile[] roots = ModuleRootManager.getInstance(module).getContentRoots();

    for (final VirtualFile root : roots) {
      ApplicationManager.getApplication().runReadAction(() -> {
        idx.iterateContentUnderDirectory(root, new ContentIterator() {
          @Override
          public boolean processFile(final VirtualFile dir) {
            if (dir.isDirectory()) {
              final PsiDirectory psiDir = PsiManager.getInstance(module.getProject()).findDirectory(dir);
              if (psiDir != null) {
                findFiles(files, psiDir, false);
              }
            }
            return true;
          }
        });
      });
    }
  }

  private void handleFiles(final List<PsiFile> files) {
    final VirtualFile[] vFiles = files.stream().map(PsiFile::getVirtualFile).toArray(VirtualFile[]::new);
    if (!ReadonlyStatusHandler.getInstance(myProject).ensureFilesWritable(vFiles).hasReadonlyFiles()) {
      if (!files.isEmpty()) {
        final Runnable[] resultRunnable = new Runnable[1];
        execute(() -> resultRunnable[0] = prepareFiles(files), () -> {
          if (resultRunnable[0] != null) {
            resultRunnable[0].run();
          }
        });
      }
    }
  }

  private static void findFiles(List<PsiFile> files, PsiDirectory directory, boolean subdirs) {
    final Project project = directory.getProject();
    PsiFile[] locals = directory.getFiles();
    for (PsiFile local : locals) {
      CopyrightProfile opts = CopyrightManager.getInstance(project).getCopyrightOptions(local);
      if (opts != null && FileTypeUtil.isSupportedFile(local)) {
        files.add(local);
      }
    }

    if (subdirs) {
      for (PsiDirectory dir : directory.getSubdirectories()) {
        findFiles(files, dir, true);
      }
    }
  }

  private void execute(final Runnable readAction, final Runnable writeAction) {
    ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> ApplicationManager.getApplication().runReadAction(() -> readAction.run()), title, true, myProject);
    new WriteCommandAction(myProject, title) {
      @Override
      protected void run(@NotNull Result result) throws Throwable {
        writeAction.run();
      }
    }.execute();
  }

  private static final Logger logger = Logger.getInstance(AbstractFileProcessor.class.getName());
}


text:
module OneviewCookbook
  module API300
    module C7000
      # StorageSystem API300 C7000 provider
      class StorageSystemProvider < API200::StorageSystemProvider
      end
    end
  end
end


text:
"""ParameterCodec tests"""

import unittest
import mock

from ros3ddevcontroller.param.store import ParametersStore, ParameterLoader
from ros3ddevcontroller.param.parameter import Parameter, ReadOnlyParameter, Evaluator

class StoreLoadingTestCase(unittest.TestCase):
    def setUp(self):
        ParameterLoader.load()

    def tearDown(self):
        ParametersStore.clear_parameters()

class StoreLoadClearTestCase(unittest.TestCase):
    PARAMETERS = [
        Parameter('foo', 1, int),
        Parameter('bar', 2, float)
    ]

    def setUp(self):
        ParametersStore.clear_parameters()

    def test_load_clear(self):
        self.assertEqual(ParametersStore.PARAMETERS, {})

        ParametersStore.load_parameters(self.PARAMETERS)
        self.assertNotEqual(ParametersStore.PARAMETERS, {})
        self.assertIn('foo', ParametersStore.PARAMETERS)
        self.assertIn('bar', ParametersStore.PARAMETERS)

        ParametersStore.clear_parameters()
        self.assertEqual(ParametersStore.PARAMETERS, {})

class GetSetStoreTestCase(StoreLoadingTestCase):

    def test_get_existing(self):
        from ros3ddevcontroller.param.sysparams import SYSTEM_PARAMETERS

        for param in SYSTEM_PARAMETERS:
            name = param.name
            value = param.value

            try:
                from_store = ParametersStore.get(param.name)
            except KeyError:
                self.fail('Expecting key in the set')

            self.assertEqual(name, from_store.name)
            self.assertEqual(value, from_store.value)
            self.assertEqual(param.value_type, from_store.value_type)

    def test_get_missing(self):

        self.assertRaises(KeyError,
                          ParametersStore.get, 'non-existent-param')
        self.assertRaises(KeyError,
                          ParametersStore.get, '')
        self.assertRaises(KeyError,
                          ParametersStore.get, None)

    def test_set(self):
        # test that a parameter can be set
        test_param = 'focus_distance_m'
        test_val = 10.0

        self.assertTrue(ParametersStore.set(test_param, test_val))
        focus_set = ParametersStore.get(test_param)

        self.assertEqual(focus_set.value, test_val)

    def test_set_convert(self):
        # test that parameter can be set, and the value is
        # automatically converted to proper type
        test_param = 'focus_distance_m'
        test_val = 10
        expecting_type = float

        # test value is an int
        self.assertIsInstance(test_val, int)

        # first read it
        param = ParametersStore.get(test_param)
        self.assertEqual(param.value_type, expecting_type)
        self.assertIsInstance(param.value, expecting_type)

        # set
        ParametersStore.set(test_param, test_val)
        as_set = ParametersStore.get(test_param)
        # the type should have been converted according to parameter
        # description
        self.assertIsInstance(as_set.value, expecting_type)
        self.assertEqual(as_set.value, expecting_type(test_val))

    def test_set_validate_failed(self):
        # test setting of parameter where the automatic conversion fails
        # set

        test_param = 'focus_distance_m'
        test_val = 'foo'
        expecting_type = float

        # this will raise ValueError obviously
        self.assertRaises(ValueError, expecting_type, test_val)

        focus_before = ParametersStore.get(test_param)

        # same as this one
        self.assertRaises(ValueError, ParametersStore.set,
                          test_param, test_val)
        self.assertRaises(ValueError, ParametersStore.validate,
                          test_param, test_val)
        self.assertRaises(KeyError, ParametersStore.validate,
                          test_param + '=foo', test_val)
        self.assertRaises(KeyError, ParametersStore.set,
                          test_param + '=foo', test_val)

        # try to fetch the parameter again to compare that its value
        # is unchaged
        focus_after = ParametersStore.get(test_param)

        self.assertIs(focus_before, focus_after)

    def test_validate_pdesc_failed(self):
        # test setting of parameter where the automatic conversion fails
        # set

        test_param = 'focus_distance_m'
        test_val = 'foo'
        expecting_type = float

        param = Parameter(test_param, test_val, expecting_type)

        # we know the parameter, this should not raise anything
        ParametersStore.get(test_param)

        # same as this one
        self.assertRaises(ValueError, ParametersStore.set,
                          param.name, param.value)
        self.assertRaises(ValueError, ParametersStore.validate,
                          param.name, param.value)
        self.assertRaises(ValueError, ParametersStore.validate_desc,
                          param)

        # change value to correct one
        param.value = 10
        try:
            ParametersStore.validate_desc(param)
        except Exception as err:
            self.fail("Exception raised")

    def test_validate_not_pdesc_failed(self):
        param = 1

        # param is not Parameter(), this should fail
        self.assertRaises(AssertionError, ParametersStore.validate_desc,
                          param)

class ListenerTestCase(StoreLoadingTestCase):
    def test_called(self):
        # verify that a callback was called only once for each set
        tmock = mock.Mock()

        test_param = 'focus_distance_m'
        test_value = 10.0

        # register mock callback a couple of times, only one
        # registration is used
        ParametersStore.change_listeners.add(tmock)
        ParametersStore.change_listeners.add(tmock)
        ParametersStore.change_listeners.add(tmock)

        # set a parameter
        ParametersStore.set(test_param, test_value)

        # has to be called
        self.assertTrue(tmock.called)
        # called only once
        self.assertEquals(tmock.call_count, 1)
        self.assertEquals(len(tmock.call_args), 2)
        # grab the first list parameter
        pdesc = tmock.call_args[0][0]
        self.assertIsInstance(pdesc, Parameter)
        self.assertEquals(pdesc.name, test_param)
        self.assertEquals(pdesc.value, test_value)

        # set once again
        ParametersStore.set(test_param, test_value + 1)
        self.assertEquals(tmock.call_count, 2)
        # grab the first list parameter
        pdesc = tmock.call_args[0][0]
        self.assertEquals(pdesc.value, test_value + 1)

        # remove callback
        ParametersStore.change_listeners.remove(tmock)
        # and again, should not fail
        ParametersStore.change_listeners.remove(tmock)
        # now something different
        ParametersStore.change_listeners.remove(None)

class CameraServoTestCase(StoreLoadingTestCase):

    def setUp(self):
        super(CameraServoTestCase, self).setUp()
        from ros3ddevcontroller.param.sysparams import SERVO_PARAMETERS, CAMERA_PARAMETERS
        self.servo_parameters = SERVO_PARAMETERS
        self.camera_parameters = CAMERA_PARAMETERS

    def test_servo(self):

        for p in self.servo_parameters:
            self.assertTrue(ParametersStore.is_servo_parameter(p))
        for p in self.camera_parameters:
            self.assertFalse(ParametersStore.is_servo_parameter(p))

    def test_camera(self):

        for p in self.camera_parameters:
            self.assertTrue(ParametersStore.is_camera_parameter(p))
        for p in self.servo_parameters:
            self.assertFalse(ParametersStore.is_camera_parameter(p))

class ReadOnlyParameterTestCase(unittest.TestCase):

    def setUp(self):

        ParametersStore.load_parameters([
            ReadOnlyParameter('foo-readonly', 'bar', str),
            Parameter('foo-writable', 'bar', str)
        ])

    def test_parameter_readonly(self):

        self.assertTrue(ParametersStore.is_read_only('foo-readonly'))
        self.assertFalse(ParametersStore.is_read_only('foo-writable'))

class ParameterGetValueTestCase(unittest.TestCase):
    PARAMETERS = [
            Parameter('foo', 1, int),
            Parameter('bar', 'baz', str)
    ]

    def setUp(self):
        ParametersStore.load_parameters(self.PARAMETERS)

    def tearDown(self):
        ParametersStore.clear_parameters()

    def find_key_param(self, name):
        found = [pdesc for pdesc in self.PARAMETERS
                 if pdesc.name == name]
        return found[0]

    def test_get_value(self):

        for param_in in self.PARAMETERS:
            pdesc = ParametersStore.get(param_in.name)
            self.assertEqual(param_in.name, pdesc.name)
            self.assertEqual(param_in.value, pdesc.value)
            self.assertEqual(param_in.value_type, pdesc.value_type)

            pvalue = ParametersStore.get_value(param_in.name)
            self.assertEqual(pvalue, param_in.value)
            self.assertEqual(type(pvalue), param_in.value_type)

class ParameterEvaluationTestCase(unittest.TestCase):
    class BarEvaluator(Evaluator):
        REQUIRES = [
            'foo'
        ]

        def __call__(self, foo=None):
            return foo + 1

    class BazEvaluator(Evaluator):
        REQUIRES = [
            'foo',
            'bar'
        ]

        def __call__(self, foo=None, bar=None):
            return foo * bar + 1

    class CafeEvaluator(Evaluator):
        REQUIRES = [
            'baz',
            'bar'
        ]

        def __call__(self, baz=None, bar=None):
            return baz ** 2 + bar

    PARAMETERS = [
        Parameter('foo', 1, int),
        Parameter('cafe', 0, int, evaluator=CafeEvaluator),
        Parameter('bar', 0, int, evaluator=BarEvaluator),
        Parameter('baz', 0, int, evaluator=BazEvaluator),
    ]

    def setUp(self):
        ParametersStore.load_parameters(self.PARAMETERS)

    def tearDown(self):
        ParametersStore.clear_parameters()

    def test_set_value(self):

        self.assertNotEqual(ParametersStore.DEPENDENCIES, {})
        pdesc_bar = ParametersStore.get('bar')

        ParametersStore.set('foo', 3)
        bar_val = ParametersStore.get_value('bar')
        # bar = foo + 1
        self.assertEqual(bar_val, 4)
        baz_val = ParametersStore.get_value('baz')
        # baz = foo * bar + 1
        self.assertEqual(baz_val, 13)
        # cafe = baz ** 2 + bar
        cafe_val = ParametersStore.get_value('cafe')
        self.assertEqual(cafe_val, 173)


text:
<?php
namespace JSend;

class JSendResponse
{
    const SUCCESS = 'success';
    const FAIL = 'fail';
    const ERROR = 'error';

    protected $status;
    protected $data;
    protected $errorCode;
    protected $errorMessage;

    public static function success(array $data = null)
    {
        return new self(self::SUCCESS, $data);
    }

    public static function fail(array $data = null)
    {
        return new self(self::FAIL, $data);
    }

    public static function error($errorMessage, $errorCode = null, array $data = null)
    {
        return new self(self::ERROR, $data, $errorMessage, $errorCode);
    }

    public function __construct($status, array $data = null, $errorMessage = null, $errorCode = null)
    {
        if (! $this->isStatusValid($status)) {
            throw new InvalidJSendException('Status does not conform to JSend spec.');
        }
        $this->status = $status;

        if ($status === self::ERROR)
        {
            if (empty($errorMessage))
            {
                throw new InvalidJSendException('Errors must contain a message.');
            }
            $this->errorMessage = $errorMessage;
            $this->errorCode = $errorCode;
        }

        $this->data = $data;
    }

    public function getStatus()
    {
        return $this->status;
    }

    public function getData()
    {
        return $this->data;
    }

    public function getErrorMessage()
    {
        if ($this->isError()) {
            return $this->errorMessage;
        }

        throw new \BadMethodCallException(
            'Only responses with a status of error may have an error message.');
    }

    public function getErrorCode()
    {
        if ($this->isError()) {
            return $this->errorCode;
        }

        throw new \BadMethodCallException(
            'Only responses with a status of error may have an error code.');
    }

    protected function isStatusValid($status)
    {
        $validStatuses = array(self::SUCCESS, self::FAIL, self::ERROR);

        return in_array($status, $validStatuses);
    }

    public function isSuccess()
    {
        return $this->status === self::SUCCESS;
    }

    public function isFail()
    {
        return $this->status === self::FAIL;
    }

    public function isError()
    {
        return $this->status === self::ERROR;
    }

    /**
     * Encodes the class into JSON
     * @return string the raw JSON
     */
    public function encode()
    {
        $toEncode = array(
            'status' => $this->status,
        );

        if ($this->data) {
            $toEncode['data'] = $this->data;
        } else {
            if (! $this->isError()) {
                // Data is optional for errors, so it should not be set
                // rather than be null.
                $toEncode['data'] = null;
            }
        }

        if ($this->isError()) {
            $toEncode['message'] = (string) $this->errorMessage;

            if (! empty($this->errorCode)) {
                $toEncode['code'] = (int) $this->errorCode;
            }
        }

        return json_encode($toEncode);
    }

    public function __toString()
    {
        return $this->encode();
    }

    /**
     * Takes raw JSON (JSend) and builds it into a new JSendResponse
     * @param string $json the raw JSON (JSend) to decode
     * @see json_decode()
     * @throws UnexpectedValueException if JSON is invalid
     * @throws InvalidJSendException if JSend does not conform to spec
     * @return JSendResponse the response created from the JSON
     */
    public static function decode($json, $depth = 512, $options = 0)
    {
        $rawDecode = json_decode($json, true, $depth, $options);

        if ($rawDecode === null) {
            throw new UnexpectedValueException('JSON is invalid.');
        }

        if ((! is_array($rawDecode)) or (! array_key_exists('status', $rawDecode))) {
            throw new InvalidJSendException(
                'JSend must be an object with a valid status.');
        }

        $status = $rawDecode['status'];
        $data = array_key_exists('data', $rawDecode) ? $rawDecode['data'] : null;
        $errorMessage = array_key_exists('message', $rawDecode) ? $rawDecode['message'] : null;
        $errorCode = array_key_exists('code', $rawDecode) ? $rawDecode['code'] : null;

        if ($status === self::ERROR) {
            if ($errorMessage === null) {
                throw new InvalidJSendException('JSend errors must contain a message.');
            }
        } elseif (! array_key_exists('data', $rawDecode)) {
            throw new InvalidJSendException('JSend must contain data unless it is an error.');
        }

        return new self($status, $data, $errorMessage, $errorCode);

    }
}

class InvalidJSendException extends \Exception { };


text:
title: Rammi samræmingar
inshort: Óskilgreint
translator: Microsoft Cognitive Services
---

Heimild til að leita upplýsinga á skrifstofu 365 samræmi
-[samræmisvottorð fyrir skrifstofu 365 (trustcenter)](https://products.office.com/en-us/business/office-365-trust-center-compliance-certifications)
-[Office365 samræmingarrammi fyrir staðla og reglugerðir (PDF)](http://1.comhttp:/2, com & usg = AFQjCNGqqtp_GA4DkPeSvr5MHxJt3GNy1A)


text:
package com.seleniumtests.browserfactory;

import org.openqa.selenium.remote.DesiredCapabilities;

import com.seleniumtests.driver.DriverConfig;

public interface ICapabilitiesFactory {

    DesiredCapabilities createCapabilities(DriverConfig cfg);

}


text:
<?php
namespace Sample;

use Calgamo\Di\ContainerInterface;
use Calgamo\Di\ContainerModuleInterface;

class ConstantContainerModule implements ContainerModuleInterface
{
    /**
     * Install service(s) into container
     *
     * @param ContainerInterface $container
     */
    public function install(ContainerInterface $container)
    {
        // string.my_model_name immediate value
        $container['string.my_model_name'] = function(){
            return 'Prius';
        };
        $container->slot('string.my_model_name')->lock()->mustBeTypeOf('string');
        // array.toyota_branches immediate value
        $container['array.toyota_branches'] = function(){
            return ['Tokyo','Osaka','Sapporo'];
        };
        $container->slot('array.toyota_branches')->lock()->mustBeTypeOf('array');
        // integer.car_seats_sedan immediate value
        $container['integer.car_seats_sedan'] = function(){
            return 4;
        };
    }
}


text:
#ifndef ROOM_H
#define ROOM_H

#include <iostream>
#include <ctime>
#include <cmath>
#include <cstring>
#include <vector>

#include "tinyxml2.h"

#include "vec.h"
#include "RoomEdge.h"

typedef struct AABB2f
{
	v2f m_posMin;
	v2f m_posMax;
} AABB2f;

typedef CLineBase RoomWall;
typedef CLineBase RoomDoor;

class CRoom
{
public:
	CRoom();

	std::vector<v2f>& GetVertices() { return m_vertices; }

	void SetVertices(std::vector<v2f>& vertices) { m_vertices = vertices; }

	void SetVertex(v2f& pos, int idx) { m_vertices[idx] = pos; }

	void SetCenterShift(v2f& shift) { m_centerShift = shift; }

	v2f GetCenterShift() const { return m_centerShift; }

	v2f GetVertex(int idx) const { return m_vertices[idx]; }

	CRoomEdge GetEdge(int idx) const;

	int GetNumOfVertices() const { return int(m_vertices.size()); }

	int GetNumOfEdges() const { return int(m_vertices.size()); }

	v2f GetRoomCenter() const;

	v2f GetShiftedRoomCenter();

	void TranslateRoom(v2f trans);

	void RotateRoom(float rad);

	void ScaleRoom(float scaling);

	void ScaleRoom(v2f scaling);

	void GetRoomBoundingBox(v2f& posMin, v2f& posMax);

	void GetRoomBoundingBox(AABB2f& boundingBox);

	v3f GetColor() { return m_color; }
	void SetColor(v3f color) { m_color = color; }

	float GetEnergy() { return m_energy; }
	void SetEnergy(float energy) { m_energy = energy; }
	void ResetEnergy() { SetEnergy(1.f); }
	void UpdateEnergy(float factor) { m_energy *= factor; }

	void PrintRoom();

	bool HasWalls() const { return (m_walls.empty() == false); }

	void InitWalls();

	bool EraseWall(int idx);

	void InsertWall(RoomWall& wall) { m_walls.push_back(wall); }

	int GetNumOfWalls() const { return int(m_walls.size()); }

	RoomWall& GetWall(int idx) { return m_walls[idx]; }

	int GetTemplateType() const { return m_templateType; }
	void SetTemplateType(int type) { m_templateType = type; }

	int GetBoundaryType() const { return m_boundaryType; }
	void SetBoundaryType(int type) { m_boundaryType = type; }

	bool GetFlagFixed() const { return m_flagFixed; }
	void SetFlagFixed(bool flagFixed) { m_flagFixed = flagFixed; }

	void ResetDoorFlags();
	void SetDoorFlag(int edgeIdx, bool doorFlag);
	bool GetDoorFlag(int edgeIdx) const;
	std::vector<bool> GetDoorFlags() const;
	bool HasRestrictedDoorPosition() const;

private:
	std::vector<v2f> m_vertices;
	v2f m_centerShift = v2f(0.f, 0.f);;
	std::vector<RoomWall> m_walls;
	v3f m_color = v3f(0.5f, 0.5f, 0.5f);
	float m_energy;
	int m_templateType;
	bool m_flagFixed;
	int m_boundaryType;
	std::vector<bool> m_doorFlags;
};

#endif // ROOM_H


text:
function [ConvulutionKernel] = getConvulutionKernel(XyzData)

%% precalculation

XyData = XyzData(:,1:2); % hier sind nur die Kantenlängen interessant
EdgeLength = max(XyData(:));

% calculate odd EdgeLength / der cloue

if rem(EdgeLength,2) == 1 % odd

elseif rem(EdgeLength,2) == 0 % even

    EdgeLength = EdgeLength+1;

end

%% Bivariate Gaussian Kernel Density Estimation
% ob und warum das die richtige ist / wäre ist noch unklar

p=gkde2(XyData);

Bandwidth = round(mean(p.h));

%% calculation of the convulution kernel
% due to usage of meshgrid dramtic reduction of calculation time
% lookup-table is not needed any more

[ConvulutionKernel] = calcConvulutionKernel(Bandwidth, EdgeLength);

Nonsense = ConvulutionKernel; % hier wird nur eine Fehlermeldung ignoriert;
clear ConvulutionKernel

ConvulutionKernel.Kernel = Nonsense;
ConvulutionKernel.Bandwidth= Bandwidth;
ConvulutionKernel.EdgeLength= EdgeLength;

figure(1), imagesc(ConvulutionKernel.Kernel), colormap 'jet', colorbar, title('convulution kernel according to bivariate kernel density estimation')

end


text:
pyexcel.Sheet.columns
=====================

.. currentmodule:: pyexcel

.. automethod:: Sheet.columns


text:
const ReactIs = require('react-is');
const REACT_STATICS = {
    childContextTypes: true,
    contextType: true,
    contextTypes: true,
    defaultProps: true,
    displayName: true,
    getDefaultProps: true,
    getDerivedStateFromError: true,
    getDerivedStateFromProps: true,
    mixins: true,
    propTypes: true,
    type: true
};

const KNOWN_STATICS = {
    name: true,
    length: true,
    prototype: true,
    caller: true,
    callee: true,
    arguments: true,
    arity: true
};

const FORWARD_REF_STATICS = {
    '$$typeof': true,
    render: true,
    defaultProps: true,
    displayName: true,
    propTypes: true
};

const TYPE_STATICS = {};
TYPE_STATICS[ReactIs.ForwardRef] = FORWARD_REF_STATICS;

const defineProperty = Object.defineProperty;
const getOwnPropertyNames = Object.getOwnPropertyNames;
const getOwnPropertySymbols = Object.getOwnPropertySymbols;
const getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
const getPrototypeOf = Object.getPrototypeOf;
const objectPrototype = Object.prototype;

export default function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) {
    if (typeof sourceComponent !== 'string') { // don't hoist over string (html) components

        if (objectPrototype) {
            const inheritedComponent = getPrototypeOf(sourceComponent);
            if (inheritedComponent && inheritedComponent !== objectPrototype) {
                hoistNonReactStatics(targetComponent, inheritedComponent, blacklist);
            }
        }

        let keys = getOwnPropertyNames(sourceComponent);

        if (getOwnPropertySymbols) {
            keys = keys.concat(getOwnPropertySymbols(sourceComponent));
        }

        const targetStatics = TYPE_STATICS[targetComponent['$$typeof']] || REACT_STATICS;
        const sourceStatics = TYPE_STATICS[sourceComponent['$$typeof']] || REACT_STATICS;

        for (let i = 0; i < keys.length; ++i) {
            const key = keys[i];
            if (!KNOWN_STATICS[key] &&
                !(blacklist && blacklist[key]) &&
                !(sourceStatics && sourceStatics[key]) &&
                !(targetStatics && targetStatics[key])
            ) {
                const descriptor = getOwnPropertyDescriptor(sourceComponent, key);
                try { // Avoid failures from read-only properties
                    defineProperty(targetComponent, key, descriptor);
                } catch (e) {}
            }
        }

        return targetComponent;
    }

    return targetComponent;
};


text:
<?php $this->load->view("partial/header"); ?>

<?php echo $this->lang->line('recvs_register'); ?>

<?php
// echo "
";print_r($cart);die;
if(isset($error))
{
	echo "
".$error."
";
}
?>

	<?php echo form_open("receivings/change_mode",array('id'=>'mode_form')); ?>
		<?php echo $this->lang->line('recvs_mode') ?>
	<?php echo form_dropdown('mode',$modes,$mode,'onchange="$(\'#mode_form\').submit();"'); ?>

	<?php
	if ($show_stock_locations)
	{
	?>
    <?php echo $this->lang->line('recvs_stock_source') ?>
    <?php echo form_dropdown('stock_source',$stock_locations,$stock_source,'onchange="$(\'#mode_form\').submit();"'); ?>
    <?php
    if($mode=='requisition')
    {
    ?>
    <?php echo $this->lang->line('recvs_stock_destination') ?>
	<?php echo form_dropdown('stock_destination',$stock_locations,$stock_destination,'onchange="$(\'#mode_form\').submit();"');
    }
	}
	?>
	</form>
	<?php echo form_open("receivings/add",array('id'=>'add_item_form')); ?>

	<?php
	if($mode=='receive' or $mode=='requisition')
	{
		echo $this->lang->line('recvs_find_or_scan_item');
	}
	else
	{
		echo $this->lang->line('recvs_find_or_scan_item_or_receipt');
	}
	?>

	<?php echo form_input(array('name'=>'item','id'=>'item','size'=>'40'));?>

			<?php echo anchor("items/view/-1/width:450",
			"
".$this->lang->line('sales_new_item')."
",
			array('class'=>'thickbox none','title'=>$this->lang->line('sales_new_item')));
			?>

	</form>

	<?php echo $this->lang->line('common_delete'); ?>
	<?php echo $this->lang->line('recvs_item_name'); ?>
	<?php echo $this->lang->line('recvs_cost'); ?>
	<?php echo $this->lang->line('recvs_quantity'); ?>

	<?php echo $this->lang->line('recvs_discount'); ?>
	VAT
	Expiry Date (m/d/Y)

	<?php echo $this->lang->line('recvs_total'); ?>
	<?php echo $this->lang->line('recvs_edit'); ?>

<?php
if(count($cart)==0)
{
?>

<?php echo $this->lang->line('sales_no_items_in_cart'); ?>

<?php
}
else
{
	foreach(array_reverse($cart, true) as $line=>$item)
	{
        echo form_open("receivings/edit_item/$line");

?>

	    <?php echo anchor("receivings/delete_item/$line",'['.$this->lang->line('common_delete').']');?>
		<?php echo $item['name']; ?>
 [<?php echo $item['in_stock']; ?> in <?php echo $item['stock_name']; ?>]
            <?php echo form_hidden('location', $item['item_location']); ?>

		<?php if ($items_module_allowed && $mode !='requisition')
		{
		?>
			<?php echo form_input(array('name'=>'price','value'=>$item['price'],'size'=>'6'));?>
		<?php
		}
		else
		{
		?>
			<?php echo $item['price']; ?>
			<?php echo form_hidden('price',$item['price']); ?>
		<?php
		}
		?>

		<?php
            echo form_input(array('name'=>'quantity','value'=>$item['quantity'],'size'=>'2'));
            if ($item['receiving_quantity'] > 1)
			{
		?>

        x <?php echo $item['receiving_quantity']; ?>
		<?php
			}
			else
			{
		?>

		<?php
			}
		?>

		<?php
			if ($items_module_allowed && $mode!='requisition')
		    {
		?>
	    <?php echo form_input(array('name'=>'discount','value'=>$item['discount'],'size'=>'3'));?>
		<?php
		    }
		    else
		    {
		?>
		     <?php echo $item['discount']; ?>
		     <?php echo form_hidden('discount',$item['discount']); ?>
		<?php }
			$new_value = 1;
			$cost = intval($item['price']);
			$vat = intval($item['vat']);
			$quantity = intval($item['quantity']);
			$discount = intval($item['discount']);
			$totalsfinal = 0;
			$receiving_quantity = intval($item['receiving_quantity']);
			$totaldiscount = $cost*$quantity*$discount;
			// $totaldiscount = $cost*$quantity*$discount*$receiving_quantity;
			$totalcost = $cost*$quantity;
			// echo "$discount";die;
			if($discount==0){
				$totalsfinal = $totalcost;
			}else{
				$totalsfinal = ($totalcost - ($totaldiscount/100));
			}
			if($vat==0){
				$totalsfinal = $totalsfinal;
			}else{
				$vat_amount = $totalcost * ($vat/100);
				$totalsfinal = round(($totalsfinal+$vat_amount),2);
			}
		    // foreach($taxes as $name=>$value){
		    // 	$new_value = $value;

			?>

		 	<?php echo form_input(array('name'=>'vat','size'=>'5','value'=>$item['vat']));?>
			<?php echo form_input(array('name'=>'expiry','size'=>'5','class'=>'expiry_datepicker','value'=>$item['expiry']));?>

			<?php echo to_currency($totalsfinal); ?>

			<?php echo form_submit("edit_item", $this->lang->line('sales_edit_item'));?>

		</form>
	<?php
	}
}
?>

	<?php
	if(isset($supplier))
	{
		echo $this->lang->line("recvs_supplier").': '.$supplier. '
';
		echo anchor("receivings/delete_supplier",'['.$this->lang->line('common_delete').' '.$this->lang->line('suppliers_supplier').']');
	}
	else
	{
		echo form_open("receivings/select_supplier",array('id'=>'select_supplier_form')); ?>
		<?php echo $this->lang->line('recvs_select_supplier'); ?>
		<?php echo form_input(array('name'=>'supplier','id'=>'supplier','size'=>'30','value'=>$this->lang->line('recvs_start_typing_supplier_name')));?>
		</form>

<?php echo $this->lang->line('common_or'); ?>

		<?php echo anchor("suppliers/view/-1/width:400",
		"
".$this->lang->line('recvs_new_supplier')."
",
		array('class'=>'thickbox none','title'=>$this->lang->line('recvs_new_supplier')));
		?>

		<?php
	}
	?>

    <?php
        if($mode != 'requisition')
        {
    ?>

<?php echo $this->lang->line('sales_total'); ?>:

		<?php
			$total = 0;
			if(count($cart)>0){
				foreach ($cart as $key => $value) {
					$total= $total + $value['total'];
				}
			}
			echo to_currency($total);
		?>

	<?php
        }
	?>
	<?php
	if(count($cart) > 0)
	{
		if($mode == 'requisition')
		{
		?>

		        <?php echo form_open("receivings/requisition_complete",array('id'=>'finish_receiving_form')); ?>

		        <?php echo $this->lang->line('common_comments'); ?>:
		        <?php echo form_textarea(array('name'=>'comment','id'=>'comment','value'=>$comment,'rows'=>'4','cols'=>'23'));?>

		        	<?php echo $this->lang->line('recvs_complete_receiving') ?>

		        </form>
		        <?php echo form_open("receivings/cancel_receiving",array('id'=>'cancel_receiving_form')); ?>

		        <?php echo $this->lang->line('recvs_cancel_receiving')?>

		        </form>

	    <?php
	        }
	        else
	        {
	?>

		<?php echo form_open("receivings/complete",array('id'=>'finish_receiving_form')); ?>

		<?php echo $this->lang->line('common_comments'); ?>:
		<?php echo form_textarea(array('name'=>'comment','id'=>'comment','value'=>$comment,'rows'=>'4','cols'=>'23'));?>

				<?php echo $this->lang->line('recvs_print_after_sale'); ?>

				<?php if ($print_after_sale)
				{
					echo form_checkbox(array('name'=>'recv_print_after_sale','id'=>'recv_print_after_sale','checked'=>'checked'));
				}
				else
				{
					echo form_checkbox(array('name'=>'recv_print_after_sale','id'=>'recv_print_after_sale'));
				}
				?>

		<?php if ($mode == "receive")
		{
		?>

		<?php echo $this->lang->line('recvs_invoice_enable'); ?>

		<?php if ($invoice_number_enabled)
		{
			echo form_checkbox(array('name'=>'recv_invoice_enable','id'=>'recv_invoice_enable','size'=>10,'checked'=>'checked'));
		}
		else
		{
			echo form_checkbox(array('name'=>'recv_invoice_enable','id'=>'recv_invoice_enable','size'=>10));
		}
		?>

		<?php echo $this->lang->line('recvs_invoice_number').':   ';?>

		<?php echo form_input(array('name'=>'recv_invoice_number','id'=>'recv_invoice_number','value'=>$invoice_number,'size'=>10));?>

		<?php
		}
		?>

		<?php
			echo $this->lang->line('sales_payment').':   ';?>

		<?php
		    echo form_dropdown('payment_type',$payment_options);?>

        <?php
			echo $this->lang->line('sales_amount_tendered').':   ';?>

		<?php
		    echo form_input(array('name'=>'amount_tendered','value'=>'','size'=>'10'));
		?>

			<?php echo $this->lang->line('recvs_complete_receiving') ?>

		</form>

	    <?php echo form_open("receivings/cancel_receiving",array('id'=>'cancel_receiving_form')); ?>

					<?php echo $this->lang->line('recvs_cancel_receiving')?>

        </form>

	<?php
	}
}
	?>

<?php $this->load->view("partial/footer"); ?>


text:
import { Cache, CacheContainer } from "node-ts-cache"
import * as _ from "lodash"
import * as Fs from "fs"
import { NodeFsStorage } from "node-ts-cache-storage-node-fs"
import { IoRedisStorage } from "node-ts-cache-storage-ioredis"
import { MemoryStorage } from "node-ts-cache-storage-memory"
import * as IORedis from "ioredis"

const IoRedisMock: typeof IORedis = require("ioredis-mock")

const fsCacheFile = "user-cache.json"

const caches = [
    new CacheContainer(new MemoryStorage()),
    new CacheContainer(new NodeFsStorage(fsCacheFile)),
    new CacheContainer(new IoRedisStorage(new IoRedisMock()))
]

const data = ["user", "max", "test"]

caches.forEach((c) => testForCache(c))

function testForCache(cache: CacheContainer) {
    class TestClass {
        @Cache(cache, { ttl: 2 })
        public async getUsers() {
            return await this.expensiveMethod()
        }

        public async expensiveMethod() {
            return new Promise((resolve) => setTimeout(() => resolve(data), 50))
        }
    }

    describe(`Cache Dead Lock Queue ${
        (cache as any).storage.constructor.name
    }`, () => {
        beforeEach(async () => {
            await cache.clear()
        })

        afterEach(async () => {
            try {
                await Fs.unlinkSync(fsCacheFile)
            } catch (e) {}
        })

        it("Should correctly enqueue simultaneous calls", async () => {
            const myClass = new TestClass()

            const expensiveMethodSpy = jest.spyOn(myClass, "expensiveMethod")
            const storageGetSpy = jest.spyOn(cache, "getItem")
            const storageSetSpy = jest.spyOn(cache, "setItem")

            const responses = await Promise.all(
                _.times(100).map(() => myClass.getUsers())
            )

            expect(storageSetSpy.mock.calls.length).toStrictEqual(1)
            expect(storageGetSpy.mock.calls.length).toStrictEqual(1)
            expect(expensiveMethodSpy.mock.calls.length).toStrictEqual(1)
            expect(responses).toStrictEqual(_.times(100, () => data))
        })
    })
}


text:
package com.nhaarman.sqlitebuilder.impl;

import com.nhaarman.sqlitebuilder.DropTable;
import com.nhaarman.sqlitebuilder.RawSqlBuilder;
import com.nhaarman.sqlitebuilder.SqlPart;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

class DropTableImpl extends BaseFinishedStatement implements DropTable {

  @Nullable
  private final String mDatabaseName;

  @NotNull
  private final String mTableName;

  @NotNull
  private final SqlPart mPrevious;

  DropTableImpl(@Nullable final String databaseName, @NotNull final String tableName, @NotNull final SqlPart previous) {
    mDatabaseName = databaseName;
    mTableName = tableName;
    mPrevious = previous;
  }

  @Override
  public void prependTo(@NotNull final RawSqlBuilder builder) {
    builder.prepend(mTableName);

    if (mDatabaseName != null) {
      builder.prepend('.').prepend(mDatabaseName);
    }

    builder.prepend("TABLE ");
  }

  @Nullable
  @Override
  public SqlPart previous() {
    return mPrevious;
  }
}


text:
var package = require('../../../node_modules/offshore-sql/package.json');
module.exports = {
  name: 'offshore-sql (Mysql)',
  adapter: require('../../../node_modules/offshore-sql'),
  interfaces: package['offshoreAdapter'].interfaces,
  features: package['offshoreAdapter'].features || [],
  config: {
    host: process.env.MYSQL_PORT_3306_TCP_ADDR || 'localhost',
    port: 3306,
    user: process.env.MYSQL_ENV_MYSQL_USER || 'root',
    password: process.env.MYSQL_ENV_MYSQL_PASSWORD || '',
    database: process.env.MYSQL_ENV_MYSQL_DATABASE || 'offshoresql',
    dbType: 'mysql'
  }
};


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
es5id: 15.4.4.18-7-c-i-12
description: >
    Array.prototype.forEach - element to be retrieved is own accessor
    property that overrides an inherited data property on an Array
---*/

        var testResult = false;

        function callbackfn(val, idx, obj) {
            if (idx === 0) {
                testResult = (val === 111);
            }
        }

        var arr = [];

            Array.prototype[0] = 10;

            Object.defineProperty(arr, "0", {
                get: function () {
                    return 111;
                },
                configurable: true
            });

            arr.forEach(callbackfn);

assert(testResult, 'testResult !== true');


text:
using namespace OryolTools;

//------------------------------------------------------------------------------
void
IRep::ComputeVertexMagnitude() {
    assert((this->VertexComponents[0].Attr == VertexAttr::Position) &&
           (this->VertexComponents[0].Format == VertexFormat::Float3));
    glm::vec4 mag(0.0f);
    for (const auto& node : this->Nodes) {
        for (const auto& mesh : node.Meshes) {
            for (const auto& vtx : mesh.Vertices) {
                const glm::vec4& pos = vtx[VertexAttr::Position];
                mag = glm::max(mag, glm::abs(pos));
            }
        }
    }
   this->VertexMagnitude = glm::vec3(mag);
}

//------------------------------------------------------------------------------
void
IRep::ComputeCurveMagnitudes() {
    for (auto& clip : this->AnimClips) {
        for (auto& curve : clip.Curves) {
            curve.Magnitude = glm::vec4(0.0f);
            for (const auto& key : curve.Keys) {
                curve.Magnitude = glm::max(curve.Magnitude, glm::abs(key));
            }
        }
    }
}

//------------------------------------------------------------------------------
bool
IRep::HasVertexAttr(VertexAttr::Code attr) const {
    for (const auto& comp : this->VertexComponents) {
        if (comp.Attr == attr) {
            return true;
        }
    }
    return false;
}

//------------------------------------------------------------------------------
int
IRep::MaterialIndex(const std::string& name) const {
    for (size_t i = 0; i < this->Materials.size(); i++) {
        if (name == this->Materials[i].Name) {
            return (int)i;
        }
    }
    return -1;
}

//------------------------------------------------------------------------------
int
IRep::NumVertices() const {
    int num = 0;
    for (const auto& node : this->Nodes) {
        for (const auto& mesh : node.Meshes) {
            num += mesh.Vertices.size();
        }
    }
    return num;
}

//------------------------------------------------------------------------------
int
IRep::NumIndices() const {
    int num = 0;
    for (const auto& node : this->Nodes) {
        for (const auto& mesh : node.Meshes) {
            Log::FailIf((mesh.Indices.size() % 3) != 0, "Index data size isn't multiple of 3!\n");
            num += mesh.Indices.size();
        }
    }
    return num;
}

//------------------------------------------------------------------------------
int
IRep::NumValueProps() const {
    size_t num = 0;
    for (const auto& mat : this->Materials) {
        num += mat.Values.size();
    }
    return (int)num;
}

//------------------------------------------------------------------------------
int
IRep::NumPropValues() const {
    size_t num = 0;
    for (const auto& mat : this->Materials) {
        for (const auto& prop : mat.Values) {
            num += PropType::NumFloats(prop.Type);
        }
    }
    return num;
}

//------------------------------------------------------------------------------
int
IRep::NumTextureProps() const {
    size_t num = 0;
    for (const auto& mat : this->Materials) {
        num += mat.Textures.size();
    }
    return (int)num;
}

//------------------------------------------------------------------------------
int
IRep::NumMeshes() const {
    size_t num = 0;
    for (const auto& node : this->Nodes) {
        num += node.Meshes.size();
    }
    return num;
}

//------------------------------------------------------------------------------
int
IRep::NumAnimCurves() const {
    size_t num = 0;
    for (const auto& clip : this->AnimClips) {
        num += clip.Curves.size();
    }
    return (int)num;
}

//------------------------------------------------------------------------------
int
IRep::NumAnimCurvesPerClip() const {
    if (this->AnimClips.empty()) {
        return 0;
    }
    else {
        return this->AnimClips[0].Curves.size();
    }
}

//------------------------------------------------------------------------------
int
IRep::AnimClipKeyStride(int clipIndex) const {
    int stride = 0;
    const auto& clip = this->AnimClips[clipIndex];
    for (const auto& curve : clip.Curves) {
        if (!curve.IsStatic) {
            stride += KeyType::ByteSize(curve.Type);
        }
    }
    return stride;
}

//------------------------------------------------------------------------------
int
IRep::AnimClipLength(int clipIndex) const {
    for (const auto& curve : this->AnimClips[clipIndex].Curves) {
        // all curves in the clip either have no keys, or the same number of keys
        if (!curve.Keys.empty()) {
            return curve.Keys.size();
        }
    }
    return 0;
}

//------------------------------------------------------------------------------
int
IRep::AnimKeyDataSize() const {
    int animKeyDataSize = 0;
    for (int clipIndex = 0; clipIndex < int(this->AnimClips.size()); clipIndex++) {
        animKeyDataSize += this->AnimClipKeyStride(clipIndex) * this->AnimClipLength(clipIndex);
    }
    return animKeyDataSize;
}

//------------------------------------------------------------------------------
int
IRep::AnimKeyOffset(int clipIndex, int curveIndex) const {
    int keyOffset = 0;
    for (int i = 0; i < clipIndex; i++) {
        keyOffset += this->AnimClipLength(i) * this->AnimClipKeyStride(i);
    }
    const auto& clip = this->AnimClips[clipIndex];
    for (int i = 0; i < curveIndex; i++) {
        const auto& curve = clip.Curves[i];
        if (!curve.IsStatic) {
            keyOffset += KeyType::ByteSize(curve.Type);
        }
    }
    return keyOffset;
}

//------------------------------------------------------------------------------
std::vector<std::string>
IRep::NodeNames() const {
    std::vector<std::string> res;
    res.reserve(this->Nodes.size());
    for (const auto& node : this->Nodes) {
        res.push_back(node.Name);
    }
    return res;
}

//------------------------------------------------------------------------------
std::vector<std::string>
IRep::ClipNames() const {
    std::vector<std::string> res;
    res.reserve(this->AnimClips.size());
    for (const auto& clip : this->AnimClips) {
        res.push_back(clip.Name);
    }
    return res;
}


text:
import Auth from 'api/Auth';

class Platform {
  static cache = {};

  /**
   *
   * @param {string} endpoint
   * @param {*} config
   * @returns {Promise}
   */
  fetch(endpoint, config) {
    return fetch(endpoint, config)
      .then((resp) => {
        if (!resp.ok) {
          throw Error(`${resp.status} - ${resp.statusText}`);
        }
        return resp.json();
      });
  }

  /**
   *
   * @param {string} endpoint
   * @param {*} config
   * @param {string} cacheKey
   * @returns {Promise}
   */
  fetchCached(endpoint, config, cacheKey) {
    if (this.cacheExists(cacheKey)) {
      return new Promise((resolve) => {
        resolve(this.cacheGet(cacheKey));
      });
    }

    return fetch(endpoint, config)
      .then((resp) => {
        if (!resp.ok) {
          throw Error(`${resp.status} - ${resp.statusText}`);
        }
        return resp.json();
      })
      .then((json) => {
        this.cacheSet(cacheKey, json);
        return json;
      });
  }

  /**
   *
   * @param {string} method
   * @param {*|string} extraHeaders
   * @param {string|null} body
   * @returns {{method: *, body: *, headers: {Accept: string}}}
   */
  buildConfig(method, extraHeaders = {}, body = null) {
    if (typeof extraHeaders === 'string') {
      body = extraHeaders;
      extraHeaders = {};
    }
    const headers = this.buildHeaders(extraHeaders);

    return {
      method,
      body,
      headers
    };
  }

  /**
   *
   * @param {*} extra
   * @returns {{Accept: string}}
   * @private
   */
  buildHeaders(extra = {}) {
    const headers = {
      Accept:         'application/json',
      'Content-Type': 'application/json'
    };
    if (Auth.isAuthenticated()) {
      headers.Authorization = `Bearer ${Auth.getToken()}`;
    }

    return Object.assign({}, headers, extra);
  }

  /**
   *
   * @param {string} key
   * @param {*} value
   */
  cacheSet(key, value) {
    Platform.cache[key] = value;
  }

  /**
   *
   * @param {string} key
   * @returns {*}
   */
  cacheGet(key) {
    return Platform.cache[key];
  }

  /**
   *
   * @param {string} key
   * @returns {boolean}
   */
  cacheExists(key) {
    return Platform.cache[key] !== undefined;
  }
}

export default Platform;


text:
namespace ContosoUniversity.Migrations
{
    using System.Data.Entity.Migrations;
    using System.Data.Entity.Migrations.Infrastructure;
    using System.Resources;

    public sealed partial class InitialCreate : IMigrationMetadata
    {
        private readonly ResourceManager Resources = new ResourceManager(typeof(InitialCreate));

        string IMigrationMetadata.Id
        {
            get { return "201307230521326_InitialCreate"; }
        }

        string IMigrationMetadata.Source
        {
            get { return null; }
        }

        string IMigrationMetadata.Target
        {
            get { return Resources.GetString("Target"); }
        }
    }
}