/*
 * Copyright (C) 2013 4th Line GmbH, Switzerland
 *
 * The contents of this file are subject to the terms of either the GNU
 * Lesser General Public License Version 2 or later ("LGPL") or the
 * Common Development and Distribution License Version 1 or later
 * ("CDDL") (collectively, the "License"). You may not use this file
 * except in compliance with the License. See LICENSE.txt for more
 * information.
 *
 * 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.
 */

package org.fourthline.cling.binding.annotations;

import org.fourthline.cling.binding.LocalServiceBinder;
import org.fourthline.cling.binding.LocalServiceBindingException;
import org.fourthline.cling.model.ValidationError;
import org.fourthline.cling.model.ValidationException;
import org.fourthline.cling.model.action.ActionExecutor;
import org.fourthline.cling.model.action.QueryStateVariableExecutor;
import org.fourthline.cling.model.meta.Action;
import org.fourthline.cling.model.meta.LocalService;
import org.fourthline.cling.model.meta.QueryStateVariableAction;
import org.fourthline.cling.model.meta.StateVariable;
import org.fourthline.cling.model.state.FieldStateVariableAccessor;
import org.fourthline.cling.model.state.GetterStateVariableAccessor;
import org.fourthline.cling.model.state.StateVariableAccessor;
import org.fourthline.cling.model.types.ServiceId;
import org.fourthline.cling.model.types.ServiceType;
import org.fourthline.cling.model.types.UDAServiceId;
import org.fourthline.cling.model.types.UDAServiceType;
import org.fourthline.cling.model.types.csv.CSV;
import org.seamless.util.Reflections;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URI;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.Locale;
import java.util.logging.Logger;

/**
 * Reads {@link org.fourthline.cling.model.meta.LocalService} metadata from annotations.
 *
 * @author Christian Bauer
 */
public class AnnotationLocalServiceBinder implements LocalServiceBinder {

    private static Logger log = Logger.getLogger(AnnotationLocalServiceBinder.class.getName());

    public LocalService read(Class<?> clazz) throws LocalServiceBindingException {
        log.fine("Reading and binding annotations of service implementation class: " + clazz);

        // Read the service ID and service type from the annotation
        if (clazz.isAnnotationPresent(UpnpService.class)) {

            UpnpService annotation = clazz.getAnnotation(UpnpService.class);
            UpnpServiceId idAnnotation = annotation.serviceId();
            UpnpServiceType typeAnnotation = annotation.serviceType();

            ServiceId serviceId = idAnnotation.namespace().equals(UDAServiceId.DEFAULT_NAMESPACE)
                    ? new UDAServiceId(idAnnotation.value())
                    : new ServiceId(idAnnotation.namespace(), idAnnotation.value());

            ServiceType serviceType = typeAnnotation.namespace().equals(UDAServiceType.DEFAULT_NAMESPACE)
                    ? new UDAServiceType(typeAnnotation.value(), typeAnnotation.version())
                    : new ServiceType(typeAnnotation.namespace(), typeAnnotation.value(), typeAnnotation.version());

            boolean supportsQueryStateVariables = annotation.supportsQueryStateVariables();

            Set<Class> stringConvertibleTypes = readStringConvertibleTypes(annotation.stringConvertibleTypes());

            return read(clazz, serviceId, serviceType, supportsQueryStateVariables, stringConvertibleTypes);
        } else {
            throw new LocalServiceBindingException("Given class is not an @UpnpService");
        }
    }

    public LocalService read(Class<?> clazz, ServiceId id, ServiceType type,
                             boolean supportsQueryStateVariables, Class[] stringConvertibleTypes) throws LocalServiceBindingException {
        return read(clazz, id, type, supportsQueryStateVariables, new HashSet<>(Arrays.asList(stringConvertibleTypes)));
    }

    public LocalService read(Class<?> clazz, ServiceId id, ServiceType type,
                                   boolean supportsQueryStateVariables, Set<Class> stringConvertibleTypes)
            throws LocalServiceBindingException {

        Map<StateVariable, StateVariableAccessor> stateVariables = readStateVariables(clazz, stringConvertibleTypes);
        Map<Action, ActionExecutor> actions = readActions(clazz, stateVariables, stringConvertibleTypes);

        // Special treatment of the state variable querying action
        if (supportsQueryStateVariables) {
            actions.put(new QueryStateVariableAction(), new QueryStateVariableExecutor());
        }

        try {
            return new LocalService(type, id, actions, stateVariables, stringConvertibleTypes, supportsQueryStateVariables);

        } catch (ValidationException ex) {
            log.severe("Could not validate device model: " + ex.toString());
            for (ValidationError validationError : ex.getErrors()) {
                log.severe(validationError.toString());
            }
            throw new LocalServiceBindingException("Validation of model failed, check the log");
        }
    }

    protected Set<Class> readStringConvertibleTypes(Class[] declaredTypes) throws LocalServiceBindingException {

        for (Class stringConvertibleType : declaredTypes) {
            if (!Modifier.isPublic(stringConvertibleType.getModifiers())) {
                throw new LocalServiceBindingException(
                        "Declared string-convertible type must be public: " + stringConvertibleType
                );
            }
            try {
                stringConvertibleType.getConstructor(String.class);
            } catch (NoSuchMethodException ex) {
                throw new LocalServiceBindingException(
                        "Declared string-convertible type needs a public single-argument String constructor: " + stringConvertibleType
                );
            }
        }
        Set<Class> stringConvertibleTypes = new HashSet(Arrays.asList(declaredTypes));

        // Some defaults
        stringConvertibleTypes.add(URI.class);
        stringConvertibleTypes.add(URL.class);
        stringConvertibleTypes.add(CSV.class);

        return stringConvertibleTypes;
    }

    protected Map<StateVariable, StateVariableAccessor> readStateVariables(Class<?> clazz, Set<Class> stringConvertibleTypes)
            throws LocalServiceBindingException {

        Map<StateVariable, StateVariableAccessor> map = new HashMap<>();

        // State variables declared on the class
        if (clazz.isAnnotationPresent(UpnpStateVariables.class)) {
            UpnpStateVariables variables = clazz.getAnnotation(UpnpStateVariables.class);
            for (UpnpStateVariable v : variables.value()) {

                if (v.name().length() == 0)
                    throw new LocalServiceBindingException("Class-level @UpnpStateVariable name attribute value required");

                String javaPropertyName = toJavaStateVariableName(v.name());

                Method getter = Reflections.getGetterMethod(clazz, javaPropertyName);
                Field field = Reflections.getField(clazz, javaPropertyName);

                StateVariableAccessor accessor = null;
                if (getter != null && field != null) {
                    accessor = variables.preferFields() ?
                            new FieldStateVariableAccessor(field)
                            : new GetterStateVariableAccessor(getter);
                } else if (field != null) {
                    accessor = new FieldStateVariableAccessor(field);
                } else if (getter != null) {
                    accessor = new GetterStateVariableAccessor(getter);
                } else {
                    log.finer("No field or getter found for state variable, skipping accessor: " + v.name());
                }

                StateVariable stateVar =
                        new AnnotationStateVariableBinder(v, v.name(), accessor, stringConvertibleTypes)
                                .createStateVariable();

                map.put(stateVar, accessor);
            }
        }

        // State variables declared on fields
        for (Field field : Reflections.getFields(clazz, UpnpStateVariable.class)) {

            UpnpStateVariable svAnnotation = field.getAnnotation(UpnpStateVariable.class);

            StateVariableAccessor accessor = new FieldStateVariableAccessor(field);

            StateVariable stateVar = new AnnotationStateVariableBinder(
                    svAnnotation,
                    svAnnotation.name().length() == 0
                            ? toUpnpStateVariableName(field.getName())
                            : svAnnotation.name(),
                    accessor,
                    stringConvertibleTypes
            ).createStateVariable();

            map.put(stateVar, accessor);
        }

        // State variables declared on getters
        for (Method getter : Reflections.getMethods(clazz, UpnpStateVariable.class)) {

            String propertyName = Reflections.getMethodPropertyName(getter.getName());
            if (propertyName == null) {
                throw new LocalServiceBindingException(
                        "Annotated method is not a getter method (: " + getter
                );
            }

            if (getter.getParameterTypes().length > 0)
                throw new LocalServiceBindingException(
                        "Getter method defined as @UpnpStateVariable can not have parameters: " + getter
                );

            UpnpStateVariable svAnnotation = getter.getAnnotation(UpnpStateVariable.class);

            StateVariableAccessor accessor = new GetterStateVariableAccessor(getter);

            StateVariable stateVar = new AnnotationStateVariableBinder(
                    svAnnotation,
                    svAnnotation.name().length() == 0
                            ?
                            toUpnpStateVariableName(propertyName)
                            : svAnnotation.name(),
                    accessor,
                    stringConvertibleTypes
            ).createStateVariable();

            map.put(stateVar, accessor);
        }

        return map;
    }

    protected Map<Action, ActionExecutor> readActions(Class<?> clazz,
                                                      Map<StateVariable, StateVariableAccessor> stateVariables,
                                                      Set<Class> stringConvertibleTypes)
            throws LocalServiceBindingException {

        Map<Action, ActionExecutor> map = new HashMap<>();

        for (Method method : Reflections.getMethods(clazz, UpnpAction.class)) {
            AnnotationActionBinder actionBinder =
                    new AnnotationActionBinder(method, stateVariables, stringConvertibleTypes);
            Action action = actionBinder.appendAction(map);
            if(isActionExcluded(action)) {
            	map.remove(action);
            }
        }

        return map;
    }

    /**
     * Override this method to exclude action/methods after they have been discovered.
     */
    protected  boolean isActionExcluded(Action action) {
    	return false;
    }

    // TODO: I don't like the exceptions much, user has no idea what to do

    static String toUpnpStateVariableName(String javaName) {
        if (javaName.length() < 1) {
            throw new IllegalArgumentException("Variable name must be at least 1 character long");
        }
        return javaName.substring(0, 1).toUpperCase(Locale.ROOT) + javaName.substring(1);
    }

    static String toJavaStateVariableName(String upnpName) {
        if (upnpName.length() < 1) {
            throw new IllegalArgumentException("Variable name must be at least 1 character long");
        }
        return upnpName.substring(0, 1).toLowerCase(Locale.ROOT) + upnpName.substring(1);
    }

    static String toUpnpActionName(String javaName) {
        if (javaName.length() < 1) {
            throw new IllegalArgumentException("Action name must be at least 1 character long");
        }
        return javaName.substring(0, 1).toUpperCase(Locale.ROOT) + javaName.substring(1);
    }

    static String toJavaActionName(String upnpName) {
        if (upnpName.length() < 1) {
            throw new IllegalArgumentException("Variable name must be at least 1 character long");
        }
        return upnpName.substring(0, 1).toLowerCase(Locale.ROOT) + upnpName.substring(1);
    }

}

