<?php

declare(strict_types=1);

/**
 * This file is part of phpDocumentor.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @link https://phpdoc.org
 */

namespace phpDocumentor\Descriptor\Builder\Reflector;

use phpDocumentor\Descriptor\ConstantDescriptor;
use phpDocumentor\Reflection\Php\Constant;
use function strlen;
use function substr;

/**
 * Assembles a ConstantDescriptor from a ConstantReflector.
 */
class ConstantAssembler extends AssemblerAbstract
{
    public const SEPARATOR_SIZE = 2;

    /**
     * Creates a Descriptor from the provided data.
     *
     * @param Constant $data
     */
    public function create(object $data) : ConstantDescriptor
    {
        $constantDescriptor = new ConstantDescriptor();
        $constantDescriptor->setName($data->getName());
        $constantDescriptor->setValue($this->pretifyValue($data->getValue()));
        // Reflection library formulates namespace as global but this is not wanted for phpDocumentor itself
        $constantDescriptor->setNamespace(
            substr((string) $data->getFqsen(), 0, - strlen($data->getName()) - self::SEPARATOR_SIZE)
        );
        $constantDescriptor->setFullyQualifiedStructuralElementName($data->getFqsen());

        $this->assembleDocBlock($data->getDocBlock(), $constantDescriptor);

        $constantDescriptor->setLine($data->getLocation()->getLineNumber());
        $constantDescriptor->setVisibility((string) $data->getVisibility() ?: 'public');

        return $constantDescriptor;
    }
}

{'repo_name': 'phpDocumentor/phpDocumentor', 'stars': '2579', 'repo_language': 'PHP', 'file_name': 'package-lock.json', 'mime_type': 'text/plain', 'hash': -9042039331262696330, 'source_dataset': 'data'}


# -*- coding: utf-8 -*-
import sys
import requests
import time

'''
Usage:
    moon.py -u  kindeditor http://127.0.0.1:8080/kidneditor
    影响：kindeditor<=4.1.5   文件上传漏洞   可上传txt和html，用作钓鱼或者跳转博彩网站
    检测方式：这里采用版本判断和查看上传文件的方式确认漏洞是否存在
             首先查询编辑器版本，如果在4.1.5版本之下，且存在相应的上传文件，则认为漏洞存在
'''

def attack(URL):
    print('[+]开始检测-kindeditor<=4.1.5文件上传漏洞。[+]')
    user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"
    headers={"User-Agent":user_agent}

    #获取版本
    try:
        url1 = URL+'/kindeditor-min.js'
        verify_response = requests.get(url1, headers=headers)
        # print(verify_response.status_code)
        print('开始检查kindeditor版本，kindeditor<=4.1.5存在文件上传漏洞:')
        if verify_response.status_code ==200:
            print('此kindeditor的版本为：',verify_response.content[:40])
            print('-----------------------------------------------------')
        else:
            print('未发现获取版本的文件:',verify_response.status_code)
            print('-----------------------------------------------------')
    except:
        print('获取版本失败。')

    #检测上传页面是否存在
    urls = (
        '/asp/upload_json.asp',
        '/asp.net/upload_json.ashx',
        '/jsp/upload_json.jsp',
        '/php/upload_json.php'
    )
    for url in urls:
        url = URL + url
        try:
            verify_response = requests.get(url, headers=headers)

            if verify_response.status_code == 200:
                try:
                    print('存在此页面：'+url+'    '+str(verify_response.status_code))
                except:
                    pass
            else :
                print('未发现此页面：'+url+'    '+str(verify_response.status_code))
                continue
        except :
            print("Someerror!")
    print('[+]检测结束-kindeditor<=4.1.5文件上传漏洞。[+]')
    print('\n')

if __name__ == "__main__":
    attack('')

{'repo_name': '1120362990/vulnerability-list', 'stars': '595', 'repo_language': 'Python', 'file_name': 'Main_js_find.py', 'mime_type': 'text/x-python', 'hash': -7067407957656090453, 'source_dataset': 'data'}


Evernote's ENML library in Javascript

{'repo_name': 'porter-io/tag-github', 'stars': '159', 'repo_language': 'None', 'file_name': '__meta__.json', 'mime_type': 'text/plain', 'hash': 4096201827890403976, 'source_dataset': 'data'}


[ExifTool, ExifTool, ExifTool] ExifToolVersion - ExifTool Version Number: 12.03
[File, System, Other] FileName - File Name: Minolta.jpg
[File, System, Other] Directory - Directory: t/images
[File, System, Other] FileSize - File Size: 13 kB
[File, System, Time] FileModifyDate - File Modification Date/Time: 2006:01:04 14:02:27-05:00
[File, System, Time] FileAccessDate - File Access Date/Time: 2020:07:29 09:04:11-04:00
[File, System, Time] FileInodeChangeDate - File Inode Change Date/Time: 2017:12:27 12:00:59-05:00
[File, System, Other] FilePermissions - File Permissions: rw-r--r--
[File, File, Other] FileType - File Type: JPEG
[File, File, Other] FileTypeExtension - File Type Extension: jpg
[File, File, Other] MIMEType - MIME Type: image/jpeg
[File, File, Image] ExifByteOrder - Exif Byte Order: Big-endian (Motorola, MM)
[File, File, Image] ImageWidth - Image Width: 8
[File, File, Image] ImageHeight - Image Height: 8
[File, File, Image] EncodingProcess - Encoding Process: Baseline DCT, Huffman coding
[File, File, Image] BitsPerSample - Bits Per Sample: 8
[File, File, Image] ColorComponents - Color Components: 3
[File, File, Image] YCbCrSubSampling - Y Cb Cr Sub Sampling: YCbCr4:2:0 (2 2)
[EXIF, IFD0, Image] 270 - Image Description: DCF 1.0
[EXIF, IFD0, Camera] 271 - Make: Minolta Co., Ltd.
[EXIF, IFD0, Camera] 272 - Camera Model Name: DiMAGE 7i
[EXIF, IFD0, Image] 274 - Orientation: Horizontal (normal)
[EXIF, IFD0, Image] 282 - X Resolution: 72
[EXIF, IFD0, Image] 283 - Y Resolution: 72
[EXIF, IFD0, Image] 296 - Resolution Unit: inches
[EXIF, IFD0, Image] 305 - Software: Ver.1.00u
[EXIF, IFD0, Time] 306 - Modify Date: 2002:06:01 12:37:27
[EXIF, IFD0, Image] 531 - Y Cb Cr Positioning: Centered
[EXIF, ExifIFD, Image] 33434 - Exposure Time: 1/180
[EXIF, ExifIFD, Image] 33437 - F Number: 5.6
[EXIF, ExifIFD, Camera] 34850 - Exposure Program: Program AE
[EXIF, ExifIFD, Image] 34855 - ISO: 100
[EXIF, ExifIFD, Image] 36864 - Exif Version: 0220
[EXIF, ExifIFD, Time] 36867 - Date/Time Original: 2002:06:01 12:37:27
[EXIF, ExifIFD, Time] 36868 - Create Date: 2002:06:01 12:37:27
[EXIF, ExifIFD, Image] 37121 - Components Configuration: Y, Cb, Cr, -
[EXIF, ExifIFD, Image] 37379 - Brightness Value: 7.5
[EXIF, ExifIFD, Image] 37380 - Exposure Compensation: 0
[EXIF, ExifIFD, Camera] 37381 - Max Aperture Value: 3.4
[EXIF, ExifIFD, Camera] 37383 - Metering Mode: Multi-segment
[EXIF, ExifIFD, Camera] 37384 - Light Source: Unknown
[EXIF, ExifIFD, Camera] 37385 - Flash: Off, Did not fire
[EXIF, ExifIFD, Camera] 37386 - Focal Length: 42.3 mm
[EXIF, ExifIFD, Camera] 37396 - Subject Area: 960 960 320 192
[EXIF, ExifIFD, Image] 40960 - Flashpix Version: 0100
[EXIF, ExifIFD, Image] 40961 - Color Space: sRGB
[EXIF, ExifIFD, Image] 40962 - Exif Image Width: 2560
[EXIF, ExifIFD, Image] 40963 - Exif Image Height: 1920
[EXIF, InteropIFD, Image] 1 - Interoperability Index: R98 - DCF basic file (sRGB)
[EXIF, InteropIFD, Image] 2 - Interoperability Version: 0100
[EXIF, ExifIFD, Image] 41985 - Custom Rendered: Custom
[EXIF, ExifIFD, Camera] 41986 - Exposure Mode: Auto
[EXIF, ExifIFD, Camera] 41987 - White Balance: Auto
[EXIF, ExifIFD, Camera] 41988 - Digital Zoom Ratio: 0
[EXIF, ExifIFD, Camera] 41989 - Focal Length In 35mm Format: 167 mm
[EXIF, ExifIFD, Camera] 41990 - Scene Capture Type: Standard
[EXIF, ExifIFD, Camera] 41991 - Gain Control: None
[EXIF, ExifIFD, Camera] 41992 - Contrast: Normal
[EXIF, ExifIFD, Camera] 41993 - Saturation: Normal
[EXIF, ExifIFD, Camera] 41994 - Sharpness: Normal
[EXIF, ExifIFD, Camera] 41996 - Subject Distance Range: Close
[EXIF, IFD1, Image] 259 - Compression: JPEG (old-style)
[EXIF, IFD1, Image] 274 - Orientation: Horizontal (normal)
[EXIF, IFD1, Image] 282 - X Resolution: 72
[EXIF, IFD1, Image] 283 - Y Resolution: 72
[EXIF, IFD1, Image] 296 - Resolution Unit: inches
[EXIF, IFD1, Image] 513 - Thumbnail Offset: 13224
[EXIF, IFD1, Image] 514 - Thumbnail Length: 28
[EXIF, IFD1, Image] 531 - Y Cb Cr Positioning: Centered
[EXIF, IFD1, Preview] Exif-ThumbnailImage - Thumbnail Image: (Binary data 28 bytes)
[MakerNotes, Minolta, Camera] 0 - Maker Note Version: MLT0
[MakerNotes, Minolta, Camera] 1 - Exposure Mode: Program
[MakerNotes, Minolta, Camera] 2 - Flash Mode: Fill flash
[MakerNotes, Minolta, Camera] 3 - White Balance: Auto
[MakerNotes, Minolta, Camera] 4 - Minolta Image Size: Full
[MakerNotes, Minolta, Camera] 5 - Minolta Quality: Fine
[MakerNotes, Minolta, Camera] 6 - Drive Mode: Single
[MakerNotes, Minolta, Camera] 7 - Metering Mode: Multi-segment
[MakerNotes, Minolta, Camera] 8 - ISO: 100
[MakerNotes, Minolta, Camera] 9 - Exposure Time: 1/181
[MakerNotes, Minolta, Camera] 10 - F Number: 5.7
[MakerNotes, Minolta, Camera] 11 - Macro Mode: Off
[MakerNotes, Minolta, Camera] 12 - Digital Zoom: Off
[MakerNotes, Minolta, Camera] 13 - Exposure Compensation: 0
[MakerNotes, Minolta, Camera] 14 - Bracket Step: 1/3 EV
[MakerNotes, Minolta, Camera] 16 - Interval Length: 0
[MakerNotes, Minolta, Camera] 17 - Interval Number: 2
[MakerNotes, Minolta, Camera] 18 - Focal Length: 41.4 mm
[MakerNotes, Minolta, Camera] 19 - Focus Distance: 2 m
[MakerNotes, Minolta, Camera] 20 - Flash Fired: No
[MakerNotes, Minolta, Time] 21 - Minolta Date: 2002:06:01
[MakerNotes, Minolta, Time] 22 - Minolta Time: 12:37:27
[MakerNotes, Minolta, Camera] 23 - Max Aperture: 3.4
[MakerNotes, Minolta, Camera] 26 - File Number Memory: On
[MakerNotes, Minolta, Camera] 27 - Last File Number: 32
[MakerNotes, Minolta, Camera] 28 - Color Balance Red: 1.49609375
[MakerNotes, Minolta, Camera] 29 - Color Balance Green: 1
[MakerNotes, Minolta, Camera] 30 - Color Balance Blue: 1.375
[MakerNotes, Minolta, Camera] 31 - Saturation: Normal
[MakerNotes, Minolta, Camera] 32 - Contrast: Normal
[MakerNotes, Minolta, Camera] 33 - Sharpness: Normal
[MakerNotes, Minolta, Camera] 34 - Subject Program: None
[MakerNotes, Minolta, Camera] 35 - Flash Exposure Compensation: 0
[MakerNotes, Minolta, Camera] 36 - ISO Setting: 100
[MakerNotes, Minolta, Camera] 37 - Minolta Model ID: DiMAGE 7i
[MakerNotes, Minolta, Camera] 38 - Interval Mode: Still Image
[MakerNotes, Minolta, Camera] 39 - Folder Name: Standard Form
[MakerNotes, Minolta, Camera] 40 - Color Mode: Natural color
[MakerNotes, Minolta, Camera] 41 - Color Filter: 0
[MakerNotes, Minolta, Camera] 42 - BW Filter: 0
[MakerNotes, Minolta, Camera] 43 - Internal Flash: No
[MakerNotes, Minolta, Camera] 44 - Brightness: 7.5
[MakerNotes, Minolta, Camera] 45 - Spot Focus Point X: 1280
[MakerNotes, Minolta, Camera] 46 - Spot Focus Point Y: 960
[MakerNotes, Minolta, Camera] 47 - Wide Focus Zone: Left zone
[MakerNotes, Minolta, Camera] 48 - Focus Mode: AF
[MakerNotes, Minolta, Camera] 49 - Focus Area: Wide Focus (normal)
[MakerNotes, Minolta, Camera] 50 - DEC Position: Exposure
[MakerNotes, Minolta, Camera] 64 - Compressed Image Size: 2396300
[MakerNotes, Minolta, Camera] 136 - Preview Image Start: 13042
[MakerNotes, Minolta, Camera] 137 - Preview Image Length: 26
[MakerNotes, Minolta, Preview] Exif-PreviewImage - Preview Image: (Binary data 26 bytes)
[PrintIM, PrintIM, Printing] PrintIMVersion - PrintIM Version: 0100
[PrintIM, PrintIM, Printing] PrintIMVersion - PrintIM Version: 0250
[Composite, Composite, Image] Exif-Aperture - Aperture: 5.6
[Composite, Composite, Image] Exif-ImageSize - Image Size: 8x8
[Composite, Composite, Image] Exif-Megapixels - Megapixels: 0.000064
[Composite, Composite, Camera] Exif-ScaleFactor35efl - Scale Factor To 35 mm Equivalent: 3.9
[Composite, Composite, Image] Exif-ShutterSpeed - Shutter Speed: 1/180
[Composite, Composite, Camera] Exif-CircleOfConfusion - Circle Of Confusion: 0.008 mm
[Composite, Composite, Image] Exif-DOF - Depth Of Field: 0.19 m (1.91 - 2.10 m)
[Composite, Composite, Image] Exif-FOV - Field Of View: 12.0 deg (0.42 m)
[Composite, Composite, Camera] Exif-FocalLength35efl - Focal Length: 42.3 mm (35 mm equivalent: 167.0 mm)
[Composite, Composite, Camera] Exif-HyperfocalDistance - Hyperfocal Distance: 42.01 m
[Composite, Composite, Image] Exif-LightValue - Light Value: 12.5

