text:
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/smp.h>
#include <linux/io.h>
#include <linux/of.h>
#include <linux/of_fdt.h>
#include <linux/vexpress.h>

#include <asm/mcpm.h>
#include <asm/smp_scu.h>
#include <asm/mach/map.h>

#include <mach/motherboard.h>

#include <plat/platsmp.h>

#include "core.h"

#if defined(CONFIG_OF)

static enum {
	GENERIC_SCU,
	CORTEX_A9_SCU,
} vexpress_dt_scu __initdata = GENERIC_SCU;

static struct map_desc vexpress_dt_cortex_a9_scu_map __initdata = {
	.virtual	= V2T_PERIPH,
	/* .pfn	set in vexpress_dt_init_cortex_a9_scu() */
	.length		= SZ_128,
	.type		= MT_DEVICE,
};

static void *vexpress_dt_cortex_a9_scu_base __initdata;

const static char *vexpress_dt_cortex_a9_match[] __initconst = {
	"arm,cortex-a5-scu",
	"arm,cortex-a9-scu",
	NULL
};

static int __init vexpress_dt_find_scu(unsigned long node,
		const char *uname, int depth, void *data)
{
	if (of_flat_dt_match(node, vexpress_dt_cortex_a9_match)) {
		phys_addr_t phys_addr;
		const __be32 *reg = of_get_flat_dt_prop(node, "reg", NULL);

		if (WARN_ON(!reg))
			return -EINVAL;

		phys_addr = be32_to_cpup(reg);
		vexpress_dt_scu = CORTEX_A9_SCU;

		vexpress_dt_cortex_a9_scu_map.pfn = __phys_to_pfn(phys_addr);
		iotable_init(&vexpress_dt_cortex_a9_scu_map, 1);
		vexpress_dt_cortex_a9_scu_base = ioremap(phys_addr, SZ_256);
		if (WARN_ON(!vexpress_dt_cortex_a9_scu_base))
			return -EFAULT;
	}

	return 0;
}

void __init vexpress_dt_smp_map_io(void)
{
	if (initial_boot_params)
		WARN_ON(of_scan_flat_dt(vexpress_dt_find_scu, NULL));
}

static int __init vexpress_dt_cpus_num(unsigned long node, const char *uname,
		int depth, void *data)
{
	static int prev_depth = -1;
	static int nr_cpus = -1;

	if (prev_depth > depth && nr_cpus > 0)
		return nr_cpus;

	if (nr_cpus < 0 && strcmp(uname, "cpus") == 0)
		nr_cpus = 0;

	if (nr_cpus >= 0) {
		const char *device_type = of_get_flat_dt_prop(node,
				"device_type", NULL);

		if (device_type && strcmp(device_type, "cpu") == 0)
			nr_cpus++;
	}

	prev_depth = depth;

	return 0;
}

static void __init vexpress_dt_smp_init_cpus(void)
{
	int ncores = 0, i;

	switch (vexpress_dt_scu) {
	case GENERIC_SCU:
		ncores = of_scan_flat_dt(vexpress_dt_cpus_num, NULL);
		break;
	case CORTEX_A9_SCU:
		ncores = scu_get_core_count(vexpress_dt_cortex_a9_scu_base);
		break;
	default:
		WARN_ON(1);
		break;
	}

	if (ncores < 2)
		return;

	if (ncores > nr_cpu_ids) {
		pr_warn("SMP: %u cores greater than maximum (%u), clipping\n",
				ncores, nr_cpu_ids);
		ncores = nr_cpu_ids;
	}

	for (i = 0; i < ncores; ++i)
		set_cpu_possible(i, true);
}

static void __init vexpress_dt_smp_prepare_cpus(unsigned int max_cpus)
{
	int i;

	switch (vexpress_dt_scu) {
	case GENERIC_SCU:
		for (i = 0; i < max_cpus; i++)
			set_cpu_present(i, true);
		break;
	case CORTEX_A9_SCU:
		scu_enable(vexpress_dt_cortex_a9_scu_base);
		break;
	default:
		WARN_ON(1);
		break;
	}
}

#else

static void __init vexpress_dt_smp_init_cpus(void)
{
	WARN_ON(1);
}

void __init vexpress_dt_smp_prepare_cpus(unsigned int max_cpus)
{
	WARN_ON(1);
}

#endif

/*
 * Initialise the CPU possible map early - this describes the CPUs
 * which may be present or become present in the system.
 */
static void __init vexpress_smp_init_cpus(void)
{
	if (ct_desc)
		ct_desc->init_cpu_map();
	else
		vexpress_dt_smp_init_cpus();

}

static void __init vexpress_smp_prepare_cpus(unsigned int max_cpus)
{
	/*
	 * Initialise the present map, which describes the set of CPUs
	 * actually populated at the present time.
	 */
	if (ct_desc)
		ct_desc->smp_enable(max_cpus);
	else
		vexpress_dt_smp_prepare_cpus(max_cpus);

	/*
	 * Write the address of secondary startup into the
	 * system-wide flags register. The boot monitor waits
	 * until it receives a soft interrupt, and then the
	 * secondary CPU branches to this address.
	 */
	vexpress_flags_set(virt_to_phys(versatile_secondary_startup));
}

struct smp_operations __initdata vexpress_smp_ops = {
	.smp_init_cpus		= vexpress_smp_init_cpus,
	.smp_prepare_cpus	= vexpress_smp_prepare_cpus,
	.smp_secondary_init	= versatile_secondary_init,
	.smp_boot_secondary	= versatile_boot_secondary,
#ifdef CONFIG_HOTPLUG_CPU
	.cpu_die		= vexpress_cpu_die,
#endif
};

bool __init vexpress_smp_init_ops(void)
{
#ifdef CONFIG_MCPM
	/*
	 * The best way to detect a multi-cluster configuration at the moment
	 * is to look for the presence of a CCI in the system.
	 * Override the default vexpress_smp_ops if so.
	 */
	struct device_node *node;
	node = of_find_compatible_node(NULL, NULL, "arm,cci-400");
	if (node && of_device_is_available(node)) {
		mcpm_smp_set_ops();
		return true;
	}
#endif
	return false;
}


text:
@implementation FDListEntity

- (instancetype)initWithDictionary:(NSDictionary *)dictionary
{
    self = super.init;
    if (self) {
        self.title = dictionary[@"title"];
        self.content = dictionary[@"content"];
        self.imageName = dictionary[@"imageName"];
        self.hasAudioClip = [dictionary[@"audio"] boolValue];
    }
    return self;
}

@end

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace App\View\Helper;

use Cake\View\Helper;

/**
 * LevelBar helper
 */
class LevelBarHelper extends Helper
{

    /**
     * Default configuration.
     *
     * @var array
     */
    protected $_defaultConfig = [];

    /**
     * Build the helper
     *
     * @param array $config Array of helper configuration
     * @return void
     * @throws \RuntimeException
     */
    public function initialize(array $config)
    {
        parent::initialize($config);

        if (empty($this->getConfig('rarities'))) {
            throw new \RuntimeException(__('Expected an array of Rarity entities set to the view.'));
        }
    }

    /**
     * Generate a level progress bar
     *
     * @param int $level Units current level
     * @param int $rarity Units rarity tier
     * @return string
     */
    public function progress($level, $rarity): string
    {
        $maxLevel = $this->getConfig('rarities.' . ($rarity - 1))->get('max_level');
        $percent = $this->percentComplete($level, $maxLevel);

        if ($level === $maxLevel) {
            $barLabel = 'MAX (' . $maxLevel . ')';
        } else {
            $barLabel = $level . '/' . $maxLevel . ' (' . number_format($percent, 0) . '%)';
        }

        $output = "
";
        $output .= "barClass($percent) . "' style='width:" . $percent . "%'>";
        $output .= "" . $barLabel . "";
        $output .= "
";

        return $output;
    }

    /**
     * How much of the rarity tier is completed as a percentage
     *
     * @param int $level Units current level
     * @param int $max Max level of the rarity tier
     * @return float
     */
    protected function percentComplete($level, $max): float
    {
        if ($level <= $max) {
            return ($level / $max) * 100;
        }

        return 0.0;
    }

    /**
     * Generate an appropriate css class depending on the percentage complete
     *
     * @param float $percentComplete Percentage completion of a rarity tier
     * @return string
     */
    protected function barClass($percentComplete): string
    {
        switch ($percentComplete) {
            case $percentComplete >= 0 && $percentComplete <= 25:
            default:
                return 'low';
            case $percentComplete >= 26 && $percentComplete <= 50:
                return 'medium';
            case $percentComplete >= 51 && $percentComplete <= 75:
                return 'high';
            case $percentComplete >= 76 && $percentComplete <= 99:
                return 'vhigh';
            case 100:
                return 'max';
        }
    }
}


text:
using System;

namespace AutoBogus
{
  internal sealed class AutoGeneratorMemberOverride<TType, TValue>
    : AutoGeneratorOverride
  {
    internal AutoGeneratorMemberOverride(string memberName, Func<AutoGenerateOverrideContext, TValue> generator)
    {
      if (string.IsNullOrWhiteSpace(memberName))
      {
        throw new ArgumentException("Value cannot be null or white space", nameof(memberName));
      }

      Type = typeof(TType);
      MemberName = memberName;
      Generator = generator ?? throw new ArgumentNullException(nameof(generator));
    }

    private Type Type { get; }
    private string MemberName { get; }
    private Func<AutoGenerateOverrideContext, TValue> Generator { get; }

    public override bool CanOverride(AutoGenerateContext context)
    {
      return context.ParentType == Type && MemberName.Equals(context.GenerateName, StringComparison.OrdinalIgnoreCase);
    }

    public override void Generate(AutoGenerateOverrideContext context)
    {
      context.Instance = Generator.Invoke(context);
    }
  }
}


text:
#include "cbi.h"
#include "common.h"
#include "compile_time_macros.h"
#include "console.h"
#include "cros_board_info.h"
#include "fw_config.h"

#define CPRINTS(format, args...) cprints(CC_CHIPSET, format, ##args)

static union agah_cbi_fw_config fw_config;
BUILD_ASSERT(sizeof(fw_config) == sizeof(uint32_t));

/*
 * FW_CONFIG defaults for agah if the CBI.FW_CONFIG data is not
 * initialized.
 */
static const union agah_cbi_fw_config fw_config_defaults = {
	.kb_bl = KEYBOARD_BACKLIGHT_ENABLED,
};

/****************************************************************************
 * Agah FW_CONFIG access
 */
void board_init_fw_config(void)
{
	if (cbi_get_fw_config(&fw_config.raw_value)) {
		CPRINTS("CBI: Read FW_CONFIG failed, using board defaults");
		fw_config = fw_config_defaults;
	}
}

union agah_cbi_fw_config get_fw_config(void)
{
	return fw_config;
}


text:
This WebInterface is developed by the Mobile and Distributed Systems Lab (MDSLab) at the University of Messina, Italy for the IoTronic project. It is based on a framework called CodeIgniter http://www.codeigniter.com/ (we used version 3.1.2).

# Requirements (satisfied during the guide)
* Server Web (apache2)
* CodeIgniter-3.1.2
* Some Linux libraries
  * curl
  * php5 / php7.3
* A CodeIgniter library
  * Curl.php