{'repo_name': 'zaneCC/AndroidUPnPDemo', 'stars': '390', 'repo_language': 'Java', 'file_name': 'ExampleUnitTest.java', 'mime_type': 'text/html', 'hash': 6789543167673589333, 'source_dataset': 'data'}


<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
  <dict>
    <key>color</key>
    <string>1,0.75,0,0.7</string>
  </dict>
</plist>

{'repo_name': 'TypeNetwork/Amstelvar', 'stars': '207', 'repo_language': 'None', 'file_name': 'font.css', 'mime_type': 'text/plain', 'hash': -4255308032275941382, 'source_dataset': 'data'}


#ifndef CLCUSTOMSCROLLBAR_H
#define CLCUSTOMSCROLLBAR_H

#include "codelite_exports.h"
#include <wx/panel.h>
#include "clColours.h"
#include <wx/event.h>

/// a wxCommandEvent that takes ownership of the clientData
class WXDLLIMPEXP_SDK clScrollEvent : public wxCommandEvent
{
protected:
    int m_position = wxNOT_FOUND;

public:
    clScrollEvent(wxEventType commandType = wxEVT_NULL, int winid = 0);
    clScrollEvent(const clScrollEvent& event);
    clScrollEvent& operator=(const clScrollEvent& src);
    virtual ~clScrollEvent();
    virtual wxEvent* Clone() const;
    void SetPosition(int position) { this->m_position = position; }
    int GetPosition() const { return m_position; }
};

typedef void (wxEvtHandler::*clScrollEventFunction)(clScrollEvent&);
#define clScrollEventHandler(func) wxEVENT_HANDLER_CAST(clScrollEventFunction, func)

class WXDLLIMPEXP_SDK clCustomScrollBar : public wxPanel
{
    double m_thumbSize = 0.0;
    double m_pageSize = 0.0;
    double m_range = 0.0;
    double m_thumbPosition = 0.0;
    long m_sbStyle = wxSB_VERTICAL;
    wxRect m_thumbRect;
    wxPoint m_mouseCapturePoint;
    wxPoint m_thumbCapturePoint;
    bool m_dragging = false;
    clColours m_colours;
    bool m_notifyScroll = false;

protected:
    void OnIdle(wxIdleEvent& event);
    void OnPaint(wxPaintEvent& e);
    void OnMouseLeftDown(wxMouseEvent& e);
    void OnMouseLeftUp(wxMouseEvent& e);
    void OnMotion(wxMouseEvent& e);
    void OnSize(wxSizeEvent& e);
    void UpdateDrag(const wxPoint& pt);
    int GetPositionFromPoint(const wxPoint& pt) const;

public:
    clCustomScrollBar(wxWindow* parent, wxWindowID id, const wxPoint& pos = wxDefaultPosition,
                      const wxSize& size = wxDefaultSize, long style = wxSB_VERTICAL);
    virtual ~clCustomScrollBar();

    bool ShouldShow() const;
    bool CanScollDown() const { return (GetThumbPosition() + GetThumbSize()) < GetRange(); }

    void SetPosition(int pos, bool notify = true);
    void UpdateScroll(int thumbSize, int range, int pageSize, int position);

    bool IsVertical() const { return m_sbStyle & wxSB_VERTICAL; }
    bool IsHorizontal() const { return m_sbStyle & wxSB_HORIZONTAL; }

    /// Accessors
    void SetPageSize(int pageSize) { this->m_pageSize = pageSize; }
    void SetRange(int range) { this->m_range = range; }
    void SetThumbPosition(int thumbPosition) { this->m_thumbPosition = thumbPosition; }
    void SetThumbSize(int thumbSize) { this->m_thumbSize = thumbSize; }
    int GetPageSize() const { return m_pageSize; }
    int GetRange() const { return m_range; }
    int GetThumbPosition() const { return m_thumbPosition; }
    int GetThumbSize() const { return m_thumbSize; }

    /// Override's parent
    virtual void SetColours(const clColours& colours);
};

wxDECLARE_EXPORTED_EVENT(WXDLLIMPEXP_SDK, wxEVT_CUSTOM_SCROLL, clScrollEvent);
#endif // CLCUSTOMSCROLLBAR_H

{'repo_name': 'eranif/codelite', 'stars': '1380', 'repo_language': 'C++', 'file_name': 'wx-config.project', 'mime_type': 'text/xml', 'hash': 6611881791650459168, 'source_dataset': 'data'}


// This file was procedurally generated from the following sources:
// - src/dstr-assignment/obj-prop-put-order.case
// - src/dstr-assignment/default/for-of.template
/*---
description: The AssignmentElements in an AssignmentElementList are evaluated in left- to-right order. (For..of statement)
esid: sec-for-in-and-for-of-statements-runtime-semantics-labelledevaluation
features: [destructuring-binding]
flags: [generated]
info: |
    IterationStatement :
      for ( LeftHandSideExpression of AssignmentExpression ) Statement

    1. Let keyResult be the result of performing ? ForIn/OfHeadEvaluation(« »,
       AssignmentExpression, iterate).
    2. Return ? ForIn/OfBodyEvaluation(LeftHandSideExpression, Statement,
       keyResult, assignment, labelSet).

    13.7.5.13 Runtime Semantics: ForIn/OfBodyEvaluation

    [...]
    4. If destructuring is true and if lhsKind is assignment, then
       a. Assert: lhs is a LeftHandSideExpression.
       b. Let assignmentPattern be the parse of the source text corresponding to
          lhs using AssignmentPattern as the goal symbol.
    [...]
---*/
var x;

var counter = 0;

for ({ z: x, a: x } of [{ a: 2, z: 1 }]) {
  assert.sameValue(x, 2);
  counter += 1;
}

assert.sameValue(counter, 1);

{'repo_name': 'tc39/test262', 'stars': '1439', 'repo_language': 'JavaScript', 'file_name': 'S11.8.4_A3.2_T1.1.js', 'mime_type': 'text/plain', 'hash': 4744829154167216611, 'source_dataset': 'data'}


                           Mesa 6.3.1 release notes

                               July XX, 2005

                              PLEASE READ!!!!

Introduction
------------

Mesa uses an even/odd version number scheme like the Linux kernel.
Odd numbered versions (such as 6.3) designate new developmental releases.
Even numbered versions (such as 6.2) designate stable releases.

DRI drivers
-----------

This release includes the DRI drivers and GLX code for hardware rendering.

Bug fixes
---------

Bugs fixed in 6.3.1 are listed in the VERSIONS file.

Driver			Status
----------------------	---------------------
XMesa (Xlib)		implements OpenGL 1.5
OSMesa (off-screen)	implements OpenGL 1.5
Glide (3dfx Voodoo1/2)	implements OpenGL 1.3
SVGA			implements OpenGL 1.3
Wind River UGL		implements OpenGL 1.3
Windows/Win32		implements OpenGL 1.5
DJGPP			implements OpenGL 1.5
GGI			implements OpenGL 1.3
BeOS			implements OpenGL 1.5
Allegro			needs updating
D3D			needs updating

----------------------------------------------------------------------

{'repo_name': 'yuq/mesa-lima', 'stars': '162', 'repo_language': 'C', 'file_name': 'i965.doxy', 'mime_type': 'text/plain', 'hash': 4398183284158210541, 'source_dataset': 'data'}


/*
 *     Generated by class-dump 3.3.4 (64 bit).
 *
 *     class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by Steve Nygard.
 */

#import "NSObject.h"

@class NSDictionary, NSMutableDictionary, NSNumber, UIImage, _UIBarButtonItemAppearanceStorage;

@interface _UINavigationBarAppearanceStorage : NSObject
{
    NSMutableDictionary *backgroundImagesForBarMetrics;
    NSDictionary *textAttributes;
    NSNumber *titleVerticalAdjustment;
    NSNumber *miniTitleVerticalAdjustment;
    UIImage *shadowImage;
    BOOL hidesShadow;
    BOOL reversesShadowOffset;
    _UIBarButtonItemAppearanceStorage *buttonAppearanceStorage;
    BOOL _deferShadowToSearchBar;
}

@property(nonatomic) BOOL deferShadowToSearchBar; // @synthesize deferShadowToSearchBar=_deferShadowToSearchBar;
@property(retain, nonatomic) UIImage *shadowImage; // @synthesize shadowImage;
@property(nonatomic) BOOL reversesShadowOffset; // @synthesize reversesShadowOffset;
@property(retain, nonatomic) NSNumber *miniTitleVerticalAdjustment; // @synthesize miniTitleVerticalAdjustment;
@property(retain, nonatomic) NSNumber *titleVerticalAdjustment; // @synthesize titleVerticalAdjustment;
@property(copy, nonatomic) NSDictionary *textAttributes; // @synthesize textAttributes;
@property(nonatomic) BOOL hidesShadow; // @synthesize hidesShadow;
- (void)dealloc;
@property(readonly, nonatomic) _UIBarButtonItemAppearanceStorage *barButtonAppearanceStorage;
@property(readonly, nonatomic) _UIBarButtonItemAppearanceStorage *_barButtonAppearanceStorage;
- (id)backgroundImageForBarMetrics:(int)arg1;
- (void)setBackgroundImage:(id)arg1 forBarMetrics:(int)arg2;
@property(readonly, nonatomic) UIImage *miniPromptBackgroundImage;
@property(readonly, nonatomic) UIImage *promptBackgroundImage;
@property(readonly, nonatomic) UIImage *miniBackgroundImage;
@property(readonly, nonatomic) UIImage *backgroundImage;

@end

{'repo_name': 'MP0w/iOS-Headers', 'stars': '405', 'repo_language': 'Objective-C', 'file_name': 'IMAVChat-IMAVChatAudioAdditions.h', 'mime_type': 'text/x-objective-c', 'hash': -348215375576026620, 'source_dataset': 'data'}


fn main() {
    let greetings = ["Hello", "Hola", "Bonjour",
                     "Ciao", "こんにちは", "안녕하세요",
                     "Cześć", "Olá", "Здравствуйте",
                     "Chào bạn", "您好", "Hallo",
                     "Hej", "Ahoj", "سلام","สวัสดี"];

    for (num, greeting) in greetings.iter().enumerate() {
        print!("{} : ", greeting);
        match num {
            0 =>  println!("This code is editable and runnable!"),
            1 =>  println!("¡Este código es editable y ejecutable!"),
            2 =>  println!("Ce code est modifiable et exécutable !"),
            3 =>  println!("Questo codice è modificabile ed eseguibile!"),
            4 =>  println!("このコードは編集して実行出来ます！"),
            5 =>  println!("여기에서 코드를 수정하고 실행할 수 있습니다!"),
            6 =>  println!("Ten kod można edytować oraz uruchomić!"),
            7 =>  println!("Este código é editável e executável!"),
            8 =>  println!("Этот код можно отредактировать и запустить!"),
            9 =>  println!("Bạn có thể edit và run code trực tiếp!"),
            10 => println!("这段代码是可以编辑并且能够运行的！"),
            11 => println!("Dieser Code kann bearbeitet und ausgeführt werden!"),
            12 => println!("Den här koden kan redigeras och köras!"),
            13 => println!("Tento kód můžete upravit a spustit"),
            14 => println!("این کد قابلیت ویرایش و اجرا دارد!"),
            15 => println!("โค้ดนี้สามารถแก้ไขได้และรันได้"),
            _ =>  {},
        }
    }
}