{'repo_name': 'exiftool/exiftool', 'stars': '562', 'repo_language': 'Perl', 'file_name': 'RandomAccess.pod', 'mime_type': 'text/plain', 'hash': 1462046903596575291, 'source_dataset': 'data'}


<!doctype html>
<meta charset="utf-8">
<title>CSS Test Reference</title>
<link rel="author" href="mailto:emilio@crisal.io">
<meta name="viewport" content="width=300">

Should be green

{'repo_name': 'web-platform-tests/wpt', 'stars': '2923', 'repo_language': 'HTML', 'file_name': 'newtarget.html', 'mime_type': 'text/html', 'hash': 6771040688323763762, 'source_dataset': 'data'}


easyblock = 'CMakeMake'

name = 'LLVM'
version = '3.7.1'

homepage = "http://llvm.org/"
description = """The LLVM Core libraries provide a modern source- and target-independent
 optimizer, along with code generation support for many popular CPUs
 (as well as some less common ones!) These libraries are built around a well
 specified code representation known as the LLVM intermediate representation
 ("LLVM IR"). The LLVM Core libraries are well documented, and it is
 particularly easy to invent your own language (or port an existing compiler)
 to use LLVM as an optimizer and code generator."""

toolchain = {'name': 'intel', 'version': '2016a'}
toolchainopts = {'cstd': 'gnu++11'}

source_urls = ["http://llvm.org/releases/%(version)s"]
sources = ["llvm-%(version)s.src.tar.xz"]

builddependencies = [
    ('CMake', '3.4.3'),
    ('Python', '2.7.11'),
]

dependencies = [
    ('ncurses', '6.0'),
]

configopts = '-DBUILD_SHARED_LIBS=ON -DCMAKE_EXE_LINKER_FLAGS="$LDFLAGS -shared-intel" '

sanity_check_paths = {
    'files': ['bin/llvm-ar'],
    'dirs': ['include/llvm', 'include/llvm-c'],
}

separate_build_dir = True

moduleclass = 'compiler'

{'repo_name': 'easybuilders/easybuild-easyconfigs', 'stars': '179', 'repo_language': 'Python', 'file_name': 'ifort', 'mime_type': 'text/x-shellscript', 'hash': 8901927876994012330, 'source_dataset': 'data'}


// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package intsets provides Sparse, a compact and fast representation
// for sparse sets of int values.
//
// The time complexity of the operations Len, Insert, Remove and Has
// is in O(n) but in practice those methods are faster and more
// space-efficient than equivalent operations on sets based on the Go
// map type.  The IsEmpty, Min, Max, Clear and TakeMin operations
// require constant time.
//
package intsets // import "golang.org/x/tools/container/intsets"

// TODO(adonovan):
// - Add InsertAll(...int), RemoveAll(...int)
// - Add 'bool changed' results for {Intersection,Difference}With too.
//
// TODO(adonovan): implement Dense, a dense bit vector with a similar API.
// The space usage would be proportional to Max(), not Len(), and the
// implementation would be based upon big.Int.
//
// TODO(adonovan): opt: make UnionWith and Difference faster.
// These are the hot-spots for go/pointer.

import (
	"bytes"
	"fmt"
)

// A Sparse is a set of int values.
// Sparse operations (even queries) are not concurrency-safe.
//
// The zero value for Sparse is a valid empty set.
//
// Sparse sets must be copied using the Copy method, not by assigning
// a Sparse value.
//
type Sparse struct {
	// An uninitialized Sparse represents an empty set.
	// An empty set may also be represented by
	//  root.next == root.prev == &root.
	//
	// The root is always the block with the smallest offset.
	// It can be empty, but only if it is the only block; in that case, offset is
	// MaxInt (which is not a valid offset).
	root block
}

type word uintptr

const (
	_m            = ^word(0)
	bitsPerWord   = 8 << (_m>>8&1 + _m>>16&1 + _m>>32&1)
	bitsPerBlock  = 256 // optimal value for go/pointer solver performance
	wordsPerBlock = bitsPerBlock / bitsPerWord
)

// Limit values of implementation-specific int type.
const (
	MaxInt = int(^uint(0) >> 1)
	MinInt = -MaxInt - 1
)

// -- block ------------------------------------------------------------

// A set is represented as a circular doubly-linked list of blocks,
// each containing an offset and a bit array of fixed size
// bitsPerBlock; the blocks are ordered by increasing offset.
//
// The set contains an element x iff the block whose offset is x - (x
// mod bitsPerBlock) has the bit (x mod bitsPerBlock) set, where mod
// is the Euclidean remainder.
//
// A block may only be empty transiently.
//
type block struct {
	offset     int                 // offset mod bitsPerBlock == 0
	bits       [wordsPerBlock]word // contains at least one set bit
	next, prev *block              // doubly-linked list of blocks
}

// wordMask returns the word index (in block.bits)
// and single-bit mask for the block's ith bit.
func wordMask(i uint) (w uint, mask word) {
	w = i / bitsPerWord
	mask = 1 << (i % bitsPerWord)
	return
}

// insert sets the block b's ith bit and
// returns true if it was not already set.
//
func (b *block) insert(i uint) bool {
	w, mask := wordMask(i)
	if b.bits[w]&mask == 0 {
		b.bits[w] |= mask
		return true
	}
	return false
}

// remove clears the block's ith bit and
// returns true if the bit was previously set.
// NB: may leave the block empty.
//
func (b *block) remove(i uint) bool {
	w, mask := wordMask(i)
	if b.bits[w]&mask != 0 {
		b.bits[w] &^= mask
		return true
	}
	return false
}

// has reports whether the block's ith bit is set.
func (b *block) has(i uint) bool {
	w, mask := wordMask(i)
	return b.bits[w]&mask != 0
}

// empty reports whether b.len()==0, but more efficiently.
func (b *block) empty() bool {
	for _, w := range b.bits {
		if w != 0 {
			return false
		}
	}
	return true
}

// len returns the number of set bits in block b.
func (b *block) len() int {
	var l int
	for _, w := range b.bits {
		l += popcount(w)
	}
	return l
}

// max returns the maximum element of the block.
// The block must not be empty.
func (b *block) max() int {
	bi := b.offset + bitsPerBlock
	// Decrement bi by number of high zeros in last.bits.
	for i := len(b.bits) - 1; i >= 0; i-- {
		if w := b.bits[i]; w != 0 {
			return bi - nlz(w) - 1
		}
		bi -= bitsPerWord
	}
	panic("BUG: empty block")
}

// min returns the minimum element of the block,
// and also removes it if take is set.
// The block must not be initially empty.
// NB: may leave the block empty.
func (b *block) min(take bool) int {
	for i, w := range b.bits {
		if w != 0 {
			tz := ntz(w)
			if take {
				b.bits[i] = w &^ (1 << uint(tz))
			}
			return b.offset + int(i*bitsPerWord) + tz
		}
	}
	panic("BUG: empty block")
}

// lowerBound returns the smallest element of the block that is greater than or
// equal to the element corresponding to the ith bit. If there is no such
// element, the second return value is false.
func (b *block) lowerBound(i uint) (int, bool) {
	w := i / bitsPerWord
	bit := i % bitsPerWord

	if val := b.bits[w] >> bit; val != 0 {
		return b.offset + int(i) + ntz(val), true
	}

	for w++; w < wordsPerBlock; w++ {
		if val := b.bits[w]; val != 0 {
			return b.offset + int(w*bitsPerWord) + ntz(val), true
		}
	}

	return 0, false
}

// forEach calls f for each element of block b.
// f must not mutate b's enclosing Sparse.
func (b *block) forEach(f func(int)) {
	for i, w := range b.bits {
		offset := b.offset + i*bitsPerWord
		for bi := 0; w != 0 && bi < bitsPerWord; bi++ {
			if w&1 != 0 {
				f(offset)
			}
			offset++
			w >>= 1
		}
	}
}

// offsetAndBitIndex returns the offset of the block that would
// contain x and the bit index of x within that block.
//
func offsetAndBitIndex(x int) (int, uint) {
	mod := x % bitsPerBlock
	if mod < 0 {
		// Euclidean (non-negative) remainder
		mod += bitsPerBlock
	}
	return x - mod, uint(mod)
}

// -- Sparse --------------------------------------------------------------

// none is a shared, empty, sentinel block that indicates the end of a block
// list.
var none block

// Dummy type used to generate an implicit panic. This must be defined at the
// package level; if it is defined inside a function, it prevents the inlining
// of that function.
type to_copy_a_sparse_you_must_call_its_Copy_method struct{}

// init ensures s is properly initialized.
func (s *Sparse) init() {
	root := &s.root
	if root.next == nil {
		root.offset = MaxInt
		root.next = root
		root.prev = root
	} else if root.next.prev != root {
		// Copying a Sparse x leads to pernicious corruption: the
		// new Sparse y shares the old linked list, but iteration
		// on y will never encounter &y.root so it goes into a
		// loop.  Fail fast before this occurs.
		// We don't want to call panic here because it prevents the
		// inlining of this function.
		_ = (interface{}(nil)).(to_copy_a_sparse_you_must_call_its_Copy_method)
	}
}

func (s *Sparse) first() *block {
	s.init()
	if s.root.offset == MaxInt {
		return &none
	}
	return &s.root
}

// next returns the next block in the list, or end if b is the last block.
func (s *Sparse) next(b *block) *block {
	if b.next == &s.root {
		return &none
	}
	return b.next
}

// prev returns the previous block in the list, or end if b is the first block.
func (s *Sparse) prev(b *block) *block {
	if b.prev == &s.root {
		return &none
	}
	return b.prev
}

// IsEmpty reports whether the set s is empty.
func (s *Sparse) IsEmpty() bool {
	return s.root.next == nil || s.root.offset == MaxInt
}

// Len returns the number of elements in the set s.
func (s *Sparse) Len() int {
	var l int
	for b := s.first(); b != &none; b = s.next(b) {
		l += b.len()
	}
	return l
}

// Max returns the maximum element of the set s, or MinInt if s is empty.
func (s *Sparse) Max() int {
	if s.IsEmpty() {
		return MinInt
	}
	return s.root.prev.max()
}

// Min returns the minimum element of the set s, or MaxInt if s is empty.
func (s *Sparse) Min() int {
	if s.IsEmpty() {
		return MaxInt
	}
	return s.root.min(false)
}

// LowerBound returns the smallest element >= x, or MaxInt if there is no such
// element.
func (s *Sparse) LowerBound(x int) int {
	offset, i := offsetAndBitIndex(x)
	for b := s.first(); b != &none; b = s.next(b) {
		if b.offset > offset {
			return b.min(false)
		}
		if b.offset == offset {
			if y, ok := b.lowerBound(i); ok {
				return y
			}
		}
	}
	return MaxInt
}