* A responsive front-end framework (foundation-5.5.3 --> http://foundation.zurb.com/downloads/foundation-5.5.3.zip).

# Installation Guides
* [Ubuntu](docs/README_Ubuntu.md)
* [Debian](docs/README_Debian.md)


text:
package org.opendatakit.provider;

import android.net.Uri;
import android.provider.BaseColumns;

import java.util.List;

/**
 * ODK Survey (only)
 * <p>
 * Tracks what forms are available in the ODK Survey forms directory.
 */
public final class FormsColumns implements BaseColumns {
  /**
   * Used in FormsProvider
   */
  @SuppressWarnings("unused")
  public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.opendatakit.form";
  /**
   * Used in FormsProvider
   */
  @SuppressWarnings("unused")
  public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.opendatakit.form";
  /**
   * The form_id that holds the common javascript files for Survey
   */
  public static final String COMMON_BASE_FORM_ID = "framework";
  // These are the only things needed for an insert
  public static final String TABLE_ID = "tableId"; // for Tables linkage
  public static final String FORM_ID = "formId";
  /**
   * the entire JSON settings portion of the formDef.json file
   * Used in FormsInfo and FormsProvider
   */
  @SuppressWarnings("WeakerAccess")
  public static final String SETTINGS = "settings";

  // these are extracted from the formDef.json for you
  /**
   * form_version | value from the settings sheet
   * Used in FormIdStruct, FormListLoader, FormsProvider and FormInfo
   */
  @SuppressWarnings("WeakerAccess")
  public static final String FORM_VERSION = "formVersion"; // can be null
  /**
   * survey | display.title from the settings sheet
   * In general, this will be an localizable JS object.
   * Used in survey AndroidShortcuts and FormListLoader, also in services in FormsProvider,
   * FormInfo, OdkResolveConflictRowLoader and OdkResolveCheckpointRowLoader
   */
  @SuppressWarnings("WeakerAccess")
  public static final String DISPLAY_NAME = "displayName";
  /**
   * locale that the form should start in (extracted from settings)
   * Used in FormInfo and FormsProvider in services
   */
  @SuppressWarnings("WeakerAccess")
  public static final String DEFAULT_FORM_LOCALE = "defaultFormLocale";
  /**
   * column name for the 'instance_name' (display name) of a submission
   * Used in FormsProvider FormInfo OdkResolveConflictRowLoader and OdkResolveCheckpointRowLoader
   * (extracted from settings)
   */
  @SuppressWarnings("WeakerAccess")
  public static final String INSTANCE_NAME = "instanceName";
  /**
   * these are generated for you
   * Used in InitializationUtil, FormsProvider, FormInfo
   */
  public static final String JSON_MD5_HASH = "jsonMd5Hash";
  /**
   * Used in FormIdStruct, FormListLoader, FormProvider, FormInfo
   * last modification date of the file (long)
   */
  @SuppressWarnings("WeakerAccess")
  public static final String DATE = "date";
  /**
   * bytes in the formDef.json (long)
   * Used inFormsProvider, FormInfo
   */
  @SuppressWarnings("WeakerAccess")
  public static final String FILE_LENGTH = "fileLength";
  /**
   * NOTE: this omits _ID (the primary key)
   * Used in FormInfo
   */
  @SuppressWarnings("unused")
  public static final String[] formsDataColumnNames = { TABLE_ID, FORM_ID, SETTINGS, FORM_VERSION,
      DISPLAY_NAME, DEFAULT_FORM_LOCALE, INSTANCE_NAME, JSON_MD5_HASH, FILE_LENGTH, DATE };

  /**
   * This class cannot be instantiated
   */
  private FormsColumns() {
  }

  /**
   * Get the create sql for the forms table
   * Used in services ODKDatabaseImplUtils
   *
   * @return a sql query that can be used to create the table
   */
  @SuppressWarnings("unused")
  public static String getTableCreateSql(String tableName) {
    //@formatter:off
    return "CREATE TABLE IF NOT EXISTS " + tableName + " ("
           + _ID + " integer not null primary key, " // for Google...
           + TABLE_ID + " text not null, " // PK part 1
           + FORM_ID + " text not null, "  // PK part 2
           + SETTINGS + " text not null, "
           + FORM_VERSION + " text, "
           + DISPLAY_NAME + " text not null, "
           + DEFAULT_FORM_LOCALE + " text null, "
           + INSTANCE_NAME + " text null, "
           + JSON_MD5_HASH + " text not null, "
           + FILE_LENGTH + " integer not null, "
           + DATE + " integer not null " // milliseconds
           + ")";
    //@formatter:on
  }

  /**
   * Gets an app name from the given URI. Used in FormIdStruct
   * @param uri a URI that contains an app name
   * @return the app name from the URI
   */
  @SuppressWarnings("unused")
  public static String extractAppNameFromFormsUri(Uri uri) {
    List<String> segments = uri.getPathSegments();

    if (segments.size() < 1) {
      throw new IllegalArgumentException("Unknown URI (incorrect number of segments!) " + uri);
    }

    return segments.get(0);
  }
}


text:
local vector = require "vector"

local walls = {}
walls.side_walls_thickness = 34
walls.top_wall_thickness = 26
walls.right_border_x_pos = 576
walls.current_level_walls = {}

function walls.new_wall( position, width, height )
   return( { position = position,
	     width = width,
	     height = height } )
end

function walls.update_wall( single_wall )
end

function walls.draw_wall( single_wall )
   love.graphics.rectangle( 'line',
			    single_wall.position.x,
			    single_wall.position.y,
			    single_wall.width,
			    single_wall.height )
   local r, g, b, a = love.graphics.getColor( )
   love.graphics.setColor( 255, 0, 0, 100 )
   love.graphics.rectangle( 'fill',
			    single_wall.position.x,
			    single_wall.position.y,
			    single_wall.width,
			    single_wall.height )
   love.graphics.setColor( r, g, b, a )
end

function walls.construct_walls()
   local left_wall = walls.new_wall(
      vector( 0, 0 ),
      walls.side_walls_thickness,
      love.graphics.getHeight()
   )
   local right_wall = walls.new_wall(
      vector( walls.right_border_x_pos, 0 ),
      walls.side_walls_thickness,
      love.graphics.getHeight()
   )
   local top_wall = walls.new_wall(
      vector( 0, 0 ),
      walls.right_border_x_pos,
      walls.top_wall_thickness
   )
   walls.current_level_walls["left"] = left_wall
   walls.current_level_walls["right"] = right_wall
   walls.current_level_walls["top"] = top_wall
end

function walls.update( dt )
end

function walls.draw()
   for _, wall in pairs( walls.current_level_walls ) do
      walls.draw_wall( wall )
   end
end

return walls


text:
import React from 'react'

const NotFound = () => {
  return
404

}

export default NotFound


text:
datarouter-logging extends log4j2 to provide logging configuration using type-safe Java, instead of XML configuration files. It also provides an easy way to modify logging levels and appenders at runtime.

## Installation with Maven

```xml
<dependency>
	<groupId>io.datarouter</groupId>
	<artifactId>datarouter-logging</artifactId>
	<version>0.0.117</version>
</dependency>
```

## Usage

### Default usage

By default, datarouter-logging defines an appender for the standard output, and sends everything with level WARN to it. To log, simply define a slf4j logger and use it like that:

```java
package io.datarouter.example;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Main{
	private static final Logger logger = LoggerFactory.getLogger(Main.class);

	public static void main(String[] args){
		logger.warn("sent to stdout");
		logger.info("not sent to stdout");
	}
}
```

### Static logging configuration

To define a custom static logging configuration, you will need to extend `BaseLog4j2Configuration`. In the constructor of your implementation, you can define appenders and logger configurations, or also use `registerParent` to inherit a configuration.

```java
package io.datarouter.example;
//imports
public class ExampleLog4j2Configuration extends BaseLog4j2Configuration{
	public ExampleLog4j2Configuration(){
		//Register the default configuration as a parent to inherit the default stdout appender
		registerParent(DatarouterLog4j2Configuration.class);

		//Retrieve the stdout appender
		Appender console = getAppender(DatarouterLog4j2Configuration.CONSOLE_APPENDER_NAME);

		//Set the logger level of the current package to INFO
		addLoggerConfig(getClass().getPackage().getName(), Level.INFO, false, console);
	}
}
```

You will need to register this configuration class by creating a file in `src/main/resources` with the `.datarouter-logging` extension that contains the full name of the class.

`src/main/resources/log4j2.datarouter-logging`
```
io.datarouter.example.ExampleLog4j2Configuration
```

### Runtime logging configuration

You can use `Log4j2Configurator` to update the configuration of your loggers at runtime.

```java
package io.datarouter.example;
//imports
public class Main{
	private static final Logger logger = LoggerFactory.getLogger(Main.class);

	public static void main(String[] args){
		logger.debug("not logged");

		//Instantiate Log4j2Configurator
		Log4j2Configurator configurator = new Log4j2Configurator();
		String console = DatarouterLog4j2Configuration.CONSOLE_APPENDER_NAME;

		//Set the level of the logger for the current class to DEBUG
		configurator.updateOrCreateLoggerConfig(Main.class.getPackage(), Level.DEBUG, false, console);

		logger.debug("logged");
	}

}
```

## License

This library is licensed under the Apache License, Version 2.0 - see [LICENSE](../LICENSE) for details.


text:
<?php namespace Ngakost\TitanWall\Models;

use Illuminate\Database\Eloquent\Model as EloquentModel;

/**
 * Odenktools Core Model
 * @license MIT
 */
class TitanWallModel extends EloquentModel
{
    /**
     * Table prefix
     *
     * @var string
     */
    protected $prefix = '';

    /**
     * Default Odenktools Table
     *
     * @var array|mixed
     */
    protected $tables = array();

    /**
     * @var array Make the model's attributes public so behaviors can modify them.
     */
    public $attributes = [];

    /**
     * @var array List of attribute names which are json encoded and decoded from the database.
     */
    protected $jsonable = [];

    /**
     * @param array $attributes
     */
    public function __construct(array $attributes = [])
    {
        parent::__construct();

		$this->fill($attributes);

        $defaultDb = \Config::get('database.default');

        if($defaultDb == 'mysql'){

            // Set the prefix
            $this->prefix = \Config::get('titanwall.prefix');

            $this->tables = \Config::get('titanwall.tables');

            $this->tables['user'] = $this->prefix.$this->tables['user'];

            $this->tables['user_fields'] = $this->prefix.$this->tables['user_fields'];

            $this->tables['role'] = $this->prefix.$this->tables['role'];

            $this->tables['role_profile_fields'] = $this->prefix.$this->tables['role_profile_fields'];

            if($this->getTable() != '' ){
                $this->table = $this->prefix.$this->getTable();
            }
        }
    }
}


text:
package org.hisp.dhis.user.action;

import static org.apache.commons.lang3.StringUtils.isNotBlank;

import java.util.List;

import org.hisp.dhis.paging.ActionPagingSupport;
import org.hisp.dhis.user.UserAuthorityGroup;
import org.hisp.dhis.user.UserService;

/**
 * @author Thanh Nguyen
 * @version $Id: GetRoleListAction.java 4079 2007-11-20 11:42:23Z larshelg $
 */
public class GetRoleListAction
    extends ActionPagingSupport<UserAuthorityGroup>
{
    // -------------------------------------------------------------------------
    // Dependencies
    // -------------------------------------------------------------------------

    private UserService userService;

    public void setUserService( UserService userService )
    {
        this.userService = userService;
    }

    // -------------------------------------------------------------------------
    // Input & Output
    // -------------------------------------------------------------------------

    private List<UserAuthorityGroup> userAuthorityGroups;

    public List<UserAuthorityGroup> getUserAuthorityGroups()
    {
        return userAuthorityGroups;
    }

    private String key;

    public void setKey( String key )
    {
        this.key = key;
    }

    public String getKey()
    {
        return key;
    }

    // -------------------------------------------------------------------------
    // Action implementation
    // -------------------------------------------------------------------------

    @Override
    public String execute()
        throws Exception
    {
        if ( isNotBlank( key ) ) // Filter on key only if set
        {
            this.paging = createPaging( userService.getUserRoleCountByName( key ) );

            userAuthorityGroups = userService.getUserRolesBetweenByName( key, paging.getStartPos(), paging.getPageSize() );
        }
        else
        {
            this.paging = createPaging( userService.getUserRoleCount() );

            userAuthorityGroups = userService.getUserRolesBetween( paging.getStartPos(), paging.getPageSize() );
        }

        return SUCCESS;
    }
}


text:
Fifty Shades of Grey
====================

Literally

![Fifty Shades of Grey](https://upload.wikimedia.org/wikipedia/en/7/73/Fifty_Shades_of_Grey_poster.jpg)


text:
namespace Volt {

SDLWindow::SDLWindow (Game* game, const string& name, int w, int h,
                      bool fullscreen)
    : m_game(game),
      m_screen(NULL) {

    LOG(INFO) << "Initializing SDLWindow...";

    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) < 0) {
        LOG(FATAL) << "Unable to initialize SDL: " << SDL_GetError();
        exit(1);
    }

    SDL_ShowCursor(SDL_DISABLE);

    // VSync.
    SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, 1);
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
    SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);

    int flags = SDL_SWSURFACE | SDL_OPENGL | (fullscreen ? SDL_FULLSCREEN : 0);
    SDL_Surface* screen = SDL_SetVideoMode(w, h, 0, flags);
    if (screen == NULL) {
        LOG(FATAL) << "Unable to set video mode: " << SDL_GetError();
        exit(1);
    }

    SDL_WM_SetCaption(name.c_str(), NULL);

    m_screen = screen;
}