{'repo_name': 'rust-lang/prev.rust-lang.org', 'stars': '152', 'repo_language': 'HTML', 'file_name': 'contribute.md', 'mime_type': 'text/plain', 'hash': -2806980184942441113, 'source_dataset': 'data'}


import { PngPong, Palette } from '../';
import { RGB } from '../util/color-types';

interface RectangleDraw {
    x1: number;
    x2: number;
    y1: number;
    y2: number;
    color: RGB;
}

/**
 * A transformer to draw basic shapes onto an image. Currently only draws rectangles.
 *
 * @export
 * @class PngPongShapeTransformer
 */
export class PngPongShapeTransformer {

    private operations: RectangleDraw[] = [];
    private operationPaletteIndexes: number[] = [];
    private imageWidth: number;

    /**
     * Creates an instance of PngPongShapeTransformer.
     * @param {PngPong} baseTransformer - the transformer you want to draw onto.
     *
     * @memberof PngPongShapeTransformer
     */
    constructor(private baseTransformer: PngPong) {

        baseTransformer.onHeader((h) => {
            this.imageWidth = h.width;
        })
        baseTransformer.onPalette(this.onPalette.bind(this));
        baseTransformer.onData(this.onData.bind(this));

    }

    private onPalette(palette: Palette) {

        this.operationPaletteIndexes = this.operations.map((o) => {

            let idx = palette.getColorIndex(o.color);

            if (idx === -1) {
                idx = palette.addColor(o.color);
            }

            return idx;
        })

    }

    private onData(array: Uint8Array, readOffset: number, x: number, y: number, length: number) {

        for (let idx = 0; idx < this.operations.length; idx++) {
            let o = this.operations[idx];
            if (y < o.y1 || y >= o.y2) {
                continue;
            }

            for (let i = Math.max(x, o.x1); i < Math.min(o.x2, x + length); i++) {
                array[readOffset - x + i] = this.operationPaletteIndexes[idx];
            }
        }

    }

    /**
     * Add a rectangle to the list of draw operations. Must use this before running PngPong.run()
     *
     * @param {number} x
     * @param {number} y
     * @param {number} width
     * @param {number} height
     * @param {RGB} color
     *
     * @memberof PngPongShapeTransformer
     */
    drawRect(x: number, y: number, width: number, height: number, color: RGB) {

        let x2 = x + width;
        let y2 = y + height;

        this.operations.push({
            x1: x,
            x2,
            y1: y,
            y2,
            color
        });

    }

}

{'repo_name': 'gdnmobilelab/png-pong', 'stars': '185', 'repo_language': 'TypeScript', 'file_name': 'pre-header.ts', 'mime_type': 'text/x-java', 'hash': 5272711306800241692, 'source_dataset': 'data'}


import { Component, OnInit } from '@angular/core';

interface ImageItem {
  id: number;
  url: string;
  show: boolean;
}
@Component({
  selector: 'ngx-viewport',
  templateUrl: './viewport.component.html',
  styleUrls: ['./viewport.component.scss'],
})
export class ViewportComponent implements OnInit {
  // prettier-ignore
  // tslint:disable:max-line-length
  imageItemCollection: ImageItem[] = [
    {
      id: 1,
      url: 'https://images.unsplash.com/photo-1512672378591-74fbb56b1d28?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=111881731843c98860fd6ede341337d7&auto=format&fit=crop&w=1350&q=80',
      show: false,
    },
    {
      id: 2,
      url: 'https://images.unsplash.com/photo-1486495939893-f384c2860f55?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=bf36a4694839666ab094bcdd0bb88651&auto=format&fit=crop&w=1350&q=80',
      show: false,
    },
    {
      id: 3,
      url: 'https://images.unsplash.com/photo-1514913274516-4aa04f176f8c?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=a6940b0c53d64fc564bed31bb6aa8d9b&auto=format&fit=crop&w=1760&q=80',
      show: false,
    },
    {
      id: 4,
      url: 'https://images.unsplash.com/photo-1523286877159-d9636545890c?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=f44497f72d77b9e8e27e87521e025edc&auto=format&fit=crop&w=1351&q=80',
      show: false,
    },
    {
      id: 5,
      url: 'https://images.unsplash.com/photo-1459886757952-87e191b82aeb?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=6c977d9f0c074c220a31f1e89449c3aa&auto=format&fit=crop&w=1350&q=80',
      show: false,
    },
    {
      id: 6,
      url: 'https://images.unsplash.com/photo-1519423961530-9131478718db?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=e6132d79c5060ba00caa99cf39457da6&auto=format&fit=crop&w=1350&q=80',
      show: false,
    },
    {
      id: 7,
      url: 'https://images.unsplash.com/photo-1482510356941-d087154c2931?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=cd6c067c548407960ec92f1e820775ee&auto=format&fit=crop&w=1355&q=80',
      show: false,
    },
    {
      id: 8,
      url: 'https://images.unsplash.com/photo-1520507215037-061ed0f37178?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=0b0ee4f4dcd684859da448cc26c707a2&auto=format&fit=crop&w=1350&q=80',
      show: false,
    },
    {
      id: 9,
      url: 'https://images.unsplash.com/photo-1522447984233-657d56c465d8?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=b2efa4e73b38094995897590487ba5b4&auto=format&fit=crop&w=1350&q=80',
      show: false,
    },
  ];

  constructor() {}

  ngOnInit() {}

  get totalImagesShown(): number {
    return (this.imageItemCollection.filter(imageItem => imageItem.show) || []).length;
  }

  show(event: Partial<IntersectionObserverEntry>, image: ImageItem) {
    if (event.intersectionRatio >= 0.5) {
      image.show = true;
      console.log(
        `in-view ==> image: ${image.id}, intersectionRatio: ${event.intersectionRatio}, isIntersecting: ${
          event.isIntersecting
        }`,
      );
    } else {
      console.log(
        `out-of-view <== image: ${image.id}, intersectionRatio: ${event.intersectionRatio}, isIntersecting: ${
          event.isIntersecting
        }`,
      );
    }
  }

  anim(event: Partial<IntersectionObserverEntry>, element: string) {
    console.log(
      `anim: ${element} intersectionRatio: ${event.intersectionRatio}, isIntersecting: ${event.isIntersecting}`,
    );
    if (event.intersectionRatio >= 0.5) {
      event.target.classList.add('fancy');
    } else {
      event.target.classList.remove('fancy');
    }
  }
}

{'repo_name': 'xmlking/ngx-starter-kit', 'stars': '425', 'repo_language': 'TypeScript', 'file_name': 'format-time-in-words.pipe.ts', 'mime_type': 'text/x-java', 'hash': -4310745540872049413, 'source_dataset': 'data'}


/*
---------------------------------------------------------------------------
Open Asset Import Library (assimp)
---------------------------------------------------------------------------

Copyright (c) 2006-2019, assimp team

All rights reserved.

Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:

* Redistributions of source code must retain the above
  copyright notice, this list of conditions and the
  following disclaimer.

* Redistributions in binary form must reproduce the above
  copyright notice, this list of conditions and the
  following disclaimer in the documentation and/or other
  materials provided with the distribution.

* Neither the name of the assimp team, nor the names of its
  contributors may be used to endorse or promote products
  derived from this software without specific prior
  written permission of the assimp team.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/

/** @file Implementation of the AC3D importer class */

#ifndef ASSIMP_BUILD_NO_AC_IMPORTER

// internal headers
#include "ACLoader.h"
#include <assimp/ParsingUtils.h>
#include <assimp/fast_atof.h>
#include <assimp/Subdivision.h>
#include "Common/Importer.h"
#include <assimp/BaseImporter.h>
#include <assimp/Importer.hpp>
#include <assimp/light.h>
#include <assimp/DefaultLogger.hpp>
#include <assimp/material.h>
#include <assimp/scene.h>
#include <assimp/config.h>
#include <assimp/IOSystem.hpp>
#include <assimp/importerdesc.h>
#include <memory>

using namespace Assimp;

static const aiImporterDesc desc = {
    "AC3D Importer",
    "",
    "",
    "",
    aiImporterFlags_SupportTextFlavour,
    0,
    0,
    0,
    0,
    "ac acc ac3d"
};

// ------------------------------------------------------------------------------------------------
// skip to the next token
#define AI_AC_SKIP_TO_NEXT_TOKEN() \
    if (!SkipSpaces(&buffer)) \
    { \
        ASSIMP_LOG_ERROR("AC3D: Unexpected EOF/EOL"); \
        continue; \
    }

// ------------------------------------------------------------------------------------------------
// read a string (may be enclosed in double quotation marks). buffer must point to "
#define AI_AC_GET_STRING(out) \
    if (*buffer == '\0') { \
        throw DeadlyImportError("AC3D: Unexpected EOF in string"); \
    } \
    ++buffer; \
    const char* sz = buffer; \
    while ('\"' != *buffer) \
    { \
        if (IsLineEnd( *buffer )) \
        { \
            ASSIMP_LOG_ERROR("AC3D: Unexpected EOF/EOL in string"); \
            out = "ERROR"; \
            break; \
        } \
        ++buffer; \
    } \
    if (IsLineEnd( *buffer ))continue; \
    out = std::string(sz,(unsigned int)(buffer-sz)); \
    ++buffer;

// ------------------------------------------------------------------------------------------------
// read 1 to n floats prefixed with an optional predefined identifier
#define AI_AC_CHECKED_LOAD_FLOAT_ARRAY(name,name_length,num,out) \
    AI_AC_SKIP_TO_NEXT_TOKEN(); \
    if (name_length) \
    { \
        if (strncmp(buffer,name,name_length) || !IsSpace(buffer[name_length])) \
        { \
            ASSIMP_LOG_ERROR("AC3D: Unexpexted token. " name " was expected."); \
            continue; \
        } \
        buffer += name_length+1; \
    } \
    for (unsigned int i = 0; i < num;++i) \
    { \
        AI_AC_SKIP_TO_NEXT_TOKEN(); \
        buffer = fast_atoreal_move<float>(buffer,((float*)out)[i]); \
    }

// ------------------------------------------------------------------------------------------------
// Constructor to be privately used by Importer
AC3DImporter::AC3DImporter()
    : buffer(),
    configSplitBFCull(),
    configEvalSubdivision(),
    mNumMeshes(),
    mLights(),
    lights(),
    groups(),
    polys(),
    worlds()
{
    // nothing to be done here
}

// ------------------------------------------------------------------------------------------------
// Destructor, private as well
AC3DImporter::~AC3DImporter()
{
    // nothing to be done here
}