// block returns the block that would contain offset,
// or nil if s contains no such block.
// Precondition: offset is a multiple of bitsPerBlock.
func (s *Sparse) block(offset int) *block {
	for b := s.first(); b != &none && b.offset <= offset; b = s.next(b) {
		if b.offset == offset {
			return b
		}
	}
	return nil
}

// Insert adds x to the set s, and reports whether the set grew.
func (s *Sparse) Insert(x int) bool {
	offset, i := offsetAndBitIndex(x)

	b := s.first()
	for ; b != &none && b.offset <= offset; b = s.next(b) {
		if b.offset == offset {
			return b.insert(i)
		}
	}

	// Insert new block before b.
	new := s.insertBlockBefore(b)
	new.offset = offset
	return new.insert(i)
}

// removeBlock removes a block and returns the block that followed it (or end if
// it was the last block).
func (s *Sparse) removeBlock(b *block) *block {
	if b != &s.root {
		b.prev.next = b.next
		b.next.prev = b.prev
		if b.next == &s.root {
			return &none
		}
		return b.next
	}

	first := s.root.next
	if first == &s.root {
		// This was the only block.
		s.Clear()
		return &none
	}
	s.root.offset = first.offset
	s.root.bits = first.bits
	if first.next == &s.root {
		// Single block remaining.
		s.root.next = &s.root
		s.root.prev = &s.root
	} else {
		s.root.next = first.next
		first.next.prev = &s.root
	}
	return &s.root
}

// Remove removes x from the set s, and reports whether the set shrank.
func (s *Sparse) Remove(x int) bool {
	offset, i := offsetAndBitIndex(x)
	if b := s.block(offset); b != nil {
		if !b.remove(i) {
			return false
		}
		if b.empty() {
			s.removeBlock(b)
		}
		return true
	}
	return false
}

// Clear removes all elements from the set s.
func (s *Sparse) Clear() {
	s.root = block{
		offset: MaxInt,
		next:   &s.root,
		prev:   &s.root,
	}
}

// If set s is non-empty, TakeMin sets *p to the minimum element of
// the set s, removes that element from the set and returns true.
// Otherwise, it returns false and *p is undefined.
//
// This method may be used for iteration over a worklist like so:
//
// 	var x int
// 	for worklist.TakeMin(&x) { use(x) }
//
func (s *Sparse) TakeMin(p *int) bool {
	if s.IsEmpty() {
		return false
	}
	*p = s.root.min(true)
	if s.root.empty() {
		s.removeBlock(&s.root)
	}
	return true
}

// Has reports whether x is an element of the set s.
func (s *Sparse) Has(x int) bool {
	offset, i := offsetAndBitIndex(x)
	if b := s.block(offset); b != nil {
		return b.has(i)
	}
	return false
}

// forEach applies function f to each element of the set s in order.
//
// f must not mutate s.  Consequently, forEach is not safe to expose
// to clients.  In any case, using "range s.AppendTo()" allows more
// natural control flow with continue/break/return.
//
func (s *Sparse) forEach(f func(int)) {
	for b := s.first(); b != &none; b = s.next(b) {
		b.forEach(f)
	}
}

// Copy sets s to the value of x.
func (s *Sparse) Copy(x *Sparse) {
	if s == x {
		return
	}

	xb := x.first()
	sb := s.first()
	for xb != &none {
		if sb == &none {
			sb = s.insertBlockBefore(sb)
		}
		sb.offset = xb.offset
		sb.bits = xb.bits
		xb = x.next(xb)
		sb = s.next(sb)
	}
	s.discardTail(sb)
}

// insertBlockBefore returns a new block, inserting it before next.
// If next is the root, the root is replaced. If next is end, the block is
// inserted at the end.
func (s *Sparse) insertBlockBefore(next *block) *block {
	if s.IsEmpty() {
		if next != &none {
			panic("BUG: passed block with empty set")
		}
		return &s.root
	}

	if next == &s.root {
		// Special case: we need to create a new block that will become the root
		// block.The old root block becomes the second block.
		second := s.root
		s.root = block{
			next: &second,
		}
		if second.next == &s.root {
			s.root.prev = &second
		} else {
			s.root.prev = second.prev
			second.next.prev = &second
			second.prev = &s.root
		}
		return &s.root
	}
	if next == &none {
		// Insert before root.
		next = &s.root
	}
	b := new(block)
	b.next = next
	b.prev = next.prev
	b.prev.next = b
	next.prev = b
	return b
}

// discardTail removes block b and all its successors from s.
func (s *Sparse) discardTail(b *block) {
	if b != &none {
		if b == &s.root {
			s.Clear()
		} else {
			b.prev.next = &s.root
			s.root.prev = b.prev
		}
	}
}

// IntersectionWith sets s to the intersection s ∩ x.
func (s *Sparse) IntersectionWith(x *Sparse) {
	if s == x {
		return
	}

	xb := x.first()
	sb := s.first()
	for xb != &none && sb != &none {
		switch {
		case xb.offset < sb.offset:
			xb = x.next(xb)

		case xb.offset > sb.offset:
			sb = s.removeBlock(sb)

		default:
			var sum word
			for i := range sb.bits {
				r := xb.bits[i] & sb.bits[i]
				sb.bits[i] = r
				sum |= r
			}
			if sum != 0 {
				sb = s.next(sb)
			} else {
				// sb will be overwritten or removed
			}

			xb = x.next(xb)
		}
	}

	s.discardTail(sb)
}

// Intersection sets s to the intersection x ∩ y.
func (s *Sparse) Intersection(x, y *Sparse) {
	switch {
	case s == x:
		s.IntersectionWith(y)
		return
	case s == y:
		s.IntersectionWith(x)
		return
	case x == y:
		s.Copy(x)
		return
	}

	xb := x.first()
	yb := y.first()
	sb := s.first()
	for xb != &none && yb != &none {
		switch {
		case xb.offset < yb.offset:
			xb = x.next(xb)
			continue
		case xb.offset > yb.offset:
			yb = y.next(yb)
			continue
		}

		if sb == &none {
			sb = s.insertBlockBefore(sb)
		}
		sb.offset = xb.offset

		var sum word
		for i := range sb.bits {
			r := xb.bits[i] & yb.bits[i]
			sb.bits[i] = r
			sum |= r
		}
		if sum != 0 {
			sb = s.next(sb)
		} else {
			// sb will be overwritten or removed
		}

		xb = x.next(xb)
		yb = y.next(yb)
	}

	s.discardTail(sb)
}

// Intersects reports whether s ∩ x ≠ ∅.
func (s *Sparse) Intersects(x *Sparse) bool {
	sb := s.first()
	xb := x.first()
	for sb != &none && xb != &none {
		switch {
		case xb.offset < sb.offset:
			xb = x.next(xb)
		case xb.offset > sb.offset:
			sb = s.next(sb)
		default:
			for i := range sb.bits {
				if sb.bits[i]&xb.bits[i] != 0 {
					return true
				}
			}
			sb = s.next(sb)
			xb = x.next(xb)
		}
	}
	return false
}

// UnionWith sets s to the union s ∪ x, and reports whether s grew.
func (s *Sparse) UnionWith(x *Sparse) bool {
	if s == x {
		return false
	}

	var changed bool
	xb := x.first()
	sb := s.first()
	for xb != &none {
		if sb != &none && sb.offset == xb.offset {
			for i := range xb.bits {
				if sb.bits[i] != xb.bits[i] {
					sb.bits[i] |= xb.bits[i]
					changed = true
				}
			}
			xb = x.next(xb)
		} else if sb == &none || sb.offset > xb.offset {
			sb = s.insertBlockBefore(sb)
			sb.offset = xb.offset
			sb.bits = xb.bits
			changed = true

			xb = x.next(xb)
		}
		sb = s.next(sb)
	}
	return changed
}

// Union sets s to the union x ∪ y.
func (s *Sparse) Union(x, y *Sparse) {
	switch {
	case x == y:
		s.Copy(x)
		return
	case s == x:
		s.UnionWith(y)
		return
	case s == y:
		s.UnionWith(x)
		return
	}

	xb := x.first()
	yb := y.first()
	sb := s.first()
	for xb != &none || yb != &none {
		if sb == &none {
			sb = s.insertBlockBefore(sb)
		}
		switch {
		case yb == &none || (xb != &none && xb.offset < yb.offset):
			sb.offset = xb.offset
			sb.bits = xb.bits
			xb = x.next(xb)

		case xb == &none || (yb != &none && yb.offset < xb.offset):
			sb.offset = yb.offset
			sb.bits = yb.bits
			yb = y.next(yb)

		default:
			sb.offset = xb.offset
			for i := range xb.bits {
				sb.bits[i] = xb.bits[i] | yb.bits[i]
			}
			xb = x.next(xb)
			yb = y.next(yb)
		}
		sb = s.next(sb)
	}

	s.discardTail(sb)
}

// DifferenceWith sets s to the difference s ∖ x.
func (s *Sparse) DifferenceWith(x *Sparse) {
	if s == x {
		s.Clear()
		return
	}

	xb := x.first()
	sb := s.first()
	for xb != &none && sb != &none {
		switch {
		case xb.offset > sb.offset:
			sb = s.next(sb)

		case xb.offset < sb.offset:
			xb = x.next(xb)

		default:
			var sum word
			for i := range sb.bits {
				r := sb.bits[i] & ^xb.bits[i]
				sb.bits[i] = r
				sum |= r
			}
			if sum == 0 {
				sb = s.removeBlock(sb)
			} else {
				sb = s.next(sb)
			}
			xb = x.next(xb)
		}
	}
}

// Difference sets s to the difference x ∖ y.
func (s *Sparse) Difference(x, y *Sparse) {
	switch {
	case x == y:
		s.Clear()
		return
	case s == x:
		s.DifferenceWith(y)
		return
	case s == y:
		var y2 Sparse
		y2.Copy(y)
		s.Difference(x, &y2)
		return
	}

	xb := x.first()
	yb := y.first()
	sb := s.first()
	for xb != &none && yb != &none {
		if xb.offset > yb.offset {
			// y has block, x has &none
			yb = y.next(yb)
			continue
		}

		if sb == &none {
			sb = s.insertBlockBefore(sb)
		}
		sb.offset = xb.offset

		switch {
		case xb.offset < yb.offset:
			// x has block, y has &none
			sb.bits = xb.bits

			sb = s.next(sb)

		default:
			// x and y have corresponding blocks
			var sum word
			for i := range sb.bits {
				r := xb.bits[i] & ^yb.bits[i]
				sb.bits[i] = r
				sum |= r
			}
			if sum != 0 {
				sb = s.next(sb)
			} else {
				// sb will be overwritten or removed
			}

			yb = y.next(yb)
		}
		xb = x.next(xb)
	}

	for xb != &none {
		if sb == &none {
			sb = s.insertBlockBefore(sb)
		}
		sb.offset = xb.offset
		sb.bits = xb.bits
		sb = s.next(sb)

		xb = x.next(xb)
	}

	s.discardTail(sb)
}

// SymmetricDifferenceWith sets s to the symmetric difference s ∆ x.
func (s *Sparse) SymmetricDifferenceWith(x *Sparse) {
	if s == x {
		s.Clear()
		return
	}

	sb := s.first()
	xb := x.first()
	for xb != &none && sb != &none {
		switch {
		case sb.offset < xb.offset:
			sb = s.next(sb)
		case xb.offset < sb.offset:
			nb := s.insertBlockBefore(sb)
			nb.offset = xb.offset
			nb.bits = xb.bits
			xb = x.next(xb)
		default:
			var sum word
			for i := range sb.bits {
				r := sb.bits[i] ^ xb.bits[i]
				sb.bits[i] = r
				sum |= r
			}
			if sum == 0 {
				sb = s.removeBlock(sb)
			} else {
				sb = s.next(sb)
			}
			xb = x.next(xb)
		}
	}

	for xb != &none { // append the tail of x to s
		sb = s.insertBlockBefore(sb)
		sb.offset = xb.offset
		sb.bits = xb.bits
		sb = s.next(sb)
		xb = x.next(xb)
	}
}

