text:
describe('WalkontableSelection', function () {
  var $table
    , $container
    , debug = false;

  beforeEach(function () {
    $container = $('

').css({'overflow': 'auto'});
    $container.width(100).height(200);
    $table = $('

'); //create a table that is not attached to document
    $container.append($table).appendTo('body');
    createDataArray();
  });

  afterEach(function () {
    if (!debug) {
      $('.wtHolder').remove();
    }
    $container.remove();
  });

  it("should add/remove class to selection when cell is clicked", function () {
    var wt = new Walkontable({
      table: $table[0],
      data: getData,
      totalRows: getTotalRows,
      totalColumns: getTotalColumns,
      selections: [
        new WalkontableSelection({
          className: 'current'
        })
      ],
      onCellMouseDown: function (event, coords, TD) {
        wt.selections.current.clear();
        wt.selections.current.add(coords);
        wt.draw();
      }
    });
    shimSelectionProperties(wt);
    wt.draw();

    var $td1 = $table.find('tbody td:eq(0)');
    var $td2 = $table.find('tbody td:eq(1)');
    $td1.simulate('mousedown');
    expect($td1.hasClass('current')).toEqual(true);

    $td2.simulate('mousedown');
    expect($td1.hasClass('current')).toEqual(false);
    expect($td2.hasClass('current')).toEqual(true);
  });

  it("should add class to selection on all overlays", function () {
    $container.width(300).height(300);

    this.data = Handsontable.helper.createSpreadsheetData(10, 10);

    var wt = new Walkontable({
      table: $table[0],
      data: getData,
      totalRows: getTotalRows,
      totalColumns: getTotalColumns,
      selections: [
        new WalkontableSelection({
          className: 'current'
        }),
        new WalkontableSelection({
          className: 'area'
        })
      ],
      fixedColumnsLeft: 2,
      fixedRowsTop: 2
    });
    shimSelectionProperties(wt);

    wt.selections.area.add(new WalkontableCellCoords(1, 1));
    wt.selections.area.add(new WalkontableCellCoords(1, 2));
    wt.selections.area.add(new WalkontableCellCoords(2, 1));
    wt.selections.area.add(new WalkontableCellCoords(2, 2));

    wt.draw();

    var tds = $container.find('td:contains(B2), td:contains(B3), td:contains(C2), td:contains(C3)');
    expect(tds.length).toBeGreaterThan(4);
    for (var i = 0, ilen = tds.length; i < ilen; i++) {
      expect(tds[i].className).toContain("area");
    }
  });

  it("should not add class to selection until it is rerendered", function () {
    var wt = new Walkontable({
      table: $table[0],
      data: getData,
      totalRows: getTotalRows,
      totalColumns: getTotalColumns,
      selections: [
        new WalkontableSelection({
          className: 'current'
        })
      ]
    });
    shimSelectionProperties(wt);
    wt.draw();
    wt.selections.current.add(new WalkontableCellCoords(0, 0));

    var $td1 = $table.find('tbody td:eq(0)');
    expect($td1.hasClass('current')).toEqual(false);

    wt.draw();
    expect($td1.hasClass('current')).toEqual(true);
  });

  it("should add/remove border to selection when cell is clicked", function () {
    var wt = new Walkontable({
      table: $table[0],
      data: getData,
      totalRows: getTotalRows,
      totalColumns: getTotalColumns,
      selections: [
        new WalkontableSelection({
          border: {
            width: 1,
            color: 'red',
            style: 'solid'
          }
        })
      ],
      onCellMouseDown: function (event, coords, TD) {
        wt.selections.current.clear();
        wt.selections.current.add(coords);
        wt.draw();
      }
    });
    shimSelectionProperties(wt);
    wt.draw();

    var $td1 = $table.find('tbody tr:eq(1) td:eq(0)');
    var $td2 = $table.find('tbody tr:eq(2) td:eq(1)');
    var $top = $(wt.selections.current.getBorder(wt).top); //cheat... get border for ht_master
    $td1.simulate('mousedown');
    var pos1 = $top.position();
    expect(pos1.top).toBeGreaterThan(0);
    expect(pos1.left).toBe(0);

    $td2.simulate('mousedown');
    var pos2 = $top.position();
    expect(pos2.top).toBeGreaterThan(pos1.top);
    expect(pos2.left).toBeGreaterThan(pos1.left);
  });

  it("should add a selection that is outside of the viewport", function () {
    var wt = new Walkontable({
      table: $table[0],
      data: getData,
      totalRows: getTotalRows,
      totalColumns: getTotalColumns,
      selections: [
        new WalkontableSelection({
          border: {
            width: 1,
            color: 'red',
            style: 'solid'
          }
        })
      ]
    });
    shimSelectionProperties(wt);
    wt.draw();

    wt.selections.current.add([20, 0]);
    expect(wt.wtTable.getCoords($table.find('tbody tr:first td:first')[0])).toEqual(new WalkontableCellCoords(0, 0));
  });

  it("should not scroll the viewport after selection is cleared", function () {
    var wt = new Walkontable({
      table: $table[0],
      data: getData,
      totalRows: getTotalRows,
      totalColumns: getTotalColumns,
      selections: [
        new WalkontableSelection({
          border: {
            width: 1,
            color: 'red',
            style: 'solid'
          }
        })
      ]
    });
    shimSelectionProperties(wt);
    wt.draw();

    wt.selections.current.add(new WalkontableCellCoords(0, 0));
    wt.draw();
    expect(wt.wtTable.getFirstVisibleRow()).toEqual(0);
    wt.scrollVertical(10).draw();
    expect(wt.wtTable.getFirstVisibleRow()).toEqual(10);
    expect(wt.wtTable.getLastVisibleRow()).toEqual(17);
    wt.selections.current.clear();
    expect(wt.wtTable.getFirstVisibleRow()).toEqual(10);
    expect(wt.wtTable.getLastVisibleRow()).toEqual(17);
  });

  it("should clear a selection that has more than one cell", function () {
    var wt = new Walkontable({
      table: $table[0],
      data: getData,
      totalRows: getTotalRows,
      totalColumns: getTotalColumns,
      selections: [
        new WalkontableSelection({
          border: {
            width: 1,
            color: 'red',
            style: 'solid'
          }
        })
      ]
    });
    shimSelectionProperties(wt);
    wt.draw();

    wt.selections.current.add(new WalkontableCellCoords(0, 0));
    wt.selections.current.add(new WalkontableCellCoords(0, 1));
    wt.selections.current.clear();

    expect(wt.selections.current.cellRange).toEqual(null);
  });

  it("should highlight cells in selected row & column", function () {
    $container.width(300);

    var wt = new Walkontable({
      table: $table[0],
      data: getData,
      totalRows: getTotalRows,
      totalColumns: getTotalColumns,
      selections: [
        new WalkontableSelection({
          highlightRowClassName: 'highlightRow',
          highlightColumnClassName: 'highlightColumn'
        })
      ]
    });
    shimSelectionProperties(wt);
    wt.draw();

    wt.selections.current.add(new WalkontableCellCoords(0, 0));
    wt.selections.current.add(new WalkontableCellCoords(0, 1));
    wt.draw(true);

    expect($table.find('.highlightRow').length).toEqual(2);
    expect($table.find('.highlightColumn').length).toEqual(wt.wtTable.getRenderedRowsCount() * 2 - 2);
  });

  it("should highlight cells in selected row & column, when same class is shared between 2 selection definitions", function () {
    $container.width(300);

    var wt = new Walkontable({
      table: $table[0],
      data: getData,
      totalRows: getTotalRows,
      totalColumns: getTotalColumns,
      selections: [
        new WalkontableSelection({
          highlightRowClassName: 'highlightRow',
          highlightColumnClassName: 'highlightColumn'
        }),
        new WalkontableSelection({
          highlightRowClassName: 'highlightRow',
          highlightColumnClassName: 'highlightColumn'
        })
      ]
    });
    shimSelectionProperties(wt);
    wt.draw();

    wt.selections.current.add(new WalkontableCellCoords(0, 0));
    wt.draw(true);

    expect($table.find('.highlightRow').length).toEqual(3);
    expect($table.find('.highlightColumn').length).toEqual(wt.wtTable.getRenderedRowsCount() - 1);
  });

  it("should remove highlight when selection is deselected", function () {
    var wt = new Walkontable({
      table: $table[0],
      data: getData,
      totalRows: getTotalRows,
      totalColumns: getTotalColumns,
      selections: [
        new WalkontableSelection({
          highlightRowClassName: 'highlightRow',
          highlightColumnClassName: 'highlightColumn'
        })
      ]
    });
    shimSelectionProperties(wt);
    wt.draw();

    wt.selections.current.add(new WalkontableCellCoords(0, 0));
    wt.selections.current.add(new WalkontableCellCoords(0, 1));
    wt.draw();

    wt.selections.current.clear();
    wt.draw();

    expect($table.find('.highlightRow').length).toEqual(0);
    expect($table.find('.highlightColumn').length).toEqual(0);
  });

  it("should add/remove appropriate class to the row/column headers of selected cells", function() {
    $container.width(300);

    var wt = new Walkontable({
      table: $table[0],
      data: getData,
      totalRows: getTotalRows,
      totalColumns: getTotalColumns,
      rowHeaders: [function (row, TH) {
        TH.innerHTML = row + 1;
      }],
      columnHeaders: [function (row, TH) {
        TH.innerHTML = row + 1;
      }],
      selections: [
        new WalkontableSelection({
          highlightRowClassName: 'highlightRow',
          highlightColumnClassName: 'highlightColumn'
        })
      ]
    });
    shimSelectionProperties(wt);
    wt.draw();

    wt.selections.current.add(new WalkontableCellCoords(1, 1));
    wt.selections.current.add(new WalkontableCellCoords(2, 2));
    wt.draw();

    // left side:
    // -2 -> because one row is partially visible

    // right side:
    // *2 -> because there are 2 columns selected
    // +2 -> because there are the headers
    // -4 -> because 4 cells are selected = there are overlapping highlightRow class
    expect($table.find('.highlightRow').length).toEqual(wt.wtViewport.columnsVisibleCalculator.count * 2 + 2 - 4);
    expect($table.find('.highlightColumn').length - 2).toEqual(wt.wtViewport.rowsVisibleCalculator.count * 2 + 2 - 4);
    expect($table.find('.highlightColumn').length).toEqual(14);
    expect(getTableTopClone().find('.highlightColumn').length).toEqual(2);
    expect(getTableTopClone().find('.highlightRow').length).toEqual(0);
    expect(getTableLeftClone().find('.highlightColumn').length).toEqual(0);
    expect(getTableLeftClone().find('.highlightRow').length).toEqual(2);

    var $colHeaders = $table.find("thead tr:first-child th"),
        $rowHeaders = $table.find("tbody tr th:first-child");

    expect($colHeaders.eq(2).hasClass('highlightColumn')).toBe(true);
    expect($colHeaders.eq(3).hasClass('highlightColumn')).toBe(true);

    expect($rowHeaders.eq(1).hasClass('highlightRow')).toBe(true);
    expect($rowHeaders.eq(2).hasClass('highlightRow')).toBe(true);

    wt.selections.current.clear();
    wt.draw();

    expect($table.find('.highlightRow').length).toEqual(0);
    expect($table.find('.highlightColumn').length).toEqual(0);
    expect(getTableTopClone().find('.highlightColumn').length).toEqual(0);
    expect(getTableTopClone().find('.highlightRow').length).toEqual(0);
    expect(getTableLeftClone().find('.highlightColumn').length).toEqual(0);
    expect(getTableLeftClone().find('.highlightRow').length).toEqual(0);
  });

  describe("replace", function() {
    it("should replace range from property and return true", function() {
      var wt = new Walkontable({
        table: $table[0],
        data: getData,
        totalRows: getTotalRows,
        totalColumns: getTotalColumns,
        selections: [
          new WalkontableSelection({
            border: {
              width: 1,
              color: 'red',
              style: 'solid'
            }
          })
        ]
      });
      shimSelectionProperties(wt);
      wt.selections.current.add(new WalkontableCellCoords(1, 1));
      wt.selections.current.add(new WalkontableCellCoords(3, 3));
      var result = wt.selections.current.replace(new WalkontableCellCoords(3, 3), new WalkontableCellCoords(4, 4));
      expect(result).toBe(true);
      expect(wt.selections.current.getCorners()).toEqual([1, 1, 4, 4]);
    });
  });
});


text:
AnsiWeather is a Shell script for displaying the current weather conditions in your
terminal, with support for ANSI colors and Unicode symbols.

![AnsiWeather Screenshot](http://www.cambus.net/content/2013/10/ansiweather.png)

Weather data comes from the `OpenWeatherMap` free weather API.

## Requirements

AnsiWeather requires the following dependencies :

- A command to fetch HTTP data such as [cURL](http://curl.haxx.se) or [wget](https://www.gnu.org/software/wget/)
- [jq](http://stedolan.github.io/jq/) (lightweight and flexible command-line JSON processor)
- [bc](https://www.gnu.org/software/bc/) (arbitrary precision numeric processing language)

## Usage

After cloning the repository, simply invoke the script by typing :

	./ansiweather

## Command Line Options

Any configuration options may also be passed in as command line options.

	./ansiweather -l Moscow,RU -u metric -s true -f 5 -d true

## Configuration

The following configuration options (detailed below) are available and should
be set according to your location and preferences.

Config options can also be set in ~/.ansiweatherrc

Example : `~/.ansiweatherrc`

	location:Moscow,RU
	fetch_cmd:ftp -V -o -
	geo_api_url:www.telize.com/geoip
	units:metric
	daylight:true

The file `ansiweatherrc.example` contains all available configuration variables.

### Location

Location format is `city,CC` where `CC` is a two-letter ISO 3166-1 alpha-2
country code. A list of country codes is available [here](http://www.statdns.com/cctlds/).

In case no location is specified, AnsiWeather will try to geolocate you
using [Telize](http://www.telize.com/).

Example : `Moscow,RU`

	location:Moscow,RU

### Fetch Command

Various tools can be used to fetch data : `curl`, `wget`, `ftp`.

Example : `curl -s`

	fetch_cmd:curl -s

Example : `wget -qO-`

	fetch_cmd:wget -qO-

Example : `ftp -V -o -`

	fetch_cmd:ftp -V -o -

Default: `curl -s`

### System of Units

Both `metric` and `imperial` systems are supported.

	units:metric

Default: `metric`

### Display symbols

Toggle Unicode symbols display. Value can be either `true` or `false` (requires an Unicode capable display).

	symbols:true

Default: `true`

### Display forecast

Show upcoming forecast for the next `N` days (for 0 <= N <= 7). `0` will show standard output.

	forecast:5

Default: `0`

### Display sunrise / sunset

Toggle daylight display. Value can be either `true` or `false`.

	daylight:false

Default: `false`

### Date and Time format

Configure date and time format display. See Unix date formatting documentation for details.

	dateformat:%a %b %d

Default : `%a %b %d`

	timeformat:%b %d %r

Default : `%b %d %r`

### GeoIP URL

Set the url for getting GeoIP data (must return json).

    	geo_api_url:www.telize.com/geoip
	geo_api_proto:https

Default : `http://www.telize.com/geoip`

## License

AnsiWeather is released under the BSD 3-Clause license. See `LICENSE` file
for details.

## Author

AnsiWeather is developed by Frederic Cambus

- Site : http://www.cambus.net
- Twitter: http://twitter.com/fcambus

## Resources

GitHub : https://github.com/fcambus/ansiweather

redpajama_set_name: RedPajamaGithub


text:
package com.aliyuncs.fc.response;

import com.aliyuncs.fc.http.HttpResponse;
import com.aliyuncs.fc.model.VersionMetaData;
import com.google.gson.annotations.SerializedName;

public class ListVersionsResponse extends HttpResponse {

    @SerializedName("versions")
    private VersionMetaData[] versions;

    @SerializedName("nextToken")
    private String nextToken;

    @SerializedName("direction")
    private String direction;

    public VersionMetaData[] getVersions() {
        return versions;
    }

    public ListVersionsResponse(VersionMetaData[] versions) {
        this.versions = versions;
    }

    public String getNextToken() {
        return nextToken;
    }

    public ListVersionsResponse setNextToken(String nextToken) {
        this.nextToken = nextToken;
        return this;
    }

    public String getDirection() {
        return direction;
    }

    public ListVersionsResponse setDirection(String direction) {
        this.direction = direction;
        return this;
    }
}


text:
package org.teavm.model;

import java.util.List;

/**
 *
 * @author Alexey Andreev
 */
public interface PhiReader {
    BasicBlockReader getBasicBlock();

    VariableReader getReceiver();

    List<? extends IncomingReader> readIncomings();
}


text:
require 'date'

# note: ruby timezone is UTC
# command line arg should be in "YYYY-MM-DD" format
today = ARGV[0].nil? ? Date.today : Date.parse(ARGV[0])

yesterday           = today - 1
yesterday_timestamp = "#{yesterday.to_time.to_i}000"

today_timestamp     = "#{today.to_time.to_i}000"

backup_dir = "/mnt/dump/"
backup     = "#{backup_dir}#{today.to_s}"
backup_tgz = "#{today.to_s}.tgz"

# Tables
cmd = "sudo mongodump --db Hungrybird -c hits -o #{backup}  -q '{ timestamp : { $gte : new Date(#{yesterday_timestamp}), $lt: new Date(#{today_timestamp}) } }'"
puts cmd
system(cmd)
puts "Done with Hits"

# Indexes
cmd = "sudo mongodump --db Hungrybird -c system.indexes -o #{backup}"
puts cmd
system(cmd)
puts "Done with Indexes"

# Zip
cmd = "cd #{backup_dir}; sudo tar -czvf #{backup_tgz} #{today.to_s}/"
puts cmd
system(cmd)
puts "Done with Zipping"

# Upload
cmd = "cd #{backup_dir}; s3cmd put #{backup_tgz} s3://#{ENV['S3_BUCKET']}/#{backup_tgz}"
puts cmd
system(cmd)
puts "Done with Upload"

# Delete
cmd = "cd #{backup_dir}; sudo rm -rf #{today.to_s}; sudo rm -rf #{backup_tgz}"
puts cmd
system(cmd)
puts "Done with Delete"


text:
/*
FUNCTION
	<<bcmp>>---compare two memory areas

INDEX
	bcmp

ANSI_SYNOPSIS
	#include <string.h>
	int bcmp(const void *<[s1]>, const void *<[s2]>, size_t <[n]>);

TRAD_SYNOPSIS
	#include <string.h>
	int bcmp(<[s1]>, <[s2]>, <[n]>)
	const void *<[s1]>;
	const void *<[s2]>;
	size_t <[n]>;

DESCRIPTION
	This function compares not more than <[n]> bytes of the
	object pointed to by <[s1]> with the object pointed to by <[s2]>.

	This function is identical to <<memcmp>>.

RETURNS
	The function returns an integer greater than, equal to or
	less than zero 	according to whether the object pointed to by
	<[s1]> is greater than, equal to or less than the object
	pointed to by <[s2]>.

PORTABILITY
<<bcmp>> requires no supporting OS subroutines.

QUICKREF
	bcmp ansi pure
*/

#include <string.h>

int
_DEFUN (bcmp, (m1, m2, n),
	_CONST void *m1 _AND
	_CONST void *m2 _AND
	size_t n)

{
  return memcmp (m1, m2, n);
}


text:
package com.alipay.api.response;

import com.alipay.api.internal.mapping.ApiField;

import com.alipay.api.AlipayResponse;

/**
 * ALIPAY API: alipay.marketing.campaign.activity.offline.trigger response.
 *
 * @author auto create
 * @since 1.0, 2017-10-24 11:22:59
 */
public class AlipayMarketingCampaignActivityOfflineTriggerResponse extends AlipayResponse {

	private static final long serialVersionUID = 6728542262782837253L;

	/**
	 * 外部奖品ID
	 */
	@ApiField("out_prize_id")
	private String outPrizeId;

	public void setOutPrizeId(String outPrizeId) {
		this.outPrizeId = outPrizeId;
	}
	public String getOutPrizeId( ) {
		return this.outPrizeId;
	}

}


text:
using namespace llvm;

AddressTakenAnalysis::~AddressTakenAnalysis() {}

static bool isAddressTaken(Value* V) {
  for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
    User *U = *I;
    if(isa<StoreInst>(U))
      return true;
    if (!isa<CallInst>(U) && !isa<InvokeInst>(U)) {
      if(U->use_empty())
        continue;
      if(isa<GlobalAlias>(U)) {
        if(isAddressTaken(U))
          return true;
      } else {
        if (Constant *C = dyn_cast<Constant>(U)) {
          if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
            if (CE->getOpcode() == Instruction::BitCast) {
              return isAddressTaken(CE);
            }
          }
        }
        return true;
      }

      // FIXME: Can be more robust here for weak aliases that
      // are never used
    } else {
      llvm::CallSite CS(cast<Instruction>(U));
      if (!CS.isCallee(I))
        return true;
    }
  }
  return false;
}

bool AddressTakenAnalysis::runOnModule(llvm::Module& M) {
  for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI){
    if(isAddressTaken(FI)) {
      addressTakenFunctions.insert(FI);
    }
  }

  return false;
}
bool AddressTakenAnalysis::hasAddressTaken(llvm::Function *F){
  return addressTakenFunctions.find(F) != addressTakenFunctions.end();
}

void AddressTakenAnalysis::getAnalysisUsage(llvm::AnalysisUsage &AU) const {
  AU.setPreservesAll();
}

char AddressTakenAnalysis::ID;
static RegisterPass<AddressTakenAnalysis> A("ata", "Identify Address Taken Functions");


text:
<#
Unity3DExtensions.psm1 - PowerShell module for locating and loading Unity 3D extensions.

Copyright (c) 2017 Marcus R. Brown <me@igetgam.es>

This file is part of the Unity3D.DLLs project (http://precisionmojo.github.io/Unity3D.DLLs/) which is distributed
under the MIT License. Refer to the LICENSE.MIT.md document located in the project directory for licensing terms.
#>

$ivyParserPath = $null

$parseFileMethod = $null

function Set-IvyParserPath
{
    param
    (
        [Parameter(Mandatory=$true)]
        [String] $Path
    )

    $script:ivyParserPath = $Path
}

function Get-IvyModule
{
    param
    (
        [Parameter(Mandatory=$true)]
        [String] $ModulePath
    )

    ParseIvyModule($ModulePath)
}

function ParseIvyModule([string] $ModulePath)
{
    if ($script:parseFileMethod -eq $null)
    {
        EnsureUnityIvyParserAssembly
        $script:parseFileMethod = [Unity.PackageManager.Ivy.IvyParser].GetMethod("ParseFile").MakeGenericMethod([Unity.PackageManager.Ivy.IvyModule])
    }

    $script:parseFileMethod.Invoke($null, $ModulePath)
}

function EnsureUnityIvyParserAssembly
{
    if (([System.AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_ -match "Unity.IvyParser" }) -eq $null)
    {
        Add-Type -Path $ivyParserPath
    }
}

Export-ModuleMember Set-IvyParserPath, Get-IvyModule


text: Services healthcare


text:
<?xml version="1.0" encoding="utf-8"?>
<install type="module" version="1.5.11">
	<name>(Apathy) Anti-Duopoly</name>
	<creationDate>20/01/10</creationDate>
	<author>Andreas Markauskas</author>
	<authorEmail>amarkauskas1@gmail.com</authorEmail>
	<authorUrl>http://joakal.com</authorUrl>
	<copyright>Andreas Markauskas 2010</copyright>
	<license>http://www.opensource.org/licenses/mit-license.php MIT</license>
	<version>1.0</version>
	<description>Display the preference of parties against the duopoly.</description>
	<files>
		<filename module="mod_duopoly">mod_duopoly.php</filename>
        	</files>
    <params>
    <param name="moduleclass_sfx" type="text" default="" label="Module Class Suffix" description="PARAMMODULECLASSSUFFIX" />

    </params>
</install>


text:
package de.st_ddt.crazyspawner.entities.properties.ai.action.goals.impl;

import org.bukkit.entity.Creature;
import org.bukkit.util.Vector;

import de.st_ddt.crazyspawner.entities.util.ai.ActionHelper;
import de.st_ddt.crazyspawner.entities.util.ai.Navigation;

public class StareInDirectionGoal extends BasicGoal
{

	protected final Vector direction;

	public StareInDirectionGoal(final Creature entity, final Vector direction)
	{
		super(entity, MUTEX_FLAG_LOOK);
		this.direction = direction;
	}

	@Override
	public boolean shouldExecute(final boolean started)
	{
		return true;
	}

	@Override
	public void start()
	{
		ActionHelper.getNavigation(entity).lookInDirection(direction, Navigation.DEFAULTROTATIONSPEED, Navigation.DEFAULTROTATIONSPEED);
	}
}


text:
package com.intellij.util.text;

import org.jetbrains.annotations.NotNull;

import java.io.Reader;

/**
 * @author max
 */
public class CharSequenceReader extends Reader {
  private final CharSequence myText;
  private int myCurPos;

  public CharSequenceReader(@NotNull CharSequence text) {
    myText = text;
    myCurPos = 0;
  }

  @Override
  public void close() {}

  @Override
  public int read(char[] cbuf, int off, int len) {
    if (off < 0 || off > cbuf.length || len < 0 || off + len > cbuf.length || off + len < 0) {
        throw new IndexOutOfBoundsException("cbuf.length="+cbuf.length+"; off="+off+"; len="+len);
    }
    if (len == 0) {
        return 0;
    }

    if (myText instanceof CharArrayCharSequence) { // Optimization
      final int readChars = ((CharArrayCharSequence)myText).readCharsTo(myCurPos, cbuf, off, len);
      if (readChars < 0) return -1;
      myCurPos += readChars;
      return readChars;
    }

    int charsToCopy = Math.min(len, myText.length() - myCurPos);
    if (charsToCopy <= 0) return -1;

    for (int n = 0; n < charsToCopy; n++) {
      cbuf[n + off] = myText.charAt(n + myCurPos);
    }

    myCurPos += charsToCopy;
    return charsToCopy;
  }

  @Override
  public int read() {
    if (myCurPos >= myText.length()) return -1;
    return myText.charAt(myCurPos++);
  }
}


text:
package de.bluemx.stocktool.fetch;

import com.google.inject.Inject;
import de.bluemx.stocktool.annotations.*;
import de.bluemx.stocktool.converter.Conversion;
import de.bluemx.stocktool.helper.StringUtil;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import static de.bluemx.stocktool.helper.ReflectionUtil.*;
import static de.bluemx.stocktool.helper.StringUtil.replacePlaceholder;

public class GenericFetcher<T> {

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

    private Provider[] providers;
    private UrlFetcher urlFetcher;
    private StringUtil stringUtil;
    private Set<String> processedFields = new HashSet<>();

    @Inject
    public GenericFetcher(UrlFetcher urlFetcher) {
        this.urlFetcher = urlFetcher;
    }

    public <T> T process(T pojo) {
        Field[] fields = pojo.getClass().getDeclaredFields();

        saveClassAnnotations(pojo);
        for (Field field : fields) {
            if (!processedFields.contains(field.getName())) {
                log.debug("Processing field: {}", field.getName());
                recursiveFetchField(field, pojo);
            }
        }
        return pojo;

    }

    private void recursiveFetchField(Field field, Object pojo) {
        Resolvers resolvers = field.getAnnotation(Resolvers.class);
        boolean isProviderMap = field.getAnnotation(ProviderMap.class) != null;
        if (resolvers instanceof Resolvers) {
            for (Resolver resolver : resolvers.value()) {
                String providername = resolver.provider();
                Provider provider = getProviderByName(providername);
                if (!provider.required().equals("")) {
                    Field newField = getFieldByName(provider.required(), pojo);
                    recursiveFetchField(newField, pojo);
                }
                fetchField(field, pojo, resolver, provider);
                if (reflectionGet(field, pojo) != null && !isProviderMap) {
                    break;
                }
                log.info("Fetching alternative for {} with Resolver {}", field.getName(), resolver.provider());
            }
        }
    }

    private void fetchField(Field field, Object pojo, Resolver resolver, Provider provider) {
        if (field.getAnnotation(ProviderMap.class) != null) {
            fetchProviderMap(field, pojo, resolver, provider);
        } else {
            fetchCommonField(field, pojo, resolver, provider);
        }
        processedFields.add(field.getName());
    }

    private void fetchCommonField(Field field, Object pojo, Resolver resolver, Provider provider) {
        try {
            String[] strArr = fetchUrlWith(provider, resolver, pojo);
            Conversion converter = getConverter(resolver);
            Object obj = converter.convert(ArrayUtils.addAll(strArr, resolver.converter().variables()));
            reflectionSet(field, pojo, obj);
        } catch (ValidationException e) {
            log.error("Please check the Definition of field {}. Actual value: {} Expected value: {}",
                    field.getName(), e.getActual(), e.getValidator().expected());
        } catch (IllegalArgumentException e) {
            log.error("Converter Error at field {} with Resolver {}. Error-Msg: {}", field, resolver, e.getMessage());
        }
    }

    private void fetchProviderMap(Field field, Object pojo, Resolver resolver, Provider provider) {
        Map<Dataprovider, String> providerMap = null;
        providerMap = (Map<Dataprovider, String>) reflectionGet(field, pojo);
        if (providerMap == null) {
            providerMap = new HashMap<>();
        }
        String[] obj = fetchUrlWith(provider, resolver, pojo);
        if (obj != null && obj.length == 1) {
            Conversion converter = getConverter(resolver);
            String mapString = (String) converter.convert(ArrayUtils.addAll(obj, resolver.converter().variables()));
            providerMap.put(provider.dataprovider(), mapString);
            reflectionSet(field, pojo, providerMap);
        } else {
            log.error("At Field {} - Reduce Extract Annotations to one.", field.getName());
            throw new IllegalArgumentException("Annotation Providermap can only fetch one value!");
        }
    }

    private String[] fetchUrlWith(Provider provider, Resolver resolver, Object pojo) {
        String url = provider.url();
        Map<String, String> variablesList = getVariables(provider, pojo);
        String completeUrl = createResultingUrl(url, variablesList);
        return urlFetcher.urlFetch(completeUrl, provider, resolver, pojo);
    }

    private String createResultingUrl(String url, Map<String, String> variablesList) {
        String finishedUrl = url;
        for (String variableKey : variablesList.keySet()) {
            finishedUrl = replacePlaceholder(finishedUrl, variableKey, variablesList.get(variableKey));
        }
        log.info("Created URL: {}", finishedUrl);
        return finishedUrl;
    }

    private Map<String, String> getVariables(Provider provider, Object pojo) {
        Map<String, String> resultingVariables = new HashMap<>();
        Variable[] variableAnnotations = provider.variables();
        for (Variable variable : variableAnnotations) {
            try {
                Field field = getFieldByName(variable.source(), pojo);
                if (field.getType().equals(Map.class)) {
                    Map<Dataprovider, String> configMap = (Map) reflectionGet(field, pojo);
                    if (configMap != null) {
                        String variableValue = configMap.get(provider.dataprovider());
                        resultingVariables.put(variable.key(), variableValue);
                    } else {
                        throw new IllegalArgumentException(
                                String.format("Definition is wrong. Field %s requested, but is null.", variable.source()));
                    }
                } else if (field.getType().equals(String.class)) {
                    String variableValue = (String) reflectionGet(field, pojo);
                    resultingVariables.put(variable.key(), variableValue);
                } else {
                    throw new IllegalArgumentException("Definition is wrong.");
                }
            } catch (RuntimeException e) {
                Method method = getMethodByName(variable.source(), pojo);
                String variableValue = (String) reflectionGet(method, pojo);
                resultingVariables.put(variable.key(), variableValue);
            }
        }
        return resultingVariables;
    }

    private Provider getProviderByName(String name) {
        for (Provider provider : this.providers) {
            if (provider != null) {
                if (provider.name().equals(name)) return provider;
            }
        }
        log.error("Providername {} not found", name);
        throw new RuntimeException("Providername not found.");
    }

    private void saveClassAnnotations(Object obj) {
        Class stockClass = obj.getClass();

        Annotation[] stockClassAnnotations = stockClass.getAnnotations();

        for (Annotation annotation : stockClassAnnotations) {
            if (annotation instanceof Config) {
                Config config = (Config) annotation;
                this.providers = config.providers();
            }
        }
    }
}


text:
'use strict';

const hds = require('..');

describe('test', function () {
    it('ok', function () {
        return hds.init();
    });
});


text:
Given a string representing a matrix of numbers, return the rows and columns of
that matrix.

So given a string with embedded newlines like:

```text
9 8 7
5 3 2
6 6 7
```

representing this matrix:

```text
    1  2  3
  |---------
1 | 9  8  7
2 | 5  3  2
3 | 6  6  7
```

your code should be able to spit out:

- A list of the rows, reading each row left-to-right while moving
  top-to-bottom across the rows,
- A list of the columns, reading each column top-to-bottom while moving
  from left-to-right.

The rows for our example matrix:

- 9, 8, 7
- 5, 3, 2
- 6, 6, 7

And its columns:

- 9, 5, 6
- 8, 3, 6
- 7, 2, 7


text:
using System;
using System.Collections.Generic;
using System.Text;
using LionFire.Applications.Hosting;
using LionFire.Hosting;
using LionFire.ObjectBus;
using LionFire.ObjectBus.Redis;
using LionFire.Referencing;
using Xunit;
using LionFire.Persistence.Handles;

namespace Redis_
{
    public class List
    {
        [Fact]
        public async void Pass()
        {
            const string testData = "testData-";

            const int itemCount = 200;

            await FrameworkHostBuilder.Create()
                    .AddObjectBus<RedisOBus>()
                    .Run(async () =>
                    {
                        var path = @"\temp\tests\" + GetType().FullName + @"\" + nameof(Pass) + @"\TestFile";

                        var r = new RedisReference(path);

                        #region Cleanup

                        for (int i = 0; i < itemCount; i++)
                        {
                            var childPath = LionPath.Combine(path, "item-" + i);
                            {
                                var childRef = new RedisReference(childPath);
                                var h = childRef.ToHandle<string>();
                                await h.Delete();
                                Assert.False(await h.Exists(), "test object exists after delete: " + childPath);
                            }
                        }

                        #endregion

                        #region Create

                        for (int i = 0; i < itemCount; i++)
                        {
                            var childPath = LionPath.Combine(path, "item-" + i);
                            {
                                var childRef = new RedisReference(childPath);
                                var h = childRef.ToHandle<string>();
                                Assert.False(await h.Exists(), "test object already exists: " + childPath);
                                h.Value = testData + i;
                                await h.Put();
                                Assert.True(await h.Exists(), "test object does not exist after saving: " + childPath);
                            }
                        }

                        #endregion

                        #region Prep Expected

                        var expected = new HashSet<string>();

                        for (int i = 0; i < itemCount; i++)
                        {
                            expected.Add("item-" + i);
                        }

                        List<string> extras = new List<string>();

                        #endregion

                        #region Get keys

                        var keys = await r.GetCollectionHandle().GetKeys(r); //TODO - extension method
                        foreach(var foundItem in keys)
                        {
                            if(!expected.Remove(foundItem))
                            {
                                extras.Add(foundItem);
                            }
                        }

                        #endregion

                        Assert.Empty(expected);
                        Assert.Empty(extras);

                        #region Cleanup

                        for (int i = 0; i < itemCount; i++)
                        {
                            var childPath = LionPath.Combine(path, "item-" + i);
                            {
                                var childRef = new RedisReference(childPath);
                                var h = childRef.ToHandle<string>();
                                await h.Delete();
                                Assert.False(await h.Exists(), "test object exists after delete: " + childPath);
                            }
                        }

                        #endregion

                        //{
                        //    var h = r.ToHandle<string>();
                        //    Assert.True(await h.Exists(), "test object does not exist after saving: " + path);

                        //    var retrievedData = h.Object;
                        //    Assert.Equal(testData, retrievedData);

                        //    h.MarkDeleted(); // TODO: make one
                        //    await h.Put();
                        //    Assert.False(await h.Exists(), "test object still exists after deleting: " + path);
                        //}
                        //{
                        //    var h = r.ToHandle<string>();
                        //    Assert.False(await h.Exists(), "test object still exists after deleting: " + path);

                        //}
                    });
        }
    }
}


text:
package oxygen

type OxygenResponse struct {
	Code        int    `json:"code"`
	Description string `json:"description"`
}

const (
	SUCCESS            = iota + 1000000
	ERROR_PARSING_JSON = iota + 1
	ERROR_INVALID_METHOD
	ERROR_INVALID_VERSION
	ERROR_MISSING_ARGUMENTS
	ERROR_INVALID_PROJECTNAME
	ERROR_PROJECT_ALREADY_EXISTS
	ERROR_INVALID_TOKEN
	ERROR_INVALID_RANGE
	ERROR_INVALID_CONTENT_LENGTH
	ERROR_INVALID_ID_PARAMETER
	ERROR_REQUIRE_TOKEN
	ERROR_MAX_PROJECTS_REACHED
	ERROR_INVALID_CREDENTIALS
	ERROR_NEED_EMAIL_PASSWORD_OR_TOKEN
	ERROR_INVALID_EMAIL
	ERROR_INVALID_PASSWORD
	ERROR_INVALID_EXPIRES
	ERROR_INVALID_ARGUMENT_TYPE
	ERROR_TOKEN_EMPTY
	ERROR_PROJECT_DOES_NOT_EXIST
	ERROR_PATH_NOT_FOUND
	ERROR_PATH_NOT_FOUND_SOURCE
	ERROR_PATH_NOT_FOUND_DESTINATION
	ERROR_INVALID_PATH
	ERROR_INVALID_SOURCE_PATH
	ERROR_INVALID_DESTINATIO_PATH
	ERROR_DIRECTORY_ALREADY_EXISTS
	ERROR_INVALID_USERNAME
	ERROR_USERNAME_ALREADY_EXISTS
	ERROR_EMAIL_ALREADY_IN_USE
	ERROR_NO_WRITE_PERMISSION
	ERROR_NOT_A_DIRECTORY
	ERROR_DIRECTORY_NOT_EMPTY
	ERROR_PATH_ALREADY_EXISTS
	ERROR_USER_CANNOT_TAKE_PROJECT
	ERROR_PROJECT_ALREADY_SHARED_WITH_USER
	ERROR_INVALID_PERMISSIONS
	ERROR_INSUFFICIENT_PERMISSIONS
	ERROR_INSUFFICIENT_PERMISSIONS_SOURCE
	ERROR_INSUFFICIENT_PERMISSIONS_DESTINATION
	ERROR_405
	ERROR_OUT_OF_RANGE
	NO_RESPONSE_REQUIRED
)


text:
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.projectView.impl;

import com.intellij.ide.projectView.TreeStructureProvider;
import com.intellij.ide.projectView.ViewSettings;
import com.intellij.ide.util.treeView.AbstractTreeNode;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.project.IndexNotReadyException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import one.util.streamex.StreamEx;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Collection;
import java.util.Objects;

/**
 * This class is intended to combine all providers for batch usages.
 */
public final class CompoundTreeStructureProvider implements TreeStructureProvider {
  private static final Key<TreeStructureProvider> KEY = Key.create("TreeStructureProvider");
  private static final Logger LOG = Logger.getInstance(CompoundTreeStructureProvider.class);
  private final Project myProject;

  /**
   * @return a shared instance for the specified project
   */
  @Nullable
  public static TreeStructureProvider get(@Nullable Project project) {
    if (project == null || project.isDisposed() || project.isDefault()) return null;
    TreeStructureProvider provider = project.getUserData(KEY);
    if (provider != null) return provider;
    provider = new CompoundTreeStructureProvider(project);
    project.putUserData(KEY, provider);
    return provider;
  }

  private CompoundTreeStructureProvider(@NotNull Project project) {
    myProject = project;
  }

  @NotNull
  @Override
  public Collection<AbstractTreeNode<?>> modify(@NotNull AbstractTreeNode<?> parent,
                                                @NotNull Collection<AbstractTreeNode<?>> children,
                                                ViewSettings settings) {
    if (myProject.isDisposed()) return children;
    for (TreeStructureProvider provider : EP.getExtensions(myProject)) {
      try {
        children = provider.modify(parent, children, settings);
        if (children.stream().anyMatch(Objects::isNull)) {
          LOG.warn("null child provided by " + provider);
          children = StreamEx.of(children).nonNull().toImmutableList();
        }
      }
      catch (IndexNotReadyException exception) {
        throw new ProcessCanceledException(exception);
      }
      catch (ProcessCanceledException exception) {
        throw exception;
      }
      catch (Exception exception) {
        LOG.warn("unexpected error in " + provider, exception);
      }
    }
    children.forEach(node -> node.setParent(parent));
    return children;
  }

  @Nullable
  @Override
  public Object getData(@NotNull Collection<AbstractTreeNode<?>> selection, @NotNull String dataId) {
    if (!myProject.isDisposed() && !selection.isEmpty()) {
      for (TreeStructureProvider provider : EP.getExtensions(myProject)) {
        try {
          Object data = provider.getData(selection, dataId);
          if (data != null) return data;
        }
        catch (IndexNotReadyException | ProcessCanceledException ignore) {
        }
        catch (Exception exception) {
          LOG.warn("unexpected error in " + provider, exception);
        }
      }
    }
    return null;
  }
}


text:
var locationTime,
	locationTimeExpired = 60 * 60 * 1000, // 1 hour
	locationDestination,
	backgroundServices,
	lastUpdated,
	geo   = require('geo'),
	Common = require('common');

	/// FIX IOS7
    	var OS_IOS7 = false,
    		ios7Interval,
    		geoLocationEventListeners = 0;
	/// FIX IOS7

exports.tracking = function(time, dest) {
	Ti.API.error( '[Location Module] - tracking...' );

    checkPermission();

	locationTime = time;
	locationDestination = dest;

	if (OS_IOS) {

		/// Check if IOS7
		var version = Ti.Platform.version.split("."),
			major   = parseInt(version[0], 10);

		OS_IOS7 = (major >= 7);
		/// Check if IOS7

	    iosTrack();

	    if ( OS_IOS7 ) {
	    	ios7Interval = setInterval(iosTrack , 10000);
	    }

  	} else { // OS_ANDROID
  		Ti.Geolocation.preferredProvider = "gps";
  		Ti.Geolocation.accuracy = Ti.Geolocation.ACCURACY_HIGH;

  		Ti.Geolocation.addEventListener('location', trackingCallback);
  	}

	//remove the location event when app closed
    Ti.App.addEventListener( 'location:stopTracking', finishTracking);
};

function iosTrack() {
	Ti.API.error( '[Location Module] - track...'  );

	if ( OS_IOS7 ) { // FIX IOS7

		if ( geoLocationEventListeners > 0 ) {
			Ti.Geolocation.removeEventListener('location', trackingCallback);
			geoLocationEventListeners--;
		}

		Ti.Geolocation.distanceFilter = 0;
	} else {
		Ti.Geolocation.distanceFilter = 10;
	}

	Ti.Geolocation.purpose = "Get user location";
	Ti.Geolocation.accuracy = Ti.Geolocation.ACCURACY_HIGH;
	Ti.Geolocation.addEventListener('location', trackingCallback);
	geoLocationEventListeners++;
}

function checkPermission() {
  	if (Ti.Geolocation.locationServicesEnabled === false) {
		showMessage('Please turn on Location services');
		return;
	}

	if (OS_IOS) {
		var authorization = Ti.Geolocation.locationServicesAuthorization;
		if (authorization == Ti.Geolocation.AUTHORIZATION_DENIED) {
			showMessage('You have disallowed Meetcute from running geolocation services.');
		} else if (authorization == Ti.Geolocation.AUTHORIZATION_RESTRICTED) {
			showMessage('Your system has disallowed Meetcute from running geolocation services.');
		}
	}
}

function trackingCallback(e) {
	Ti.API.error( '[Location Module] - trackingCallback...' );

	var message = '';

	if (!e.success || e.error) {
		message = 'error_' + e.code;
		Ti.API.log( 'Location tracking error: ' + message );
	}

	if ( !message && geo.inRange(e.coords, locationDestination)) {
		locationResult(1);
	} else if (new Date().getTime() - locationTime > locationTimeExpired) {
		locationResult(2);
	}

	if ( e.success ) {// 2 mins

		if ( !lastUpdated || (new Date().getTime() - lastUpdated) >= (2 * 60 *1000) ) {
			var coords = e.coords;

		    lastUpdated = new Date().getTime();
		    Common.trackingLocationResponse ( 3, coords.latitude + '_' + coords.longitude + '_' + coords.timestamp );// update last location
		}
	}
}

function finishTracking() {
	Ti.API.error( '[Location Module] - finishTracking...' );

  	Ti.Geolocation.removeEventListener('location', trackingCallback);
  	geoLocationEventListeners = 0;

  	if ( ios7Interval ) {
  		clearInterval(ios7Interval);
  		ios7Interval = null;
  	}

  	locationDestination = null;
  	locationTime = null;
  	lastUpdated = null;
}

function showMessage(message) {
	if ( OS_IOS ) {
        Ti.App.iOS.scheduleLocalNotification({ // TODO: Test me on background
            alertBody: 	message,
            date:		new Date(new Date().getTime() + 1000) // 1 second after unregister
        });
	} else {
		Ti.UI.createAlertDialog({
			title: 'Meetcute',
			message: message
		}).show();
	}
}

function locationResult(status) {
  	finishTracking();
  	Common.trackingLocationResponse ( status );
}

exports.locationResult = locationResult;


text:
package ru.rintd.controller.network;

import org.omg.CORBA.ORBPackage.InvalidName;
import org.omg.PortableServer.POAManagerPackage.AdapterInactive;
import org.omg.PortableServer.POAPackage.ServantNotActive;
import org.omg.PortableServer.POAPackage.WrongPolicy;
import org.rintd.g14.data.Nodes;
import org.rintd.g14.util.Commands;

public class Connector extends Commands{

	public Connector(String[] args, String addr) throws InvalidName,
			AdapterInactive, ServantNotActive, WrongPolicy {
		super(args, addr);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void Notify_fire_condition(Nodes node) {
		System.out.print("Fire: "+node.name);

	}

	@Override
	public void Notify_node_changed(Nodes node) {
		System.out.print("Changed: "+node.name);

	}

	@Override
	public void Notify_node_added(Nodes node) {
		System.out.print("Added: "+node.name);

	}

}


text:
## Roadmap

## TODOs
* Finish bew build system
* Finish Node.js backend
* Split up locales
* Create reserved strings for locales in `locales.js` (for core messages etc)
* Fix crazy IE bug where calling blur() actually minimizes the window *facepalm*

### Applications
* New Draw codebase -- layer, effect support etc.
* Writer -- Check for changes before opening/new file
* Finish Music Player
* Refactor from currentX to currentFile.x for file stuff
* CoreWM -- Finish panel item options

### GUI
* More Themes
* Finish new Menu implementation
* Custom styling for GUISelect
* Custom styling for GUISelectList
* Custom styling for GUICheckbox
* Custom styling for GUIRadio

### Not prioritized
* Create bin/ scripts for nodejs (redo create-application for PHP)
* Offline resource pre-loading
* Offline VFS
* Full Source code documentation
* Mobile version
* CoreWM: Custom keyboard binding shortcuts
* Misc FIXME and TODO in source-code
  - `grep -e 'TODO\|FIXME' frontend/* apps/*/*`

## Ideas for solving misc problems
* Unfocused windows should have a transparent overlay to prevent clicks+iframe probles
  * When DnD hide


text:
import { TraceFlagsRemover } from '@salesforce/salesforcedx-utils-vscode';
import * as fs from 'fs';
import * as path from 'path';
import * as vscode from 'vscode';
import { Disposable } from 'vscode';
import { workspaceContext } from '../../context';
import { nls } from '../../messages';
import { workspaceUtils } from '../../util';

/**
 * An enum for the different types of functions.
 */
export enum functionType {
  JAVASCRIPT = 'javascript',
  TYPESCRIPT = 'typescript',
  JAVA = 'java'
}

/**
 * A running task that can be terminated
 */
interface Terminable {
  terminate: () => Promise<void>;
}

/**
 * Tracking locally running functions
 */
export interface FunctionExecution extends Terminable {
  /**
   * root dir where project.toml is located
   */
  rootDir: string;
  /**
   * Local function port
   */
  port: number;
  /**
   * Debug port
   */
  debugPort: number;
  /**
   * Type of debug (node, java)
   */
  debugType: string;
  /**
   * Active debug session attached
   */
  debugSession?: vscode.DebugSession;
  /**
   * Flag to determine whether running in a container
   */
  isContainerLess: boolean;
}

export class FunctionService {
  private static _instance: FunctionService;
  public static get instance() {
    if (FunctionService._instance === undefined) {
      FunctionService._instance = new FunctionService();
    }
    return FunctionService._instance;
  }

  private constructor() {}

  /**
   * Locate the directory that has project.toml.
   * If sourceFsPath is the function folder that has project.toml, or a subdirectory
   * or file within that folder, this method returns the function folder by recursively looking up.
   * Otherwise, it returns undefined.
   * @param sourceFsPath path to start function from
   */
  public static getFunctionDir(sourceFsPath: string) {
    let current = fs.lstatSync(sourceFsPath).isDirectory()
      ? sourceFsPath
      : path.dirname(sourceFsPath);
    const { root } = path.parse(sourceFsPath);
    const rootWorkspacePath = workspaceUtils.getRootWorkspacePath();
    while (current !== rootWorkspacePath && current !== root) {
      const tomlPath = path.join(current, 'project.toml');
      if (fs.existsSync(tomlPath)) {
        return current;
      }
      current = path.dirname(current);
    }
    return undefined;
  }

  private startedExecutions: Map<string, FunctionExecution> = new Map();

  /**
   * Register started functions, in order to terminate the container.
   * Returns a disposable to unregister in case an error happens when starting function
   *
   * @returns {Disposable} disposable to unregister
   */
  public registerStartedFunction(
    functionExecution: FunctionExecution
  ): Disposable {
    this.startedExecutions.set(functionExecution.rootDir, functionExecution);
    return {
      dispose: () => {
        this.startedExecutions.delete(functionExecution.rootDir);
      }
    };
  }

  public updateFunction(
    rootDir: string,
    debugType: string,
    isContainerLess: boolean
  ): void {
    const functionExecution = this.getStartedFunction(rootDir);
    if (functionExecution) {
      const type = debugType.toLowerCase();
      if (type.startsWith('node')) {
        functionExecution.debugType = 'node';
      } else if (type.startsWith('java') || type.startsWith('jvm')) {
        functionExecution.debugType = 'java';
      }

      functionExecution.isContainerLess = isContainerLess;
    }
  }

  public isFunctionStarted() {
    return this.startedExecutions.size > 0;
  }

  /**
   * Returns the debugType of the first of the startedExecutions as a way to determine the language
   * of all running executions.
   * Current options: 'node', 'java'
   */
  public getFunctionLanguage() {
    const functionIterator = this.startedExecutions.values();
    if (functionIterator) {
      return functionIterator.next().value?.debugType;
    }
    return undefined;
  }

  /**
   * Get the type of function that is current running.
   * @returns FunctionType
   */
  public getFunctionType(): functionType {
    if (this.startedExecutions.size > 0) {
      const [rootDir] = this.startedExecutions.keys();

      if (fs.existsSync(`${rootDir}/tsconfig.json`)) {
        return functionType.TYPESCRIPT;
      } else if (fs.existsSync(`${rootDir}/package.json`)) {
        return functionType.JAVASCRIPT;
      }

      return functionType.JAVA;
    }

    throw new Error(nls.localize('error_function_type'));
  }

  /**
   * Stop all started function containers
   */
  public async stopFunction() {
    await Promise.all(
      [...this.startedExecutions.values()].map(functionExecution => {
        return functionExecution.terminate();
      })
    );
    this.startedExecutions.clear();
  }

  public getStartedFunction(rootDir: string) {
    return this.startedExecutions.get(rootDir);
  }

  /**
   * Start a debug session that attaches to the debug port of a locally running function.
   * Return if VS Code already has a debug session attached.
   * @param rootDir functions root directory
   */
  public async debugFunction(rootDir: string) {
    const functionExecution = this.getStartedFunction(rootDir);
    if (!functionExecution) {
      throw new Error(
        nls
          .localize('error_unable_to_get_started_function')
          .replace('{0}', rootDir)
      );
    }

    if (!functionExecution.debugSession) {
      const debugConfiguration = this.getDebugConfiguration(
        functionExecution,
        rootDir
      );

      await vscode.debug.startDebugging(
        workspaceUtils.getRootWorkspace(),
        debugConfiguration
      );
    }
  }

  /***
   * Create a DebugConfiguration object
   */
  public getDebugConfiguration(
    functionExecution: FunctionExecution,
    rootDir: string
  ): vscode.DebugConfiguration {
    const { debugPort, debugType } = functionExecution;
    const debugConfiguration: vscode.DebugConfiguration = {
      type: debugType,
      request: 'attach',
      name: 'Debug Invoke', // This name doesn't surface in UI
      resolveSourceMapLocations: ['**', '!**/node_modules/**'],
      console: 'integratedTerminal',
      internalConsoleOptions: 'openOnSessionStart',
      localRoot: rootDir,
      remoteRoot: '/workspace',
      hostName: '127.0.0.1',
      port: debugPort
    };

    if (functionExecution.isContainerLess) {
      delete debugConfiguration.remoteRoot;
    }

    return debugConfiguration;
  }

  /**
   * Detach the debugger
   * @param rootDir functions root directory
   */
  public async stopDebuggingFunction(rootDir: string) {
    const functionExecution = this.getStartedFunction(rootDir);
    if (functionExecution) {
      const { debugSession } = functionExecution;
      await vscode.debug.stopDebugging(debugSession);
    }
  }

  /**
   * Register listeners for debug session start/stop events and keep track of active debug sessions
   * @param extensionContext extension context
   */
  public handleDidStartTerminateDebugSessions(
    extensionContext: vscode.ExtensionContext
  ) {
    const handleDidStartDebugSession = vscode.debug.onDidStartDebugSession(
      session => {
        const { configuration } = session;
        const { localRoot } = configuration;
        const functionExecution = this.getStartedFunction(localRoot);
        if (functionExecution) {
          functionExecution.debugSession = session;
        }
      }
    );
    const handleDidTerminateDebugSession = vscode.debug.onDidTerminateDebugSession(
      session => {
        const { configuration } = session;
        const { localRoot } = configuration;
        const functionExecution = this.getStartedFunction(localRoot);
        if (functionExecution) {
          functionExecution.debugSession = undefined;
        }

        (async () => {
          const connection = await workspaceContext.getConnection();
          await TraceFlagsRemover.getInstance(connection).removeNewTraceFlags();
        })().catch(err => {
          throw err;
        });
      }
    );
    extensionContext.subscriptions.push(
      handleDidStartDebugSession,
      handleDidTerminateDebugSession
    );
  }
}


text:
import { WHITESPACES } from '../helpers/constants';

/* eslint-disable radix -- required for testing */
QUnit.test('parseInt', assert => {
  assert.isFunction(parseInt);
  assert.name(parseInt, 'parseInt');
  assert.arity(parseInt, 2);
  assert.looksNative(parseInt);
  for (let radix = 2; radix <= 36; ++radix) {
    assert.same(parseInt('10', radix), radix, `radix ${ radix }`);
  }
  const strings = ['01', '08', '10', '42'];
  for (const string of strings) {
    assert.same(parseInt(string), parseInt(string, 10), `default radix is 10: ${ string }`);
  }
  assert.same(parseInt('0x16'), parseInt('0x16', 16), 'default radix is 16: 0x16');
  assert.same(parseInt('  0x16'), parseInt('0x16', 16), 'ignores leading whitespace #1');
  assert.same(parseInt('  42'), parseInt('42', 10), 'ignores leading whitespace #2');
  assert.same(parseInt('  08'), parseInt('08', 10), 'ignores leading whitespace #3');
  assert.same(parseInt(`${ WHITESPACES }08`), parseInt('08', 10), 'ignores leading whitespace #4');
  assert.same(parseInt(`${ WHITESPACES }0x16`), parseInt('0x16', 16), 'ignores leading whitespace #5');
  const fakeZero = {
    valueOf() {
      return 0;
    },
  };
  assert.same(parseInt('08', fakeZero), parseInt('08', 10), 'valueOf #1');
  assert.same(parseInt('0x16', fakeZero), parseInt('0x16', 16), 'valueOf #2');
  assert.same(parseInt('-0xF'), -15, 'signed hex #1');
  assert.same(parseInt('-0xF', 16), -15, 'signed hex #2');
  assert.same(parseInt('+0xF'), 15, 'signed hex #3');
  assert.same(parseInt('+0xF', 16), 15, 'signed hex #4');
  assert.same(parseInt('10', -4294967294), 2, 'radix uses ToUint32');
  assert.same(parseInt(null), NaN);
  assert.same(parseInt(undefined), NaN);

  if (typeof Symbol == 'function' && !Symbol.sham) {
    assert.throws(() => parseInt(Symbol()), 'throws on symbol argument');
    assert.throws(() => parseInt(Object(Symbol())), 'throws on boxed symbol argument');
  }
});


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;

namespace Microsoft.NodejsTools.Npm
{
    public interface INpmLogSource
    {
        event EventHandler<NpmCommandStartedEventArgs> CommandStarted;
        event EventHandler<NpmLogEventArgs> OutputLogged;
        event EventHandler<NpmLogEventArgs> ErrorLogged;
        event EventHandler<NpmExceptionEventArgs> ExceptionLogged;
        event EventHandler<NpmCommandCompletedEventArgs> CommandCompleted;
    }
}


text:
<?php
/**
 * DO NOT EDIT THIS FILE!
 *
 * This file was automatically generated from external sources.
 *
 * Any manual change here will be lost the next time the SDK
 * is updated. You've been warned!
 */

namespace DTS\eBaySDK\MerchantData\Types;

/**
 *
 * @property integer $ShippingServicePriority
 * @property \DTS\eBaySDK\MerchantData\Enums\ShippingServiceType $ShippingServiceType
 * @property \DTS\eBaySDK\MerchantData\Types\AmountType $ShippingServiceCost
 * @property \DTS\eBaySDK\MerchantData\Types\AmountType $ShippingServiceAdditionalCost
 * @property \DTS\eBaySDK\MerchantData\Types\AmountType $ShippingSurcharge
 */
class ShippingServiceCostOverrideType extends \DTS\eBaySDK\Types\BaseType
{
    /**
     * @var array Properties belonging to objects of this class.
     */
    private static $propertyTypes = [
        'ShippingServicePriority' => [
            'type' => 'integer',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'ShippingServicePriority'
        ],
        'ShippingServiceType' => [
            'type' => 'string',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'ShippingServiceType'
        ],
        'ShippingServiceCost' => [
            'type' => 'DTS\eBaySDK\MerchantData\Types\AmountType',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'ShippingServiceCost'
        ],
        'ShippingServiceAdditionalCost' => [
            'type' => 'DTS\eBaySDK\MerchantData\Types\AmountType',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'ShippingServiceAdditionalCost'
        ],
        'ShippingSurcharge' => [
            'type' => 'DTS\eBaySDK\MerchantData\Types\AmountType',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'ShippingSurcharge'
        ]
    ];

    /**
     * @param array $values Optional properties and values to assign to the object.
     */
    public function __construct(array $values = [])
    {
        list($parentValues, $childValues) = self::getParentValues(self::$propertyTypes, $values);

        parent::__construct($parentValues);

        if (!array_key_exists(__CLASS__, self::$properties)) {
            self::$properties[__CLASS__] = array_merge(self::$properties[get_parent_class()], self::$propertyTypes);
        }

        if (!array_key_exists(__CLASS__, self::$xmlNamespaces)) {
            self::$xmlNamespaces[__CLASS__] = 'xmlns="urn:ebay:apis:eBLBaseComponents"';
        }

        $this->setValues(__CLASS__, $childValues);
    }
}


text:
require 'fog/core/collection'
require 'fog/hp/models/network/security_group_rule'

module Fog
  module HP
    class Network
      class SecurityGroupRules < Fog::Collection
        attribute :filters

        model Fog::HP::Network::SecurityGroupRule

        def initialize(attributes)
          self.filters ||= {}
          super
        end

        def all(filters = filters)
          self.filters = filters
          non_aliased_filters = Fog::HP.convert_aliased_attributes_to_original(self.model, filters)
          load(service.list_security_group_rules(non_aliased_filters).body['security_group_rules'])
        end

        def get(sec_group_rule_id)
          if sec_group_rule = service.get_security_group_rule(sec_group_rule_id).body['security_group_rule']
            new(sec_group_rule)
          end
        rescue Fog::HP::Network::NotFound
          nil
        end
      end
    end
  end
end


text:
import datetime
import os
import shutil
import sys
import glob
from optparse import OptionParser
from subprocess import Popen, PIPE

from xhtml2pdf import pisa

def render_pdf(filename, output_dir, options):
    if options.debug:
        print 'Rendering %s' % filename
    basename = os.path.basename(filename)
    outname = '%s.pdf' % os.path.splitext(basename)[0]
    outfile = os.path.join(output_dir, outname)

    input = open(filename, 'rb')
    output = open(outfile, 'wb')

    result = pisa.pisaDocument(input, output, path=filename)

    input.close()
    output.close()

    if result.err:
        print 'Error rendering %s: %s' % (filename, result.err)
        sys.exit(1)
    return outfile

def convert_to_png(infile, output_dir, options):
    if options.debug:
        print 'Converting %s to PNG' % infile
    basename = os.path.basename(infile)
    filename = os.path.splitext(basename)[0]
    outname = '%s.page%%0d.png' % filename
    globname = '%s.page*.png' % filename
    outfile = os.path.join(output_dir, outname)
    exec_cmd(options, options.convert_cmd, '-density', '150', infile, outfile)
    outfiles = glob.glob(os.path.join(output_dir, globname))
    outfiles.sort()
    return outfiles

def create_diff_image(srcfile1, srcfile2, output_dir, options):
    if options.debug:
        print 'Creating difference image for %s and %s' % (srcfile1, srcfile2)

    outname = '%s.diff%s' % os.path.splitext(srcfile1)
    outfile = os.path.join(output_dir, outname)
    _, result = exec_cmd(options, options.compare_cmd, '-metric', 'ae', srcfile1, srcfile2, '-lowlight-color', 'white', outfile)
    diff_value = int(result.strip())
    if diff_value > 0:
        if not options.quiet:
            print 'Image %s differs from reference, value is %i' % (srcfile1, diff_value)
    return outfile, diff_value

def copy_ref_image(srcname, output_dir, options):
    if options.debug:
        print 'Copying reference image %s ' % srcname
    dstname = os.path.basename(srcname)
    dstfile = os.path.join(output_dir, '%s.ref%s' % os.path.splitext(dstname))
    shutil.copyfile(srcname, dstfile)
    return dstfile

def create_thumbnail(filename, options):
    thumbfile = '%s.thumb%s' % os.path.splitext(filename)
    if options.debug:
        print 'Creating thumbnail of %s' % filename
    exec_cmd(options, options.convert_cmd, '-resize', '20%', filename, thumbfile)
    return thumbfile

def render_file(filename, output_dir, ref_dir, options):
    if not options.quiet:
        print 'Rendering %s' % filename
    pdf = render_pdf(filename, output_dir, options)
    pngs = convert_to_png(pdf, output_dir, options)
    if options.create_reference:
        return None, None, 0
    thumbs = [create_thumbnail(png, options) for png in pngs]
    pages = [{'png': p, 'png_thumb': thumbs[i]}
             for i,p in enumerate(pngs)]
    diff_count = 0
    if not options.no_compare:
        for page in pages:
            refsrc = os.path.join(ref_dir, os.path.basename(page['png']))
            if not os.path.isfile(refsrc):
                print 'Reference image for %s not found!' % page['png']
                continue
            page['ref'] = copy_ref_image(refsrc, output_dir, options)
            page['ref_thumb'] = create_thumbnail(page['ref'], options)
            page['diff'], page['diff_value'] = \
                    create_diff_image(page['png'], page['ref'],
                                      output_dir, options)
            page['diff_thumb'] = create_thumbnail(page['diff'], options)
            if page['diff_value']:
                diff_count += 1
    return pdf, pages, diff_count

def exec_cmd(options, *args):
    if options.debug:
        print 'Executing %s' % ' '.join(args)
    proc = Popen(args, stdout=PIPE, stderr=PIPE)
    result = proc.communicate()
    if options.debug:
        print result[0], result[1]
    if proc.returncode:
        print 'exec error (%i): %s' % (proc.returncode, result[1])
        sys.exit(1)
    return result[0], result[1]

def create_html_file(results, template_file, output_dir, options):
    html = []
    for pdf, pages, diff_count in results:
        if options.only_errors and not diff_count:
            continue
        pdfname = os.path.basename(pdf)
        html.append('
\n'
                    '
%(pdf)s
\n'
                    % {'pdf': pdfname})
        for i, page in enumerate(pages):
            vars = dict(((k, os.path.basename(v)) for k,v in page.items()
                         if k != 'diff_value'))
            vars['page'] = i+1
            if 'diff' in page:
                vars['diff_value'] = page['diff_value']
                if vars['diff_value']:
                    vars['class'] = 'result-page-diff error'
                else:
                    if options.only_errors:
                        continue
                    vars['class'] = 'result-page-diff'
                html.append('
\n'
                            '
Page %(page)i
\n'

                            '
\n'
                            '
Difference '
                            '(Score %(diff_value)i)
\n'
                            ''
                            '\n'
                            '
\n'

                            '
\n'
                            '
Rendered
\n'
                            ''
                            '\n'
                            '
\n'

                            '
\n'
                            '
Reference
\n'
                            ''
                            '\n'
                            '
\n'

                            '
\n' % vars)
            else:
                html.append('
\n'
                           '
Page %(page)i
\n'

                           '
\n'
                           ''
                           '\n'
                           '
\n'

                           '
\n' % vars)
        html.append('
\n\n')

    now = datetime.datetime.now()
    title = 'xhtml2pdf Test Rendering Results, %s' % now.strftime('%c')
    template = open(template_file, 'rb').read()
    template = template.replace('%%TITLE%%', title)
    template = template.replace('%%RESULTS%%', '\n'.join(html))

    htmlfile = os.path.join(output_dir, 'index.html')
    outfile = open(htmlfile, 'wb')
    outfile.write(template)
    outfile.close()
    return htmlfile

def main():
    options, args = parser.parse_args()

    base_dir = os.path.abspath(os.path.join(__file__, os.pardir))
    source_dir = os.path.join(base_dir, options.source_dir)
    if options.create_reference is not None:
        output_dir = os.path.join(base_dir, options.create_reference)
    else:
        output_dir = os.path.join(base_dir, options.output_dir)
    template_file = os.path.join(base_dir, options.html_template)
    ref_dir = os.path.join(base_dir, options.ref_dir)

    if os.path.isdir(output_dir):
        shutil.rmtree(output_dir)
    os.makedirs(output_dir)

    results = []
    diff_count = 0
    if len(args) == 0:
        files = glob.glob(os.path.join(source_dir, '*.html'))
    else:
        files = [os.path.join(source_dir, arg) for arg in args]
    for filename in files:
        pdf, pages, diff = render_file(filename, output_dir, ref_dir, options)
        diff_count += diff
        results.append((pdf, pages, diff))

    num = len(results)

    if options.create_reference is not None:
        print 'Created reference for %i file%s' % (num, '' if num == 1 else 's')
    else:
        htmlfile = create_html_file(results, template_file, output_dir, options)
        if not options.quiet:
            print 'Rendered %i file%s' % (num, '' if num == 1 else 's')
            print '%i file%s differ%s from reference' % \
                    (diff_count, diff_count != 1 and 's' or '',
                     diff_count == 1 and 's' or '')
            print 'Check %s for results' % htmlfile
        if diff_count:
            sys.exit(1)

parser = OptionParser(
    usage='rendertest.py [options] [source_file] [source_file] ...',
    description='Renders a single html source file or all files in the data '
    'directory, converts them to PNG format and prepares a result '
    'HTML file for comparing the output with an expected result')
parser.add_option('-s', '--source-dir', dest='source_dir', default='data/source',
                  help=('Path to directory containing the html source files'))
parser.add_option('-o', '--output-dir', dest='output_dir', default='output',
                  help='Path to directory for output files. CAREFUL: this '
                  'directory will be deleted and recreated before rendering!')
parser.add_option('-r', '--ref-dir', dest='ref_dir', default='data/reference',
                  help='Path to directory containing the reference images '
                  'to compare the result with')
parser.add_option('-t', '--template', dest='html_template',
                  default='data/template.html', help='Name of HTML template file')
parser.add_option('-e', '--only-errors', dest='only_errors', action='store_true',
                  default=False, help='Only include images in HTML file which '
                  'differ from reference')
parser.add_option('-q', '--quiet', dest='quiet', action='store_true',
                  default=False, help='Try to be quiet')
parser.add_option('--no-compare', dest='no_compare', action='store_true',
                  default=False, help='Do not compare with reference image, '
                  'only render to png')
parser.add_option('-c', '--create-reference', dest='create_reference',
                  metavar='DIR',
                  default=None, help='Do not output anything, render source to '
                  'specified directory for reference. CAREFUL: this directory '
                 'will be deleted and recreated before rendering!')
parser.add_option('--debug', dest='debug', action='store_true',
                  default=False, help='More output for debugging')
parser.add_option('--convert-cmd', dest='convert_cmd', default='/usr/bin/convert',
                  help='Path to ImageMagick "convert" tool')
parser.add_option('--compare-cmd', dest='compare_cmd', default='/usr/bin/compare',
                  help='Path to ImageMagick "compare" tool')

if __name__ == '__main__':
    main()


text:
require File.expand_path('boot', __dir__)

# require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"

Bundler.require(*Rails.groups)

module SS
  mattr_reader(:version) { "1.11.1" }

  class Application < Rails::Application
    config.autoload_paths << "#{config.root}/lib"
    config.autoload_paths << "#{config.root}/app/validators"
    config.autoload_paths << "#{config.root}/app/helpers/concerns"
    config.autoload_paths << "#{config.root}/app/jobs/concerns"
    config.assets.paths << "#{config.root}/public/assets/css"
    config.assets.paths << "#{config.root}/public/assets/js"
    config.assets.precompile << proc do |path, fn|
      fn =~ /#{Rails.root}\/app/ && %w(.js .css).include?(::File.extname(path)) && path !~ /\/lib\// && path !~ /\/_/
    end

    I18n.enforce_available_locales = true
    config.time_zone = 'Tokyo'
    config.i18n.default_locale = :ja
    config.i18n.fallbacks = [ :en ]

    Dir["#{config.root}/config/locales/**/*.{rb,yml}"].each do |file|
      config.i18n.load_path << file unless config.i18n.load_path.index(file)
    end
    Dir["#{config.root}/config/oem/locales/**/*.{rb,yml}"].each do |file|
      config.i18n.load_path << file unless config.i18n.load_path.index(file)
    end
    Dir["#{config.root}/config/routes/**/routes.rb"].sort.each do |file|
      config.paths["config/routes.rb"] << file
    end
    Dir["#{config.root}/config/routes/*/routes_end.rb"].sort.each do |file|
      config.paths["config/routes.rb"] << file
    end

    config.paths["config/initializers"] << "#{config.root}/config/after_initializers"

    config.middleware.use Mongoid::QueryCache::Middleware

    attr_reader :current_env

    def call(*args, &block)
      @current_env = args.first
      super
    ensure
      @current_env = nil
      @current_request = nil
    end

    def current_request
      return if @current_env.nil?
      @current_request ||= ActionDispatch::Request.new(@current_env)
    end

    def current_session_id
      return unless @current_env

      session = @current_env[Rack::RACK_SESSION]
      return unless session

      session.id
    end

    def current_request_id
      if current_request
        current_request.request_id
      else
        nil
      end
    end
  end

  def self.config
    # lazy loading
    @_ss_config ||= "SS::Config".constantize.setup
  end
end

def dump(*args)
  SS::Debug.dump(*args) #::File.open("#{Rails.root}/log/dump.log", "a") {|f| f.puts args.inspect }
end


text:
from binding import *

from classes.Type import *

REGULAR_TYPE_INTEGRATIONS = {
    "GLextension" : [ "hashable", "streamable" ],
    "GLboolean"   : [ "streamable" ],
    "GLenum"      : [ "hashable", "streamable", "addable", "comparable" ]
}
BITFIELD_TYPE_INTEGRATIONS = [ "hashable", "bitfieldStreamable", "bitOperatable"]
TYPE_INTEGRATIONS = [ "addable", "bitOperatable", "bitfieldStreamable", "comparable", "hashable", "streamable"]

def integrationMap(integrationList):
    return { integration: (integration in integrationList) for integration in TYPE_INTEGRATIONS}

def typeIntegrationMap(type):
    return integrationMap(REGULAR_TYPE_INTEGRATIONS[type.name] if type.name in REGULAR_TYPE_INTEGRATIONS else [])

# ToDo: move this to Type class? (as well as convert an multiline convert)
enum_classes = [ "GLenum" ]

def convertTypedefLine(line, name):

    if not line.startswith("typedef"):
        return line
    else:
        return "using " + name + " = " + line[8:].replace(name, "")

def multilineConvertTypedef(type):

    return "\n".join([ convertTypedefLine(line, type.name) for line in type.value.split('\n') ])

def convertTypedef(type):

    if '\n' in type.value:
        return multilineConvertTypedef(type)

    t = parseType(type)

    if type.name in enum_classes:
        return "enum class " + type.name + " : " + t + ";"

    if not type.value.startswith("typedef"):
        return t
    elif type.name == "GLboolean":
        return "// Import of GLboolean is an include"
    else:
        return "using " + type.name + " = " + t + ";"

def convertType(type):

    return convertTypedef(type).replace(" ;", ";").replace("( *)", "(*)").replace("(*)", "(GL_APIENTRY *)")

def genTypeContexts(types, bitfGroups):
    typeContexts = [{"identifier": "GLextension",
                     "definition": "enum class GLextension : int;",
                     "integrations": integrationMap([ "hashable", "streamable" ]),
                     "hasIntegrations": True}]
    for type in types: #TODO-LW: explicitly sort types and bitfGroups
        integrations = typeIntegrationMap(type)
        typeContexts.append({"identifier": type.name,
                             "definition": convertType(type),
                             "integrations": integrations,
                             "hasIntegrations": any(integrations.values()) })
    for bitf in bitfGroups:
        integrations = integrationMap(BITFIELD_TYPE_INTEGRATIONS)
        typeContexts.append({"identifier": bitf.name,
                             "definition": "enum class {} : unsigned int;".format(bitf.name),
                             "integrations": integrations,
                             "hasIntegrations": any(integrations.values()) })
    return typeContexts


text:
@class ManualFillActionItem;
@class ManualFillCardItem;

// Objects conforming to this protocol need to react when new data is available.
// TODO(crbug.com/845472): rename all class/file with 'Card' to 'CreditCard'.
@protocol ManualFillCardConsumer

// Tells the consumer to show the passed cards.
- (void)presentCards:(NSArray<ManualFillCardItem*>*)cards;

// Asks the consumer to present the passed actions
- (void)presentActions:(NSArray<ManualFillActionItem*>*)actions;

@end

#endif  // IOS_CHROME_BROWSER_UI_AUTOFILL_MANUAL_FILL_CARD_CONSUMER_H_


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.example.point.UserID">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="IDを入力してください"
        android:id="@+id/textView1"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editText1"
        android:layout_below="@+id/textView1"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="完了"
        android:id="@+id/button1"
        android:layout_marginTop="55dp"
        android:layout_below="@+id/editText1"
        android:layout_centerHorizontal="true" />
</RelativeLayout>


text:
package ua.ds.array.primitive;

import ua.ds.array.ArrayQueue;
import ua.ds.SequentialQueue;

public class BitMaskNonResizableArrayQueuePrimitive implements SequentialQueue {
  private final int[] items;
  private int head;
  private int tail;
  private int size;

  public BitMaskNonResizableArrayQueuePrimitive() {
    this(16);
  }

  public BitMaskNonResizableArrayQueuePrimitive(int capacity) {
    capacity = ArrayQueue.nextPowerOfTwo(capacity);
    items = new int[capacity];
    head = 0;
    tail = 0;
    size = 0;
  }

  @Override
  public void enqueue(int item) {
    items[tail] = item;
    tail = (tail + 1) & (items.length - 1);
    size++;
  }

  @Override
  public int deque() {
    if (isEmpty()) return -1;
    int item = items[head];
    size--;
    head = (head + 1) & (items.length - 1);
    return item;
  }

  private boolean isEmpty() {
    return size == 0;
  }
}


text:
namespace OpenApoc
{

static std::vector<UString> tracks{"music:0", "music:1", "music:2"};

MainMenu::MainMenu() : Stage(), mainmenuform(ui().getForm("FORM_MAINMENU"))
{
	auto versionLabel = mainmenuform->findControlTyped<Label>("VERSION_LABEL");
	versionLabel->setText(OPENAPOC_VERSION);
}

MainMenu::~MainMenu() = default;

void MainMenu::begin() { fw().jukebox->play(tracks); }

void MainMenu::pause() {}

void MainMenu::resume() {}

void MainMenu::finish() {}

void MainMenu::eventOccurred(Event *e)
{
	mainmenuform->eventOccured(e);

	if (e->type() == EVENT_KEY_DOWN)
	{
		if (e->keyboard().KeyCode == SDLK_ESCAPE)
		{
			stageCmd.cmd = StageCmd::Command::QUIT;
			return;
		}
	}

	if (e->type() == EVENT_FORM_INTERACTION && e->forms().EventFlag == FormEventType::ButtonClick)
	{
		if (e->forms().RaisedBy->Name == "BUTTON_OPTIONS")
		{
			stageCmd.cmd = StageCmd::Command::PUSH;
			stageCmd.nextStage = mksp<OptionsMenu>();
			return;
		}
		if (e->forms().RaisedBy->Name == "BUTTON_QUIT")
		{
			stageCmd.cmd = StageCmd::Command::QUIT;
			return;
		}
		if (e->forms().RaisedBy->Name == "BUTTON_NEWGAME")
		{
			stageCmd.cmd = StageCmd::Command::PUSH;
			stageCmd.nextStage = mksp<DifficultyMenu>();
			return;
		}
		if (e->forms().RaisedBy->Name == "BUTTON_DEBUG")
		{
			stageCmd.cmd = StageCmd::Command::PUSH;
			stageCmd.nextStage = mksp<DebugMenu>();
			return;
		}
		if (e->forms().RaisedBy->Name == "BUTTON_LOADGAME")
		{
			stageCmd.cmd = StageCmd::Command::PUSH;
			stageCmd.nextStage = mksp<SaveMenu>(SaveMenuAction::LoadNewGame, nullptr);
			return;
		}
	}
}

void MainMenu::update(StageCmd *const cmd)
{
	mainmenuform->update();
	*cmd = stageCmd;
	stageCmd = StageCmd();
}

void MainMenu::render() { mainmenuform->render(); }

bool MainMenu::isTransition() { return false; }
}; // namespace OpenApoc


text:
@interface DXNumberFormatter : NSNumberFormatter <DXSingleton>

+ (NSNumber*)numberFromString:(NSString *)string style:(NSNumberFormatterStyle)style;
+ (NSString*)stringFromNumber:(NSNumber *)number style:(NSNumberFormatterStyle)style;

- (NSNumber*)numberFromString:(NSString *)string style:(NSNumberFormatterStyle)style;
- (NSString*)stringFromNumber:(NSNumber *)number style:(NSNumberFormatterStyle)style;

@end