// ------------------------------------------------------------------------------------------------
// Returns whether the class can handle the format of the given file.
bool AC3DImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
{
    std::string extension = GetExtension(pFile);

    // fixme: are acc and ac3d *really* used? Some sources say they are
    if(extension == "ac" || extension == "ac3d" || extension == "acc") {
        return true;
    }
    if (!extension.length() || checkSig) {
        uint32_t token = AI_MAKE_MAGIC("AC3D");
        return CheckMagicToken(pIOHandler,pFile,&token,1,0);
    }
    return false;
}

// ------------------------------------------------------------------------------------------------
// Loader meta information
const aiImporterDesc* AC3DImporter::GetInfo () const
{
    return &desc;
}

// ------------------------------------------------------------------------------------------------
// Get a pointer to the next line from the file
bool AC3DImporter::GetNextLine( )
{
    SkipLine(&buffer);
    return SkipSpaces(&buffer);
}

// ------------------------------------------------------------------------------------------------
// Parse an object section in an AC file
void AC3DImporter::LoadObjectSection(std::vector<Object>& objects)
{
    if (!TokenMatch(buffer,"OBJECT",6))
        return;

    SkipSpaces(&buffer);

    ++mNumMeshes;

    objects.push_back(Object());
    Object& obj = objects.back();

    aiLight* light = NULL;
    if (!ASSIMP_strincmp(buffer,"light",5))
    {
        // This is a light source. Add it to the list
        mLights->push_back(light = new aiLight());

        // Return a point light with no attenuation
        light->mType = aiLightSource_POINT;
        light->mColorDiffuse = light->mColorSpecular = aiColor3D(1.f,1.f,1.f);
        light->mAttenuationConstant = 1.f;

        // Generate a default name for both the light source and the node
        // FIXME - what's the right way to print a size_t? Is 'zu' universally available? stick with the safe version.
        light->mName.length = ::ai_snprintf(light->mName.data, MAXLEN, "ACLight_%i",static_cast<unsigned int>(mLights->size())-1);
        obj.name = std::string( light->mName.data );

        ASSIMP_LOG_DEBUG("AC3D: Light source encountered");
        obj.type = Object::Light;
    }
    else if (!ASSIMP_strincmp(buffer,"group",5))
    {
        obj.type = Object::Group;
    }
    else if (!ASSIMP_strincmp(buffer,"world",5))
    {
        obj.type = Object::World;
    }
    else obj.type = Object::Poly;
    while (GetNextLine())
    {
        if (TokenMatch(buffer,"kids",4))
        {
            SkipSpaces(&buffer);
            unsigned int num = strtoul10(buffer,&buffer);
            GetNextLine();
            if (num)
            {
                // load the children of this object recursively
                obj.children.reserve(num);
                for (unsigned int i = 0; i < num; ++i)
                    LoadObjectSection(obj.children);
            }
            return;
        }
        else if (TokenMatch(buffer,"name",4))
        {
            SkipSpaces(&buffer);
            AI_AC_GET_STRING(obj.name);

            // If this is a light source, we'll also need to store
            // the name of the node in it.
            if (light)
            {
                light->mName.Set(obj.name);
            }
        }
        else if (TokenMatch(buffer,"texture",7))
        {
            SkipSpaces(&buffer);
            AI_AC_GET_STRING(obj.texture);
        }
        else if (TokenMatch(buffer,"texrep",6))
        {
            SkipSpaces(&buffer);
            AI_AC_CHECKED_LOAD_FLOAT_ARRAY("",0,2,&obj.texRepeat);
            if (!obj.texRepeat.x || !obj.texRepeat.y)
                obj.texRepeat = aiVector2D (1.f,1.f);
        }
        else if (TokenMatch(buffer,"texoff",6))
        {
            SkipSpaces(&buffer);
            AI_AC_CHECKED_LOAD_FLOAT_ARRAY("",0,2,&obj.texOffset);
        }
        else if (TokenMatch(buffer,"rot",3))
        {
            SkipSpaces(&buffer);
            AI_AC_CHECKED_LOAD_FLOAT_ARRAY("",0,9,&obj.rotation);
        }
        else if (TokenMatch(buffer,"loc",3))
        {
            SkipSpaces(&buffer);
            AI_AC_CHECKED_LOAD_FLOAT_ARRAY("",0,3,&obj.translation);
        }
        else if (TokenMatch(buffer,"subdiv",6))
        {
            SkipSpaces(&buffer);
            obj.subDiv = strtoul10(buffer,&buffer);
        }
        else if (TokenMatch(buffer,"crease",6))
        {
            SkipSpaces(&buffer);
            obj.crease = fast_atof(buffer);
        }
        else if (TokenMatch(buffer,"numvert",7))
        {
            SkipSpaces(&buffer);

            unsigned int t = strtoul10(buffer,&buffer);
            if (t >= AI_MAX_ALLOC(aiVector3D)) {
                throw DeadlyImportError("AC3D: Too many vertices, would run out of memory");
            }
            obj.vertices.reserve(t);
            for (unsigned int i = 0; i < t;++i)
            {
                if (!GetNextLine())
                {
                    ASSIMP_LOG_ERROR("AC3D: Unexpected EOF: not all vertices have been parsed yet");
                    break;
                }
                else if (!IsNumeric(*buffer))
                {
                    ASSIMP_LOG_ERROR("AC3D: Unexpected token: not all vertices have been parsed yet");
                    --buffer; // make sure the line is processed a second time
                    break;
                }
                obj.vertices.push_back(aiVector3D());
                aiVector3D& v = obj.vertices.back();
                AI_AC_CHECKED_LOAD_FLOAT_ARRAY("",0,3,&v.x);
            }
        }
        else if (TokenMatch(buffer,"numsurf",7))
        {
            SkipSpaces(&buffer);

            bool Q3DWorkAround = false;

            const unsigned int t = strtoul10(buffer,&buffer);
            obj.surfaces.reserve(t);
            for (unsigned int i = 0; i < t;++i)
            {
                GetNextLine();
                if (!TokenMatch(buffer,"SURF",4))
                {
                    // FIX: this can occur for some files - Quick 3D for
                    // example writes no surf chunks
                    if (!Q3DWorkAround)
                    {
                        ASSIMP_LOG_WARN("AC3D: SURF token was expected");
                        ASSIMP_LOG_DEBUG("Continuing with Quick3D Workaround enabled");
                    }
                    --buffer; // make sure the line is processed a second time
                    // break; --- see fix notes above

                    Q3DWorkAround = true;
                }
                SkipSpaces(&buffer);
                obj.surfaces.push_back(Surface());
                Surface& surf = obj.surfaces.back();
                surf.flags = strtoul_cppstyle(buffer);

                while (1)
                {
                    if(!GetNextLine())
                    {
                        throw DeadlyImportError("AC3D: Unexpected EOF: surface is incomplete");
                    }
                    if (TokenMatch(buffer,"mat",3))
                    {
                        SkipSpaces(&buffer);
                        surf.mat = strtoul10(buffer);
                    }
                    else if (TokenMatch(buffer,"refs",4))
                    {
                        // --- see fix notes above
                        if (Q3DWorkAround)
                        {
                            if (!surf.entries.empty())
                            {
                                buffer -= 6;
                                break;
                            }
                        }

                        SkipSpaces(&buffer);
                        const unsigned int m = strtoul10(buffer);
                        surf.entries.reserve(m);

                        obj.numRefs += m;

                        for (unsigned int k = 0; k < m; ++k)
                        {
                            if(!GetNextLine())
                            {
                                ASSIMP_LOG_ERROR("AC3D: Unexpected EOF: surface references are incomplete");
                                break;
                            }
                            surf.entries.push_back(Surface::SurfaceEntry());
                            Surface::SurfaceEntry& entry = surf.entries.back();

                            entry.first = strtoul10(buffer,&buffer);
                            SkipSpaces(&buffer);
                            AI_AC_CHECKED_LOAD_FLOAT_ARRAY("",0,2,&entry.second);
                        }
                    }
                    else
                    {

                        --buffer; // make sure the line is processed a second time
                        break;
                    }
                }
            }
        }
    }
    ASSIMP_LOG_ERROR("AC3D: Unexpected EOF: \'kids\' line was expected");
}

// ------------------------------------------------------------------------------------------------
// Convert a material from AC3DImporter::Material to aiMaterial
void AC3DImporter::ConvertMaterial(const Object& object,
    const Material& matSrc,
    aiMaterial& matDest)
{
    aiString s;

    if (matSrc.name.length())
    {
        s.Set(matSrc.name);
        matDest.AddProperty(&s,AI_MATKEY_NAME);
    }
    if (object.texture.length())
    {
        s.Set(object.texture);
        matDest.AddProperty(&s,AI_MATKEY_TEXTURE_DIFFUSE(0));

        // UV transformation
        if (1.f != object.texRepeat.x || 1.f != object.texRepeat.y ||
            object.texOffset.x        || object.texOffset.y)
        {
            aiUVTransform transform;
            transform.mScaling = object.texRepeat;
            transform.mTranslation = object.texOffset;
            matDest.AddProperty(&transform,1,AI_MATKEY_UVTRANSFORM_DIFFUSE(0));
        }
    }

    matDest.AddProperty<aiColor3D>(&matSrc.rgb,1, AI_MATKEY_COLOR_DIFFUSE);
    matDest.AddProperty<aiColor3D>(&matSrc.amb,1, AI_MATKEY_COLOR_AMBIENT);
    matDest.AddProperty<aiColor3D>(&matSrc.emis,1,AI_MATKEY_COLOR_EMISSIVE);
    matDest.AddProperty<aiColor3D>(&matSrc.spec,1,AI_MATKEY_COLOR_SPECULAR);

    int n;
    if (matSrc.shin)
    {
        n = aiShadingMode_Phong;
        matDest.AddProperty<float>(&matSrc.shin,1,AI_MATKEY_SHININESS);
    }
    else n = aiShadingMode_Gouraud;
    matDest.AddProperty<int>(&n,1,AI_MATKEY_SHADING_MODEL);

    float f = 1.f - matSrc.trans;
    matDest.AddProperty<float>(&f,1,AI_MATKEY_OPACITY);
}