// SymmetricDifference sets s to the symmetric difference x ∆ y.
func (s *Sparse) SymmetricDifference(x, y *Sparse) {
	switch {
	case x == y:
		s.Clear()
		return
	case s == x:
		s.SymmetricDifferenceWith(y)
		return
	case s == y:
		s.SymmetricDifferenceWith(x)
		return
	}

	sb := s.first()
	xb := x.first()
	yb := y.first()
	for xb != &none && yb != &none {
		if sb == &none {
			sb = s.insertBlockBefore(sb)
		}
		switch {
		case yb.offset < xb.offset:
			sb.offset = yb.offset
			sb.bits = yb.bits
			sb = s.next(sb)
			yb = y.next(yb)
		case xb.offset < yb.offset:
			sb.offset = xb.offset
			sb.bits = xb.bits
			sb = s.next(sb)
			xb = x.next(xb)
		default:
			var sum word
			for i := range sb.bits {
				r := xb.bits[i] ^ yb.bits[i]
				sb.bits[i] = r
				sum |= r
			}
			if sum != 0 {
				sb.offset = xb.offset
				sb = s.next(sb)
			}
			xb = x.next(xb)
			yb = y.next(yb)
		}
	}

	for xb != &none { // append the tail of x to s
		if sb == &none {
			sb = s.insertBlockBefore(sb)
		}
		sb.offset = xb.offset
		sb.bits = xb.bits
		sb = s.next(sb)
		xb = x.next(xb)
	}

	for yb != &none { // append the tail of y to s
		if sb == &none {
			sb = s.insertBlockBefore(sb)
		}
		sb.offset = yb.offset
		sb.bits = yb.bits
		sb = s.next(sb)
		yb = y.next(yb)
	}

	s.discardTail(sb)
}

// SubsetOf reports whether s ∖ x = ∅.
func (s *Sparse) SubsetOf(x *Sparse) bool {
	if s == x {
		return true
	}

	sb := s.first()
	xb := x.first()
	for sb != &none {
		switch {
		case xb == &none || xb.offset > sb.offset:
			return false
		case xb.offset < sb.offset:
			xb = x.next(xb)
		default:
			for i := range sb.bits {
				if sb.bits[i]&^xb.bits[i] != 0 {
					return false
				}
			}
			sb = s.next(sb)
			xb = x.next(xb)
		}
	}
	return true
}

// Equals reports whether the sets s and t have the same elements.
func (s *Sparse) Equals(t *Sparse) bool {
	if s == t {
		return true
	}
	sb := s.first()
	tb := t.first()
	for {
		switch {
		case sb == &none && tb == &none:
			return true
		case sb == &none || tb == &none:
			return false
		case sb.offset != tb.offset:
			return false
		case sb.bits != tb.bits:
			return false
		}

		sb = s.next(sb)
		tb = t.next(tb)
	}
}

// String returns a human-readable description of the set s.
func (s *Sparse) String() string {
	var buf bytes.Buffer
	buf.WriteByte('{')
	s.forEach(func(x int) {
		if buf.Len() > 1 {
			buf.WriteByte(' ')
		}
		fmt.Fprintf(&buf, "%d", x)
	})
	buf.WriteByte('}')
	return buf.String()
}

// BitString returns the set as a string of 1s and 0s denoting the sum
// of the i'th powers of 2, for each i in s.  A radix point, always
// preceded by a digit, appears if the sum is non-integral.
//
// Examples:
//              {}.BitString() =      "0"
//           {4,5}.BitString() = "110000"
//            {-3}.BitString() =      "0.001"
//      {-3,0,4,5}.BitString() = "110001.001"
//
func (s *Sparse) BitString() string {
	if s.IsEmpty() {
		return "0"
	}

	min, max := s.Min(), s.Max()
	var nbytes int
	if max > 0 {
		nbytes = max
	}
	nbytes++ // zero bit
	radix := nbytes
	if min < 0 {
		nbytes += len(".") - min
	}

	b := make([]byte, nbytes)
	for i := range b {
		b[i] = '0'
	}
	if radix < nbytes {
		b[radix] = '.'
	}
	s.forEach(func(x int) {
		if x >= 0 {
			x += len(".")
		}
		b[radix-x] = '1'
	})
	return string(b)
}

// GoString returns a string showing the internal representation of
// the set s.
//
func (s *Sparse) GoString() string {
	var buf bytes.Buffer
	for b := s.first(); b != &none; b = s.next(b) {
		fmt.Fprintf(&buf, "block %p {offset=%d next=%p prev=%p",
			b, b.offset, b.next, b.prev)
		for _, w := range b.bits {
			fmt.Fprintf(&buf, " 0%016x", w)
		}
		fmt.Fprintf(&buf, "}\n")
	}
	return buf.String()
}

// AppendTo returns the result of appending the elements of s to slice
// in order.
func (s *Sparse) AppendTo(slice []int) []int {
	s.forEach(func(x int) {
		slice = append(slice, x)
	})
	return slice
}

// -- Testing/debugging ------------------------------------------------

// check returns an error if the representation invariants of s are violated.
func (s *Sparse) check() error {
	s.init()
	if s.root.empty() {
		// An empty set must have only the root block with offset MaxInt.
		if s.root.next != &s.root {
			return fmt.Errorf("multiple blocks with empty root block")
		}
		if s.root.offset != MaxInt {
			return fmt.Errorf("empty set has offset %d, should be MaxInt", s.root.offset)
		}
		return nil
	}
	for b := s.first(); ; b = s.next(b) {
		if b.offset%bitsPerBlock != 0 {
			return fmt.Errorf("bad offset modulo: %d", b.offset)
		}
		if b.empty() {
			return fmt.Errorf("empty block")
		}
		if b.prev.next != b {
			return fmt.Errorf("bad prev.next link")
		}
		if b.next.prev != b {
			return fmt.Errorf("bad next.prev link")
		}
		if b.next == &s.root {
			break
		}
		if b.offset >= b.next.offset {
			return fmt.Errorf("bad offset order: b.offset=%d, b.next.offset=%d",
				b.offset, b.next.offset)
		}
	}
	return nil
}

{'repo_name': 'myitcv/react', 'stars': '232', 'repo_language': 'Go', 'file_name': 'template_test.go', 'mime_type': 'text/plain', 'hash': 7802941150102238845, 'source_dataset': 'data'}


/**
 * Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
 *
 * You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
 * copy, modify, and distribute this software in source code or binary form for use
 * in connection with the web services and APIs provided by Facebook.
 *
 * As with any software that integrates with the Facebook platform, your use of
 * this software is subject to the Facebook Developer Principles and Policies
 * [http://developers.facebook.com/policy/]. This copyright notice shall be
 * included in all copies or substantial portions of the software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

package com.facebook.share.internal;

import com.facebook.internal.DialogFeature;
import com.facebook.internal.NativeProtocol;

/**
 * com.facebook.share.internal is solely for the use of other packages within the
 * Facebook SDK for Android. Use of any of the classes in this package is
 * unsupported, and they may be modified or removed without warning at any time.
 */
public enum OpenGraphMessageDialogFeature implements DialogFeature {
    /**
     * Indicates whether the native Open Graph Message dialog itself is supported by the installed
     * version of the Facebook Messenger application.
     */
    OG_MESSAGE_DIALOG(NativeProtocol.PROTOCOL_VERSION_20140204);

    private int minVersion;

    OpenGraphMessageDialogFeature(int minVersion) {
        this.minVersion = minVersion;
    }

    /**
     * This method is for internal use only.
     */
    public String getAction() {
        return NativeProtocol.ACTION_OGMESSAGEPUBLISH_DIALOG;
    }

    /**
     * This method is for internal use only.
     */
    public int getMinVersion() {
        return minVersion;
    }
}

{'repo_name': 'honghuachen/Usdk', 'stars': '139', 'repo_language': 'HTML', 'file_name': 'module.modulemap', 'mime_type': 'text/plain', 'hash': -2243342788551670768, 'source_dataset': 'data'}


package controllers;

import models.*;

public class Jobs extends Administration {

    public static void list() {
        if (session.contains("superadmin")) {
            parent();
        }
        request.args.put("where", "company.email = '" + session.get("company") + "'");
        parent();
    }

    public static void show(Long id) {
        if (!((Job) Job.findById(id)).company.email.equals(session.get("company")) && !session.contains("superadmin")) {
            forbidden();
        }
        parent();
    }

    public static void create() {
        if (session.contains("superadmin")) {
            parent();
        }
        Company company = Company.find("byEmail", session.get("company")).first();
        params.put("object.company.id", company.id + "");
        parent();
    }

    public static void save(Long id) {
        if (session.contains("superadmin")) {
            parent();
        }
        Company company = Company.find("byEmail", session.get("company")).first();
        params.put("object.company.id", company.id + "");
        parent();
    }

}

{'repo_name': 'playframework/play1', 'stars': '1558', 'repo_language': 'Python', 'file_name': 'messages', 'mime_type': 'text/plain', 'hash': -5273324341706837110, 'source_dataset': 'data'}


// Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS.  All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
//

#define MS_CLASS "webrtc::FieldTrial"
// #define MS_LOG_DEV_LEVEL 3

#include "system_wrappers/source/field_trial.h"

#include "Logger.hpp"

#include <absl/strings/string_view.h>
#include <stddef.h>
#include <map>
#include <string>

// Simple field trial implementation, which allows client to
// specify desired flags in InitFieldTrialsFromString.
namespace webrtc {
namespace field_trial {

static const char* trials_init_string = NULL;

#ifndef WEBRTC_EXCLUDE_FIELD_TRIAL_DEFAULT
namespace {
constexpr char kPersistentStringSeparator = '/';
// Validates the given field trial string.
//  E.g.:
//    "WebRTC-experimentFoo/Enabled/WebRTC-experimentBar/Enabled100kbps/"
//    Assigns the process to group "Enabled" on WebRTCExperimentFoo trial
//    and to group "Enabled100kbps" on WebRTCExperimentBar.
//
//  E.g. invalid config:
//    "WebRTC-experiment1/Enabled"  (note missing / separator at the end).
bool FieldTrialsStringIsValid(const absl::string_view trials) {
  if (trials.empty())
    return true;

  size_t next_item = 0;
  std::map<absl::string_view, absl::string_view> field_trials;
  while (next_item < trials.length()) {
    size_t name_end = trials.find(kPersistentStringSeparator, next_item);
    if (name_end == trials.npos || next_item == name_end)
      return false;
    size_t group_name_end =
        trials.find(kPersistentStringSeparator, name_end + 1);
    if (group_name_end == trials.npos || name_end + 1 == group_name_end)
      return false;
    absl::string_view name = trials.substr(next_item, name_end - next_item);
    absl::string_view group_name =
        trials.substr(name_end + 1, group_name_end - name_end - 1);

    next_item = group_name_end + 1;

    // Fail if duplicate with different group name.
    if (field_trials.find(name) != field_trials.end() &&
        field_trials.find(name)->second != group_name) {
      return false;
    }

    field_trials[name] = group_name;
  }

  return true;
}
}  // namespace

std::string FindFullName(const std::string& name) {
  if (trials_init_string == NULL)
    return std::string();

  std::string trials_string(trials_init_string);
  if (trials_string.empty())
    return std::string();

  size_t next_item = 0;
  while (next_item < trials_string.length()) {
    // Find next name/value pair in field trial configuration string.
    size_t field_name_end =
        trials_string.find(kPersistentStringSeparator, next_item);
    if (field_name_end == trials_string.npos || field_name_end == next_item)
      break;
    size_t field_value_end =
        trials_string.find(kPersistentStringSeparator, field_name_end + 1);
    if (field_value_end == trials_string.npos ||
        field_value_end == field_name_end + 1)
      break;
    std::string field_name(trials_string, next_item,
                           field_name_end - next_item);
    std::string field_value(trials_string, field_name_end + 1,
                            field_value_end - field_name_end - 1);
    next_item = field_value_end + 1;

    if (name == field_name)
      return field_value;
  }
  return std::string();
}
#endif  // WEBRTC_EXCLUDE_FIELD_TRIAL_DEFAULT

// Optionally initialize field trial from a string.
void InitFieldTrialsFromString(const char* trials_string) {
  MS_DEBUG_TAG(bwe, "Setting field trial string: %s", trials_string);
#ifndef WEBRTC_EXCLUDE_FIELD_TRIAL_DEFAULT
  if (trials_string) {
    // RTC_DCHECK(FieldTrialsStringIsValid(trials_string))
        // << "Invalid field trials string:" << trials_string;
    MS_ASSERT(
      FieldTrialsStringIsValid(trials_string), "invalid field trials string: '%s'", trials_string);
  };
#endif  // WEBRTC_EXCLUDE_FIELD_TRIAL_DEFAULT
  trials_init_string = trials_string;
}

const char* GetFieldTrialString() {
  return trials_init_string;
}

}  // namespace field_trial
}  // namespace webrtc

{'repo_name': 'versatica/mediasoup', 'stars': '2327', 'repo_language': 'C++', 'file_name': 'VP8.hpp', 'mime_type': 'text/x-c++', 'hash': 5912654143029915570, 'source_dataset': 'data'}


import sys
import requests
import pytest
from devpi_common.request import new_requests_session

@pytest.mark.parametrize('max_retries', [
    None,
    0,
    2,
])
def test_env(monkeypatch, max_retries):
    from urllib3.util.retry import Retry
    monkeypatch.setenv("HTTP_PROXY", "http://this")
    monkeypatch.setenv("HTTPS_PROXY", "http://that")
    orig_increment = Retry.increment
    increment_retry_totals = []

    def increment(self, *args, **kwargs):
        increment_retry_totals.append(self.total)
        return orig_increment(self, *args, **kwargs)

    monkeypatch.setattr(Retry, "increment", increment)
    session = new_requests_session(max_retries=max_retries)
    with pytest.raises(requests.exceptions.RequestException):
        session.get("http://example.com")
    assert tuple(increment_retry_totals) in ((0,), (2, 1, 0))