SDLWindow::~SDLWindow () {
    LOG(INFO) << "Destroying SDLWindow...";
    Close();
}

void SDLWindow::Close () {
    SDL_Quit();
}

void SDLWindow::SetTitle (string title) {
    SDL_WM_SetCaption(title.c_str(), NULL);
}

void SDLWindow::Screenshot (const string& filename) {
    SDL_Surface* screen = (SDL_Surface*)m_screen;

    SDL_Surface* temp = SDL_CreateRGBSurface(SDL_SWSURFACE,
                                             screen->w, screen->h, 24,
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
    0x000000FF, 0x0000FF00, 0x00FF0000, 0
#else
    0x00FF0000, 0x0000FF00, 0x000000FF, 0
#endif
    );

    if (temp == NULL)
        return;

    unsigned char* pixels = (unsigned char*)malloc(3 * screen->w * screen->h);

    if (pixels == NULL) {
        SDL_FreeSurface(temp);
        return;
    }

    glReadPixels(0, 0, screen->w, screen->h,
                 GL_RGB, GL_UNSIGNED_BYTE, pixels);

    for (int i = 0; i < screen->h; i++)
        memcpy(((char *)temp->pixels) + temp->pitch * i,
               pixels + 3 * screen->w * (screen->h - i - 1),
               screen->w * 3);
    free(pixels);

    SDL_SaveBMP(temp, filename.c_str());
    SDL_FreeSurface(temp);
}

int SDLWindow::width () const {
    return ((SDL_Surface*)m_screen)->w;
}

int SDLWindow::height () const {
    return ((SDL_Surface*)m_screen)->h;
}

bool SDLWindow::IsKeyPressed (SDLKey key) {
    Uint8* state = SDL_GetKeyState(NULL);
    return state[key];
}

void SDLWindow::SwapBuffers () {
    SDL_GL_SwapBuffers();
}

void SDLWindow::UpdateInput () {
    SDL_Event event;
    while (SDL_PollEvent(&event)) {
        switch (event.type) {
            case SDL_KEYDOWN:
            case SDL_KEYUP:
                m_game->OnKeyEvent(event.key);
            break;
            case SDL_MOUSEBUTTONUP:
            case SDL_MOUSEBUTTONDOWN:
                m_game->OnMouseButtonEvent(event.button);
            break;
            case SDL_MOUSEMOTION:
                m_game->OnMouseMoveEvent(event.motion);
            break;
            case SDL_QUIT:
                m_game->Quit();
            break;
        }
    }
}

}


text:
title: Fish Farming
slug: fish-farming
subjects: life-sciences
# The following are constants: do not modify
layout: subject
type: discipline
---


text:
tQuery.World.registerInstance('addWhammyUI', function(){
	tQuery.createWhammyUI();
	// for chained API
	return this;
});

tQuery.registerStatic('createWhammyUI', function(container){
	if( !container ){
		container	= document.createElement('div')
		container.style.cssText='position: absolute; top: 0.5em; right: 0.5em;';
		container.id	= 'UIcontainer';
		document.body.appendChild(container);
	}

	var html	= [
	"
",
		"WHAMMY.js
",
		"RECORDER
",
		"",
			"<image class='switch' width='80px' height='80px'>",
		"",
  		"DOWNLOAD",
	"
"
	].join('\n');
	container.innerHTML	= html;

	var recorder	= tQuery.createWhammy();
	container.querySelector('.switch').addEventListener('click', function(event){
		recorder.pressSwitch();
	});

	var switchEl	= container.querySelector('.switch')
	switchEl.src	= tQuery.Whammy.baseUrl+'/images/play_noun_project_1541.svg';
	switchEl.title	= 'Start Recording';
	var downloadEl	= container.querySelector('.download')
	recorder.addEventListener('postStart', function(){
		switchEl.src	= tQuery.Whammy.baseUrl+'/images/stop_noun_project_2221.svg';
		switchEl.title	= 'Stop Recording';
	}.bind(this));
	recorder.addEventListener('postStop', function(){
		// update switch image
		switchEl.src	= tQuery.Whammy.baseUrl+'/images/play_noun_project_1541.svg';
		switchEl.title	= 'Start Recording';
		// init download link
		downloadEl.href	= recorder.finalizedURL();
		downloadEl.style.display	= ''
	}.bind(this));
});


text:
permalink: /
layout: page
---

# Canada can't become America

Canada has always needed to be a cautious neighbour of America. We have watched
them go through revolutions of epic proportions and build itself up on the back of
slavery. It has created and spearheaded the most important innovations in the
history of humanity. It is the driving force behind the modern world. It created
freedom. America has always been about doing good, but there is a raw force to
it that always has casualties. The further we go back in time the more you will
find Canadian leaders on all sides waning in caution to ensure that America lets
us be. This is the reason that we come across as very polite.

We are stoic people who understand the meaning of common good. This
understanding has been quintessential in the preservation of our society and
the basis of our values. We can not forget the true reason that so many of us
have died for this nation. We have no ego, because having one would put us in
danger of losing what we have worked so hard to create.

The political system in America is designed to let freedom reign, and is
naturally polarizing. It encourages an us versus them view of the world. The
reality is that there can only be one America and everyone else just has to
learn how to deal with it. Canada has always managed to be the good neighbour
and do what it can to help out. This has always been in a process to ensure our
unity. From far and wide.

# Unity before politics

In Canada we have many parties because it ensures that more points of view are
represented. In America they have as few parties as possible so that the most
amount of power can be attained. America believes that power is needed to get
things done, and it works for them. It's just two people facing off, with one
argument against the other. The better man wins and the adgenda is carried
out in its raw and pure vision. If you are the world super power, you get to
opperate this way. In America powerful people desire to be mayors and political
allegiance is paramount.

In Canada the mayor is one vote that is meant as a symbol of the common voice.
Our mayors are meant to have no political allegiance. Their role is to persaude
counsil to think about the common voice before that of their own wards. City
hall is responsible for the aspects of our lives that effect us each and every
day. There is no value in letting politics slow that process down.

# The Conservative movement is hurting Canada

For the first 70 years of Canada the Liberal party helped shape our identity.
The center-left party was Canada's first and the point of view was a truly
Canadian one. As Western Canada developed so did their points of view and so
the center-right Progressive Conservatives were started to better represent them.
As time went on the Tories weakened and the Liberals became entrenched in cronyism.
The New Democrats were kicked off to ensure that society kept up with modern
values and universal health care was born.

As American media boomed Canada began to become more acquainted with American
culture. Through this process Canadians have become inundated with the idea that
certain groups may be out to get each other. In the ninties The Bloc Québécois
came into power in an effort to separate from Canada. The Western Reform Party
proppped up a few years later with much of the same intent. In the end the
referendum of Quebec only made Canada stronger.

Stephen Harper is a brilliant politcal mind and managed to learn from all of
this. If Canada could have a Conservative Party that mirrored that of the
American Republican party it could ride on any rhetoric that suited it. American media
is designed to sell ideas and points of view to people. Ten years ago
the Canadian Alliance was created in a merger of the Reform and Progressive
Conservatives. Ever since then it has been a war between liberal and
conservative ideals. This process is destroying Canadian values and we have
become irrational in our opposition to each other.

# Amalgamation destroyed the spirit of Toronto

Once upon a time the people of Etobikoke told the GTA that they were from Etobikoke
and the rest of world that they were from Toronto. Guess what, they still do.
No one in Toronto wanted amalgamation. The conservative party had the authority
to hand the raw deal and they took no prisoners in getting it carried out. They
got to look like heros to conservative Ontario for saving a few bucks while
Toronto got to start hating itself. Mission accomplished and now it is too
expensive to reverse the process.

Today Toronto has become a polarized voting base and it is open season for
federal politicians to interfere. In the end Torontonians are left with rhetoric
and no real action.

# Rob Ford is not a politician

Rob Ford is a personality and a real voice of the people, he could have been a
very good mayor of Etobikoke. All a mayor needs to be is likeable and represent
something that everyone can relate to. The reality is that the urban core of
Toronto has a lot of elitism and apathy because that is just how big cities are.
City folk tend to have a mission beyond their home whereas suburban folks have a
strong sense of community and value their personal property. The difference in
these points of view will always clash when stacked against each other. It becomes
us vs them.

Rob Ford will always drive out more voters because he has become a symbol of
suburban values. These are not Conservative values, and by now the federal
Conservative party likely wishes they had not created this association. Rob
Ford grew up in the city burbs, and drugs are just a part of that culture. It
is not evil, just reality. The suburban voters of Toronto understand this
and will always back him. Even though they are the suburbs, it is still city
life. It tends to be a little rough, but the people are good and passionate.

# Politics is plauged with elitism

Most politicians have excelled their way through superior school systems and
executed their careers in the same fashion. While they are always extremely
capable people and have the best intentions, they will always feel that they
know best. This can be especially dangerous when they polarize their viewpoint.
If you spend your life thinking that others are dead wrong, you start to ignore
the bigger picture.

# Baby boomers need to retire

The reality is that Canadian politicians can no longer help us prepare for the
future. An entire generation of people are at retirement age in this country
with no plans of retiring. This goes for politicians, executives, union leaders
and anyone else that has a stake in our future. We need a plan to fix this.

The state of technology in government hands is atrocious. Simply, this is a
generational problem. Baby boomers fear technology and generally get ripped
off when buying it. We need people who see the potential of how technology will
impact our future and the future of our children. Technology can be free
today, not tomorrow.

# Youth will shape the future

Politicians obsess over jobs and retirement like it were mankind's eternal
battle. The reality is that no one is retiring and no industry other than
technology is generating substantial growth. Very few of those controlling the
money have even the slightest clue as to how technology is shaping itself. It
is a dead end game if we carry on this way.