// ------------------------------------------------------------------------------------------------
// Converts the loaded data to the internal verbose representation
aiNode* AC3DImporter::ConvertObjectSection(Object& object,
    std::vector<aiMesh*>& meshes,
    std::vector<aiMaterial*>& outMaterials,
    const std::vector<Material>& materials,
    aiNode* parent)
{
    aiNode* node = new aiNode();
    node->mParent = parent;
    if (object.vertices.size())
    {
        if (!object.surfaces.size() || !object.numRefs)
        {
            /* " An object with 7 vertices (no surfaces, no materials defined).
                 This is a good way of getting point data into AC3D.
                 The Vertex->create convex-surface/object can be used on these
                 vertices to 'wrap' a 3d shape around them "
                 (http://www.opencity.info/html/ac3dfileformat.html)

                 therefore: if no surfaces are defined return point data only
             */

            ASSIMP_LOG_INFO("AC3D: No surfaces defined in object definition, "
                "a point list is returned");

            meshes.push_back(new aiMesh());
            aiMesh* mesh = meshes.back();

            mesh->mNumFaces = mesh->mNumVertices = (unsigned int)object.vertices.size();
            aiFace* faces = mesh->mFaces = new aiFace[mesh->mNumFaces];
            aiVector3D* verts = mesh->mVertices = new aiVector3D[mesh->mNumVertices];

            for (unsigned int i = 0; i < mesh->mNumVertices;++i,++faces,++verts)
            {
                *verts = object.vertices[i];
                faces->mNumIndices = 1;
                faces->mIndices = new unsigned int[1];
                faces->mIndices[0] = i;
            }

            // use the primary material in this case. this should be the
            // default material if all objects of the file contain points
            // and no faces.
            mesh->mMaterialIndex = 0;
            outMaterials.push_back(new aiMaterial());
            ConvertMaterial(object, materials[0], *outMaterials.back());
        }
        else
        {
            // need to generate one or more meshes for this object.
            // find out how many different materials we have
            typedef std::pair< unsigned int, unsigned int > IntPair;
            typedef std::vector< IntPair > MatTable;
            MatTable needMat(materials.size(),IntPair(0,0));

            std::vector<Surface>::iterator it,end = object.surfaces.end();
            std::vector<Surface::SurfaceEntry>::iterator it2,end2;

            for (it = object.surfaces.begin(); it != end; ++it)
            {
                unsigned int idx = (*it).mat;
                if (idx >= needMat.size())
                {
                    ASSIMP_LOG_ERROR("AC3D: material index is out of range");
                    idx = 0;
                }
                if ((*it).entries.empty())
                {
                    ASSIMP_LOG_WARN("AC3D: surface her zero vertex references");
                }

                // validate all vertex indices to make sure we won't crash here
                for (it2  = (*it).entries.begin(),
                     end2 = (*it).entries.end(); it2 != end2; ++it2)
                {
                    if ((*it2).first >= object.vertices.size())
                    {
                        ASSIMP_LOG_WARN("AC3D: Invalid vertex reference");
                        (*it2).first = 0;
                    }
                }

                if (!needMat[idx].first)++node->mNumMeshes;

                switch ((*it).flags & 0xf)
                {
                    // closed line
                case 0x1:

                    needMat[idx].first  += (unsigned int)(*it).entries.size();
                    needMat[idx].second += (unsigned int)(*it).entries.size()<<1u;
                    break;

                    // unclosed line
                case 0x2:

                    needMat[idx].first  += (unsigned int)(*it).entries.size()-1;
                    needMat[idx].second += ((unsigned int)(*it).entries.size()-1)<<1u;
                    break;

                    // 0 == polygon, else unknown
                default:

                    if ((*it).flags & 0xf)
                    {
                        ASSIMP_LOG_WARN("AC3D: The type flag of a surface is unknown");
                        (*it).flags &= ~(0xf);
                    }

                    // the number of faces increments by one, the number
                    // of vertices by surface.numref.
                    needMat[idx].first++;
                    needMat[idx].second += (unsigned int)(*it).entries.size();
                };
            }
            unsigned int* pip = node->mMeshes = new unsigned int[node->mNumMeshes];
            unsigned int mat = 0;
            const size_t oldm = meshes.size();
            for (MatTable::const_iterator cit = needMat.begin(), cend = needMat.end();
                cit != cend; ++cit, ++mat)
            {
                if (!(*cit).first)continue;

                // allocate a new aiMesh object
                *pip++ = (unsigned int)meshes.size();
                aiMesh* mesh = new aiMesh();
                meshes.push_back(mesh);

                mesh->mMaterialIndex = (unsigned int)outMaterials.size();
                outMaterials.push_back(new aiMaterial());
                ConvertMaterial(object, materials[mat], *outMaterials.back());

                // allocate storage for vertices and normals
                mesh->mNumFaces = (*cit).first;
                if (mesh->mNumFaces == 0) {
                    throw DeadlyImportError("AC3D: No faces");
                } else if (mesh->mNumFaces > AI_MAX_ALLOC(aiFace)) {
                    throw DeadlyImportError("AC3D: Too many faces, would run out of memory");
                }
                aiFace* faces = mesh->mFaces = new aiFace[mesh->mNumFaces];

                mesh->mNumVertices = (*cit).second;
                if (mesh->mNumVertices == 0) {
                    throw DeadlyImportError("AC3D: No vertices");
                } else if (mesh->mNumVertices > AI_MAX_ALLOC(aiVector3D)) {
                    throw DeadlyImportError("AC3D: Too many vertices, would run out of memory");
                }
                aiVector3D* vertices = mesh->mVertices = new aiVector3D[mesh->mNumVertices];
                unsigned int cur = 0;

                // allocate UV coordinates, but only if the texture name for the
                // surface is not empty
                aiVector3D* uv = NULL;
                if(object.texture.length())
                {
                    uv = mesh->mTextureCoords[0] = new aiVector3D[mesh->mNumVertices];
                    mesh->mNumUVComponents[0] = 2;
                }

                for (it = object.surfaces.begin(); it != end; ++it)
                {
                    if (mat == (*it).mat)
                    {
                        const Surface& src = *it;

                        // closed polygon
                        unsigned int type = (*it).flags & 0xf;
                        if (!type)
                        {
                            aiFace& face = *faces++;
                            if((face.mNumIndices = (unsigned int)src.entries.size()))
                            {
                                face.mIndices = new unsigned int[face.mNumIndices];
                                for (unsigned int i = 0; i < face.mNumIndices;++i,++vertices)
                                {
                                    const Surface::SurfaceEntry& entry = src.entries[i];
                                    face.mIndices[i] = cur++;

                                    // copy vertex positions
                                    if (static_cast<unsigned>(vertices - mesh->mVertices) >= mesh->mNumVertices) {
                                        throw DeadlyImportError("AC3D: Invalid number of vertices");
                                    }
                                    *vertices = object.vertices[entry.first] + object.translation;

                                    // copy texture coordinates
                                    if (uv)
                                    {
                                        uv->x =  entry.second.x;
                                        uv->y =  entry.second.y;
                                        ++uv;
                                    }
                                }
                            }
                        }
                        else
                        {

                            it2  = (*it).entries.begin();

                            // either a closed or an unclosed line
                            unsigned int tmp = (unsigned int)(*it).entries.size();
                            if (0x2 == type)--tmp;
                            for (unsigned int m = 0; m < tmp;++m)
                            {
                                aiFace& face = *faces++;

                                face.mNumIndices = 2;
                                face.mIndices = new unsigned int[2];
                                face.mIndices[0] = cur++;
                                face.mIndices[1] = cur++;

                                // copy vertex positions
                                if (it2 == (*it).entries.end() ) {
                                    throw DeadlyImportError("AC3D: Bad line");
                                }
                                ai_assert((*it2).first < object.vertices.size());
                                *vertices++ = object.vertices[(*it2).first];

                                // copy texture coordinates
                                if (uv)
                                {
                                    uv->x =  (*it2).second.x;
                                    uv->y =  (*it2).second.y;
                                    ++uv;
                                }

                                if (0x1 == type && tmp-1 == m)
                                {
                                    // if this is a closed line repeat its beginning now
                                    it2  = (*it).entries.begin();
                                }
                                else ++it2;

                                // second point
                                *vertices++ = object.vertices[(*it2).first];

                                if (uv)
                                {
                                    uv->x =  (*it2).second.x;
                                    uv->y =  (*it2).second.y;
                                    ++uv;
                                }
                            }
                        }
                    }
                }
            }

            // Now apply catmull clark subdivision if necessary. We split meshes into
            // materials which is not done by AC3D during smoothing, so we need to
            // collect all meshes using the same material group.
            if (object.subDiv)  {
                if (configEvalSubdivision) {
                    std::unique_ptr<Subdivider> div(Subdivider::Create(Subdivider::CATMULL_CLARKE));
                    ASSIMP_LOG_INFO("AC3D: Evaluating subdivision surface: "+object.name);

                    std::vector<aiMesh*> cpy(meshes.size()-oldm,NULL);
                    div->Subdivide(&meshes[oldm],cpy.size(),&cpy.front(),object.subDiv,true);
                    std::copy(cpy.begin(),cpy.end(),meshes.begin()+oldm);

                    // previous meshes are deleted vy Subdivide().
                }
                else {
                    ASSIMP_LOG_INFO("AC3D: Letting the subdivision surface untouched due to my configuration: "
                        +object.name);
                }
            }
        }
    }

    if (object.name.length())
        node->mName.Set(object.name);
    else
    {
        // generate a name depending on the type of the node
        switch (object.type)
        {
        case Object::Group:
            node->mName.length = ::ai_snprintf(node->mName.data, MAXLEN, "ACGroup_%i",groups++);
            break;
        case Object::Poly:
            node->mName.length = ::ai_snprintf(node->mName.data, MAXLEN, "ACPoly_%i",polys++);
            break;
        case Object::Light:
            node->mName.length = ::ai_snprintf(node->mName.data, MAXLEN, "ACLight_%i",lights++);
            break;

            // there shouldn't be more than one world, but we don't care
        case Object::World:
            node->mName.length = ::ai_snprintf(node->mName.data, MAXLEN, "ACWorld_%i",worlds++);
            break;
        }
    }

    // setup the local transformation matrix of the object
    // compute the transformation offset to the parent node
    node->mTransformation = aiMatrix4x4 ( object.rotation );

    if (object.type == Object::Group || !object.numRefs)
    {
        node->mTransformation.a4 = object.translation.x;
        node->mTransformation.b4 = object.translation.y;
        node->mTransformation.c4 = object.translation.z;
    }

    // add children to the object
    if (object.children.size())
    {
        node->mNumChildren = (unsigned int)object.children.size();
        node->mChildren = new aiNode*[node->mNumChildren];
        for (unsigned int i = 0; i < node->mNumChildren;++i)
        {
            node->mChildren[i] = ConvertObjectSection(object.children[i],meshes,outMaterials,materials,node);
        }
    }

    return node;
}

// ------------------------------------------------------------------------------------------------
void AC3DImporter::SetupProperties(const Importer* pImp)
{
    configSplitBFCull = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_AC_SEPARATE_BFCULL,1) ? true : false;
    configEvalSubdivision =  pImp->GetPropertyInteger(AI_CONFIG_IMPORT_AC_EVAL_SUBDIVISION,1) ? true : false;
}