def test_useragent():
    s = new_requests_session(agent=("hello", "1.2"))
    ua = s.headers["user-agent"]
    assert "devpi-hello/1.2" in ua
    assert sys.version.split()[0] in ua
    assert "*" not in ua

def test_exception_attributes():
    session = new_requests_session()
    assert isinstance(session.Errors, tuple)

{'repo_name': 'devpi/devpi', 'stars': '393', 'repo_language': 'Python', 'file_name': 'examples.rst', 'mime_type': 'text/plain', 'hash': -6001332507845798244, 'source_dataset': 'data'}


/*
 * xed-dirs.c
 * This file is part of xed
 *
 * Copyright (C) 2008 Ignacio Casal Quinteiro
 * Copyright (C) 2011 Perberos
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include <config.h>

#include "xed-dirs.h"

static gchar *user_config_dir      = NULL;
static gchar *user_cache_dir       = NULL;
static gchar *user_styles_dir      = NULL;
static gchar *user_plugins_dir     = NULL;
static gchar *xed_data_dir         = NULL;
static gchar *xed_locale_dir       = NULL;
static gchar *xed_lib_dir          = NULL;
static gchar *xed_plugins_dir      = NULL;
static gchar *xed_plugins_data_dir = NULL;

void
xed_dirs_init ()
{
    if (xed_data_dir == NULL)
    {
        xed_data_dir = g_build_filename (DATADIR, "xed", NULL);
        xed_locale_dir = g_build_filename (DATADIR, "locale", NULL);
        xed_lib_dir = g_build_filename (LIBDIR, "xed", NULL);
    }

    user_cache_dir = g_build_filename (g_get_user_cache_dir (), "xed", NULL);
    user_config_dir = g_build_filename (g_get_user_config_dir (), "xed", NULL);
    user_styles_dir = g_build_filename (g_get_user_data_dir (), "xed", "styles", NULL);
    user_plugins_dir = g_build_filename (g_get_user_data_dir (), "xed", "plugins", NULL);
    xed_plugins_dir = g_build_filename (xed_lib_dir, "plugins", NULL);
    xed_plugins_data_dir = g_build_filename (xed_data_dir, "plugins", NULL);
}

void
xed_dirs_shutdown ()
{
    g_free (user_config_dir);
    g_free (user_cache_dir);
    g_free (user_plugins_dir);
    g_free (xed_data_dir);
    g_free (xed_locale_dir);
    g_free (xed_lib_dir);
    g_free (xed_plugins_dir);
    g_free (xed_plugins_data_dir);
}

const gchar *
xed_dirs_get_user_config_dir (void)
{
    return user_config_dir;
}

const gchar *
xed_dirs_get_user_cache_dir (void)
{
    return user_cache_dir;
}

const gchar *
xed_dirs_get_user_styles_dir (void)
{
    return user_styles_dir;
}

const gchar *
xed_dirs_get_user_plugins_dir (void)
{
    return user_plugins_dir;
}

const gchar *
xed_dirs_get_xed_data_dir (void)
{
    return xed_data_dir;
}

const gchar *
xed_dirs_get_xed_locale_dir (void)
{
    return xed_locale_dir;
}

const gchar *
xed_dirs_get_xed_lib_dir (void)
{
    return xed_lib_dir;
}

const gchar *
xed_dirs_get_xed_plugins_dir (void)
{
    return xed_plugins_dir;
}

const gchar *
xed_dirs_get_xed_plugins_data_dir (void)
{
    return xed_plugins_data_dir;
}

const gchar *
xed_dirs_get_binding_modules_dir (void)
{
    return xed_lib_dir;
}

gchar *
xed_dirs_get_ui_file (const gchar *file)
{
    gchar *ui_file;

    g_return_val_if_fail (file != NULL, NULL);

    ui_file = g_build_filename (xed_dirs_get_xed_data_dir (), "ui", file, NULL);

    return ui_file;
}

{'repo_name': 'linuxmint/xed', 'stars': '192', 'repo_language': 'C', 'file_name': 'xed-spell-marshal.list', 'mime_type': 'text/plain', 'hash': 7426245107568321591, 'source_dataset': 'data'}


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

/**
 * @fileoverview Menu where items can be filtered based on user keyboard input.
 * If a filter is specified only the items matching it will be displayed.
 *
 * @author eae@google.com (Emil A Eklund)
 * @see ../demos/filteredmenu.html
 */

goog.provide('goog.ui.FilteredMenu');

goog.require('goog.a11y.aria');
goog.require('goog.a11y.aria.AutoCompleteValues');
goog.require('goog.a11y.aria.State');
goog.require('goog.dom');
goog.require('goog.dom.InputType');
goog.require('goog.dom.TagName');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('goog.events.InputHandler');
goog.require('goog.events.KeyCodes');
goog.require('goog.object');
goog.require('goog.string');
goog.require('goog.style');
goog.require('goog.ui.Component');
goog.require('goog.ui.FilterObservingMenuItem');
goog.require('goog.ui.Menu');
goog.require('goog.ui.MenuItem');
goog.require('goog.userAgent');

/**
 * Filtered menu class.
 * @param {goog.ui.MenuRenderer=} opt_renderer Renderer used to render filtered
 *     menu; defaults to {@link goog.ui.MenuRenderer}.
 * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper.
 * @constructor
 * @extends {goog.ui.Menu}
 */
goog.ui.FilteredMenu = function(opt_renderer, opt_domHelper) {
  goog.ui.Menu.call(this, opt_domHelper, opt_renderer);
};
goog.inherits(goog.ui.FilteredMenu, goog.ui.Menu);
goog.tagUnsealableClass(goog.ui.FilteredMenu);

/**
 * Events fired by component.
 * @enum {string}
 */
goog.ui.FilteredMenu.EventType = {
  /** Dispatched after the component filter criteria has been changed. */
  FILTER_CHANGED: 'filterchange'
};

/**
 * Filter menu element ids.
 * @enum {string}
 * @private
 */
goog.ui.FilteredMenu.Id_ = {
  CONTENT_ELEMENT: 'content-el'
};

/**
 * Filter input element.
 * @type {Element|undefined}
 * @private
 */
goog.ui.FilteredMenu.prototype.filterInput_;

/**
 * The input handler that provides the input event.
 * @type {goog.events.InputHandler|undefined}
 * @private
 */
goog.ui.FilteredMenu.prototype.inputHandler_;

/**
 * Maximum number of characters for filter input.
 * @type {number}
 * @private
 */
goog.ui.FilteredMenu.prototype.maxLength_ = 0;

/**
 * Label displayed in the filter input when no text has been entered.
 * @type {string}
 * @private
 */
goog.ui.FilteredMenu.prototype.label_ = '';

/**
 * Label element.
 * @type {Element|undefined}
 * @private
 */
goog.ui.FilteredMenu.prototype.labelEl_;

/**
 * Whether multiple items can be entered comma separated.
 * @type {boolean}
 * @private
 */
goog.ui.FilteredMenu.prototype.allowMultiple_ = false;

/**
 * List of items entered in the search box if multiple entries are allowed.
 * @type {Array<string>|undefined}
 * @private
 */
goog.ui.FilteredMenu.prototype.enteredItems_;

/**
 * Index of first item that should be affected by the filter. Menu items with
 * a lower index will not be affected by the filter.
 * @type {number}
 * @private
 */
goog.ui.FilteredMenu.prototype.filterFromIndex_ = 0;

/**
 * Filter applied to the menu.
 * @type {string|undefined|null}
 * @private
 */
goog.ui.FilteredMenu.prototype.filterStr_;

/**
 * @private {Element}
 */
goog.ui.FilteredMenu.prototype.contentElement_;

/**
 * Map of child nodes that shouldn't be affected by filtering.
 * @type {Object|undefined}
 * @private
 */
goog.ui.FilteredMenu.prototype.persistentChildren_;

/** @override */
goog.ui.FilteredMenu.prototype.createDom = function() {
  goog.ui.FilteredMenu.superClass_.createDom.call(this);

  var dom = this.getDomHelper();
  var el = dom.createDom(goog.dom.TagName.DIV,
      goog.getCssName(this.getRenderer().getCssClass(), 'filter'),
      this.labelEl_ = dom.createDom(goog.dom.TagName.DIV, null, this.label_),
      this.filterInput_ = dom.createDom(goog.dom.TagName.INPUT,
                                        {'type': goog.dom.InputType.TEXT}));
  var element = this.getElement();
  dom.appendChild(element, el);
  var contentElementId = this.makeId(goog.ui.FilteredMenu.Id_.CONTENT_ELEMENT);
  this.contentElement_ = dom.createDom(goog.dom.TagName.DIV, goog.object.create(
      'class', goog.getCssName(this.getRenderer().getCssClass(), 'content'),
      'id', contentElementId));
  dom.appendChild(element, this.contentElement_);

  this.initFilterInput_();

  goog.a11y.aria.setState(this.filterInput_, goog.a11y.aria.State.AUTOCOMPLETE,
      goog.a11y.aria.AutoCompleteValues.LIST);
  goog.a11y.aria.setState(this.filterInput_, goog.a11y.aria.State.OWNS,
      contentElementId);
  goog.a11y.aria.setState(this.filterInput_, goog.a11y.aria.State.EXPANDED,
      true);
};

/**
 * Helper method that initializes the filter input element.
 * @private
 */
goog.ui.FilteredMenu.prototype.initFilterInput_ = function() {
  this.setFocusable(true);
  this.setKeyEventTarget(this.filterInput_);

  // Workaround for mozilla bug #236791.
  if (goog.userAgent.GECKO) {
    this.filterInput_.setAttribute('autocomplete', 'off');
  }

  if (this.maxLength_) {
    this.filterInput_.maxLength = this.maxLength_;
  }
};

/**
 * Sets up listeners and prepares the filter functionality.
 * @private
 */
goog.ui.FilteredMenu.prototype.setUpFilterListeners_ = function() {
  if (!this.inputHandler_ && this.filterInput_) {
    this.inputHandler_ = new goog.events.InputHandler(
        /** @type {Element} */ (this.filterInput_));
    goog.style.setUnselectable(this.filterInput_, false);
    goog.events.listen(this.inputHandler_,
                       goog.events.InputHandler.EventType.INPUT,
                       this.handleFilterEvent, false, this);
    goog.events.listen(this.filterInput_.parentNode,
                       goog.events.EventType.CLICK,
                       this.onFilterLabelClick_, false, this);
    if (this.allowMultiple_) {
      this.enteredItems_ = [];
    }
  }
};

/**
 * Tears down listeners and resets the filter functionality.
 * @private
 */
goog.ui.FilteredMenu.prototype.tearDownFilterListeners_ = function() {
  if (this.inputHandler_) {
    goog.events.unlisten(this.inputHandler_,
                         goog.events.InputHandler.EventType.INPUT,
                         this.handleFilterEvent, false, this);
    goog.events.unlisten(this.filterInput_.parentNode,
                         goog.events.EventType.CLICK,
                         this.onFilterLabelClick_, false, this);

    this.inputHandler_.dispose();
    this.inputHandler_ = undefined;
    this.enteredItems_ = undefined;
  }
};

/** @override */
goog.ui.FilteredMenu.prototype.setVisible = function(show, opt_force, opt_e) {
  var visibilityChanged = goog.ui.FilteredMenu.superClass_.setVisible.call(this,
      show, opt_force, opt_e);
  if (visibilityChanged && show && this.isInDocument()) {
    this.setFilter('');
    this.setUpFilterListeners_();
  } else if (visibilityChanged && !show) {
    this.tearDownFilterListeners_();
  }

  return visibilityChanged;
};

/** @override */
goog.ui.FilteredMenu.prototype.disposeInternal = function() {
  this.tearDownFilterListeners_();
  this.filterInput_ = undefined;
  this.labelEl_ = undefined;
  goog.ui.FilteredMenu.superClass_.disposeInternal.call(this);
};

/**
 * Sets the filter label (the label displayed in the filter input element if no
 * text has been entered).
 * @param {?string} label Label text.
 */
goog.ui.FilteredMenu.prototype.setFilterLabel = function(label) {
  this.label_ = label || '';
  if (this.labelEl_) {
    goog.dom.setTextContent(this.labelEl_, this.label_);
  }
};

/**
 * @return {string} The filter label.
 */
goog.ui.FilteredMenu.prototype.getFilterLabel = function() {
  return this.label_;
};

/**
 * Sets the filter string.
 * @param {?string} str Filter string.
 */
goog.ui.FilteredMenu.prototype.setFilter = function(str) {
  if (this.filterInput_) {
    this.filterInput_.value = str;
    this.filterItems_(str);
  }
};

/**
 * Returns the filter string.
 * @return {string} Current filter or an an empty string.
 */
goog.ui.FilteredMenu.prototype.getFilter = function() {
  return this.filterInput_ && goog.isString(this.filterInput_.value) ?
      this.filterInput_.value : '';
};