We must allow youth to turn their infinite potential away from video games and
social media to focus on designing the future. There is no other rational
alternative if all options are considered pragmatically.

# Government can be open-source

If we keep putting each other in places of power we will never get what we
need. In today's age voting is still not available online and we elect people
who tailor their platform to a generation on the way out. No one wants to fix
this because there is no benefit to those in control now.

If we can figure out how to get the things that we need to rise to the top we
can start to make a difference. This will never happen if we elect any one
person to represent us in today's age.

# It starts with the Mayor

Rob Ford proves that Toronto runs fine without a Mayor and that there is no real
danger in experimenting with the role. His personality has been exploited by the
media and in the wake Toronto has been put on an internationl stage. He is a
good man but is likely becoming corrupted by celebrity. Rob Ford is now seeking
media attention wherever he can find it and this is not helpful for the future
of Toronto. It is a great strategy to win, but Toronto needs to see past it.
We must remember that the media makes it's money by covering every detail of his
way of life.

This opportunity can be seized. Toronto can redefine politics. The plan is
shaping [here](http://openmayor.ca/the-plan), and anyone can contribute
[here](https://github.com/freesurface/mayor).


text:
angular.module('myApp')
    .controller('overviewController', function($scope, $http, $routeParams) {
       $scope.bookName = '';

        $http({
            method: 'GET',
            url: 'http://localhost:8080/bookDescriptions'
        }).then(function successCallback(response) {
            $scope.books = response.data._embedded.bookDescriptions;
        }, function errorCallback(response) {
            console.log(response);
        });
});


text:
package com.mercadopago.android.px.model;

public class CouponDiscount extends Discount {
    public CouponDiscount(Builder builder) {
        super(builder);
    }
}


text:
<?php
session_start();
header("Content-Type: text/plain"); // Utilisation d'un header pour spécifier le type de contenu de la page. Ici, il s'agit juste de texte brut (text/plain).
include('log.php'); // chargement de la fonction de log
addlog("Chargement suppression_modele_service.php");

include_once('connexion_sql_supervision.php');
$sID_Modele_Service = (isset($_POST["ID_Modele_Service"])) ? $_POST["ID_Modele_Service"] : NULL;

try {
	$bdd_supervision->beginTransaction();
	/**
	 * Suppression du modèle de service
	 */
	$del_Modele = $bdd_supervision->prepare('DELETE
			 FROM modele_service
			 WHERE ID_Modele_Service = :ID_Modele_Service');
	$del_Modele->execute(Array(
			'ID_Modele_Service' => htmlspecialchars($sID_Modele_Service)
	)) or die(print_r($del_Modele->errorInfo()));
	$del_Relation_Modele = $bdd_supervision->prepare('DELETE
			 FROM relation_modeles
			 WHERE ID_Modele_Service = :ID_Modele_Service');
	$del_Relation_Modele->execute(Array(
			'ID_Modele_Service' => htmlspecialchars($sID_Modele_Service)
	)) or die(print_r($del_Relation_Modele->errorInfo()));
	$bdd_supervision->commit();
} catch (Exception $e) {
	$bdd_supervision->rollBack();
	http_response_code(500);
	die('Erreur suppression_modele_service: ' . $e->getMessage());
};

echo "Le modèle a bien été supprimé.";


text:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Driver;
using MongoDBSample.Entities;

namespace MongoDBSample.DataLayer
{
    public class SampleContext : IContext, IDisposable
    {
        private IMongoDatabase _db;

        public SampleContext(string databasePassword)
        {
            var connectionString = new AppSettingsReader().GetValue("sampleDb", typeof (string)).ToString();
            connectionString = connectionString.Replace("{{password}}", databasePassword);
            var client = new MongoClient(connectionString);
            _db = client.GetDatabase(connectionString.Split('/').Last());
        }

        public IMongoCollection<User> AppUsers()
        {
            return _db.GetCollection<User>("User");
        }

        public void Dispose()
        {
            throw new NotImplementedException();
        }
    }
}


text:
package org.sparkcommerce.core.search.domain;

import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

/**
 * @author Jeff Fischer
 */
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "SC_SEARCH_FACET_XREF")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "blStandardElements")
public class RequiredFacetImpl implements RequiredFacet {

    protected static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(generator= "RequiredFacetId")
    @GenericGenerator(
        name="RequiredFacetId",
        strategy="org.sparkcommerce.common.persistence.IdOverrideTableGenerator",
        parameters = {
            @Parameter(name="segment_value", value="RequiredFacetImpl"),
            @Parameter(name="entity_name", value="org.sparkcommerce.core.search.domain.RequiredFacetImpl")
        }
    )
    @Column(name = "ID")
    protected Long id;

    @ManyToOne(targetEntity = SearchFacetImpl.class)
    @JoinColumn(name = "SEARCH_FACET_ID")
    protected SearchFacet searchFacet;

    @ManyToOne(targetEntity = SearchFacetImpl.class, optional=false)
    @JoinColumn(name = "REQUIRED_FACET_ID", referencedColumnName = "SEARCH_FACET_ID")
    protected SearchFacet requiredFacet;

    @Override
    public Long getId() {
        return id;
    }

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

    @Override
    public SearchFacet getRequiredFacet() {
        return requiredFacet;
    }

    @Override
    public void setRequiredFacet(SearchFacet requiredFacet) {
        this.requiredFacet = requiredFacet;
    }

    @Override
    public SearchFacet getSearchFacet() {
        return searchFacet;
    }

    @Override
    public void setSearchFacet(SearchFacet searchFacet) {
        this.searchFacet = searchFacet;
    }
}


text:
@(iv: Int)

    <meta http-equiv="refresh" content="@iv">

@{iv}秒ごとに更新されます


text:
from unittest import TestCase, main
import sys
import os
import svtools.utils as su

class InputStreamTest(TestCase):
    def test_init_hyphen(self):
        new_handle = su.InputStream('-')
        self.assertIs(new_handle.handle, sys.stdin)

    def test_init_stdin(self):
        new_handle = su.InputStream('stdin')
        self.assertIs(new_handle.handle, sys.stdin)

    def test_valid(self):
        self.assertTrue(su.InputStream.valid('-'))
        with self.assertRaises(IOError):
            su.InputStream.valid(None)

    def test_context_manager(self):
        test_directory = os.path.dirname(os.path.abspath(__file__))
        test_data_dir = os.path.join(test_directory, 'test_data', 'utils')
        test_input = os.path.join(test_data_dir, 'file.txt.gz')

        temporary_obj = None
        with su.InputStream(test_input) as stream:
            temporary_obj = stream
            for line in stream:
                sys.stdout.write(line)
        self.assertTrue(temporary_obj.closed)

    def test_plain_iteration(self):
        test_directory = os.path.dirname(os.path.abspath(__file__))
        test_data_dir = os.path.join(test_directory, 'test_data', 'utils')
        test_input = os.path.join(test_data_dir, 'file.txt')

        stream = su.InputStream(test_input)
        for line in stream:
            sys.stdout.write(line)
        stream.close()
        self.assertTrue(stream.handle.closed)

if __name__ == "__main__":
    main()


text:
class BrowserDistribution;

// Internal free-standing functions that are exported here for testing.
namespace profiles {
namespace internal {

// Returns the full path to the profile icon file.
base::FilePath GetProfileIconPath(const base::FilePath& profile_path);

// Returns the default shortcut filename for the given profile name,
// given |distribution|. Returns a filename appropriate for a
// single-user installation if |profile_name| is empty.
base::string16 GetShortcutFilenameForProfile(const base::string16& profile_name,
                                             BrowserDistribution* distribution);

// The same as GetShortcutFilenameForProfile but uniqueness is guaranteed.
// Makes an unique filename among |excludes|.
base::string16 GetUniqueShortcutFilenameForProfile(
    const base::string16& profile_name,
    const std::set<base::FilePath>& excludes,
    BrowserDistribution* distribution);

// This class checks that shortcut filename matches certain profile.
class ShortcutFilenameMatcher {
 public:
  ShortcutFilenameMatcher(const base::string16& profile_name,
                          BrowserDistribution* distribution);

  // Check that shortcut filename has a name given by us (by
  // GetShortcutFilenameForProfile or GetUniqueShortcutFilenameForProfile).
  bool IsCanonical(const base::string16& filename) const;

 private:
  const base::string16 profile_shortcut_filename_;
  const base::StringPiece16 lnk_ext_;
  base::StringPiece16 profile_shortcut_name_;

  DISALLOW_COPY_AND_ASSIGN(ShortcutFilenameMatcher);
};

// Returns the command-line flags to launch Chrome with the given profile.
base::string16 CreateProfileShortcutFlags(const base::FilePath& profile_path);

}  // namespace internal
}  // namespace profiles

class ProfileShortcutManagerWin : public ProfileShortcutManager,
                                  public ProfileInfoCacheObserver,
                                  public content::NotificationObserver {
 public:
  // Specifies whether only the existing shortcut should be updated, a new
  // shortcut should be created if none exist, or only the icon for this profile
  // should be created in the profile directory.
  enum CreateOrUpdateMode {
    UPDATE_EXISTING_ONLY,
    CREATE_WHEN_NONE_FOUND,
    CREATE_OR_UPDATE_ICON_ONLY,
  };
  // Specifies whether non-profile shortcuts should be updated.
  enum NonProfileShortcutAction {
    IGNORE_NON_PROFILE_SHORTCUTS,
    UPDATE_NON_PROFILE_SHORTCUTS,
  };

  explicit ProfileShortcutManagerWin(ProfileManager* manager);
  ~ProfileShortcutManagerWin() override;

  // ProfileShortcutManager implementation:
  void CreateOrUpdateProfileIcon(const base::FilePath& profile_path) override;
  void CreateProfileShortcut(const base::FilePath& profile_path) override;
  void RemoveProfileShortcuts(const base::FilePath& profile_path) override;
  void HasProfileShortcuts(const base::FilePath& profile_path,
                           const base::Callback<void(bool)>& callback) override;
  void GetShortcutProperties(const base::FilePath& profile_path,
                             base::CommandLine* command_line,
                             base::string16* name,
                             base::FilePath* icon_path) override;

  // ProfileInfoCacheObserver implementation:
  void OnProfileAdded(const base::FilePath& profile_path) override;
  void OnProfileWasRemoved(const base::FilePath& profile_path,
                           const base::string16& profile_name) override;
  void OnProfileNameChanged(const base::FilePath& profile_path,
                            const base::string16& old_profile_name) override;
  void OnProfileAvatarChanged(const base::FilePath& profile_path) override;

  // content::NotificationObserver implementation:
  void Observe(int type,
               const content::NotificationSource& source,
               const content::NotificationDetails& details) override;

 private:
  // Gives the profile path of an alternate profile than |profile_path|.
  // Must only be called when the number profiles is 2.
  base::FilePath GetOtherProfilePath(const base::FilePath& profile_path);

  // Creates or updates shortcuts for the profile at |profile_path| according
  // to the specified |create_mode| and |action|. This will always involve
  // creating or updating the icon file for this profile.
  void CreateOrUpdateShortcutsForProfileAtPath(
      const base::FilePath& profile_path,
      CreateOrUpdateMode create_mode,
      NonProfileShortcutAction action);

  ProfileManager* profile_manager_;

  content::NotificationRegistrar registrar_;

  DISALLOW_COPY_AND_ASSIGN(ProfileShortcutManagerWin);
};

#endif  // CHROME_BROWSER_PROFILES_PROFILE_SHORTCUT_MANAGER_WIN_H_


text:
LayerSet::LayerSet(const sf::Texture& texture)
	: texture(texture)
{
}

LayerSet::~LayerSet()
{
}

TileQuad::Ptr LayerSet::addTile(sf::Vertex v0, sf::Vertex v1, sf::Vertex v2, sf::Vertex v3)
{
	vertices.push_back(v0);
	vertices.push_back(v1);
	vertices.push_back(v2);
	vertices.push_back(v3);

	int i = vertices.size() - 4;
	quads.push_back(std::make_shared<TileQuad>(i, i + 1, i + 2, i + 3));

	return quads.back();
}

void LayerSet::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
	states.texture = &texture;
	target.draw(&vertices[0], (unsigned int)vertices.size(), sf::Quads, states);
}


text:
class Retailer::BackgroundersController < RetailerController
  before_filter :verify_partner_permissions

  def index
    @backgrounders = get_backgrounders(params)
    @backgrounder = new_backgrounder()
    @location = "backgrounders"
    @view_title = "Company Backgrounders"
  end

  def create
    params[:company_backgrounder][:company_id] = @partner.company.id
    params[:company_backgrounder][:partner_id] = @partner.id
    @backgrounder = new_backgrounder(params[:company_backgrounder])
    @backgrounder.save!
    flash[:notice] = "#{@backgrounder.title} has been created."
    redirect_to(retailer_backgrounders_url)
  rescue ActiveRecord::RecordInvalid => e
    @backgrounders = get_backgrounders(params)
    render(:action => 'index')
  end

  def destroy
    @backgrounder = CompanyBackgrounder.find(params[:id], :conditions => { :company_id => @partner.company.id })
    if @backgrounder
      @backgrounder.destroy
      flash[:notice] = "#{@backgrounder.title} has been removed."
    end
    redirect_to(retailer_backgrounders_url)
  end

private

  def get_backgrounders(params)
    backgrounders = CompanyBackgrounder.paginate(
      :all,
      :conditions => ["company_id = ?", @partner.company.id],
      :per_page => 10,
      :page => params[:page]
    )
    backgrounders
  end

  def new_backgrounder(params = nil)
    backgrounder = CompanyBackgrounder.new(params)
    backgrounder.waiting_approval = true
    backgrounder.approved = false
    backgrounder
  end

  def verify_partner_permissions
    unless @partner.can_manage_company_backgrounders
      flash[:notice] = 'You do not have the permissions to perform that action.'
      redirect_to(retailer_dashboard_url)
    end
  end
end


text:
package com.intellij.lang.jsgraphql.endpoint;

import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiNameIdentifierOwner;
import com.intellij.spellchecker.inspections.IdentifierSplitter;
import com.intellij.spellchecker.tokenizer.SpellcheckingStrategy;
import com.intellij.spellchecker.tokenizer.Tokenizer;
import com.intellij.spellchecker.tokenizer.TokenizerBase;
import org.jetbrains.annotations.NotNull;

public class JSGraphQLEndpointSpellcheckingStrategy extends SpellcheckingStrategy {

    private static final TokenizerBase<PsiElement> IDENTIFIER_TOKENIZER = new TokenizerBase<>(IdentifierSplitter.getInstance());

    @NotNull
    @Override
    public Tokenizer getTokenizer(PsiElement element) {
        if (element.getParent() instanceof PsiNameIdentifierOwner) {
            return EMPTY_TOKENIZER;
        }
        if (element.getNode().getElementType() == JSGraphQLEndpointTokenTypes.IDENTIFIER) {
            return IDENTIFIER_TOKENIZER;
        }
        return super.getTokenizer(element);
    }
}


text:
package integration_test

import (
	"os"
	"path/filepath"

	"github.com/cloudfoundry/libbuildpack/cutlass"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("CF PHP Buildpack", func() {
	var app *cutlass.App
	AfterEach(func() { app = DestroyApp(app) })

	Context("in offline mode", func() {
		BeforeEach(func() {
			SkipUnlessCached()
		})

		It("succeeds", func() {
			app = cutlass.New(filepath.Join(bpDir, "fixtures", "with_newrelic"))
			app.SetEnv("COMPOSER_GITHUB_OAUTH_TOKEN", os.Getenv("COMPOSER_GITHUB_OAUTH_TOKEN"))
			app.SetEnv("BP_DEBUG", "true")
			PushAppAndConfirm(app)

			By("downloads the binaries directly from the buildpack")
			Eventually(app.Stdout.String).Should(MatchRegexp(`Downloaded \[file://.*/dependencies/https___download.newrelic.com_php_agent_archive_[\d\.]+_newrelic-php5-[\d\.]+-linux\.tar\.gz\] to \[/tmp\]`))

			By("sets up New Relic")
			Eventually(app.Stdout.String).Should(ContainSubstring("Installing NewRelic"))
			Eventually(app.Stdout.String).Should(ContainSubstring("NewRelic Installed"))

			By("installs the default version of newrelic")
			Eventually(app.Stdout.String).Should(ContainSubstring("Using NewRelic default version:"))
		})

		AssertNoInternetTraffic("with_newrelic")
	})
})


text:
    <link rel="stylesheet" href="../bower_components/leaflet/dist/leaflet.css" />
    <link rel="stylesheet" href="../bower_components/leaflet.markerclusterer/dist/MarkerCluster.Default.css" />
    <link rel='stylesheet' href='style.css' />

    <title>SolrSpatialExplorer</title>


text:
{
"Ryuzine Elements" : "Ryuzine Elements",
"Lightbox Item (Landscape)" : "Lightbox vare (Landskap)",
"Lightbox Item (Portrait)" : "Lightbox vare (Portrett)",
"Lightbox Link" : "lysbokskobling",
"Dynamic Thumbnail" : "dynamisk Thumbnail",
"Dynamic Image" : "dynamisk bilde",
"OVR Image" : "OVR bilde",
"Lightbox Caption" : "Lightbox Caption",
"Enter Number of Frames in OVR Animation:" : "Skriv inn Antall rammer i OVR Animasjon:",
"Enter Link Target Value (number or name):" : "Tast Link Target Value (nummer eller navn):",
"Lightbox Content Type 0 = General 1 = Enlarge 2 = Magnify 3 = Photo 4 = Video 5 = Movie 6 = Info 7 = 3D Object 8 = Website 9 = Document " : "Lightbox Content Type 0 = Generelt 1 = Større 2 = Magnify 3 = Foto 4 = Video 5 = Movie 6 = Info 7 = 3D Object 8 = Nettstedet 9 = Dokument",
"Enter Image ID:" : "Tast Bilde ID:",
"You must enter a number!!" : "Du må angi et tall !!",
"Caption" : "Caption",
"Enter Page Content Here" : "Tast Page Content her"
};


text:
using hw.DebugFormatter;
using Reni.SyntaxTree;
using Reni.TokenClasses;

namespace Reni.SyntaxFactory;

sealed class MatchedBracketHandler : DumpableObject, IValueProvider
{
    ValueSyntax IValueProvider.Get(BinaryTree target, Factory factory, Anchor anchor)
        => new ExpressionSyntax
        (
            factory.GetValueSyntax(target.Left)
            , null
            , target.Token
            , factory.GetValueSyntax(target.Right)
            , Anchor.Create(target).Combine(anchor)
        );
}


text:
#ifndef RoundedIntRect_h
#define RoundedIntRect_h

#include "IntRect.h"

//namespace WebCore {

class RoundedIntRect {
public:
    class Radii {
    public:
        Radii() {}
        Radii(const IntSize& topLeft, const IntSize& topRight, const IntSize& bottomLeft, const IntSize& bottomRight)
            : m_topLeft(topLeft)
            , m_topRight(topRight)
            , m_bottomLeft(bottomLeft)
            , m_bottomRight(bottomRight)
        {
        }

        void setTopLeft(const IntSize& size) { m_topLeft = size; }
        void setTopRight(const IntSize& size) { m_topRight = size; }
        void setBottomLeft(const IntSize& size) { m_bottomLeft = size; }
        void setBottomRight(const IntSize& size) { m_bottomRight = size; }
        const IntSize& topLeft() const { return m_topLeft; }
        const IntSize& topRight() const { return m_topRight; }
        const IntSize& bottomLeft() const { return m_bottomLeft; }
        const IntSize& bottomRight() const { return m_bottomRight; }

        bool isZero() const;

        void includeLogicalEdges(const Radii& edges, bool isHorizontal, bool includeLogicalLeftEdge, bool includeLogicalRightEdge);
        void excludeLogicalEdges(bool isHorizontal, bool excludeLogicalLeftEdge, bool excludeLogicalRightEdge);

        void scale(float factor);
        void expand(int topWidth, int bottomWidth, int leftWidth, int rightWidth);
        void expand(int size) { expand(size, size, size, size); }
        void shrink(int topWidth, int bottomWidth, int leftWidth, int rightWidth) { expand(-topWidth, -bottomWidth, -leftWidth, -rightWidth); }
        void shrink(int size) { shrink(size, size, size, size); }

    private:
        IntSize m_topLeft;
        IntSize m_topRight;
        IntSize m_bottomLeft;
        IntSize m_bottomRight;
    };

    explicit RoundedIntRect(const IntRect&, const Radii& = Radii());
    RoundedIntRect(int x, int y, int width, int height);
    RoundedIntRect(const IntRect&, const IntSize& topLeft, const IntSize& topRight, const IntSize& bottomLeft, const IntSize& bottomRight);

    const IntRect& rect() const { return m_rect; }
    const Radii& radii() const { return m_radii; }
    bool isRounded() const { return !m_radii.isZero(); }
    bool isEmpty() const { return m_rect.isEmpty(); }

    void setRect(const IntRect& rect) { m_rect = rect; }
    void setRadii(const Radii& radii) { m_radii = radii; }

    void move(const IntSize& size) { m_rect.move(size); }
    void inflate(int size) { m_rect.inflate(size);  }
    void inflateWithRadii(int size) { m_rect.inflate(size); m_radii.expand(size); }
    void expandRadii(int size) { m_radii.expand(size); }
    void shrinkRadii(int size) { m_radii.shrink(size); }

    void includeLogicalEdges(const Radii& edges, bool isHorizontal, bool includeLogicalLeftEdge, bool includeLogicalRightEdge);
    void excludeLogicalEdges(bool isHorizontal, bool excludeLogicalLeftEdge, bool excludeLogicalRightEdge);

    bool isRenderable() const;

private:
    IntRect m_rect;
    Radii m_radii;
};

inline bool operator==(const RoundedIntRect::Radii& a, const RoundedIntRect::Radii& b)
{
    return a.topLeft() == b.topLeft() && a.topRight() == b.topRight() && a.bottomLeft() == b.bottomLeft() && a.bottomRight() == b.bottomRight();
}

inline bool operator==(const RoundedIntRect& a, const RoundedIntRect& b)
{
    return a.rect() == b.rect() && a.radii() == b.radii();
}

//} // namespace WebCore

#endif // RoundedIntRect_h


text:
import os
import os.path
files = os.listdir(os.path.dirname(__file__))
__all__ = [filename[:-3] for filename in files if not filename.startswith('__') and filename.endswith('.py')]


text:
from django.db import migrations

def cleanup_tags(apps, schema_editor):
    Tag = apps.get_model("taggit", "Tag")
    PageTag = apps.get_model("core", "PageTag")
    tags_processed = []
    duplicated_tags_id = []
    for tag in Tag.objects.all():
        if tag.name.lower() not in tags_processed:

            tags_iexact = Tag.objects.filter(name__iexact=tag.name).order_by("id")
            first_tag = tags_iexact.first()
            tags_processed.append(tag.name.lower())

            for duplicated_tag in tags_iexact:
                if duplicated_tag != first_tag:

                    for page_tag in PageTag.objects.filter(tag=duplicated_tag):
                        pt_objects = PageTag.objects
                        if not pt_objects.filter(
                            tag=first_tag, content_object=page_tag.content_object
                        ).exists():
                            PageTag.objects.create(
                                tag=first_tag, content_object=page_tag.content_object
                            )
                        pt_objects.filter(
                            tag=duplicated_tag, content_object=page_tag.content_object
                        ).delete()
                    duplicated_tags_id.append(duplicated_tag.id)
    Tag.objects.filter(id__in=duplicated_tags_id).delete()

class Migration(migrations.Migration):

    dependencies = [
        ("core", "0004_auto_20160511_1652"),
    ]

    operations = [
        migrations.RunPython(cleanup_tags, migrations.RunPython.noop),
    ]


text:
var Transform, chai, expect, sinon, ss;

chai = require("chai");

sinon = require("sinon");

chai.use(require("sinon-chai"));

Transform = require("readable-stream").Transform;

expect = chai.expect;

chai.config.showDiff = false;

ss = require("./index");

describe("exported value:", function() {
  it('must be a Object', function() {
    return expect(ss).to.be.an["instanceof"](Object);
  });
  return it('must have through method', function() {
    expect(ss).to.have.property("through");
    return expect(ss.through).to.be.an["instanceof"](Function);
  });
});

describe("through method", function() {
  return it('must return a Transform stream', function() {
    return expect(ss.through()).to.be.an["instanceof"](Transform);
  });
});


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Can. J. Bot. 56(7): 731 (1978)

#### Original name
Rhinocladiella cristaspora Matsush.

### Remarks
null


text:
package org.springframework.context.index.sample;

import org.springframework.stereotype.Component;

/**
 * Candidate with an inner class that isn't static (and should therefore not be added).
 *
 * @author Stephane Nicoll
 */
public class SampleNonStaticEmbedded {

	@Component
	public class InvalidCandidate {

	}

}


text:
"""Just a persistent list
"""

import os
import pickle
import logging

class PersistentList(list):

    """Just a persistent list
    """

    _file_path = os.path.join(
        os.path.dirname(__file__), os.pardir, '.disabled_views')

    def __init__(self):

        super(PersistentList, self).__init__()
        try:
            with open(self._file_path, 'rb') as fileobj:
                self.load(fileobj)
        except IOError:
            pass
        except Exception as e:
            logging.error(
                'Detected error {}, deleting persistent list...'.format(e))
            os.remove(self._file_path)

    def __setitem__(self, key, value):

        super(PersistentList, self).__setitem__(key, value)
        self.sync()

    def __delitem__(self, key):

        super(PersistentList, self).__delitem__(key)
        self.sync()

    def append(self, value):

        super(PersistentList, self).append(value)
        self.sync()

    def remove(self, value):

        super(PersistentList, self).remove(value)
        self.sync()

    def pop(self, index=None):

        if index is not None:
            value = super(PersistentList, self).pop(index)
        else:
            value = super(PersistentList, self).pop()

        self.sync()
        return value

    def sort(self, **kwargs):

        super(PersistentList, self).sort(**kwargs)
        self.sync()

    def load(self, fileobj):
        """Load the pickle contents
        """

        return self.extend(pickle.load(fileobj))

    def sync(self):
        """Write bytes and str elements of the list to the disk
        """

        with open(self._file_path, 'wb') as fileobj:
            l = [i for i in list(self) if type(i) is str or type(i) is bytes]
            return pickle.dump(l, fileobj, 2)


text:
ConstantInfo::ConstantInfo(byte tag, vector<byte> info) {
    this->tag = tag;
    this->info = info;
}

u_long ConstantInfo::getBytesLength() const {
    return this->info.size() + 1;
}

bool ConstantInfo::skipIndex() const {
    if (this->tag==LONG || this->tag==DOUBLE){
        return true;
    }

    return false;
}

u_short ConstantInfo::calculateInfoLength(u_short tag, vector<byte> lengthBytes) {
    u_short infoLength = 0;
    switch (tag) {
        case UTF8:
            infoLength = ByteUtil::twoByteToUShort(lengthBytes[0], lengthBytes[1]) + (u_short) 2;//需要加上长度本身两个字节
            break;
        case CLASS:
        case STRING:
        case METHOD_TYPE:
            infoLength = 2;
            break;
        case METHOD_HANDLER:
            infoLength = 3;
            break;
        case FIELD_REF:
        case METHOD_REF:
        case INTERFACE_METHOD_REF:
        case INTEGER:
        case FLOAT:
        case NAME_AND_TYPE:
        case INVOKE_DYNAMIC:
            infoLength = 4;
            break;
        case LONG:
        case DOUBLE:
            infoLength = 8;
            break;
        default:
            std::stringstream ss;
            ss << "异常tag: " << tag;
            throw std::invalid_argument(ss.str());
    }
    return infoLength;
}


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

 namespace LocalCar\Model;

 use Zend\Db\TableGateway\TableGateway;

 class LocalCarTable
 {
     protected $tableGateway;

     public function __construct(TableGateway $tableGateway)
     {
         $this->tableGateway = $tableGateway;
     }

     public function fetchAll()
     {
         $resultSet = $this->tableGateway->select();
         return $resultSet;
     }

     public function getLocalCar($id)
     {
         $id  = (int) $id;
         $rowset = $this->tableGateway->select(array('id' => $id));
         $row = $rowset->current();
         if (!$row) {
             throw new \Exception("Could not find row $id");
         }
         return $row;
     }

     public function saveLocalCar(LocalCar $inst)
     {
         $data = array(
             'nom' => $inst->nom,
             'chemin'  => $inst->chemin,
         );

         $id = (int) $inst->id;
         if ($id == 0) {
             $this->tableGateway->insert($data);
         } else {
             if ($this->getLocalCar($id)) {
                 $this->tableGateway->update($data, array('id' => $id));
             } else {
                 throw new \Exception('LocalCar id does not exist');
             }
         }
     }

     public function deleteLocalCar($id)
     {
         $this->tableGateway->delete(array('id' => (int) $id));
     }
 }


text:
django-href-field
=================

Django HrefField - a model field for storing the value of an HTML href attribute

## Spec

`HreField` takes the following keyword arguments:

* `protocols` (iterable) - allows you to specify which protocols are allowed.
  * Defaults to `('http', 'https', 'mailto', 'tel')`.
  * You may add other protocols such as `ftp`, `spotify`, `javascript` or `myownprotocol`.
  * Validators are provided for the default protocols plus `ftp`.  You will need to provide your own validation for other protocols via the `validators` keyword argument.
* `allow_paths` (boolean) - specifies whether protocol-less paths, such as `/` or `/about-us` are allowed.
  * Defaults to `True`.
* `allow_fragments` (boolean) - specifies whether fragment only hrefs such as `#edit` are allowed.
  * Defaults to `True`.
* `allow_query_strings` (boolean)- specifies whether query string-only hrefs such as `?sausage=1` are allowed.
  * Defaults to `True`.

`HrefField` is a subclass of `CharField`, so it exhibits the same behaviour in terms of `blank` and `null`, i.e. it defaults to `""`, so `null=True` is not required unless you specifically want to store `None`.

## Example

```
class Link(models.Model):

    text = models.CharField(max_length=100)

    href = HrefField(
        protocols=('http', 'https', 'mailto'),
        blank=True,
    )
```


text:
function log(w) { this.postMessage(w) }
function f() { log("FAIL") }
function p() { log("PASS") }

["", "?type=", "?type=x", "?type=x/x"].forEach(function(urlpart) {
  try {
    importScripts("resources/js.py" + urlpart)
  } catch(e) {
    (e.name == "NetworkError") ? p() : log("FAIL (no NetworkError exception): " + urlpart)
  }

})
importScripts("resources/js.py?type=text/javascript&outcome=p")
importScripts("resources/js.py?type=text/ecmascript&outcome=p")
importScripts("resources/js.py?type=text/ecmascript;blah&outcome=p")
log("END")


text:
<?php

namespace App\DataFixtures;

use App\Entity\CategorieArtiste;
use App\Entity\CategorieOeuvre;
use App\Service\General;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\DataFixtures\DependentFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Psr\Log\LoggerInterface;

class LoadMappingCategorieOeuvreAndCategorieArtisteData extends Fixture implements DependentFixtureInterface
{
    private $general;

    private $logger;

    public function __construct(General $general, LoggerInterface $logger)
    {
        $this->general = $general;
        $this->logger = $logger;
        $this->general->setLogger($this->logger);
    }

    /**
     * @param ObjectManager $manager
     *
     * @throws \TypeError
     */
    public function load(ObjectManager $manager)
    {
        $tic = $this->general->tic(
            'Début du mapping entre les fixtures CategorieOeuvre et CategorieArtiste'
        );
        $categoriesOeuvres = $manager
            ->getRepository(CategorieOeuvre::class)->findAll();
        foreach ($categoriesOeuvres as $categorieOeuvre) {
            $log = 'La catégorie d\'oeuvre "'
                . $categorieOeuvre->getIdentifiant()
                . '" a été liée aux catégories d\'artiste';
            if ('bande-dessinee' === $categorieOeuvre->getIdentifiant()) {
                $identifiantsCategoriesArtistes = [
                    'auteur-bande-dessinee',
                    'coloriste',
                    'dessinateur',
                ];
                foreach ($identifiantsCategoriesArtistes as $identifiant) {
                    /** @var CategorieArtiste $categorieArtiste */
                    $categorieArtiste = $manager
                        ->getRepository(CategorieArtiste::class)
                        ->findOneByIdentifiant($identifiant);
                    $categorieOeuvre->addCategorieArtiste($categorieArtiste);
                    $categorieArtiste->addCategorieOeuvre($categorieOeuvre);
                    $log .= ' "' . $categorieArtiste->getIdentifiant() . '"';
                }
            }
            if ('cinéma' === $categorieOeuvre->getCategorie()) {
                $identifiantsCategoriesArtistes = [
                    'realisateur',
                    'auteur-scenariste',
                    'auteur-dialoguiste',
                    'acteur',
                    'musicien-compositeur-musique-de-film',
                ];
                foreach ($identifiantsCategoriesArtistes as $identifiant) {
                    $categorieArtiste = $manager
                        ->getRepository(CategorieArtiste::class)
                        ->findOneByIdentifiant($identifiant);
                    $categorieOeuvre->addCategorieArtiste($categorieArtiste);
                    $categorieArtiste->addCategorieOeuvre($categorieOeuvre);
                    $log .= ' "' . $categorieArtiste->getIdentifiant() . '"';
                }
            }
            if ('musique' === $categorieOeuvre->getCategorie()) {
                $categoriesArtistes = $manager
                    ->getRepository(CategorieArtiste::class)
                    ->findByCategorie('musicien');
                foreach ($categoriesArtistes as $categorieArtiste) {
                    $categorieOeuvre->addCategorieArtiste($categorieArtiste);
                    $categorieArtiste->addCategorieOeuvre($categorieOeuvre);
                    $log .= ' "' . $categorieArtiste->getIdentifiant() . '"';
                }
            }
            if ('spectacle-concert' === $categorieOeuvre->getIdentifiant()) {
                $categoriesArtistes = $manager
                    ->getRepository(CategorieArtiste::class)
                    ->findByCategorie('musicien');
                foreach ($categoriesArtistes as $categorieArtiste) {
                    $categorieOeuvre->addCategorieArtiste($categorieArtiste);
                    $log .= ' "' . $categorieArtiste->getIdentifiant() . '"';
                }
            }
            if ('spectacle-danse' === $categorieOeuvre->getIdentifiant()) {
                $categories = ['danseur', 'chorégraphe', 'musicien'];
                foreach ($categories as $categorie) {
                    $categoriesArtistes = $manager
                        ->getRepository(CategorieArtiste::class)
                        ->findByCategorie($categorie);
                    foreach ($categoriesArtistes as $categorieArtiste) {
                        $categorieOeuvre->addCategorieArtiste($categorieArtiste);
                        $categorieArtiste->addCategorieOeuvre($categorieOeuvre);
                        $log .= ' "' . $categorieArtiste->getIdentifiant() . '"';
                    }
                }
            }
            if ('spectacle-humour' === $categorieOeuvre->getIdentifiant()) {
                $identifiantsCategoriesArtistes = [
                    'humoriste',
                    'metteur-en-scene',
                ];
                foreach ($identifiantsCategoriesArtistes as $identifiant) {
                    $categorieArtiste = $manager
                        ->getRepository(CategorieArtiste::class)
                        ->findOneByIdentifiant($identifiant);
                    $categorieOeuvre->addCategorieArtiste($categorieArtiste);
                    $categorieArtiste->addCategorieOeuvre($categorieOeuvre);
                    $log .= ' "' . $categorieArtiste->getIdentifiant() . '"';
                }
            }
            if ('spectacle-theatre' === $categorieOeuvre->getIdentifiant()) {
                $identifiantsCategoriesArtistes = [
                    'acteur',
                    'auteur-ecrivain',
                    'metteur-en-scene',
                ];
                foreach ($identifiantsCategoriesArtistes as $identifiant) {
                    $categorieArtiste = $manager
                        ->getRepository(CategorieArtiste::class)
                        ->findOneByIdentifiant($identifiant);
                    $categorieOeuvre->addCategorieArtiste($categorieArtiste);
                    $categorieArtiste->addCategorieOeuvre($categorieOeuvre);
                    $log .= ' "' . $categorieArtiste->getIdentifiant() . '"';
                }
            }
            if ('littérature' === $categorieOeuvre->getCategorie()) {
                if ('humour' === $categorieOeuvre->getSousCategorie()) {
                    $categorieArtiste = $manager
                        ->getRepository(CategorieArtiste::class)
                        ->findOneByIdentifiant('humoriste');
                    $categorieOeuvre->addCategorieArtiste($categorieArtiste);
                    $categorieArtiste->addCategorieOeuvre($categorieOeuvre);
                    $log .= ' "' . $categorieArtiste->getIdentifiant() . '"';
                } else {
                    $sousCategorieEcrivains = [
                        'conte',
                        'fable',
                        'nouvelle',
                        'poème',
                        'roman',
                        'pièce de théâtre',
                    ];
                    if (
                        in_array(
                            $categorieOeuvre->getSousCategorie(),
                            $sousCategorieEcrivains, true
                    )
                    ) {
                        $categorieArtiste = $manager
                            ->getRepository(CategorieArtiste::class)
                            ->findOneByIdentifiant('auteur-ecrivain');
                    } else {
                        $categorieArtiste = $manager
                            ->getRepository(CategorieArtiste::class)
                            ->findOneByIdentifiant('auteur');
                    }
                    $categorieOeuvre->addCategorieArtiste($categorieArtiste);
                    $categorieArtiste->addCategorieOeuvre($categorieOeuvre);
                    $log .= ' "' . $categorieArtiste->getIdentifiant() . '"';
                }
            }
            $manager->flush();
            $this->logger->debug($log);
        }
        $manager->clear();
        $this->general->toc(
            $tic,
            'Mapping entre les fixtures CategorieOeuvre et CategorieArtiste'
        );
    }

    /**
     * @return array
     */
    public function getDependencies()
    {
        return [
            LoadCategorieArtisteData::class,
            LoadCategorieOeuvreData::class,
        ];
    }
}


text:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if ( ! function_exists('element')){

    function getSessionButton($session){ ?>

            <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                <?php
                    if (!$session->userdata('logged')) {
                        echo "Usuario";
                    } else {
                        echo $session->userdata('first_name');
                    }
                ?>
            </button>

                <?php  if (!$session->userdata('logged')) { ?>

 Ingreso

                    <form name="sessionForm" class="form-row col-12" method="POST" id="login"
                      style="padding-left: 0px; padding-right: 0px; margin-right: 5px; margin-left: 0px;"
                      onkeypress="if (event.keyCode === 13) dataSubmitSessionForm()">

                            <input type="text" class="form-control form-control-sm" id="email" placeholder="Correo" name="email">

                            <input type="password" class="form-control form-control-sm" id="password" placeholder="Contraseña" name="password">

                            <button type="button" class="btn btn-sm btn-success" data-submit-session-form>Ingresar</button>

                    </form>

                           Registrarte

                        <a class="btn btn-sm btn-danger btn-block" href="<?= base_url() . 'user/recuperarPassword' ?>" class="btn btn-sm btn-danger">
                            Recuperar Clave

                <?php } else {?>

                       Hola, <?= $session->userdata('first_name')?>

                        Chango pesos: <?= $session->userdata('couponsAmount') ?>

                            Mis compras

                            Cerrar sesión

                <?php } ?>

<?php
    }
}
?>


text:
#ifndef MYSQL_AUTH_DIALOG_CLIENT_INCLUDED

/**
  @file

  Definitions needed to use Dialog client authentication plugin
*/

struct st_mysql;

#define MYSQL_AUTH_DIALOG_CLIENT_INCLUDED

/**
  type of the mysql_authentication_dialog_ask function

  @param mysql          mysql
  @param type           type of the input
                        1 - ordinary string input
                        2 - password string
  @param prompt         prompt
  @param buf            a buffer to store the use input
  @param buf_len        the length of the buffer

  @retval               a pointer to the user input string.
                        It may be equal to 'buf' or to 'mysql->password'.
                        In all other cases it is assumed to be an allocated
                        string, and the "dialog" plugin will free() it.
*/
typedef char *(*mysql_authentication_dialog_ask_t)(struct st_mysql *mysql,
                      int type, const char *prompt, char *buf, int buf_len);

/**
  first byte of the question string is the question "type".
  It can be an "ordinary" or a "password" question.
  The last bit set marks a last question in the authentication exchange.
*/
#define ORDINARY_QUESTION       "\2"
#define LAST_QUESTION           "\3"
#define PASSWORD_QUESTION       "\4"
#define LAST_PASSWORD           "\5"

#endif


text:
Custom Actions for Emaroo 3.x
=========================

Getting started
---------------

### To import an individual custom action

* Copy the link URI of the custom action you want to use to the clipboard.
* Start Emaroo, open the Settings tab ( ![](../_images/ConfigTabIcon.png) ).
* In the "Applications" list, select the tool/application you want to add the custom action to.
* In the "Custom Actions for ..." list, press the "Import" button ( ![](../_images/CustomAction_Import.png) ).
* On the "Open File" dialog, paste the URI you copied before, click the "Open" button.

### To import a collection of custom actions...

* Copy the link URI of the config file.
* Start Emaroo, open the Settings tab ( ![](../_images/ConfigTabIcon.png) ).
* In the lower left corner, press the "Import" button ( ![](../_images/Config_Import.png) ).
* On the "Open File" dialog, paste the URI you copied before, click the "Open" button.
* In the import dialog, decide what you want to import, then click the "Import" button.

**Before running an imported custom action you don't know, always review what it will do!!**

[Questions? The FAQ is here to help!](FAQ.md)

---

Visual Studio
-------------

### Developer Command Line

Opens the developer commandline for Visual Studio (@RWeigelt)

#### Individual custom actions
* Visual Studio 2017 - [**Link**](https://raw.githubusercontent.com/RWeigelt/EmarooCustomActions/master/visualStudio/Developer%20CMD%20(2017).action.json)
* Visual Studio 2015 - [**Link**](https://raw.githubusercontent.com/RWeigelt/EmarooCustomActions/master/visualStudio/Developer%20CMD%20(2015).action.json)
* Visual Studio 2013 - [**Link**](https://raw.githubusercontent.com/RWeigelt/EmarooCustomActions/master/visualStudio/Developer%20CMD%20(2013).action.json)
* Visual Studio 2012 - [**Link**](https://raw.githubusercontent.com/RWeigelt/EmarooCustomActions/master/visualStudio/Developer%20CMD%20(2012).action.json)
* Visual Studio 2010 - [**Link**](https://raw.githubusercontent.com/RWeigelt/EmarooCustomActions/master/visualStudio/Developer%20CMD%20(2010).action.json)

#### Collection

* Visual Studio 2010-2017 - [**Link**](https://raw.githubusercontent.com/RWeigelt/EmarooCustomActions/master/visualStudio/Developer%20CMD%20(2010-2017).config.json)

**Note:** The custom actions use the `$(ExeDirPath)` macro to honor the installation path of Visual Studio. If you want to use one of these custom actions on another application/tool's MRU list, you have to use an absolute path matching your system.

---

Misc Developer Stuff
--------------------

### Open Folder in VS Code - [**x86**](https://raw.githubusercontent.com/RWeigelt/EmarooCustomActions/master/misc/Open%20Folder%20in%20VS%20Code%20(x86).action.json)/[**x64**](https://raw.githubusercontent.com/RWeigelt/EmarooCustomActions/master/misc/Open%20Folder%20in%20VS%20Code%20(x64).action.json)

Opens the current directory in Visual Studio Code (@RWeigelt)

### Git Bash here - [**Link**](https://raw.githubusercontent.com/RWeigelt/EmarooCustomActions/master/git/GitBashHere.action.json)

Opens a Git Bash in the directory of the selected list item (@RWeigelt)

### Git GUI here - [**Link**](https://raw.githubusercontent.com/RWeigelt/EmarooCustomActions/master/git/GitGuiHere.action.json)

Opens the Git GUI  in the directory of the selected list item (@RWeigelt)

### Hg Workbench - [**Link**](https://raw.githubusercontent.com/RWeigelt/EmarooCustomActions/master/misc/Hg%20WorkBench.action.json)

Opens the Hg Workbench of [TortoiseHg](https://tortoisehg.bitbucket.io/) in the current directory (@RWeigelt)

---


text:
package io.kubernetes.client.openapi.models;

import io.kubernetes.client.fluent.VisitableBuilder;

public class V2beta2ExternalMetricStatusBuilder
    extends V2beta2ExternalMetricStatusFluentImpl<V2beta2ExternalMetricStatusBuilder>
    implements VisitableBuilder<V2beta2ExternalMetricStatus, V2beta2ExternalMetricStatusBuilder> {
  public V2beta2ExternalMetricStatusBuilder() {
    this(false);
  }

  public V2beta2ExternalMetricStatusBuilder(Boolean validationEnabled) {
    this(new V2beta2ExternalMetricStatus(), validationEnabled);
  }

  public V2beta2ExternalMetricStatusBuilder(V2beta2ExternalMetricStatusFluent<?> fluent) {
    this(fluent, false);
  }

  public V2beta2ExternalMetricStatusBuilder(
      V2beta2ExternalMetricStatusFluent<?> fluent, Boolean validationEnabled) {
    this(fluent, new V2beta2ExternalMetricStatus(), validationEnabled);
  }

  public V2beta2ExternalMetricStatusBuilder(
      V2beta2ExternalMetricStatusFluent<?> fluent, V2beta2ExternalMetricStatus instance) {
    this(fluent, instance, false);
  }

  public V2beta2ExternalMetricStatusBuilder(
      V2beta2ExternalMetricStatusFluent<?> fluent,
      V2beta2ExternalMetricStatus instance,
      Boolean validationEnabled) {
    this.fluent = fluent;
    fluent.withCurrent(instance.getCurrent());

    fluent.withMetric(instance.getMetric());

    this.validationEnabled = validationEnabled;
  }

  public V2beta2ExternalMetricStatusBuilder(V2beta2ExternalMetricStatus instance) {
    this(instance, false);
  }

  public V2beta2ExternalMetricStatusBuilder(
      V2beta2ExternalMetricStatus instance, Boolean validationEnabled) {
    this.fluent = this;
    this.withCurrent(instance.getCurrent());

    this.withMetric(instance.getMetric());

    this.validationEnabled = validationEnabled;
  }

  V2beta2ExternalMetricStatusFluent<?> fluent;
  Boolean validationEnabled;

  public V2beta2ExternalMetricStatus build() {
    V2beta2ExternalMetricStatus buildable = new V2beta2ExternalMetricStatus();
    buildable.setCurrent(fluent.getCurrent());
    buildable.setMetric(fluent.getMetric());
    return buildable;
  }
}


text:
package org.kohsuke.stapler;

import java.io.IOException;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.servlet.ServletException;
import static org.junit.Assert.*;
import org.junit.Test;
import org.kohsuke.stapler.verb.GET;
import org.kohsuke.stapler.verb.POST;

/**
 * @author Alan Harder
 */
public class ClassDescriptorTest {

    @Test public void loadConstructorParam() throws Exception {
        assertEquals(0,ClassDescriptor.loadParameterNames(C.class.getConstructor()).length);
        String[] names = ClassDescriptor.loadParameterNames(C.class.getConstructor(int.class, int.class, String.class));
        assertEquals("[a, b, x]",Arrays.asList(names).toString());
    }

    @Test public void loadParametersFromAsm() throws Exception {
        // get private method that is being tested
        Method lpfa = ClassDescriptor.ASM.class.getDeclaredMethod(
                "loadParametersFromAsm", Method.class);
        lpfa.setAccessible(true);
        // collect test cases
        Map<String,Method> testCases = new HashMap<String,Method>();
        for (Method m : ClassDescriptorTest.class.getDeclaredMethods())
            if (m.getName().startsWith("methodWith"))
                testCases.put(m.getName().substring(10), m);
        // expected results
        Map<String,String[]> expected = new HashMap<String,String[]>();
        expected.put("NoParams", new String[0]);
        expected.put("NoParams_static", new String[0]);
        expected.put("ManyParams", new String[] { "a", "b", "c", "d", "e", "f", "g", "h", "i" });
        expected.put("Params_static", new String[] { "abc", "def", "ghi" });
        // run tests
        for (Map.Entry<String,String[]> entry : expected.entrySet()) {
            Method testMethod = testCases.get(entry.getKey());
            assertNotNull("Method missing for " + entry.getKey(), testMethod);
            String[] result = (String[])lpfa.invoke(null, testMethod);
            assertNotNull("Null result for " + entry.getKey());
            if (!Arrays.equals(entry.getValue(), result)) {
                StringBuilder buf = new StringBuilder('|');
                for (String s : result) buf.append(s).append('|');
                fail("Unexpected result for " + entry.getKey() + ": " + buf);
            }
        }
    }

    @Test public void inheritedWebMethods() throws Exception {
        // http://bugs.sun.com/view_bug.do?bug_id=6342411
        assertEquals(1, new ClassDescriptor(Sub.class).methods.name("doDynamic").signature(StaplerRequest.class, StaplerResponse.class).size());
    }

    public static class C {
        public C() {}
        public C(int a, int b, String x) {}
    }

    private void methodWithNoParams() { }
    private static void methodWithNoParams_static() { }
    private void methodWithManyParams(String a, boolean b, int c, long d,
            Boolean e, Integer f, Long g, Object h, ClassDescriptorTest i) { }
    private static void methodWithParams_static(String abc, long def, Object ghi) { }

    protected static abstract class Super {
        public void doDynamic(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {}
    }
    public static class Sub extends Super {}

    /**
     * D.x() overries B.x()
     */
    @Test
    public void overridingMethod() throws Exception {
        FunctionList methods = new ClassDescriptor(D.class).methods.name("x");
        assertEquals(1, methods.size());

        // we should be able to see both annotations
        Function f = methods.get(0);
        assertEquals(3, f.getAnnotation(AnnA.class).value());
        assertNotNull(f.getAnnotation(AnnB.class));
        // similarly parameter annotations should be fused together
        assertSame(Nullable.class, f.getParameterAnnotations()[0][0].annotationType());

        // method should be dispatched to D.x() which overrides B.x()
        assertEquals(2, f.bindAndInvoke(new D(), null, null, "Hello"));
    }

    public static class B<T> {
        @AnnA @AnnB
        public int x(@Nullable T t) { return 1; }
    }

    public static class D extends B<String> {
        @AnnA(3)
        public int x(String t) { return 2; }
    }

    @Retention(RetentionPolicy.RUNTIME)
    @interface AnnA {
        int value() default 0;
    }

    @Retention(RetentionPolicy.RUNTIME)
    @interface AnnB {
        int value() default 0;
    }
}


text:
<?php
/**
 * OriginalReleaseTime.php
 *
 * Creation date: 2014-09-27
 * Creation time: 18:32
 *
 * @author Arkadiusz Moskwa <a.moskwa@gmail.com>
 */

namespace Nakard\MusicFormats\Media\Id3v2\Frame\TextInformation\Other;

use Nakard\MusicFormats\Media\Id3v2\Frame\TextInformation\AbstractFrame;

/**
 * Class OriginalReleaseTime
 *
 * @package Nakard\MusicFormats\Media\Id3v2\Frame\TextInformation\Other
 */
class OriginalReleaseTime extends AbstractFrame
{
    protected $identifier = 'TDOR';
}


text:
<?php

namespace SoundCloud\File;

class Format
{
    /**
     * Supported audio MIME types
     *
     * @var array
     *
     * @access private
     * @static
     */
    private static $_audioMimeTypes = array(
        'aac'  => 'video/mp4',
        'aiff' => 'audio/x-aiff',
        'flac' => 'audio/flac',
        'mp3'  => 'audio/mpeg',
        'ogg'  => 'audio/ogg',
        'wav'  => 'audio/x-wav'
    );

    /**
     * Get the corresponding MIME type for a given file extension
     *
     * @param string $extension Given extension
     *
     * @return string
     * @throws Services_Soundcloud_Unsupported_Audio_Format_Exception
     *
     * @access public
     * @static
     */
    public static function getMimeType($extension)
    {
        if (array_key_exists($extension, self::$_audioMimeTypes)) {
            return self::$_audioMimeTypes[$extension];
        } else {
            throw new Services_Soundcloud_Unsupported_Audio_Format_Exception();
        }
    }
}


text:
using Version.Plugin.Abstractions;
using System;

namespace Version.Plugin
{
    /// <summary>
    /// Cross platform Version implemenations
    /// </summary>
    public class CrossVersion
    {
        static readonly Lazy<IVersion> Implementation = new Lazy<IVersion>(() =>
            #if PORTABLE
                null,
            #else
                new VersionImplementation(),
            #endif
              System.Threading.LazyThreadSafetyMode.PublicationOnly);

        public static IVersion Current
        {
            get
            {
                var version = Implementation.Value;
                if (version == null)
                {
                    throw new NotImplementedException("Don't use CrossVersion from your PCL without first installing the NuGet package in your main project.");
                }
                return version;
            }
        }
    }
}


text:
ActiveRecord::Schema.define(version: 20140526214145) do

  create_table "appusers", force: true do |t|
    t.string   "login"
    t.string   "hashed_pwd"
    t.string   "email"
    t.string   "salt"
    t.boolean  "confirmed"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "avatar_url"
  end

  create_table "apuesta", force: true do |t|
    t.string   "type"
    t.integer  "appuser_id"
    t.integer  "partido_id"
    t.integer  "equipo_id"
    t.string   "resultado"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "apuesta", ["appuser_id"], name: "index_apuesta_on_appuser_id"
  add_index "apuesta", ["equipo_id"], name: "index_apuesta_on_equipo_id"
  add_index "apuesta", ["partido_id"], name: "index_apuesta_on_partido_id"

  create_table "equipos", force: true do |t|
    t.string   "nombre"
    t.string   "grupo"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "partidos", force: true do |t|
    t.integer  "local_id"
    t.integer  "visitante_id"
    t.string   "type"
    t.integer  "resultlocal"
    t.integer  "resultvisitante"
    t.datetime "fecha"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "vencedor_id"
    t.string   "generador"
    t.string   "codigo"
  end

  create_table "sessions", force: true do |t|
    t.string   "session_id", null: false
    t.text     "data"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "sessions", ["session_id"], name: "index_sessions_on_session_id"
  add_index "sessions", ["updated_at"], name: "index_sessions_on_updated_at"

  create_table "solicituds", force: true do |t|
    t.string  "mensaje"
    t.boolean "confirmado"
    t.boolean "rechazado"
    t.boolean "requestadmin"
    t.boolean "admin"
    t.integer "usergroup_id"
    t.integer "appuser_id"
  end

  create_table "usergroups", force: true do |t|
    t.string  "nombre"
    t.integer "creador_id"
    t.string  "avatar_url"
  end

end


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#8f000000">

    <RelativeLayout
        android:id="@+id/popup_anima"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/bg_dialog"
        android:layout_centerInParent="true"
        android:layout_margin="25dp">
        <TextView
            android:id="@+id/title"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:textColor="#3dd1a5"
            android:text="This is title"
            android:gravity="left|center_vertical"
            android:textSize="18sp"
            android:paddingLeft="15dp"
            />
        <View
            android:id="@+id/line"
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:background="#3dd1a5"
            android:layout_below="@id/title"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"/>
        <TextView
            android:id="@+id/content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/line"
            android:paddingTop="20dp"
            android:paddingLeft="15dp"
            android:paddingRight="15dp"
            android:paddingBottom="15dp"
            android:textSize="14sp"
            android:textColor="#1a1a1a"
            android:lineSpacingMultiplier="1.2"
            android:text="Warning:nuclear silo detected.\nWarning:nuclear silo detected.\nWarning:nuclear silo detected."
            />
        <View
            android:id="@+id/line2"
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:layout_below="@id/content"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="15dp"
            android:background="@color/line_bg"
            android:layout_marginTop="15dp"/>
        <TextView
            android:id="@+id/cancel"
            android:layout_width="60dp"
            android:layout_height="40dp"
            android:gravity="center"
            android:padding="3dp"
            android:textColor="#bfbfbf"
            android:textSize="14sp"
            android:layout_below="@id/line2"
            android:layout_alignParentRight="true"
            android:layout_marginRight="15dp"
            android:text="CANCEL"/>
        <TextView
            android:id="@+id/ok"
            android:layout_width="60dp"
            android:layout_height="40dp"
            android:gravity="center"
            android:padding="3dp"
            android:textColor="#3dd1a5"
            android:textSize="14sp"
            android:layout_below="@id/line2"
            android:layout_toLeftOf="@id/cancel"
            android:layout_marginRight="15dp"
            android:text="OK"/>

    </RelativeLayout>
</RelativeLayout>