// ------------------------------------------------------------------------------------------------
// Imports the given file into the given scene structure.
void AC3DImporter::InternReadFile( const std::string& pFile,
    aiScene* pScene, IOSystem* pIOHandler)
{
    std::unique_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));

    // Check whether we can read from the file
    if( file.get() == NULL)
        throw DeadlyImportError( "Failed to open AC3D file " + pFile + ".");

    // allocate storage and copy the contents of the file to a memory buffer
    std::vector<char> mBuffer2;
    TextFileToBuffer(file.get(),mBuffer2);

    buffer = &mBuffer2[0];
    mNumMeshes = 0;

    lights = polys = worlds = groups = 0;

    if (::strncmp(buffer,"AC3D",4)) {
        throw DeadlyImportError("AC3D: No valid AC3D file, magic sequence not found");
    }

    // print the file format version to the console
    unsigned int version = HexDigitToDecimal( buffer[4] );
    char msg[3];
    ASSIMP_itoa10(msg,3,version);
    ASSIMP_LOG_INFO_F("AC3D file format version: ", msg);

    std::vector<Material> materials;
    materials.reserve(5);

    std::vector<Object> rootObjects;
    rootObjects.reserve(5);

    std::vector<aiLight*> lights;
    mLights = & lights;

    while (GetNextLine())
    {
        if (TokenMatch(buffer,"MATERIAL",8))
        {
            materials.push_back(Material());
            Material& mat = materials.back();

            // manually parse the material ... sscanf would use the buldin atof ...
            // Format: (name) rgb %f %f %f  amb %f %f %f  emis %f %f %f  spec %f %f %f  shi %d  trans %f

            AI_AC_SKIP_TO_NEXT_TOKEN();
            if ('\"' == *buffer)
            {
                AI_AC_GET_STRING(mat.name);
                AI_AC_SKIP_TO_NEXT_TOKEN();
            }

            AI_AC_CHECKED_LOAD_FLOAT_ARRAY("rgb",3,3,&mat.rgb);
            AI_AC_CHECKED_LOAD_FLOAT_ARRAY("amb",3,3,&mat.amb);
            AI_AC_CHECKED_LOAD_FLOAT_ARRAY("emis",4,3,&mat.emis);
            AI_AC_CHECKED_LOAD_FLOAT_ARRAY("spec",4,3,&mat.spec);
            AI_AC_CHECKED_LOAD_FLOAT_ARRAY("shi",3,1,&mat.shin);
            AI_AC_CHECKED_LOAD_FLOAT_ARRAY("trans",5,1,&mat.trans);
        }
        LoadObjectSection(rootObjects);
    }

    if (rootObjects.empty() || !mNumMeshes)
    {
        throw DeadlyImportError("AC3D: No meshes have been loaded");
    }
    if (materials.empty())
    {
        ASSIMP_LOG_WARN("AC3D: No material has been found");
        materials.push_back(Material());
    }

    mNumMeshes += (mNumMeshes>>2u) + 1;
    std::vector<aiMesh*> meshes;
    meshes.reserve(mNumMeshes);

    std::vector<aiMaterial*> omaterials;
    materials.reserve(mNumMeshes);

    // generate a dummy root if there are multiple objects on the top layer
    Object* root;
    if (1 == rootObjects.size())
        root = &rootObjects[0];
    else
    {
        root = new Object();
    }

    // now convert the imported stuff to our output data structure
    pScene->mRootNode = ConvertObjectSection(*root,meshes,omaterials,materials);
    if (1 != rootObjects.size())delete root;

    if (!::strncmp( pScene->mRootNode->mName.data, "Node", 4))
        pScene->mRootNode->mName.Set("<AC3DWorld>");

    // copy meshes
    if (meshes.empty())
    {
        throw DeadlyImportError("An unknown error occurred during converting");
    }
    pScene->mNumMeshes = (unsigned int)meshes.size();
    pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
    ::memcpy(pScene->mMeshes,&meshes[0],pScene->mNumMeshes*sizeof(void*));

    // copy materials
    pScene->mNumMaterials = (unsigned int)omaterials.size();
    pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials];
    ::memcpy(pScene->mMaterials,&omaterials[0],pScene->mNumMaterials*sizeof(void*));

    // copy lights
    pScene->mNumLights = (unsigned int)lights.size();
    if (lights.size())
    {
        pScene->mLights = new aiLight*[lights.size()];
        ::memcpy(pScene->mLights,&lights[0],lights.size()*sizeof(void*));
    }
}

#endif //!defined ASSIMP_BUILD_NO_AC_IMPORTER

{'repo_name': 'ultimatepp/ultimatepp', 'stars': '172', 'repo_language': 'C++', 'file_name': 'GrabYourScreen.upp', 'mime_type': 'text/plain', 'hash': 4583892554087823544, 'source_dataset': 'data'}


/*
 *  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.
 */
package org.codehaus.groovy.runtime;

import groovy.lang.EmptyRange;
import groovy.lang.IntRange;
import groovy.lang.NumberRange;
import groovy.lang.Range;
import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation;

import java.io.Closeable;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.lang.reflect.Array;
import java.nio.charset.Charset;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Properties;
import java.util.Queue;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Vector;
import java.util.WeakHashMap;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.logging.Logger;

/**
 * Support methods for DefaultGroovyMethods and PluginDefaultMethods.
 */
public class DefaultGroovyMethodsSupport {

    private static final Logger LOG = Logger.getLogger(DefaultGroovyMethodsSupport.class.getName());
    private static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];

    // helper method for getAt and putAt
    protected static RangeInfo subListBorders(int size, Range range) {
        if (range instanceof IntRange) {
            return ((IntRange) range).subListBorders(size);
        }
        if (range instanceof NumberRange) {
            return ((NumberRange) range).subListBorders(size);
        }
        int from = normaliseIndex(DefaultTypeTransformation.intUnbox(range.getFrom()), size);
        int to = normaliseIndex(DefaultTypeTransformation.intUnbox(range.getTo()), size);
        boolean reverse = range.isReverse();
        if (from > to) {
            // support list[1..-1]
            int tmp = to;
            to = from;
            from = tmp;
            reverse = !reverse;
        }
        return new RangeInfo(from, to + 1, reverse);
    }

    // helper method for getAt and putAt
    protected static RangeInfo subListBorders(int size, EmptyRange range) {
        int from = normaliseIndex(DefaultTypeTransformation.intUnbox(range.getFrom()), size);
        return new RangeInfo(from, from, false);
    }

    /**
     * This converts a possibly negative index to a real index into the array.
     *
     * @param i    the unnormalized index
     * @param size the array size
     * @return the normalised index
     */
    protected static int normaliseIndex(int i, int size) {
        int temp = i;
        if (i < 0) {
            i += size;
        }
        if (i < 0) {
            throw new ArrayIndexOutOfBoundsException("Negative array index [" + temp + "] too large for array size " + size);
        }
        return i;
    }

    /**
     * Close the Closeable. Logging a warning if any problems occur.
     *
     * @param closeable the thing to close
     */
    public static void closeWithWarning(Closeable closeable) {
        tryClose(closeable, true); // ignore result
    }

    /**
     * Attempts to close the closeable returning rather than throwing
     * any Exception that may occur.
     *
     * @param closeable the thing to close
     * @param logWarning if true will log a warning if an exception occurs
     * @return throwable Exception from the close method, else null
     */
    static Throwable tryClose(AutoCloseable closeable, boolean logWarning) {
        Throwable thrown = null;
        if (closeable != null) {
            try {
                closeable.close();
            } catch (Exception e) {
                thrown = e;
                if (logWarning) {
                    LOG.warning("Caught exception during close(): " + e);
                }
            }
        }
        return thrown;
    }

    /**
     * Close the Closeable. Ignore any problems that might occur.
     *
     * @param c the thing to close
     */
    public static void closeQuietly(Closeable c) {
        if (c != null) {
            try {
                c.close();
            } catch (IOException e) {
                /* ignore */
            }
        }
    }

    @SuppressWarnings("unchecked")
    protected static <T> Collection<T> cloneSimilarCollection(Collection<T> orig, int newCapacity) {
        Collection<T> answer = (Collection<T>) cloneObject(orig);
        if (answer != null) return answer;

        // fall back to creation
        answer = createSimilarCollection(orig, newCapacity);
        answer.addAll(orig);
        return answer;
    }

    private static Object cloneObject(Object orig) {
        if (orig instanceof Cloneable) {
            try {
                return InvokerHelper.invokeMethod(orig, "clone", EMPTY_OBJECT_ARRAY);
            } catch (Exception ex) {
                // ignore
            }
        }
        return null;
    }

    protected static Collection createSimilarOrDefaultCollection(Object object) {
        if (object instanceof Collection) {
            return createSimilarCollection((Collection<?>) object);
        }
        return new ArrayList();
    }

    protected static <T> Collection<T> createSimilarCollection(Iterable<T> iterable) {
        if (iterable instanceof Collection) {
            return createSimilarCollection((Collection<T>) iterable);
        } else {
            return new ArrayList<T>();
        }
    }

    protected static <T> Collection<T> createSimilarCollection(Collection<T> collection) {
        return createSimilarCollection(collection, collection.size());
    }

    protected static <T> Collection<T> createSimilarCollection(Collection<T> orig, int newCapacity) {
        if (orig instanceof Set) {
            return createSimilarSet((Set<T>) orig);
        }
        if (orig instanceof List) {
            return createSimilarList((List<T>) orig, newCapacity);
        }
        if (orig instanceof Queue) {
            return createSimilarQueue((Queue<T>) orig);
        }
        return new ArrayList<T>(newCapacity);
    }

    protected static <T> List<T> createSimilarList(List<T> orig, int newCapacity) {
        if (orig instanceof LinkedList)
            return new LinkedList<T>();

        if (orig instanceof Stack)
            return new Stack<T>();

        if (orig instanceof Vector)
            return new Vector<T>();

        if (orig instanceof CopyOnWriteArrayList)
            return new CopyOnWriteArrayList<T>();

        return new ArrayList<T>(newCapacity);
    }

    @SuppressWarnings("unchecked")
    protected static <T> T[] createSimilarArray(T[] orig, int newCapacity) {
        Class<T> componentType = (Class<T>) orig.getClass().getComponentType();
        return (T[]) Array.newInstance(componentType, newCapacity);
    }

    @SuppressWarnings("unchecked")
    protected static <T> Set<T> createSimilarSet(Set<T> orig) {
        if (orig instanceof SortedSet) {
            Comparator comparator = ((SortedSet) orig).comparator();
            if (orig instanceof ConcurrentSkipListSet) {
                return new ConcurrentSkipListSet<T>(comparator);
            } else {
                return new TreeSet<T>(comparator);
            }
        } else {
            if (orig instanceof CopyOnWriteArraySet) {
                return new CopyOnWriteArraySet<T>();
            } else {
                // Do not use HashSet
                return new LinkedHashSet<T>();
            }
        }
    }

    @SuppressWarnings("unchecked")
    protected static <T> Queue<T> createSimilarQueue(Queue<T> orig) {
        if (orig instanceof ArrayBlockingQueue) {
            ArrayBlockingQueue queue = (ArrayBlockingQueue) orig;
            return new ArrayBlockingQueue<T>(queue.size() + queue.remainingCapacity());
        } else if (orig instanceof ArrayDeque) {
            return new ArrayDeque<T>();
        } else if (orig instanceof ConcurrentLinkedQueue) {
            return new ConcurrentLinkedQueue<T>();
        } else if (orig instanceof DelayQueue) {
            return new DelayQueue();
        } else if (orig instanceof LinkedBlockingDeque) {
            return new LinkedBlockingDeque<T>();
        } else if (orig instanceof LinkedBlockingQueue) {
            return new LinkedBlockingQueue<T>();
        } else if (orig instanceof PriorityBlockingQueue) {
            return new PriorityBlockingQueue<T>();
        } else if (orig instanceof PriorityQueue) {
            return new PriorityQueue<T>(11, ((PriorityQueue) orig).comparator());
        } else if (orig instanceof SynchronousQueue) {
            return new SynchronousQueue<T>();
        } else {
            return new LinkedList<T>();
        }
    }

    @SuppressWarnings("unchecked")
    protected static <K, V> Map<K, V> createSimilarMap(Map<K, V> orig) {
        if (orig instanceof SortedMap) {
            Comparator comparator = ((SortedMap) orig).comparator();
            if (orig instanceof ConcurrentSkipListMap) {
                return new ConcurrentSkipListMap<K, V>(comparator);
            } else {
                return new TreeMap<K, V>(comparator);
            }
        } else {
            if (orig instanceof ConcurrentHashMap) {
                return new ConcurrentHashMap<K, V>();
            } else if (orig instanceof Hashtable) {
                if (orig instanceof Properties) {
                    return (Map<K, V>) new Properties();
                } else {
                    return new Hashtable<K, V>();
                }
            } else if (orig instanceof IdentityHashMap) {
                return new IdentityHashMap<K, V>();
            } else if (orig instanceof WeakHashMap) {
                return new WeakHashMap<K, V>();
            } else {
                // Do not use HashMap
                return new LinkedHashMap<K, V>();
            }
        }
    }

    @SuppressWarnings("unchecked")
    protected static <K, V> Map<K ,V> cloneSimilarMap(Map<K, V> orig) {
        Map<K, V> answer = (Map<K, V>) cloneObject(orig);
        if (answer != null) return answer;

        // fall back to some defaults
        if (orig instanceof SortedMap) {
            if (orig instanceof ConcurrentSkipListMap) {
                return new ConcurrentSkipListMap<K, V>(orig);
            } else {
                return new TreeMap<K, V>(orig);
            }
        } else {
            if (orig instanceof ConcurrentHashMap) {
                return new ConcurrentHashMap<K, V>(orig);
            } else if (orig instanceof Hashtable) {
                if (orig instanceof Properties) {
                    Map<K, V> map = (Map<K, V>) new Properties();
                    map.putAll(orig);
                    return map;
                } else {
                    return new Hashtable<K, V>(orig);
                }
            } else if (orig instanceof IdentityHashMap) {
                return new IdentityHashMap<K, V>(orig);
            } else if (orig instanceof WeakHashMap) {
                return new WeakHashMap<K, V>(orig);
            } else {
                // Do not use HashMap
                return new LinkedHashMap<K, V>(orig);
            }
        }
    }

    /**
     * Determines if all items of this array are of the same type.
     *
     * @param cols an array of collections
     * @return true if the collections are all of the same type
     */
    @SuppressWarnings("unchecked")
    protected static boolean sameType(Collection[] cols) {
        List all = new LinkedList();
        for (Collection col : cols) {
            all.addAll(col);
        }
        if (all.isEmpty())
            return true;

        Object first = all.get(0);

        //trying to determine the base class of the collections
        //special case for Numbers
        Class baseClass;
        if (first instanceof Number) {
            baseClass = Number.class;
        } else if (first == null) {
            baseClass = NullObject.class;
        } else {
            baseClass = first.getClass();
        }

        for (Collection col : cols) {
            for (Object o : col) {
                if (!baseClass.isInstance(o)) {
                    return false;
                }
            }
        }
        return true;
    }

    protected static void writeUTF16BomIfRequired(final Writer writer, final String charset) throws IOException {
        writeUTF16BomIfRequired(writer, Charset.forName(charset));
    }

    protected static void writeUTF16BomIfRequired(final Writer writer, final Charset charset) throws IOException {
        if ("UTF-16BE".equals(charset.name())) {
            writeUtf16Bom(writer, true);
        } else if ("UTF-16LE".equals(charset.name())) {
            writeUtf16Bom(writer, false);
        }
    }

    protected static void writeUTF16BomIfRequired(final OutputStream stream, final String charset) throws IOException {
        writeUTF16BomIfRequired(stream, Charset.forName(charset));
    }

    protected static void writeUTF16BomIfRequired(final OutputStream stream, final Charset charset) throws IOException {
        if ("UTF-16BE".equals(charset.name())) {
            writeUtf16Bom(stream, true);
        } else if ("UTF-16LE".equals(charset.name())) {
            writeUtf16Bom(stream, false);
        }
    }

    private static void writeUtf16Bom(OutputStream stream, boolean bigEndian) throws IOException {
        if (bigEndian) {
            stream.write(-2);  // FE
            stream.write(-1);  // FF
        } else {
            stream.write(-1);  // FF
            stream.write(-2);  // FE
        }
    }

    private static void writeUtf16Bom(Writer writer, boolean bigEndian) throws IOException {
        if (bigEndian) {
            writer.write(-2);  // FE
            writer.write(-1);  // FF
        } else {
            writer.write(-1);  // FF
            writer.write(-2);  // FE
        }
    }
}