/**
 * Sets the index of first item that should be affected by the filter. Menu
 * items with a lower index will not be affected by the filter.
 * @param {number} index Index of first item that should be affected by filter.
 */
goog.ui.FilteredMenu.prototype.setFilterFromIndex = function(index) {
  this.filterFromIndex_ = index;
};

/**
 * Returns the index of first item that is affected by the filter.
 * @return {number} Index of first item that is affected by filter.
 */
goog.ui.FilteredMenu.prototype.getFilterFromIndex = function() {
  return this.filterFromIndex_;
};

/**
 * Gets a list of items entered in the search box.
 * @return {!Array<string>} The entered items.
 */
goog.ui.FilteredMenu.prototype.getEnteredItems = function() {
  return this.enteredItems_ || [];
};

/**
 * Sets whether multiple items can be entered comma separated.
 * @param {boolean} b Whether multiple items can be entered.
 */
goog.ui.FilteredMenu.prototype.setAllowMultiple = function(b) {
  this.allowMultiple_ = b;
};

/**
 * @return {boolean} Whether multiple items can be entered comma separated.
 */
goog.ui.FilteredMenu.prototype.getAllowMultiple = function() {
  return this.allowMultiple_;
};

/**
 * Sets whether the specified child should be affected (shown/hidden) by the
 * filter criteria.
 * @param {goog.ui.Component} child Child to change.
 * @param {boolean} persistent Whether the child should be persistent.
 */
goog.ui.FilteredMenu.prototype.setPersistentVisibility = function(child,
                                                                  persistent) {
  if (!this.persistentChildren_) {
    this.persistentChildren_ = {};
  }
  this.persistentChildren_[child.getId()] = persistent;
};

/**
 * Returns whether the specified child should be affected (shown/hidden) by the
 * filter criteria.
 * @param {goog.ui.Component} child Menu item to check.
 * @return {boolean} Whether the menu item is persistent.
 */
goog.ui.FilteredMenu.prototype.hasPersistentVisibility = function(child) {
  return !!(this.persistentChildren_ &&
            this.persistentChildren_[child.getId()]);
};

/**
 * Handles filter input events.
 * @param {goog.events.BrowserEvent} e The event object.
 */
goog.ui.FilteredMenu.prototype.handleFilterEvent = function(e) {
  this.filterItems_(this.filterInput_.value);

  // Highlight the first visible item unless there's already a highlighted item.
  var highlighted = this.getHighlighted();
  if (!highlighted || !highlighted.isVisible()) {
    this.highlightFirst();
  }
  this.dispatchEvent(goog.ui.FilteredMenu.EventType.FILTER_CHANGED);
};

/**
 * Shows/hides elements based on the supplied filter.
 * @param {?string} str Filter string.
 * @private
 */
goog.ui.FilteredMenu.prototype.filterItems_ = function(str) {
  // Do nothing unless the filter string has changed.
  if (this.filterStr_ == str) {
    return;
  }

  if (this.labelEl_) {
    this.labelEl_.style.visibility = str == '' ? 'visible' : 'hidden';
  }

  if (this.allowMultiple_ && this.enteredItems_) {
    // Matches all non space characters after the last comma.
    var lastWordRegExp = /^(.+),[ ]*([^,]*)$/;
    var matches = str.match(lastWordRegExp);
    // matches[1] is the string up to, but not including, the last comma and
    // matches[2] the part after the last comma. If there are no non-space
    // characters after the last comma matches[2] is undefined.
    var items = matches && matches[1] ? matches[1].split(',') : [];

    // If the number of comma separated items has changes recreate the
    // entered items array and fire a change event.
    if (str.substr(str.length - 1, 1) == ',' ||
        items.length != this.enteredItems_.length) {
      var lastItem = items[items.length - 1] || '';

      // Auto complete text in input box based on the highlighted item.
      if (this.getHighlighted() && lastItem != '') {
        var caption = this.getHighlighted().getCaption();
        if (caption.toLowerCase().indexOf(lastItem.toLowerCase()) == 0) {
          items[items.length - 1] = caption;
          this.filterInput_.value = items.join(',') + ',';
        }
      }
      this.enteredItems_ = items;
      this.dispatchEvent(goog.ui.Component.EventType.CHANGE);
      this.setHighlightedIndex(-1);
    }

    if (matches) {
      str = matches.length > 2 ? goog.string.trim(matches[2]) : '';
    }
  }

  var matcher = new RegExp('(^|[- ,_/.:])' +
      goog.string.regExpEscape(str), 'i');
  for (var child, i = this.filterFromIndex_; child = this.getChildAt(i); i++) {
    if (child instanceof goog.ui.FilterObservingMenuItem) {
      child.callObserver(str);
    } else if (!this.hasPersistentVisibility(child)) {
      // Only show items matching the filter and highlight the part of the
      // caption that matches.
      var caption = child.getCaption();
      if (caption) {
        var matchArray = caption.match(matcher);
        if (str == '' || matchArray) {
          child.setVisible(true);
          var pos = caption.indexOf(matchArray[0]);

          // If position is non zero increase by one to skip the separator.
          if (pos) {
            pos++;
          }
          this.boldContent_(child, pos, str.length);
        } else {
          child.setVisible(false);
        }
      } else {

        // Hide separators and other items without a caption if a filter string
        // has been entered.
        child.setVisible(str == '');
      }
    }
  }
  this.filterStr_ = str;
};

/**
 * Updates the content of the given menu item, bolding the part of its caption
 * from start and through the next len characters.
 * @param {!goog.ui.Control} child The control to bold content on.
 * @param {number} start The index at which to start bolding.
 * @param {number} len How many characters to bold.
 * @private
 */
goog.ui.FilteredMenu.prototype.boldContent_ = function(child, start, len) {
  var caption = child.getCaption();
  var boldedCaption;
  if (len == 0) {
    boldedCaption = this.getDomHelper().createTextNode(caption);
  } else {
    var preMatch = caption.substr(0, start);
    var match = caption.substr(start, len);
    var postMatch = caption.substr(start + len);
    boldedCaption = this.getDomHelper().createDom(
        goog.dom.TagName.SPAN,
        null,
        preMatch,
        this.getDomHelper().createDom(goog.dom.TagName.B, null, match),
        postMatch);
  }
  var accelerator = child.getAccelerator && child.getAccelerator();
  if (accelerator) {
    child.setContent([boldedCaption, this.getDomHelper().createDom(
        goog.dom.TagName.SPAN,
        goog.ui.MenuItem.ACCELERATOR_CLASS, accelerator)]);
  } else {
    child.setContent(boldedCaption);
  }
};

/**
 * Handles the menu's behavior for a key event. The highlighted menu item will
 * be given the opportunity to handle the key behavior.
 * @param {goog.events.KeyEvent} e A browser event.
 * @return {boolean} Whether the event was handled.
 * @override
 */
goog.ui.FilteredMenu.prototype.handleKeyEventInternal = function(e) {
  // Home, end and the arrow keys are normally used to change the selected menu
  // item. Return false here to prevent the menu from preventing the default
  // behavior for HOME, END and any key press with a modifier.
  if (e.shiftKey || e.ctrlKey || e.altKey ||
      e.keyCode == goog.events.KeyCodes.HOME ||
      e.keyCode == goog.events.KeyCodes.END) {
    return false;
  }

  if (e.keyCode == goog.events.KeyCodes.ESC) {
    this.dispatchEvent(goog.ui.Component.EventType.BLUR);
    return true;
  }

  return goog.ui.FilteredMenu.superClass_.handleKeyEventInternal.call(this, e);
};

/**
 * Sets the highlighted index, unless the HIGHLIGHT event is intercepted and
 * cancelled.  -1 = no highlight. Also scrolls the menu item into view.
 * @param {number} index Index of menu item to highlight.
 * @override
 */
goog.ui.FilteredMenu.prototype.setHighlightedIndex = function(index) {
  goog.ui.FilteredMenu.superClass_.setHighlightedIndex.call(this, index);
  var contentEl = this.getContentElement();
  var el = /** @type {!HTMLElement} */ (
      this.getHighlighted() ? this.getHighlighted().getElement() : null);
  if (this.filterInput_) {
    goog.a11y.aria.setActiveDescendant(this.filterInput_, el);
  }

  if (el && goog.dom.contains(contentEl, el)) {
    var contentTop = goog.userAgent.IE && !goog.userAgent.isVersionOrHigher(8) ?
        0 : contentEl.offsetTop;

    // IE (tested on IE8) sometime does not scroll enough by about
    // 1px. So we add 1px to the scroll amount. This still looks ok in
    // other browser except for the most degenerate case (menu height <=
    // item height).

    // Scroll down if the highlighted item is below the bottom edge.
    var diff = (el.offsetTop + el.offsetHeight - contentTop) -
        (contentEl.clientHeight + contentEl.scrollTop) + 1;
    contentEl.scrollTop += Math.max(diff, 0);

    // Scroll up if the highlighted item is above the top edge.
    diff = contentEl.scrollTop - (el.offsetTop - contentTop) + 1;
    contentEl.scrollTop -= Math.max(diff, 0);
  }
};

/**
 * Handles clicks on the filter label. Focuses the input element.
 * @param {goog.events.BrowserEvent} e A browser event.
 * @private
 */
goog.ui.FilteredMenu.prototype.onFilterLabelClick_ = function(e) {
  this.filterInput_.focus();
};

/** @override */
goog.ui.FilteredMenu.prototype.getContentElement = function() {
  return this.contentElement_ || this.getElement();
};

/**
 * Returns the filter input element.
 * @return {Element} Input element.
 */
goog.ui.FilteredMenu.prototype.getFilterInputElement = function() {
  return this.filterInput_ || null;
};

/** @override */
goog.ui.FilteredMenu.prototype.decorateInternal = function(element) {
  this.setElementInternal(element);

  // Decorate the menu content.
  this.decorateContent(element);

  // Locate internally managed elements.
  var el = this.getDomHelper().getElementsByTagNameAndClass(
      goog.dom.TagName.DIV,
      goog.getCssName(this.getRenderer().getCssClass(), 'filter'), element)[0];
  this.labelEl_ = goog.dom.getFirstElementChild(el);
  this.filterInput_ = goog.dom.getNextElementSibling(this.labelEl_);
  this.contentElement_ = goog.dom.getNextElementSibling(el);

  // Decorate additional menu items (like 'apply').
  this.getRenderer().decorateChildren(this, el.parentNode,
      this.contentElement_);

  this.initFilterInput_();
};

{'repo_name': 'blinktrade/frontend', 'stars': '123', 'repo_language': 'JavaScript', 'file_name': 'chart.js', 'mime_type': 'text/plain', 'hash': -446934383912742310, 'source_dataset': 'data'}


#ifndef BOOST_STATECHART_FIFO_WORKER_HPP_INCLUDED
#define BOOST_STATECHART_FIFO_WORKER_HPP_INCLUDED
//////////////////////////////////////////////////////////////////////////////
// Copyright 2002-2008 Andreas Huber Doenni
// Distributed under the Boost Software License, Version 1.0. (See accompany-
// ing file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//////////////////////////////////////////////////////////////////////////////

#include <boost/assert.hpp>
#include <boost/noncopyable.hpp>
#include <boost/function/function0.hpp>
#include <boost/bind.hpp>
// BOOST_HAS_THREADS, BOOST_MSVC
#include <boost/config.hpp>

#include <boost/detail/allocator_utilities.hpp>

#ifdef BOOST_HAS_THREADS
#  ifdef BOOST_MSVC
#    pragma warning( push )
     // "conditional expression is constant" in basic_timed_mutex.hpp
#    pragma warning( disable: 4127 )
     // "conversion from 'int' to 'unsigned short'" in microsec_time_clock.hpp
#    pragma warning( disable: 4244 )
     // "... needs to have dll-interface to be used by clients of class ..."
#    pragma warning( disable: 4251 )
     // "... assignment operator could not be generated"
#    pragma warning( disable: 4512 )
     // "Function call with parameters that may be unsafe" in
     // condition_variable.hpp
#    pragma warning( disable: 4996 )
#  endif

#  include <boost/thread/mutex.hpp>
#  include <boost/thread/condition.hpp>

#  ifdef BOOST_MSVC
#    pragma warning( pop )
#  endif
#endif

#include <list>
#include <memory>   // std::allocator

namespace boost
{
namespace statechart
{

template< class Allocator = std::allocator< void > >
class fifo_worker : noncopyable
{
  public:
    //////////////////////////////////////////////////////////////////////////
    #ifdef BOOST_HAS_THREADS
    fifo_worker( bool waitOnEmptyQueue = false ) :
      waitOnEmptyQueue_( waitOnEmptyQueue ),
    #else
    fifo_worker() :
    #endif
      terminated_( false )
    {
    }

    typedef function0< void > work_item;