{'repo_name': 'apache/groovy', 'stars': '3742', 'repo_language': 'Java', 'file_name': 'antlr4-license.txt', 'mime_type': 'text/plain', 'hash': 8733295658798610921, 'source_dataset': 'data'}


/* -------------------------------------------------------------------------- */
/* Copyright 2002-2020, OpenNebula Project, OpenNebula Systems                */
/*                                                                            */
/* 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.                                             */
/* -------------------------------------------------------------------------- */

#ifndef HOOK_H_
#define HOOK_H_

#include <string>

#include "Template.h"
#include "PoolObjectSQL.h"
#include "NebulaUtil.h"

class HookImplementation;

class Hook : public PoolObjectSQL
{
public:

    ~Hook();

    /**
     *  Defines the hook type, so a whole hook class can be masked
     */
    enum HookType
    {
        STATE     = 0x01,
        API       = 0x02,
        UNDEFINED = 0x04
    };

    static std::string hook_type_to_str(HookType ht)
    {
        switch(ht)
        {
            case STATE:     return "state";
            case API:       return "api";
            case UNDEFINED: return "";
        }

        return "";
    };

    static HookType str_to_hook_type(std::string& ht)
    {
        one_util::tolower(ht);

        if (ht == "state")
        {
            return STATE;
        }
        else if (ht == "api")
        {
            return API;
        }

        return UNDEFINED;
    }

    /**
     * Function to print the Hook object into a string in XML format
     *  @param xml the resulting XML string
     *  @return a reference to the generated string
     */
    std::string& to_xml(std::string& xml) const
    {
        return _to_xml(xml, false);
    }

    /**
     *  Include exection records for the hook
     */
    std::string& to_xml_extended(std::string& xml) const
    {
        return _to_xml(xml, true);
    }

private:

    friend class HookPool;

    // *************************************************************************
    // Constructor/Destructor
    // *************************************************************************

    Hook(std::unique_ptr<Template> tmpl);

    /**
     * Set hook implementation attribute depending of the hook type.
     */
    int set_hook(HookType hook_type, std::string& error);

    /**
     *  Factory method for Hook templates
     */
    std::unique_ptr<Template> get_new_template() const
    {
        return std::make_unique<Template>();
    }

    /**
     *  Rebuilds the object from an xml formatted string
     *    @param xml_str The xml-formatted string
     *
     *    @return 0 on success, -1 otherwise
     */
    int from_xml(const std::string &xml_str);

    /* Checks the mandatory templates attrbutes
     *    @param error string describing the error if any
     *    @return 0 on success
     */
    int post_update_template(std::string& error);

    // -------------------------------------------------------------------------
    // Hook Attributes
    // -------------------------------------------------------------------------

    /**
     * The hook type
     */
    HookType type;

    /**
     *  The command to be executed
     */
    std::string   cmd;

    /**
     *  True if the command is to be executed remotely
     */
    bool     remote;

    /**
     * Object which implement type dependent methods.
     */
    HookImplementation * _hook;

    // *************************************************************************
    // Database implementation
    // *************************************************************************

    /**
     *  Construct the XML representation of the hook
     *  @param xml the resulting XML string
     *  @param log to include the execution log
     *
     *  @return a reference to the generated string
     */
    std::string& _to_xml(std::string& xml, bool log) const;

    /**
     *  Bootstraps the database table(s) associated to the Host
     *    @return 0 on success
     */
    static int bootstrap(SqlDB * db);

    /**
     *  Writes/updates the Hosts data fields in the database.
     *    @param db pointer to the db
     *    @return 0 on success
     */
    int update(SqlDB *db) override
    {
        std::string error_str;
        return insert_replace(db, true, error_str);
    };

    /**
     *  Writes the Hook in the database.
     *    @param db pointer to the db
     *    @return 0 on success
     */
    int insert(SqlDB *db, std::string& error_str) override;

    /**
     *  Execute an INSERT or REPLACE Sql query.
     *    @param db The SQL DB
     *    @param replace Execute an INSERT or a REPLACE
     *    @param error_str Returns the error reason, if any
     *    @return 0 one success
     */
    int insert_replace(SqlDB *db, bool replace, std::string& error_str);

    /**
     *  Drops object from the database
     *    @param db pointer to the db
     *    @return 0 on success
     */
    int drop(SqlDB *db) override;
};

#endif /*HOOK_H_*/

{'repo_name': 'OpenNebula/one', 'stars': '645', 'repo_language': 'C++', 'file_name': '05-sunstone.sh', 'mime_type': 'text/plain', 'hash': 5422724524356515468, 'source_dataset': 'data'}


# Copyright 1999-2019 Gentoo Authors
# Distributed under the terms of the GNU General Public License v2

EAPI=6

inherit cmake-utils git-r3 llvm

MY_PN="CastXML"

DESCRIPTION="CastXML is a C-family abstract syntax tree XML output tool."
HOMEPAGE="https://github.com/CastXML/CastXML"
SRC_URI=""
EGIT_REPO_URI="https://github.com/gerddie/CastXML"
EGIT_COMMIT="6b3d3f985f4607430d0e7ecd835ee80b29f3ae96"

LICENSE="Apache-2.0"
SLOT="0"
KEYWORDS="~amd64 ~x86"