    // We take a non-const reference so that we can move (i.e. swap) the item
    // into the queue, what avoids copying the (possibly heap-allocated)
    // implementation object inside work_item.
    void queue_work_item( work_item & item )
    {
      if ( item.empty() )
      {
        return;
      }

      #ifdef BOOST_HAS_THREADS
      mutex::scoped_lock lock( mutex_ );
      #endif

      workQueue_.push_back( work_item() );
      workQueue_.back().swap( item );

      #ifdef BOOST_HAS_THREADS
      queueNotEmpty_.notify_one();
      #endif
    }

    // Convenience overload so that temporary objects can be passed directly
    // instead of having to create a work_item object first. Under most
    // circumstances, this will lead to one unnecessary copy of the
    // function implementation object.
    void queue_work_item( const work_item & item )
    {
      work_item copy = item;
      queue_work_item( copy );
    }

    void terminate()
    {
      work_item item = boost::bind( &fifo_worker::terminate_impl, this );
      queue_work_item( item );
    }

    // Is not mutex-protected! Must only be called from the thread that also
    // calls operator().
    bool terminated() const
    {
      return terminated_;
    }

    unsigned long operator()( unsigned long maxItemCount = 0 )
    {
      unsigned long itemCount = 0;

      while ( !terminated() &&
        ( ( maxItemCount == 0 ) || ( itemCount < maxItemCount ) ) )
      {
        work_item item = dequeue_item();

        if ( item.empty() )
        {
          // item can only be empty when the queue is empty, which only
          // happens in ST builds or when users pass false to the fifo_worker
          // constructor
          return itemCount;
        }

        item();
        ++itemCount;
      }

      return itemCount;
    }

  private:
    //////////////////////////////////////////////////////////////////////////
    work_item dequeue_item()
    {
      #ifdef BOOST_HAS_THREADS
      mutex::scoped_lock lock( mutex_ );

      if ( !waitOnEmptyQueue_ && workQueue_.empty() )
      {
        return work_item();
      }

      while ( workQueue_.empty() )
      {
        queueNotEmpty_.wait( lock );
      }
      #else
      // If the queue happens to run empty in a single-threaded system,
      // waiting for new work items (which means to loop indefinitely!) is
      // pointless as there is no way that new work items could find their way
      // into the queue. The only sensible thing is to exit the loop and
      // return to the caller in this case.
      // Users can then queue new work items before calling operator() again.
      if ( workQueue_.empty() )
      {
        return work_item();
      }
      #endif

      // Optimization: Swap rather than assign to avoid the copy of the
      // implementation object inside function
      work_item result;
      result.swap( workQueue_.front() );
      workQueue_.pop_front();
      return result;
    }

    void terminate_impl()
    {
      terminated_ = true;
    }

    typedef std::list<
      work_item,
      typename boost::detail::allocator::rebind_to<
        Allocator, work_item >::type
    > work_queue_type;

    work_queue_type workQueue_;

    #ifdef BOOST_HAS_THREADS
    mutex mutex_;
    condition queueNotEmpty_;
    const bool waitOnEmptyQueue_;
    #endif

    bool terminated_;
};

} // namespace statechart
} // namespace boost

#endif

{'repo_name': 'vovkasm/react-native-web-image', 'stars': '139', 'repo_language': 'Java', 'file_name': 'index.d.ts', 'mime_type': 'text/x-java', 'hash': 2952618412417837708, 'source_dataset': 'data'}


// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.

// If you have no idea what ASN.1 or BER is, see this:
// ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc

var Ber = require('./ber/index');

///--- Exported API

module.exports = {

  Ber: Ber,

  BerReader: Ber.Reader,

  BerWriter: Ber.Writer

};

{'repo_name': 'bennadel/JavaScript-Demos', 'stars': '578', 'repo_language': 'HTML', 'file_name': 'tsc', 'mime_type': 'text/plain', 'hash': 6257126068021115424, 'source_dataset': 'data'}


<?php
/**
 * System messages translation for CodeIgniter(tm)
 *
 * @author	CodeIgniter community
 * @copyright	Copyright (c) 2014 - 2016, British Columbia Institute of Technology (http://bcit.ca/)
 * @license	http://opensource.org/licenses/MIT	MIT License
 * @link	https://codeigniter.com
 */
defined('BASEPATH') OR exit('No direct script access allowed');

$lang['db_invalid_connection_str'] = 'Неможливо визначити параметри бази даних на основі рядка підключення, який Ви надали.';
$lang['db_unable_to_connect'] = 'Неможливо підключитись до серверу бази даних, використовуючи надані параметри.';
$lang['db_unable_to_select'] = 'Неможливо вибрати вказану базу даних: %s';
$lang['db_unable_to_create'] = 'Неможливо створити вказану базу даних: %s';
$lang['db_invalid_query'] = 'Наданий Вами запит є неприйнятним.';
$lang['db_must_set_table'] = 'Необхідно вказати таблицю бази даних, котра буде використана у Вашому запиті.';
$lang['db_must_use_set'] = 'Необхідно використовувати метод "set" для оновлення запису.';
$lang['db_must_use_index'] = 'Необхідно вказати індекс для пакетного оновлення.';
$lang['db_batch_missing_index'] = 'Один чи декілька рядків, наданих для пакетного оновлення, не має вказаного індекса.';
$lang['db_must_use_where'] = 'Оновлення неприйнятне без вказаної через оператор "where" умови.';
$lang['db_del_must_use_where'] = 'Видалення неприйнятне без умови, вказаної через параметр "where" або "like".';
$lang['db_field_param_missing'] = 'Для вибору полів необхідне ім’я таблиці в якості параметру.';
$lang['db_unsupported_function'] = 'Ця функція неприйнятна для вибраної бази даних.';
$lang['db_transaction_failure'] = 'Збій транзакції: відкат.';
$lang['db_unable_to_drop'] = 'Неможливо видалити вказану базу даних.';
$lang['db_unsupported_feature'] = 'Непідтримувана особливість платформи бази даних, яку Ви використовуєте.';
$lang['db_unsupported_compression'] = 'Формат стискання файлів, який Ви вибрали, не підтримується Вашим сервером.';
$lang['db_filepath_error'] = 'Неможливо записати дані в файл за вказаним шляхом.';
$lang['db_invalid_cache_path'] = 'Вказаний шлях до кеш файлів некоректний або недоступний для запису.';
$lang['db_table_name_required'] = 'Необхідно вказати ім’я таблиці для цієї операції.';
$lang['db_column_name_required'] = 'Необхідно вказати ім’я стовпця для цієї операції.';
$lang['db_column_definition_required'] = 'Назва стовпця обов’язкова для цієї операції.';
$lang['db_unable_to_set_charset'] = 'Неможливо встановити кодування з’єднання: %s';
$lang['db_error_heading'] = 'Помилка бази даних.';

{'repo_name': 'waifung0207/ci_bootstrap_3', 'stars': '372', 'repo_language': 'JavaScript', 'file_name': 'index.html', 'mime_type': 'text/html', 'hash': -8796128056298382735, 'source_dataset': 'data'}


/*
    Copyright (C) 2014-2019 de4dot@gmail.com

    This file is part of dnSpy

    dnSpy is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    dnSpy is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with dnSpy.  If not, see <http://www.gnu.org/licenses/>.
*/

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.Win32;

namespace dnSpy.Documents {
	sealed class DotNetCorePathProvider {
		readonly FrameworkPaths[] netcorePaths;

		public bool HasDotNetCore => netcorePaths.Length != 0;

		readonly struct NetCorePathInfo {
			public readonly string Directory;
			public readonly int Bitness;
			public NetCorePathInfo(string directory, int bitness) {
				Directory = directory ?? throw new ArgumentNullException(nameof(directory));
				Bitness = bitness;
			}
		}

		// It treats all previews/alphas as the same version. This is needed because .NET Core 3.0 preview's
		// shared frameworks don't have the same version numbers, eg.:
		//		shared\Microsoft.AspNetCore.App\3.0.0-preview-18579-0056
		//		shared\Microsoft.NETCore.App\3.0.0-preview-27216-02
		//		shared\Microsoft.WindowsDesktop.App\3.0.0-alpha-27214-12
		readonly struct FrameworkVersionIgnoreExtra : IEquatable<FrameworkVersionIgnoreExtra> {
			readonly FrameworkVersion version;

			public FrameworkVersionIgnoreExtra(FrameworkVersion version) => this.version = version;

			public bool Equals(FrameworkVersionIgnoreExtra other) =>
				version.Major == other.version.Major &&
				version.Minor == other.version.Minor &&
				version.Patch == other.version.Patch &&
				(version.Extra.Length == 0) == (other.version.Extra.Length == 0);

			public override bool Equals(object? obj) => obj is FrameworkVersionIgnoreExtra other && Equals(other);
			public override int GetHashCode() => version.Major ^ version.Minor ^ version.Patch ^ (version.Extra.Length == 0 ? 0 : -1);
		}

		public DotNetCorePathProvider() {
			var list = new List<FrameworkPath>();
			foreach (var info in GetDotNetCoreBaseDirs())
				list.AddRange(GetDotNetCorePaths(info.Directory, info.Bitness));

			var paths = from p in list
						group p by new { Path = (Path.GetDirectoryName(Path.GetDirectoryName(p.Path)) ?? string.Empty).ToUpperInvariant(), p.Bitness, Version = new FrameworkVersionIgnoreExtra(p.Version) } into g
						where !string.IsNullOrEmpty(g.Key.Path)
						select new FrameworkPaths(g.ToArray());
			var array = paths.ToArray();
			Array.Sort(array);
			netcorePaths = array;
		}

		public string[]? TryGetDotNetCorePaths(Version version, int bitness) {
			Debug.Assert(bitness == 32 || bitness == 64);
			int bitness2 = bitness ^ 0x60;
			FrameworkPaths? info;

			info = TryGetDotNetCorePathsCore(version.Major, version.Minor, bitness) ??
				TryGetDotNetCorePathsCore(version.Major, version.Minor, bitness2);
			if (!(info is null))
				return info.Paths;

			info = TryGetDotNetCorePathsCore(version.Major, bitness) ??
				TryGetDotNetCorePathsCore(version.Major, bitness2);
			if (!(info is null))
				return info.Paths;

			info = TryGetDotNetCorePathsCore(bitness) ??
				TryGetDotNetCorePathsCore(bitness2);
			if (!(info is null))
				return info.Paths;

			return null;
		}

		FrameworkPaths? TryGetDotNetCorePathsCore(int major, int minor, int bitness) {
			FrameworkPaths? fpMajor = null;
			FrameworkPaths? fpMajorMinor = null;
			for (int i = netcorePaths.Length - 1; i >= 0; i--) {
				var info = netcorePaths[i];
				if (info.Bitness == bitness && info.Version.Major == major) {
					if (fpMajor is null)
						fpMajor = info;
					else
						fpMajor = BestMinorVersion(minor, fpMajor, info);
					if (info.Version.Minor == minor) {
						if (info.HasDotNetCoreAppPath)
							return info;
						if (fpMajorMinor is null)
							fpMajorMinor = info;
					}
				}
			}
			return fpMajorMinor ?? fpMajor;
		}

		static FrameworkPaths BestMinorVersion(int minor, FrameworkPaths a, FrameworkPaths b) {
			uint da = VerDist(minor, a.Version.Minor);
			uint db = VerDist(minor, b.Version.Minor);
			if (da < db)
				return a;
			if (db < da)
				return b;
			if (!string.IsNullOrEmpty(b.Version.Extra))
				return a;
			if (!string.IsNullOrEmpty(a.Version.Extra))
				return b;
			return a;
		}

		// Any ver < minVer is worse than any ver >= minVer
		static uint VerDist(int minVer, int ver) {
			if (ver >= minVer)
				return (uint)(ver - minVer);
			return 0x80000000 + (uint)minVer - (uint)ver - 1;
		}

		FrameworkPaths? TryGetDotNetCorePathsCore(int major, int bitness) {
			FrameworkPaths? fpMajor = null;
			for (int i = netcorePaths.Length - 1; i >= 0; i--) {
				var info = netcorePaths[i];
				if (info.Bitness == bitness && info.Version.Major == major) {
					if (info.HasDotNetCoreAppPath)
						return info;
					if (fpMajor is null)
						fpMajor = info;
				}
			}
			return fpMajor;
		}

		FrameworkPaths? TryGetDotNetCorePathsCore(int bitness) {
			FrameworkPaths? best = null;
			for (int i = netcorePaths.Length - 1; i >= 0; i--) {
				var info = netcorePaths[i];
				if (info.Bitness == bitness) {
					if (info.HasDotNetCoreAppPath)
						return info;
					if (best is null)
						best = info;
				}
			}
			return best;
		}

		const string DotNetExeName = "dotnet.exe";
		static IEnumerable<NetCorePathInfo> GetDotNetCoreBaseDirs() {
			var hash = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
			foreach (var tmp in GetDotNetCoreBaseDirCandidates()) {
				var path = tmp.Trim();
				if (!Directory.Exists(path))
					continue;
				try {
					path = Path.Combine(Path.GetDirectoryName(path)!, Path.GetFileName(path));
				}
				catch (ArgumentException) {
					continue;
				}
				catch (PathTooLongException) {
					continue;
				}
				if (!hash.Add(path))
					continue;
				string file;
				try {
					file = Path.Combine(path, DotNetExeName);
				}
				catch {
					continue;
				}
				if (!File.Exists(file))
					continue;
				int bitness;
				try {
					bitness = GetPeFileBitness(file);
				}
				catch {
					continue;
				}
				if (bitness == -1)
					continue;
				yield return new NetCorePathInfo(path, bitness);
			}
		}

		// NOTE: This same method exists in DotNetCoreHelpers (CorDebug project). Update both methods if this one gets updated.
		static IEnumerable<string> GetDotNetCoreBaseDirCandidates() {
			// Microsoft tools don't check the PATH env var, only the default locations (eg. ProgramFiles)
			var envVars = new string[] {
				"PATH",
				"DOTNET_ROOT(x86)",
				"DOTNET_ROOT",
			};
			foreach (var envVar in envVars) {
				var pathEnvVar = Environment.GetEnvironmentVariable(envVar) ?? string.Empty;
				foreach (var path in pathEnvVar.Split(new[] { Path.PathSeparator }, StringSplitOptions.RemoveEmptyEntries))
					yield return path;
			}

			var regPathFormat = IntPtr.Size == 4 ?
				@"SOFTWARE\dotnet\Setup\InstalledVersions\{0}" :
				@"SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\{0}";
			var archs = new[] { "x86", "x64" };
			foreach (var arch in archs) {
				var regPath = string.Format(regPathFormat, arch);
				if (TryGetInstallLocationFromRegistry(regPath, out var installLocation))
					yield return installLocation;
			}

			// Check default locations
			var progDirX86 = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);
			var progDir = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
			if (!string.IsNullOrEmpty(progDirX86) && StringComparer.OrdinalIgnoreCase.Equals(progDirX86, progDir) && Path.GetDirectoryName(progDir) is string baseDir)
				progDir = Path.Combine(baseDir, "Program Files");
			const string dotnetDirName = "dotnet";
			if (!string.IsNullOrEmpty(progDir))
				yield return Path.Combine(progDir, dotnetDirName);
			if (!string.IsNullOrEmpty(progDirX86))
				yield return Path.Combine(progDirX86, dotnetDirName);
		}

		static bool TryGetInstallLocationFromRegistry(string regPath, [NotNullWhen(true)] out string? installLocation) {
			using (var key = Registry.LocalMachine.OpenSubKey(regPath)) {
				installLocation = key?.GetValue("InstallLocation") as string;
				return !(installLocation is null);
			}
		}

		static IEnumerable<FrameworkPath> GetDotNetCorePaths(string basePath, int bitness) {
			if (!Directory.Exists(basePath))
				yield break;
			var sharedDir = Path.Combine(basePath, "shared");
			if (!Directory.Exists(sharedDir))
				yield break;
			// Known dirs: Microsoft.NETCore.App, Microsoft.WindowsDesktop.App, Microsoft.AspNetCore.All, Microsoft.AspNetCore.App
			foreach (var versionsDir in GetDirectories(sharedDir)) {
				foreach (var dir in GetDirectories(versionsDir)) {
					var name = Path.GetFileName(dir);
					var m = Regex.Match(name, @"^(\d+)\.(\d+)\.(\d+)$");
					if (m.Groups.Count == 4) {
						var g = m.Groups;
						yield return new FrameworkPath(dir, bitness, ToFrameworkVersion(g[1].Value, g[2].Value, g[3].Value, string.Empty));
					}
					else {
						m = Regex.Match(name, @"^(\d+)\.(\d+)\.(\d+)-(.*)$");
						if (m.Groups.Count == 5) {
							var g = m.Groups;
							yield return new FrameworkPath(dir, bitness, ToFrameworkVersion(g[1].Value, g[2].Value, g[3].Value, g[4].Value));
						}
					}
				}
			}
		}

		static int ParseInt32(string s) => int.TryParse(s, out var res) ? res : 0;
		static FrameworkVersion ToFrameworkVersion(string a, string b, string c, string d) =>
			new FrameworkVersion(ParseInt32(a), ParseInt32(b), ParseInt32(c), d);

		static string[] GetDirectories(string dir) {
			try {
				return Directory.GetDirectories(dir);
			}
			catch {
			}
			return Array.Empty<string>();
		}

		static int GetPeFileBitness(string file) {
			using (var f = File.OpenRead(file)) {
				var r = new BinaryReader(f);
				if (r.ReadUInt16() != 0x5A4D)
					return -1;
				f.Position = 0x3C;
				f.Position = r.ReadUInt32();
				if (r.ReadUInt32() != 0x4550)
					return -1;
				f.Position += 0x14;
				ushort magic = r.ReadUInt16();
				if (magic == 0x10B)
					return 32;
				if (magic == 0x20B)
					return 64;
				return -1;
			}
		}

		public Version? TryGetDotNetCoreVersion(string filename) {
			foreach (var info in netcorePaths) {
				foreach (var path in info.Paths) {
					if (FileUtils.IsFileInDir(path, filename))
						return info.SystemVersion;
				}
			}

			return null;
		}
	}
}

{'repo_name': '0xd4d/dnSpy', 'stars': '15116', 'repo_language': 'C#', 'file_name': 'ToolBarButtonBase.cs', 'mime_type': 'text/plain', 'hash': 4547447991940585781, 'source_dataset': 'data'}


/*
 * Copyright 2016 Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
#include <folly/io/async/DelayedDestructionBase.h>

#include <functional>
#include <list>
#include <vector>

#include <folly/portability/GTest.h>

using namespace folly;

class DestructionOnCallback : public DelayedDestructionBase {
 public:
  DestructionOnCallback() : state_(0), deleted_(false) {
  }

  void onComplete(int n, int& state) {
    DestructorGuard dg(this);
    for (auto i = n; i >= 0; --i) {
      onStackedComplete(i);
    }
    state = state_;
  }

  int state() const { return state_; }
  bool deleted() const { return deleted_; }

 protected:
  void onStackedComplete(int recur) {
    DestructorGuard dg(this);
    ++state_;
    if (recur <= 0) {
      return;
    }
    onStackedComplete(--recur);
  }
 private:
  int state_;
  bool deleted_;

  void onDelayedDestroy(bool delayed) override {
    deleted_ = true;
    delete this;
    (void)delayed; // prevent unused variable warnings
  }
};

struct DelayedDestructionBaseTest : public ::testing::Test {
};

TEST_F(DelayedDestructionBaseTest, basic) {
  DestructionOnCallback* d = new DestructionOnCallback();
  EXPECT_NE(d, nullptr);
  int32_t state;
  d->onComplete(3, state);
  EXPECT_EQ(state, 10); // 10 = 6 + 3 + 1
}

{'repo_name': 'discourse/DiscourseMobile', 'stars': '153', 'repo_language': 'JavaScript', 'file_name': 'App-test.js', 'mime_type': 'text/x-java', 'hash': -541619303175932762, 'source_dataset': 'data'}


%%-------------------------------------------------------------------
%% @author
%%     ChicagoBoss Team and contributors, see AUTHORS file in root directory
%% @end
%% @copyright
%%     This file is part of ChicagoBoss project.
%%     See AUTHORS file in root directory
%%     for license information, see LICENSE file in root directory
%% @end
%% @doc
%%-------------------------------------------------------------------

-module(boss_web_controller_handle_request_test).

-include_lib("eunit/include/eunit.hrl").

perms([]) -> [[]];
perms(L)  -> [[H|T] || H <- L, T <- perms(L--[H])].

f1(_) ->
    {ok, test}.
f2(_) ->
    {ok, test2}.
f3(_) ->
    {error, test3}.

fold_operations_test() ->
    ErrorList = [fun f1/1, fun f2/1, fun f3/1],
    OKList    = [fun f1/1, fun f2/1],
    ?assertEqual({error, test3}, boss_web_controller_handle_request:fold_operations(app,ErrorList)),
    ?assertEqual({ok, test2}, boss_web_controller_handle_request:fold_operations(app,OKList)),
    ErrLists = perms(ErrorList),
    lists:foreach(fun(List) ->
              ?assertEqual({error, test3},
                       boss_web_controller_handle_request:fold_operations(app,List))
          end, ErrLists),
    lists:foreach(fun(List) ->
              ?assertMatch({ok, _},
                       boss_web_controller_handle_request:fold_operations(app,List))
          end,perms(OKList)).

make_controlle_names_test() ->
    ?assertEqual(["foo","bar","baz"],
         boss_web_controller_handle_request:make_controller_names([foo,bar,baz])).

make_etag_test() ->
    Sha1 = boss_web_controller_handle_request:make_etag(boss, "", "empty"),
    ?assertEqual("2jmj7l5rSw0yVb/vlWAYkK/YBwk=", Sha1).

%% This test should be rewritten
%% * remove usage of mochicow
%% * remove paths specific to zkessin machine
%% dev_headers_test() ->
%%     Module = {simple_bridge_response_wrapper,mochiweb_response_bridge,
%%           {{mochicow_request,port,'GET',"/static/test.txt",
%%         {1,1},
%%         {3,
%%          {"user-agent",
%%           {"user-agent","curl/7.32.0"},
%%           {"host",
%%            {"host","erlang-ci.com:8001"},
%%            {"accept",{"accept","*/*"},nil,nil},
%%            nil},
%%           nil}},
%%         <<>>},
%%            "/home/zkessin/Documents/erlang_ci/priv/static"},
%%           {response,200,[{header,"Cache-Control","no-cache"}],[],[]}},
%%     ?assertEqual(Module, boss_web_controller_handle_request:dev_headers(Module, production)),
%%     {_,_,_,Response} = boss_web_controller_handle_request:dev_headers(Module, development),
%%     ?assertMatch({response, 200, [{header, "Cache-Control","no-cache"}],_,_}, Response).

{'repo_name': 'ChicagoBoss/ChicagoBoss', 'stars': '1787', 'repo_language': 'Erlang', 'file_name': 'README_FILTERS.md', 'mime_type': 'text/plain', 'hash': 8581873059918998565, 'source_dataset': 'data'}


/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2013-2017 Oracle and/or its affiliates. All rights reserved.
 *
 * The contents of this file are subject to the terms of either the GNU
 * General Public License Version 2 only ("GPL") or the Common Development
 * and Distribution License("CDDL") (collectively, the "License").  You
 * may not use this file except in compliance with the License.  You can
 * obtain a copy of the License at
 * https://oss.oracle.com/licenses/CDDL+GPL-1.1
 * or LICENSE.txt.  See the License for the specific
 * language governing permissions and limitations under the License.
 *
 * When distributing the software, include this License Header Notice in each
 * file and include the License file at LICENSE.txt.
 *
 * GPL Classpath Exception:
 * Oracle designates this particular file as subject to the "Classpath"
 * exception as provided by Oracle in the GPL Version 2 section of the License
 * file that accompanied this code.
 *
 * Modifications:
 * If applicable, add the following below the License Header, with the fields
 * enclosed by brackets [] replaced by your own identifying information:
 * "Portions Copyright [year] [name of copyright owner]"
 *
 * Contributor(s):
 * If you wish your version of this file to be governed by only the CDDL or
 * only the GPL Version 2, indicate your decision by adding "[Contributor]
 * elects to include this software in this distribution under the [CDDL or GPL
 * Version 2] license."  If you don't indicate a single choice of license, a
 * recipient has the option to distribute your version of this file under
 * either the CDDL, the GPL Version 2 or to extend the choice of license to
 * its licensees as provided above.  However, if you add GPL Version 2 code
 * and therefore, elected the GPL Version 2 license, then the option applies
 * only if the new code is made subject to such option by the copyright
 * holder.
 */

package org.glassfish.jersey.tests.integration.jersey1829;

import java.util.Collections;
import java.util.Set;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Response;

/**
 * Application class with test resource that returns custom status reason phrase.
 *
 * @author Miroslav Fuksa
 */
public class Jersey1829 extends Application {

    public static final String REASON_PHRASE = "my-phrase";

    @SuppressWarnings("unchecked")
    @Override
    public Set<Class<?>> getClasses() {
        return Collections.<Class<?>>singleton(TestResource.class);
    }

    @Path("resource")
    public static class TestResource {

        @GET
        @Path("428")
        public Response get() {
            return Response.status(new Custom428Type()).build();
        }

        @GET
        @Path("428-entity")
        public Response getWithEntity() {
            return Response.status(new Custom428Type()).entity("entity").build();
        }
    }

    public static class Custom428Type implements Response.StatusType {

        @Override
        public int getStatusCode() {
            return 428;
        }

        @Override
        public String getReasonPhrase() {
            return REASON_PHRASE;
        }

        @Override
        public Response.Status.Family getFamily() {
            return Response.Status.Family.CLIENT_ERROR;
        }
    }

}

{'repo_name': 'jersey/jersey', 'stars': '2919', 'repo_language': 'Java', 'file_name': 'FormProviderTest.java', 'mime_type': 'text/x-java', 'hash': 3620953163233415636, 'source_dataset': 'data'}