DEPEND="${RDEPEND}"
RDEPEND="
		dev-libs/glib:2
		dev-libs/libxml2
		sys-devel/llvm:=
		sys-devel/clang:=
		"

src_test() {
	cd "${BUILD_DIR}" || die
	ctest -j 20
}

{'repo_name': 'gentoo/sci', 'stars': '115', 'repo_language': 'Shell', 'file_name': 'API.odocl', 'mime_type': 'text/plain', 'hash': -7268551100601146667, 'source_dataset': 'data'}


//
//     Generated by class-dump 3.5 (64 bit).
//
//     class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//

#import "PBCodable.h"

#import "NSCopying.h"

@class CKDPShare;

__attribute__((visibility("hidden")))
@interface CKDPShareParticipantUpdateResponse : PBCodable <NSCopying>
{
    CKDPShare *_share;
}

@property(retain, nonatomic) CKDPShare *share; // @synthesize share=_share;
- (void).cxx_destruct;
- (void)mergeFrom:(id)arg1;
- (unsigned int)hash;
- (BOOL)isEqual:(id)arg1;
- (id)copyWithZone:(struct _NSZone *)arg1;
- (void)copyTo:(id)arg1;
- (void)writeTo:(id)arg1;
- (BOOL)readFrom:(id)arg1;
- (id)dictionaryRepresentation;
- (id)description;
@property(readonly, nonatomic) BOOL hasShare;

@end

{'repo_name': 'MP0w/iOS-Headers', 'stars': '405', 'repo_language': 'Objective-C', 'file_name': 'IMAVChat-IMAVChatAudioAdditions.h', 'mime_type': 'text/x-objective-c', 'hash': -2209939813594702133, 'source_dataset': 'data'}


/*
 * Copyright (c) 2016-2020 VMware, Inc. All Rights Reserved.
 * This software is released under MIT license.
 * The full license information can be found in LICENSE in the root directory of this project.
 */
import { Component, ContentChild } from '@angular/core';

import { ClrDatagridColumnToggle } from './datagrid-column-toggle';
import { Selection } from './providers/selection';
import { SelectionType } from './enums/selection-type';
import { ColumnsService } from './providers/columns.service';
import { DetailService } from './providers/detail.service';

@Component({
  selector: 'clr-dg-footer',
  template: `
    <ng-container *ngIf="selection.selectionType === SELECTION_TYPE.Multi && selection.current.length > 0">

        <clr-checkbox-wrapper class="datagrid-footer-select">
          <input clrCheckbox type="checkbox" checked="checked" disabled />
          {{ selection.current.length }}
        </clr-checkbox-wrapper>

    </ng-container>
    <ng-container *ngIf="!detailService.isOpen">
      <ng-content select="clr-dg-column-toggle"></ng-content>
      <clr-dg-column-toggle *ngIf="hasHideableColumns && !toggle"></clr-dg-column-toggle>

        <ng-content></ng-content>

    </ng-container>
    <ng-content select="clr-dg-pagination"></ng-content>
  `,
  host: {
    '[class.datagrid-footer]': 'true',
  },
})
export class ClrDatagridFooter<T = any> {
  constructor(
    public selection: Selection<T>,
    public detailService: DetailService,
    private columnsService: ColumnsService
  ) {}

  /* reference to the enum so that template can access */
  public SELECTION_TYPE = SelectionType;

  @ContentChild(ClrDatagridColumnToggle) toggle: ClrDatagridColumnToggle;

  get hasHideableColumns(): boolean {
    return this.columnsService.hasHideableColumns;
  }
}

{'repo_name': 'vmware/clarity', 'stars': '5918', 'repo_language': 'TypeScript', 'file_name': 'settings.json', 'mime_type': 'text/plain', 'hash': -1296268359945494620, 'source_dataset': 'data'}


/*
 * Licensed to Crate under one or more contributor license agreements.
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.  Crate 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.
 *
 * However, if you have executed another commercial license agreement
 * with Crate these terms will supersede the license and you may use the
 * software solely pursuant to the terms of the relevant commercial
 * agreement.
 */

package io.crate.execution.dsl.projection;

import io.crate.expression.symbol.InputColumn;
import io.crate.expression.symbol.SelectSymbol;
import io.crate.expression.symbol.Symbol;
import io.crate.expression.symbol.SymbolVisitors;
import io.crate.expression.symbol.Symbols;
import io.crate.metadata.Reference;
import io.crate.metadata.RowGranularity;
import io.crate.types.DataTypes;
import org.elasticsearch.Version;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;

import javax.annotation.Nullable;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class SysUpdateProjection extends Projection {

    private final Symbol uidSymbol;

    private Map<Reference, Symbol> assignments;

    private Symbol[] outputs;

    @Nullable
    private Symbol[] returnValues;

    public SysUpdateProjection(Symbol uidSymbol,
                               Map<Reference, Symbol> assignments,
                               Symbol[] outputs,
                               @Nullable Symbol[] returnValues
    ) {
        this.uidSymbol = uidSymbol;
        this.assignments = assignments;
        this.returnValues = returnValues;
        assert Arrays.stream(outputs).noneMatch(s -> SymbolVisitors.any(Symbols.IS_COLUMN.or(x -> x instanceof SelectSymbol), s))
            : "Cannot operate on Reference, Field or SelectSymbol symbols: " + outputs;
        this.outputs = outputs;
    }

    public SysUpdateProjection(StreamInput in) throws IOException {
        uidSymbol = Symbols.fromStream(in);
        int numAssignments = in.readVInt();
        assignments = new HashMap<>(numAssignments, 1.0f);
        for (int i = 0; i < numAssignments; i++) {
            assignments.put(Reference.fromStream(in), Symbols.fromStream(in));
        }
        if (in.getVersion().onOrAfter(Version.V_4_2_0)) {
            int outputSize = in.readVInt();
            outputs = new Symbol[outputSize];
            for (int i = 0; i < outputSize; i++) {
                outputs[i] = Symbols.fromStream(in);
            }
            int returnValuesSize = in.readVInt();
            if (returnValuesSize > 0) {
                returnValues = new Symbol[returnValuesSize];
                for (int i = 0; i < returnValuesSize; i++) {
                    returnValues[i] = Symbols.fromStream(in);
                }
            }
        } else {
            //Outputs should never be null and for BwC reasons
            //the default value in pre 4.1 was a long for a count
            outputs = new Symbol[]{new InputColumn(0, DataTypes.LONG)};
        }
    }

    @Override
    public ProjectionType projectionType() {
        return ProjectionType.SYS_UPDATE;
    }

    @Nullable
    public Symbol[] returnValues() {
        return returnValues;
    }

    @Override
    public List<? extends Symbol> outputs() {
        return List.of(outputs);
    }

    @Override
    public <C, R> R accept(ProjectionVisitor<C, R> visitor, C context) {
        return visitor.visitSysUpdateProjection(this, context);
    }

    public Map<Reference, Symbol> assignments() {
        return assignments;
    }

    @Override
    public void writeTo(StreamOutput out) throws IOException {
        Symbols.toStream(uidSymbol, out);
        out.writeVInt(assignments.size());
        for (Map.Entry<Reference, Symbol> e : assignments.entrySet()) {
            Reference.toStream(e.getKey(), out);
            Symbols.toStream(e.getValue(), out);
        }

        if (out.getVersion().onOrAfter(Version.V_4_2_0)) {
            out.writeVInt(outputs.length);
            for (int i = 0; i < outputs.length; i++) {
                Symbols.toStream(outputs[i], out);
            }
            if (returnValues != null) {
                out.writeVInt(returnValues.length);
                for (int i = 0; i < returnValues.length; i++) {
                    Symbols.toStream(returnValues[i], out);
                }
            } else {
                out.writeVInt(0);
            }
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        SysUpdateProjection that = (SysUpdateProjection) o;
        return Objects.equals(uidSymbol, that.uidSymbol) &&
               Objects.equals(assignments, that.assignments) &&
               Arrays.equals(outputs, that.outputs) &&
               Arrays.equals(returnValues, that.returnValues);
    }

    @Override
    public int hashCode() {
        int result = Objects.hash(super.hashCode(), uidSymbol, assignments);
        result = 31 * result + Arrays.hashCode(outputs);
        result = 31 * result + Arrays.hashCode(returnValues);
        return result;
    }

    @Override
    public RowGranularity requiredGranularity() {
        return RowGranularity.NODE;
    }
}

{'repo_name': 'crate/crate', 'stars': '2777', 'repo_language': 'Java', 'file_name': 'AssertingLeafReader.java', 'mime_type': 'text/x-java', 'hash': 6145086294366693418, 'source_dataset': 'data'}


/*
 * Copyright (c) 2018 THL A29 Limited, a Tencent company. 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.
 */

namespace TencentCloud.Vod.V20180717.Models
{
    using Newtonsoft.Json;
    using System.Collections.Generic;
    using TencentCloud.Common;

    public class ProcessMediaByProcedureResponse : AbstractModel
    {

        /// <summary>
        /// 任务 ID。
        /// </summary>
        [JsonProperty("TaskId")]
        public string TaskId{ get; set; }

        /// <summary>
        /// 唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
        /// </summary>
        [JsonProperty("RequestId")]
        public string RequestId{ get; set; }

        /// <summary>
        /// For internal usage only. DO NOT USE IT.
        /// </summary>
        internal override void ToMap(Dictionary<string, string> map, string prefix)
        {
            this.SetParamSimple(map, prefix + "TaskId", this.TaskId);
            this.SetParamSimple(map, prefix + "RequestId", this.RequestId);
        }
    }
}

{'repo_name': 'TencentCloud/tencentcloud-sdk-dotnet', 'stars': '235', 'repo_language': 'C#', 'file_name': 'Resources.Designer.cs', 'mime_type': 'text/plain', 'hash': -4366287012405221001, 'source_dataset': 'data'}


<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>分组列表</title>
    <link rel="shortcut icon" href="favicon.ico">
    <link href="__CSS__/bootstrap.min.css?v=3.3.6" rel="stylesheet">
    <link href="__CSS__/font-awesome.min.css?v=4.4.0" rel="stylesheet">
    <link href="__CSS__/plugins/bootstrap-table/bootstrap-table.min.css" rel="stylesheet">
    <link href="__CSS__/animate.min.css" rel="stylesheet">
    <link href="__CSS__/style.min.css?v=4.1.0" rel="stylesheet">

分组列表

            <form id='commentForm' role="form" method="post" class="form-inline pull-right">

                        分组名称：
                        <input type="text" class="form-control" id="username" name="name">

                        <button class="btn btn-primary" type="button" style="margin-top:5px" id="search">搜 索
                        </button>

            </form>

                        分组ID
                        分组名称
                        客服人数
                        分组状态
                        操作

{'repo_name': 'shmilylbelva/laykefu', 'stars': '187', 'repo_language': 'PHP', 'file_name': 'jquery.metisMenu.js', 'mime_type': 'text/plain', 'hash': -3544147439762559057, 'source_dataset': 'data'}