text:
namespace grok {
namespace libs {
using namespace grok::obj;

auto GetStringIndex(JSString::size_type sz, std::shared_ptr<Object> obj,
    JSString::size_type def)
                -> decltype(sz)
{
    std::string str;
    if (!IsJSNumber(obj)) {
        str = obj->as<JSObject>()->ToString();
        obj = CreateJSNumber(str);

        if (IsUndefined(obj))
            return def;
    }

    auto num = obj->as<JSDouble>()->GetNumber();
    if (num < 0)
        num += sz;

    if (num < 0)
        return 0;
    if ((num) > ((decltype(num))sz)) {
        num = sz;
    }
    return num;
}

std::shared_ptr<Object> StringSlice(std::shared_ptr<Argument> Args)
{
    auto This = Args->GetProperty("this");

    if (!IsJSString(This))
        return CreateUndefinedObject();

    auto A = This->as<JSString>();
    auto Astr = A->ToString();
    auto Start = Args->GetProperty("start");
    auto End = Args->GetProperty("end");
    auto Sz = Astr.size();

    auto start_idx = GetStringIndex(Sz, Start, 0);
    auto end_idx = GetStringIndex(Sz, End, Sz - 1);

    if (start_idx > end_idx)
        return CreateJSString("");

    auto result = CreateJSString("");
    auto &result_str = result->as<JSString>()->GetString();
    result_str.assign(Astr.begin() + start_idx, Astr.begin() + end_idx + 1);
    return result;
}

}
}


text:
//========================================================================
//Copyright 2007-2010 David Yu dyuproject@gmail.com
//------------------------------------------------------------------------
//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.
//========================================================================

package com.dyuproject.protostuff;

import java.io.IOException;

import junit.framework.TestCase;

/**
 * Test for parsing numbers from raw ascii buffers.
 *
 * @author David Yu
 * @created Dec 4, 2010
 */
public class NumberParserTest extends TestCase
{

    public void testParseInt() throws Exception
    {
        assertTrue(0 == NumberParser.parseInt(new byte[]{'0'}, 0, 1, 10));
        assertTrue(1 == NumberParser.parseInt(new byte[]{'1'}, 0, 1, 10));
        assertTrue(-1 == NumberParser.parseInt(new byte[]{'-', '1'}, 0, 2, 10));

        final LinkedBuffer lb = LinkedBuffer.allocate(256);
        final WriteSession session = new WriteSession(lb);

        assertTrue(lb == StringSerializer.writeInt(
                Integer.MAX_VALUE, session, session.tail));

        assertTrue(Integer.MAX_VALUE == NumberParser.parseInt(
                session.toByteArray(), 0, session.size, 10));

        session.clear();

        assertTrue(lb == StringSerializer.writeInt(
                Integer.MAX_VALUE-1, session, session.tail));

        assertTrue(Integer.MAX_VALUE-1 == NumberParser.parseInt(
                session.toByteArray(), 0, session.size, 10));

        session.clear();

        assertTrue(lb == StringSerializer.writeInt(
                Integer.MIN_VALUE, session, session.tail));

        assertTrue(Integer.MIN_VALUE == NumberParser.parseInt(
                session.toByteArray(), 0, session.size, 10));

        session.clear();

        assertTrue(lb == StringSerializer.writeInt(
                Integer.MIN_VALUE+1, session, session.tail));

        assertTrue(Integer.MIN_VALUE+1 == NumberParser.parseInt(
                session.toByteArray(), 0, session.size, 10));

    }

    public void testParseLong() throws IOException
    {
        assertTrue(0l == NumberParser.parseLong(new byte[]{'0'}, 0, 1, 10));
        assertTrue(1l == NumberParser.parseLong(new byte[]{'1'}, 0, 1, 10));
        assertTrue(-1l == NumberParser.parseLong(new byte[]{'-', '1'}, 0, 2, 10));

        final LinkedBuffer lb = LinkedBuffer.allocate(256);
        final WriteSession session = new WriteSession(lb);

        assertTrue(lb == StringSerializer.writeLong(
                Long.MAX_VALUE, session, session.tail));

        assertTrue(Long.MAX_VALUE == NumberParser.parseLong(
                session.toByteArray(), 0, session.size, 10));

        session.clear();

        assertTrue(lb == StringSerializer.writeLong(
                Long.MAX_VALUE-1, session, session.tail));

        assertTrue(Long.MAX_VALUE-1 == NumberParser.parseLong(
                session.toByteArray(), 0, session.size, 10));

        session.clear();

        assertTrue(lb == StringSerializer.writeLong(
                Long.MIN_VALUE, session, session.tail));

        assertTrue(Long.MIN_VALUE == NumberParser.parseLong(
                session.toByteArray(), 0, session.size, 10));

        session.clear();

        assertTrue(lb == StringSerializer.writeLong(
                Long.MIN_VALUE+1, session, session.tail));

        assertTrue(Long.MIN_VALUE+1 == NumberParser.parseLong(
                session.toByteArray(), 0, session.size, 10));
    }

}

redpajama_set_name: RedPajamaGithub


text:
-include ../tools.mk

all:
	# Let's get a nice error message
	$(BARE_RUSTC) foo.rs --emit dep-info --out-dir foo/bar/baz 2>&1 | \
		grep "error writing dependencies"
	# Make sure the filename shows up
	$(BARE_RUSTC) foo.rs --emit dep-info --out-dir foo/bar/baz 2>&1 | grep "baz"


text:
package net.anotheria.moskito.core.blueprint;

/**
 * This interface defines the executor for a call on a monitored blueprinted object. Whenever the surrounding code wants to call a method on a monitorable
 * blueprinted object, it calls the appropriate blueprint producer, which performs measurements and updates the use-case tracking and afterwards passes the control to an
 * instance of the executor.
 * @author lrosenberg
 *
 */
public interface BlueprintCallExecutor {
	/**
	 * Called by the producer. Passes all parameters.
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
	Object execute(Object... parameters) throws Exception;
}


text:
This rule bans specific matchers & modifiers from being used, and can suggest
alternatives.

## Rule Details

Bans are expressed in the form of a map, with the value being either a string
message to be shown, or `null` if the default rule message should be used.

Both matchers, modifiers, and chains of the two are checked, allowing for
specific variations of a matcher to be banned if desired.

By default, this map is empty, meaning no matchers or modifiers are banned.

For example:

```json
{
  "jest/no-restricted-matchers": [
    "error",
    {
      "toBeFalsy": null,
      "resolves": "Use `expect(await promise)` instead.",
      "not.toHaveBeenCalledWith": null
    }
  ]
}
```

Examples of **incorrect** code for this rule with the above configuration

```js
it('is false', () => {
  expect(a).toBeFalsy();
});

it('resolves', async () => {
  await expect(myPromise()).resolves.toBe(true);
});

describe('when an error happens', () => {
  it('does not upload the file', async () => {
    expect(uploadFileMock).not.toHaveBeenCalledWith('file.name');
  });
});
```


text:
if (!window.tinyHippos) {
    window.tinyHippos = {};
    var _panel = th_panel;

    (function () {
        var injection = _panel.LAYOUT_HTML.replace(/#URL_PREFIX#/g, rippleExtensionId);

        document.open();
        document.write(injection);

        window.setTimeout(function () {
            document.close();
        }, 100);
    }());

}

delete window.th_panel;


text:
<?php namespace Ipunkt\Multitenant\Tenant;
use Illuminate\Auth\UserInterface;

/**
 * Interface Tenant
 * @package Ipunkt\Multitenant\Tenant
 */
interface Tenant {
	/**
	 * Returns the unique prefix that identifies this tenant
	 *
	 * @return mixed
	 */
	function getPrefix();

	/**
	 * Returns the id by which this tenant can be retrieved from the repository
	 *
	 * @return mixed
	 */
	function getId();

	/**
	 * Returns true if the tenant has this user assigned to it.
	 *
	 * @param UserInterface $user
	 * @return bool
	 */
	function hasUser(UserInterface $user);
}


text:
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC 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.openqa.selenium.remote.server;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;

import org.junit.Test;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.ImmutableCapabilities;
import org.openqa.selenium.remote.NewSessionPayload;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.List;
import java.util.Map;

/**
 * There's an interesting problem that appears relatively often with New Session and incorrectly
 * prepared payloads. The key problem manifests where something is added to the OSS payload, and
 * this is incorrectly reflected in the w3c payload. To work around this, we'll inspect the two sets
 * of data. If we can expand the W3C payloads (using the guidelines from the spec) into something
 * that matches the OSS payload, we'll just forward the blob unchanged. If, however, we can't then
 * we need to do some fancy foot work, in which we'll:
 *
 *

 *
Create a new W3C "firstMatch" blob that matches the OSS payload

 *
Expand all W3C payloads, so that they are complete

 *
Forward a new New Session payload composed of the OSS payload and the combined list of
 *     "firstMatches", with the OSS equivalent first.

 *

 *

 * This test has been broken out to make this behaviour clearer, and to allow for this comment.
 */
public class SyntheticNewSessionPayloadTest {

  @Test
  public void shouldDoNothingIfOssAndW3CPayloadsAreBothEmpty() {
    Map<String, Object> empty = ImmutableMap.of(
        "desiredCapabilities", ImmutableMap.of(),
        "capabilities", ImmutableMap.of(
            "alwaysMatch", ImmutableMap.of(),
            "firstMatch", ImmutableList.of(ImmutableMap.of())));

    List<Capabilities> allCaps = getCapabilities(empty);

    assertEquals(ImmutableList.of(new ImmutableCapabilities()), allCaps);
  }

  @Test
  public void shouldDoNothingIfCapabilitiesArePresentButLeftEmpty() {
    Map<String, Object> empty = ImmutableMap.of(
        "desiredCapabilities", ImmutableMap.of(),
        "capabilities", ImmutableMap.of());

    List<Capabilities> allCaps = getCapabilities(empty);

    assertEquals(ImmutableList.of(new ImmutableCapabilities()), allCaps);

  }

  @Test
  public void shouldDoNothingIfOssPayloadMatchesAlwaysMatchAndThereAreNoFirstMatches() {
    ImmutableMap<String, String> identicalCaps = ImmutableMap.of("browserName", "cheese");

    Map<String, Object> payload= ImmutableMap.of(
        "desiredCapabilities", identicalCaps,
        "capabilities", ImmutableMap.of(
            "alwaysMatch", identicalCaps));

    List<Capabilities> allCaps = getCapabilities(payload);

    assertEquals(ImmutableList.of(new ImmutableCapabilities(identicalCaps)), allCaps);
  }

  @Test
  public void shouldDoNothingIfOssPayloadMatchesAFirstMatchAndThereIsNoAlwaysMatch() {
    ImmutableMap<String, String> identicalCaps = ImmutableMap.of("browserName", "cheese");

    Map<String, Object> payload= ImmutableMap.of(
        "desiredCapabilities", identicalCaps,
        "capabilities", ImmutableMap.of(
            "firstMatch", ImmutableList.of(identicalCaps)));

    List<Capabilities> allCaps = getCapabilities(payload);

    assertEquals(ImmutableList.of(new ImmutableCapabilities(identicalCaps)), allCaps);
  }

  @Test
  public void shouldDoNothingIfOssPayloadMatchesAValidMergedW3CPayload() {
    ImmutableMap<String, String> caps = ImmutableMap.of(
        "browserName", "cheese",
        "se:cake", "more cheese");

    Map<String, Object> payload= ImmutableMap.of(
        "desiredCapabilities", caps,
        "capabilities", ImmutableMap.of(
            "alwaysMatch", ImmutableMap.of("browserName", "cheese"),
            "firstMatch", ImmutableList.of(ImmutableMap.of("se:cake", "more cheese"))));

    List<Capabilities> allCaps = getCapabilities(payload);

    assertEquals(ImmutableList.of(new ImmutableCapabilities(caps)), allCaps);
  }

  @Test
  public void shouldExpandAllW3CMatchesToFirstMatchesAndRemoveAlwaysMatchIfSynthesizingAPayload()
      throws IOException {
    Map<String, Object> payload = ImmutableMap.of(
      // OSS capabilities request a chrome webdriver
      "desiredCapabilities", ImmutableMap.of("browserName", "chrome"),
      // Yet the w3c ones ask for IE and edge
      "capabilities", ImmutableMap.of(
          "alwaysMatch", ImmutableMap.of("se:cake", "cheese"),
          "firstMatch", ImmutableList.of(
              ImmutableMap.of("browserName", "edge"),
              ImmutableMap.of("browserName", "cheese"))));

    try (NewSessionPayload newSession = NewSessionPayload.create(payload)) {
      List<Capabilities> allCaps = newSession.stream().collect(ImmutableList.toImmutableList());

      assertEquals(3, allCaps.size());
      assertTrue(allCaps.contains(new ImmutableCapabilities("browserName", "cheese", "se:cake", "cheese")));
      assertTrue(allCaps.contains(new ImmutableCapabilities("browserName", "chrome")));
      assertTrue(allCaps.contains(new ImmutableCapabilities("browserName", "edge", "se:cake", "cheese")));
    }
  }

  @Test
  public void ossPayloadWillBeFirstW3CPayload() {
    // This is one of the common cases --- asking for marionette to be false. There's no way to
    // encode this legally into the w3c payload (as it doesn't start with "se:"), yet it's a use-
    // case that needs to be properly supported.
    Map<String, Object> rawCapabilities = ImmutableMap.of(
        "desiredCapabilities", ImmutableMap.of("marionette", false),
        "capabilities", ImmutableMap.of(
            "alwaysMatch", ImmutableMap.of("browserName", "chrome")));

    List<Capabilities> allCaps = getCapabilities(rawCapabilities);

    assertEquals(3, allCaps.size());
    assertEquals(false, allCaps.get(0).getCapability("marionette"));
  }

  private List<Capabilities> getCapabilities(Map<String, Object> payload) {
    try (NewSessionPayload newSessionPayload = NewSessionPayload.create(payload)) {
      StringBuilder b = new StringBuilder();
      newSessionPayload.writeTo(b);
      return newSessionPayload.stream().collect(ImmutableList.toImmutableList());
    } catch (IOException e) {
      throw new UncheckedIOException(e);
    }
  }

}


text:
package com.projecttango.experiments.nativearealearning;

import android.util.Log;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;

// Util class provides handy utility functions.
public class Util {

  // Checks if the calling app has the specified permission.
  // It is recommended that an app check if it has a permission before trying
  // to request it; this will save time by avoiding re-requesting permissions
  // that have already been granted.

  // @param context The context of the calling app.
  // @param permissionType The type of permission to request; either
  // PERMISSIONTYPE_MOTION_TRACKING or PERMISSIONTYPE_ADF_LOAD_SAVE.
  // @return boolean Whether or not the permission was already granted.
  public static boolean hasPermission(Context context, String permissionType){
    Uri uri = Uri.parse("content://com.google.atap.tango.PermissionStatusProvider/" +
        permissionType);
    Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
    if (cursor == null) {
      return false;
    } else {
      return true;
    }
  }
}


text:
<!doctype html>

  <meta charset="utf-8">
  <title>DogApp</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link href="https://unpkg.com/@angular/material/core/theming/prebuilt/indigo-pink.css" rel="stylesheet" async>
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

  <app-root>

   </app-root>


text:
package jsonapi

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"strconv"
	"strings"
)

type Error struct {
	Id     string `json:"id,omitempty"`
	Href   string `json:"href,omitempty"`
	Status int    `json:"status,string,omitempty"`
	Code   string `json:"code,omitempty"`
	Title  string `json:"title,omitempty"`
	Detail string `json:"detail,omitempty"`
}

func (e *Error) UnmarshalJSON(data []byte) error {

	dst := struct {
		Id     string     `json:"id"`
		Href   string     `json:"href"`
		Status statusCode `json:"status"`
		Code   string     `json:"code"`
		Title  string     `json:"title"`
		Detail string     `json:"detail"`
	}{
		Id:     e.Id,
		Href:   e.Href,
		Status: statusCode(e.Status),
		Code:   e.Code,
		Title:  e.Title,
		Detail: e.Detail,
	}

	if err := json.Unmarshal(data, &dst); err != nil {
		return err
	}

	e.Id = dst.Id
	e.Href = dst.Href
	e.Status = int(dst.Status)
	e.Code = dst.Code
	e.Title = dst.Title
	e.Detail = dst.Detail

	return nil
}

func (e Error) Error() string {
	return e.Detail
}

type errors []*Error

func (e errors) Error() string {
	messages := make([]string, len(e))
	for i, err := range e {
		messages[i] = err.Error()
	}
	return fmt.Sprintf("jsonapi: %d api error(s): %s", len(messages), strings.Join(messages, "; "))
}

// NewError creates a new Error.
func NewError(status int, err error) *Error {
	return &Error{
		Status: status,
		Detail: err.Error(),
	}
}

// NewErrorf creates a new Error with a single error message.
func NewErrorf(status int, format string, a ...interface{}) *Error {
	return &Error{
		Status: status,
		Detail: fmt.Sprintf(format, a...),
	}
}

// NewClientError produces a Error with status 400 (Bad Request).
func NewClientError(err error) *Error {
	return NewError(http.StatusBadRequest, err)
}

// NewClientErrorf produdces a formatted Error with status 400 (Bad Request).
func NewClientErrorf(format string, a ...interface{}) *Error {
	return NewErrorf(http.StatusBadRequest, format, a...)
}

// NewNotFoundError produces an Error with status 404 that details the missing resource.
func NewNotFoundError(resourceType, id string) *Error {
	return NewErrorf(http.StatusNotFound, "%s \"%s\" not found", resourceType, id)
}

// NewNotAllowedError produces an Error with status 405 that details the disallowed HTTP method for the resource.
func NewNotAllowedError(resourceType, method string) *Error {
	return NewErrorf(http.StatusMethodNotAllowed, "%s does not allow %s requests", resourceType, method)
}

// NewConflictError produces an Error with status 409 that details when a conflict is encountered for the resource.
func NewConflictError(resourceType, method string) *Error {
	return NewErrorf(http.StatusConflict, "%s encountered a conflict during %s", resourceType, method)
}

// NewServerError produces a Service Error with status 500 (Internal Server Error).
func NewServerError(err error) *Error {
	return NewError(http.StatusInternalServerError, err)
}

// NewServerError produces a formatted SeviceError with status 500 (Internal Server Error).
func NewServerErrorf(format string, a ...interface{}) *Error {
	return NewErrorf(http.StatusInternalServerError, format, a...)
}

type statusCode int

func (s *statusCode) UnmarshalJSON(data []byte) error {
	decoder := json.NewDecoder(bytes.NewReader(data))
	token, err := decoder.Token()
	if err != nil {
		return fmt.Errorf("cannot unmarshal status code: %s", err)
	}

	switch token := token.(type) {
	case float64:
		*s = statusCode(token)
	case string:
		s64, err := strconv.ParseInt(token, 10, 64)
		if err != nil {
			return fmt.Errorf("cannot unmarshal status code: %s", err)
		}

		*s = statusCode(s64)
	default:
		return fmt.Errorf("cannot unmarshal status code, must be int or string")
	}

	return nil
}

func (s statusCode) MarshalJSON() ([]byte, error) {
	return json.Marshal(strconv.FormatInt(int64(s), 10))
}


text:
package org.beanmaker.util;

import net.pythoud.passwords.CharacterSets;
import net.pythoud.passwords.PasswordMaker;

import org.dbbeans.sql.DBAccess;
import org.dbbeans.sql.DBQueryRetrieveData;
import org.dbbeans.sql.DBQuerySetup;

import org.dbbeans.util.Dates;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class ProtectedIdManager {

    private static final PasswordMaker CODE_GENERATOR =
            PasswordMaker.getFactory()
                    .setCharCount(32)
                    .setMainChars(CharacterSets.UPPER_CASES + CharacterSets.LOWER_CASES + CharacterSets.DIGITS)
                    .create();

    private final DBAccess dbAccess;
    private final String table;

    public ProtectedIdManager(final DBAccess dbAccess, final String table) {
        this.dbAccess = dbAccess;
        this.table = table;
    }

    public String getCode(final long id) {
        String code = getCodeFromDB(id);

        if (code == null)
            code = createCode(id);

        return code;
    }

    public long getId(final String code) {
        return getIdFromDB(code);
    }

    public boolean codeMatchesId(final String code, final long id) {
        return getId(code) == id;
    }

    private String getCodeFromDB(final long id) {
        return dbAccess.processQuery(
                "SELECT code FROM " + table + " WHERE protected_id=?",
                new DBQuerySetup() {
                    @Override
                    public void setupPreparedStatement(final PreparedStatement stat) throws SQLException {
                        stat.setLong(1, id);
                    }
                },
                new DBQueryRetrieveData<String>() {
                    @Override
                    public String processResultSet(final ResultSet rs) throws SQLException {
                        if (rs.next())
                            return rs.getString(1);

                        return null;
                    }
                }
        );
    }

    private String createCode(final long id) {
        final String code = CODE_GENERATOR.getPassword();

        if (!exists(code))
            dbAccess.processUpdate(
                    "INSERT INTO " + table + " (protected_id, code, creation_date) VALUES (?, ?, ?)",
                    new DBQuerySetup() {
                        @Override
                        public void setupPreparedStatement(final PreparedStatement stat) throws SQLException {
                            stat.setLong(1, id);
                            stat.setString(2, code);
                            stat.setTimestamp(3, Dates.getCurrentTimestamp());
                        }
                    }
            );

        return code;
    }

    private boolean exists(final String code) {
        return dbAccess.processQuery(
                "SELECT protected_id FROM " + table + " WHERE code=?",
                new DBQuerySetup() {
                    @Override
                    public void setupPreparedStatement(final PreparedStatement stat) throws SQLException {
                        stat.setString(1, code);
                    }
                },
                new DBQueryRetrieveData<Boolean>() {
                    @Override
                    public Boolean processResultSet(ResultSet rs) throws SQLException {
                        return rs.next();
                    }
                }
        );
    }

    private long getIdFromDB(final String code) {
        return dbAccess.processQuery(
                "SELECT protected_id FROM " + table + " WHERE code=?",
                new DBQuerySetup() {
                    @Override
                    public void setupPreparedStatement(final PreparedStatement stat) throws SQLException {
                        stat.setString(1, code);
                    }
                },
                new DBQueryRetrieveData<Long>() {
                    @Override
                    public Long processResultSet(final ResultSet rs) throws SQLException {
                        if (rs.next())
                            return rs.getLong(1);

                        return 0L;
                    }
                }
        );
    }
}


text:
@(loginForm: play.data.Form[controllers.bo.UserLogin.Login])

@import helper._
@implicitField = @{ FieldConstructor(const.customFieldConstructor.f) }

@main("Identifiez-vous sur le BackOffice")(breadcrum(
	Collections.emptyMap()
	)) {

Identifiez-vous

		@if(loginForm.hasGlobalErrors) {

	    	<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
	        Attention! @loginForm.globalError.message

		}

	    @form(controllers.bo.routes.UserLogin.authenticate, 'role -> "form") {

		    @inputText(loginForm("email"), '_label -> null, '_showConstraints -> false, 'placeholder -> "email", 'addon -> "@", 'class -> "form-control input-group-lg")

		    @inputPassword(loginForm("password"), '_label -> null, '_showConstraints -> false, 'placeholder -> "mot de passe", 'addon -> "***", 'class -> "form-control input-group-lg")

		        <input class="btn btn-lg btn-primary" type="submit" value="S'identifier">

	    }

}


text:
/*****************************************************************************/
/**
 *  @file   GridPoint.h
 *  @author Naohisa Sakamoto
 */
/*****************************************************************************/
#pragma once
#include <string>
#include <fstream>
#include <kvs/ValueArray>
#include <kvs/Type>

namespace kvs
{

namespace grads
{

/*===========================================================================*/
/**
 *  @brief  XDEF/YDEF/ZDEF entry.
 */
/*===========================================================================*/
struct XYZDef
{
    enum MappingMethod
    {
        Linear,
        Levels,
        GausT62,
        GausR15,
        GausR20,
        GausR30,
        GausR40
    };

    size_t num = 0; ///< number of grid points
    MappingMethod mapping = MappingMethod::Linear; ///< mapping method
    kvs::ValueArray<kvs::Real32> values{}; ///< values

    bool read( std::string line, std::ifstream& ifs );
};

} // end of namespace grads

} // end of namespace kvs


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using MongoDB.Linq.Expressions;
using MongoDB.Util;
using System.Reflection;

namespace MongoDB.Linq.Translators
{
    internal class FieldBinder : ExpressionVisitor
    {
        private static readonly HashSet<Type> CollectionTypes = new HashSet<Type>
        {
            typeof(ICollection), typeof(ICollection<>)
        };

        private Alias _alias;
        private FieldFinder _finder;
        private Type _elementType;
        private Dictionary<MemberInfo, Expression> _memberMap;

        public Expression Bind(Expression expression, Type elementType)
        {
            _alias = new Alias();
            _memberMap = new Dictionary<MemberInfo, Expression>();
            _finder = new FieldFinder(_memberMap);
            _elementType = elementType;
            return Visit(expression);
        }

        protected override Expression Visit(Expression exp)
        {
            if (exp == null)
                return exp;

            var fieldName = _finder.Find(exp);
            if (fieldName != null)
                return new FieldExpression(exp, _alias, fieldName);

            return base.Visit(exp);
        }

        protected override NewExpression VisitNew(NewExpression nex)
        {
            var newNex = base.VisitNew(nex);
            if (newNex != nex && newNex.Members != null) //we only get Members when it is an anonymous type
            {
                var properties = newNex.Type.GetProperties();
                var joined = from param in newNex.Constructor.GetParameters()
                             join prop in properties on param.Name equals prop.Name
                             select new { Parameter = param, Property = prop };

                foreach (var j in joined)
                    _memberMap[j.Property] = newNex.Arguments[j.Parameter.Position];
            }
            return newNex;
        }

        protected override Expression VisitParameter(ParameterExpression p)
        {
            if(p.Type == _elementType)
                return new FieldExpression(p, _alias, "*");

            return base.VisitParameter(p);
        }

        private class FieldFinder : ExpressionVisitor
        {
            private Stack<string> _fieldParts;
            private bool _isBlocked;
            private readonly Dictionary<MemberInfo, Expression> _memberMap;

            public FieldFinder(Dictionary<MemberInfo, Expression> memberMap)
            {
                _memberMap = memberMap;
            }

            public string Find(Expression expression)
            {
                if (expression.NodeType == ExpressionType.Parameter)
                    return null;

                _fieldParts = new Stack<string>();
                _isBlocked = false;
                Visit(expression);
                var fieldName = string.Join(".", _fieldParts.ToArray());
                if (_isBlocked)
                    fieldName = null;

                return fieldName;
            }

            protected override Expression Visit(Expression exp)
            {
                if (exp == null)
                    return null;

                switch (exp.NodeType)
                {
                    case ExpressionType.ArrayIndex:
                    case ExpressionType.Call:
                    case ExpressionType.MemberAccess:
                    case ExpressionType.Parameter:
                        return base.Visit(exp);
                    default:
                        _isBlocked = true;
                        return exp;
                }
            }

            protected override Expression VisitBinary(BinaryExpression b)
            {
                //this is an ArrayIndex Node
                _fieldParts.Push(((int)((ConstantExpression)b.Right).Value).ToString());
                Visit(b.Left);
                return b;
            }

            protected override Expression VisitMemberAccess(MemberExpression m)
            {
                var declaringType = m.Member.DeclaringType;
                if (!IsNativeToMongo(declaringType) && !IsCollection(declaringType))
                {
                    Expression e;
                    if (_memberMap.TryGetValue(m.Member, out e) && e is FieldExpression)
                    {
                        _fieldParts.Push(((FieldExpression)e).Name);
                        _memberMap[m.Member] = e;
                        Visit(m.Expression);
                        return m;
                    }
                    else if (e == null)
                    {
                        _fieldParts.Push(m.Member.Name);
                        Visit(m.Expression);
                        return m;
                    }
                }

                _isBlocked = true;
                return m;
            }

            protected override Expression VisitMethodCall(MethodCallExpression m)
            {
                if (m.Method.DeclaringType == typeof(Queryable) || m.Method.DeclaringType == typeof(Enumerable))
                {
                    if (m.Method.Name == "ElementAt" || m.Method.Name == "ElementAtOrDefault")
                    {
                        _fieldParts.Push(((int)((ConstantExpression)m.Arguments[1]).Value).ToString());
                        Visit(m.Arguments[0]);
                        return m;
                    }
                }
                else if (m.Method.DeclaringType == typeof(MongoQueryable))
                {
                    if (m.Method.Name == "Key")
                    {
                        _fieldParts.Push((string)((ConstantExpression)m.Arguments[1]).Value);
                        Visit(m.Arguments[0]);
                        return m;
                    }
                }
                else if (typeof(Document).IsAssignableFrom(m.Method.DeclaringType))
                {
                    if (m.Method.Name == "get_Item") //TODO: does this work for VB?
                    {
                        _fieldParts.Push((string)((ConstantExpression)m.Arguments[0]).Value);
                        Visit(m.Object);
                        return m;
                    }
                }
                else if (typeof(IList<>).IsOpenTypeAssignableFrom(m.Method.DeclaringType) || typeof(IList).IsAssignableFrom(m.Method.DeclaringType))
                {
                    if (m.Method.Name == "get_Item")
                    {
                        _fieldParts.Push(((int)((ConstantExpression)m.Arguments[0]).Value).ToString());
                        Visit(m.Object);
                        return m;
                    }
                }

                _isBlocked = true;
                return m;
            }

            //protected override Expression VisitParameter(ParameterExpression p)
            //{
            //    if (p.Type.IsGenericType && p.Type.GetGenericTypeDefinition() == typeof(IGrouping<,>))
            //        _isBlocked = true;
            //    return base.VisitParameter(p);
            //}

            private static bool IsCollection(Type type)
            {
                //HACK: this is going to generally subvert custom objects that implement ICollection or ICollection<T>,
                //but are not collections
                if (type.IsGenericType)
                    type = type.GetGenericTypeDefinition();

                return CollectionTypes.Any(x => x.IsAssignableFrom(type));
            }

            private static bool IsNativeToMongo(Type type)
            {
                //TODO: this code exists here and in BsonClassMapDescriptor.  Should probably be centralized...
                var typeCode = Type.GetTypeCode(type);

                if (typeCode != TypeCode.Object)
                    return true;

                if (type == typeof(Guid))
                    return true;

                if (type == typeof(Oid))
                    return true;

                if (type == typeof(byte[]))
                    return true;

                return false;
            }
        }
    }
}


text:
#import "UIViewController.h"

#import "SBUIStarkHomeScreenBackgroundProviderInterface-Protocol.h"

@interface SBUIStarkHomeScreenBackgroundProviderViewController : UIViewController <SBUIStarkHomeScreenBackgroundProviderInterface>
{
    struct CGRect _viewportFrame;
}

+ (id)_exportedInterface;
+ (id)_remoteViewControllerInterface;
@property(nonatomic) struct CGRect viewportFrame; // @synthesize viewportFrame=_viewportFrame;
- (void)switchToState:(id)arg1 withAnimationName:(id)arg2;
- (void)dealloc;
- (id)initWithNibName:(id)arg1 bundle:(id)arg2;

@end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace FormsGeneratorWebApplication.Models
{
    public class SelectedModel
    {
        [Key]
        public int key { get; set; }

        //this is the string for the selected option that this model represents
        public virtual string selected { get; set; }

        //this is the question that this selected option belongs to
        public virtual FormItemModel question { get; set; }
    }
}


text:
module Encase
  require_relative 'object_item'
  require_relative 'factory_item'
  require_relative 'singleton_item'

  class ContainerItemFactory
    def self.build(type, container)
      container_item_for(type).new(container)
    end

    def self.container_item_for(type)
      case type
      when 'object' then ObjectItem
      when 'factory' then FactoryItem
      when 'singleton' then SingletonItem
      else
        ContainerItem
      end
    end
  end
end


text:
.class Lcom/android/systemui/qs/bar/QuickConnectBar$3;
.super Landroid/animation/AnimatorListenerAdapter;
.source "QuickConnectBar.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/android/systemui/qs/bar/QuickConnectBar;->animateViews(Landroid/view/View;Landroid/view/View;)V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/systemui/qs/bar/QuickConnectBar;

.field final synthetic val$out:Landroid/view/View;

# direct methods
.method constructor <init>(Lcom/android/systemui/qs/bar/QuickConnectBar;Landroid/view/View;)V
    .locals 0

    iput-object p1, p0, Lcom/android/systemui/qs/bar/QuickConnectBar$3;->this$0:Lcom/android/systemui/qs/bar/QuickConnectBar;

    iput-object p2, p0, Lcom/android/systemui/qs/bar/QuickConnectBar$3;->val$out:Landroid/view/View;

    invoke-direct {p0}, Landroid/animation/AnimatorListenerAdapter;-><init>()V

    return-void
.end method

# virtual methods
.method public onAnimationEnd(Landroid/animation/Animator;)V
    .locals 2

    iget-object v0, p0, Lcom/android/systemui/qs/bar/QuickConnectBar$3;->val$out:Landroid/view/View;

    const/16 v1, 0x8

    invoke-virtual {v0, v1}, Landroid/view/View;->setVisibility(I)V

    iget-object v0, p0, Lcom/android/systemui/qs/bar/QuickConnectBar$3;->this$0:Lcom/android/systemui/qs/bar/QuickConnectBar;

    invoke-static {v0}, Lcom/android/systemui/qs/bar/QuickConnectBar;->-get0(Lcom/android/systemui/qs/bar/QuickConnectBar;)Landroid/view/ViewGroup;

    move-result-object v0

    iget-object v1, p0, Lcom/android/systemui/qs/bar/QuickConnectBar$3;->val$out:Landroid/view/View;

    invoke-virtual {v0, v1}, Landroid/view/ViewGroup;->removeView(Landroid/view/View;)V

    return-void
.end method


text:
from zope.interface import implementer

from .shell_script_installer import IShellScriptInstaller

@implementer(IShellScriptInstaller)
class PoshScriptInstaller:
	pass


text:
import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { ItemListPage } from './item-list';
import { TranslateModule } from '@ngx-translate/core';
import { ItemsModule } from '../../item.module';
import { SharedModule } from '../../../shared/shared.module';
import { InventoryBarComponentModule } from '../../../inventory/components/inventory-bar/inventory-bar.module';

@NgModule({
  declarations: [
    ItemListPage,
  ],
  imports: [
    IonicPageModule.forChild(ItemListPage),
    TranslateModule.forChild(),
    ItemsModule,
    SharedModule,
    InventoryBarComponentModule,
  ],
  exports: [
    ItemListPage,
  ]
})
export class ItemListPageModule { }


text:
package org.apache.jena.sparql.sse;

import org.apache.jena.graph.Node;

public class ItemTransformBase implements ItemTransform
{
    public static final boolean COPY_ALWAYS = true;
    public static final boolean COPY_ONLY_ON_CHANGE = false;
    private boolean alwaysCopy = false;

    public ItemTransformBase() {
        this(COPY_ONLY_ON_CHANGE);
    }

    public ItemTransformBase(boolean alwaysDuplicate) {
        this.alwaysCopy = alwaysDuplicate;
    }

    @Override
    public Item transform(Item item, ItemList itemList) {
        return xform(item, itemList);
    }

    @Override
    public Item transform(Item item, Node node) {
        return xform(item, node);
    }

    @Override
    public Item transform(Item item, String symbol) {
        return xform(item, symbol);
    }

    @Override
    public Item transformNil(Item item) {
        return xformNil(item);
    }

    private Item xform(Item item, ItemList itemList) {
        if ( !alwaysCopy && item.getList() == itemList )
            return item;
        return Item.createList(itemList, item.getLine(), item.getColumn());
    }

    private Item xform(Item item, Node node) {
        if ( !alwaysCopy && item.getNode().equals(node) )
            return item;
        return Item.createNode(node, item.getLine(), item.getColumn());
    }

    private Item xform(Item item, String symbol) {
        if ( !alwaysCopy && item.getSymbol().equals(symbol) )
            return item;
        return Item.createSymbol(symbol, item.getLine(), item.getColumn());
    }

    private Item xformNil(Item item) {
        return item;
    }

}


text:
typedef struct
{
    char szAppName[ 32 ];
    HANDLE hInstance;
    HWND hwndMainFrame;
    BOOL bFatalError;
} AppVars;

void PlayerMessageBox( UINT nResource );

int PASCAL PlayMovie( HINSTANCE hInstance,
                    HINSTANCE hPrevInstance,
                    int nCmdShow , HWND Hwnd);

void PlayVideoInWindow(HWND hTargetWindow);
void    NewDoMainLoop( void );

#endif  // CPLAY_INC


text:
$output.resource("META-INF", "spring-persistence.xml")##
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
             version="2.1">
	<persistence-unit name="${configuration.applicationName}PU" transaction-type="RESOURCE_LOCAL">
		<description><![CDATA[
			Main persistence unit.
			It is named spring-persistence.xml to prevent JBoss from picking it automatically, which would create a mess as we use Spring.
			With JBoss/Spring it is required to list the classes explicitly.
		]]></description>
		<mapping-file>META-INF/spring-orm.xml</mapping-file>
#foreach ($entity in $project.withoutManyToManyJoinEntities.list)
#if(!$entity.isVirtual())
		<class>${entity.model.fullType}</class>
#end
#end
#if($project.search.isNotEmpty())
		<properties>
			<property name="hibernate.search.model_mapping" value="${Search.packageName}.SearchMappingFactory" />
		</properties>
#end
	</persistence-unit>
</persistence>


text:
BUILDDIR = ../..

PACKAGE = java.jexec
PRODUCT = sun
PROGRAM = jexec

include $(BUILDDIR)/common/Defs.gmk

ifeq ($(COMPILE_APPROACH),batch)
  override COMPILE_APPROACH = normal
endif

include $(BUILDDIR)/common/Rules.gmk

JEXE_SRC =      $(PLATFORM_SRC)/bin

FILES_c =       jexec.c
FILES_o =       $(patsubst %.c,$(OBJDIR)/%.o,$(FILES_c))

vpath %.c       $(JEXE_SRC)

ifeq ($(PLATFORM), linux)
  #
  # On Linux jexec goes in lib, not lib/<arch>
  #
  LIB_LOCATION = $(LIBDIR)

  #
  # Also include the manifest_info.h header file.
  #
  OTHER_INCLUDES += -I$(SHARE_SRC)/bin
endif # PLATFORM

build: $(LIB_LOCATION)/$(PROGRAM)

$(LIB_LOCATION)/$(PROGRAM):: $(FILES_o)
	$(prep-target)
	$(LINK_PRE_CMD) $(CC) $(LDFLAGS) $(FILES_o) $(CC_OBJECT_OUTPUT_FLAG)$@

clean clobber::
	$(RM) $(FILES_o) $(LIB_LOCATION)/$(PROGRAM)


text:
var xmlrpc = require('xmlrpc');
var RSVP = require('rsvp');

module.exports = function (host) {
	var hostIp,
	hostPort,
	hostUsername,
	hostPassword,
	client;

	if (typeof host === 'string') {
		var hostParts = host.split(':');

		if (hostParts.length === 2) {
			hostIp = hostParts[0];
			hostPort = hostParts[1];
		} else {
			throw "Argument exception, invalid host provided : " + host;
		}

	} else {
		if (host.hasOwnProperty('ip') && host.hasOwnProperty('port')) {
			hostIp = host.ip;
			hostPort = host.port;

			if (host.hasOwnProperty('username') && host.hasOwnProperty('password')) {
				hostUsername = host.username;
				hostPassword = host.password;
			}
		} else {
			throw "Argument exception, invalid host details provided : " + JSON.stringify(host);
		}
	}

	this.connect = function () {
		this.client = xmlrpc.createClient({
			host: hostIp,
			port: hostPort,
			path: '/RPC2',
			basic_auth: {
				user: hostUsername,
				pass: hostPassword
			}
		});
	}

	this.init = function () {
		var self = this;

		return new RSVP.Promise(function(resolve, reject) {
		  self.client.methodCall('system.listMethods', null, function (error, value) {
		    if (error) {
		    	console.log('ERROR : server.system.listMethods' + error);
		    	reject(error);
		    } else {
		    	var methods = value;

		    	methods.forEach(function (apiMethod) {
		    		self[apiMethod.split('.').pop()] = function () {
		    			var args = Array.prototype.slice.call(arguments);
					    callback = args.pop();

					    self.xmlrpcMethodCall(apiMethod, args, callback);
		    		}
		    	});

		    	resolve();
		    }
		  });
		});
	}

	this.xmlrpcMethodCall = function(method, args, callback) {
    	this.client.methodCall(method, args, callback);
	}

}


text:
Title: The Real Cost Of An iPhone 5 - Forbes
Date: 2012-09-13 12:18
Link: http://www.forbes.com/sites/kellyclay/2012/09/12/the-real-cost-of-an-iphone-5/
Tags: Tech

This is actually on Forbes.com, I kid you not:

> Let's break that down in terms of total cost with the cheapest version of each accessory:

> iPhone 5: $199 (base 16GB unit with contract)
> Case: $50
> Car Charger: $10
> Stereo Dock: $100
> Armband: $10

> Minimum Total Cost: $369

No, the *minimum* total cost is $199 + contract + tax. The cost of re-buying an iPhone *and* all your stupid accessories instead of getting a $39 adapter is, apparently, $369.

Forbes.com has become the Geo Cities of journalism.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>FixCrLfFilter (Apache Ant API)</title>
<meta name="date" content="2016-04-09">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.tools.ant.filters

Class FixCrLfFilter

java.lang.Object

java.io.Reader

java.io.FilterReader

org.apache.tools.ant.filters.BaseFilterReader

org.apache.tools.ant.filters.BaseParamFilterReader

org.apache.tools.ant.filters.FixCrLfFilter

All Implemented Interfaces:

java.io.Closeable, java.lang.AutoCloseable, java.lang.Readable, ChainableReader, Parameterizable

public final class FixCrLfFilter
extends BaseParamFilterReader
implements ChainableReader

Converts text to local OS formatting conventions, as well as repair text
 damaged by misconfigured or misguided editors or file transfer programs.

 This filter can take the following arguments:

eof

eol

fixlast

javafiles

tab

tablength

 None of which are required.

 This version generalises the handling of EOL characters, and allows for
 CR-only line endings (the standard on Mac systems prior to OS X). Tab
 handling has also been generalised to accommodate any tabwidth from 2 to 80,
 inclusive. Importantly, it can leave untouched any literal TAB characters
 embedded within Java string or character constants.

 Caution: run with care on carefully formatted files. This may
 sound obvious, but if you don't specify asis, presume that your files are
 going to be modified. If "tabs" is "add" or "remove", whitespace characters
 may be added or removed as necessary. Similarly, for EOLs, eol="asis"
 actually means convert to your native O/S EOL convention while eol="crlf" or
 cr="add" can result in CR characters being removed in one special case
 accommodated, i.e., CRCRLF is regarded as a single EOL to handle cases where
 other programs have converted CRLF into CRCRLF.

 Example:

 <<fixcrlf tab="add" eol="crlf" eof="asis"/>

 Or:

 <filterreader classname="org.apache.tools.ant.filters.FixCrLfFilter">
   <param eol="crlf" tab="asis"/>
  </filterreader>

Nested Class Summary

Nested Classes

Modifier and Type
Class and Description

static class
FixCrLfFilter.AddAsisRemove

Enumerated attribute with the values "asis", "add" and "remove".

static class
FixCrLfFilter.CrLf

Enumerated attribute with the values "asis", "cr", "lf" and "crlf".

Field Summary

Fields inherited from class java.io.FilterReader

in

Fields inherited from class java.io.Reader

lock

Constructor Summary

Constructors

Constructor and Description

FixCrLfFilter()

Constructor for "dummy" instances.

FixCrLfFilter(java.io.Reader in)

Create a new filtered reader.

Method Summary

Methods

Modifier and Type
Method and Description

java.io.Reader
chain(java.io.Reader rdr)

Create a new FixCrLfFilter using the passed in Reader for instantiation.

FixCrLfFilter.AddAsisRemove
getEof()

Get how DOS EOF (control-z) characters are being handled.

FixCrLfFilter.CrLf
getEol()

Get how EndOfLine characters are being handled.

boolean
getFixlast()

Get whether a missing EOL be added to the final line of the stream.

boolean
getJavafiles()

Get whether the stream is to be treated as though it contains Java
 source.

FixCrLfFilter.AddAsisRemove
getTab()

Return how tab characters are being handled.

int
getTablength()

Get the tab length to use.

int
read()

Return the next character in the filtered stream.

void
setEof(FixCrLfFilter.AddAsisRemove attr)

Specify how DOS EOF (control-z) characters are to be handled.

void
setEol(FixCrLfFilter.CrLf attr)

Specify how end of line (EOL) characters are to be handled.

void
setFixlast(boolean fixlast)

Specify whether a missing EOL will be added to the final line of input.

void
setJavafiles(boolean javafiles)

Indicate whether this stream contains Java source.

void
setTab(FixCrLfFilter.AddAsisRemove attr)

Specify how tab characters are to be handled.

void
setTablength(int tabLength)

Specify tab length in characters.

Methods inherited from class org.apache.tools.ant.filters.BaseParamFilterReader

getParameters, setParameters

Methods inherited from class org.apache.tools.ant.filters.BaseFilterReader

getInitialized, getProject, read, readFully, readLine, setInitialized, setProject, skip

Methods inherited from class java.io.FilterReader

close, mark, markSupported, ready, reset

Methods inherited from class java.io.Reader

read, read

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

FixCrLfFilter

public FixCrLfFilter()

Constructor for "dummy" instances.

See Also:

BaseFilterReader.BaseFilterReader()

FixCrLfFilter

public FixCrLfFilter(java.io.Reader in)
              throws java.io.IOException

Create a new filtered reader.

Parameters:

in - A Reader object providing the underlying stream. Must not be
            null.

Throws:

java.io.IOException - on error.

Method Detail

chain

public java.io.Reader chain(java.io.Reader rdr)

Create a new FixCrLfFilter using the passed in Reader for instantiation.

Specified by:

chain in interface ChainableReader

Parameters:

rdr - A Reader object providing the underlying stream. Must not be
            null.

Returns:

a new filter based on this configuration, but filtering the
         specified reader.

getEof

public FixCrLfFilter.AddAsisRemove getEof()

Get how DOS EOF (control-z) characters are being handled.

Returns:

values:

add: ensure that there is an eof at the end of the file

asis: leave eof characters alone

remove: remove any eof character found at the end

getEol

public FixCrLfFilter.CrLf getEol()

Get how EndOfLine characters are being handled.

Returns:

values:

asis: convert line endings to your O/S convention

cr: convert line endings to CR

lf: convert line endings to LF

crlf: convert line endings to CRLF

getFixlast

public boolean getFixlast()

Get whether a missing EOL be added to the final line of the stream.

Returns:

true if a filtered file will always end with an EOL

getJavafiles

public boolean getJavafiles()

Get whether the stream is to be treated as though it contains Java
 source.

 This attribute is only used in association with the "tab"
 attribute. Tabs found in Java literals are protected from changes by this
 filter.

Returns:

true if whitespace in Java character and string literals is
         ignored.

getTab

public FixCrLfFilter.AddAsisRemove getTab()

Return how tab characters are being handled.

Returns:

values:

add: convert sequences of spaces which span a tab stop to
         tabs

asis: leave tab and space characters alone

remove: convert tabs to spaces

getTablength

public int getTablength()

Get the tab length to use.

Returns:

the length of tab in spaces

read

public int read()
         throws java.io.IOException

Return the next character in the filtered stream.

Overrides:

read in class java.io.FilterReader

Returns:

the next character in the resulting stream, or -1 if the end of
         the resulting stream has been reached.

Throws:

java.io.IOException - if the underlying stream throws an IOException during
                reading.

setEof

public void setEof(FixCrLfFilter.AddAsisRemove attr)

Specify how DOS EOF (control-z) characters are to be handled.

Parameters:

attr - valid values:

add: ensure that there is an eof at the end of the file

asis: leave eof characters alone

remove: remove any eof character found at the end

setEol

public void setEol(FixCrLfFilter.CrLf attr)

Specify how end of line (EOL) characters are to be handled.

Parameters:

attr - valid values:

asis: convert line endings to your O/S convention

cr: convert line endings to CR

lf: convert line endings to LF

crlf: convert line endings to CRLF

setFixlast

public void setFixlast(boolean fixlast)

Specify whether a missing EOL will be added to the final line of input.

Parameters:

fixlast - if true a missing EOL will be appended.

setJavafiles

public void setJavafiles(boolean javafiles)

Indicate whether this stream contains Java source.

 This attribute is only used in association with the "tab"
 attribute.

Parameters:

javafiles - set to true to prevent this filter from changing tabs found in
            Java literals.

setTab

public void setTab(FixCrLfFilter.AddAsisRemove attr)

Specify how tab characters are to be handled.

Parameters:

attr - valid values:

add: convert sequences of spaces which span a tab stop to
            tabs

asis: leave tab and space characters alone

remove: convert tabs to spaces

setTablength

public void setTablength(int tabLength)
                  throws java.io.IOException

Specify tab length in characters.

Parameters:

tabLength - specify the length of tab in spaces. Valid values are between
            2 and 80 inclusive. The default for this parameter is 8.

Throws:

java.io.IOException - on error.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package edu.neu.ccs.pyramid.regression.regression_tree;

import java.util.List;
import java.util.Optional;

/**
 * Created by chengli on 8/5/14.
 */
public class RegTreeConfig {
    private int numSplitIntervals=100;
    private int maxNumLeaves=2;
    private int minDataPerLeaf=0;
    private boolean parallel=true;
    private int numActiveFeatures=10;
    //"none", "weak", "strong", "xgboost"
    private String monotonicityType="none";

    public RegTreeConfig setMaxNumLeaves(int maxNumLeaves) {
        this.maxNumLeaves = maxNumLeaves;
        return this;
    }

    public RegTreeConfig setMinDataPerLeaf(int minDataPerLeaf) {
        this.minDataPerLeaf = minDataPerLeaf;
        return this;
    }

    public RegTreeConfig setParallel(boolean parallel) {
        this.parallel = parallel;
        return this;
    }

    public RegTreeConfig setNumSplitIntervals(int numSplitIntervals) {
        if (numSplitIntervals<=1){
            throw new IllegalArgumentException("numSplitIntervals must be greater than 2");
        }
        this.numSplitIntervals = numSplitIntervals;
        return this;
    }

    public RegTreeConfig setNumActiveFeatures(int numActiveFeatures){
        this.numActiveFeatures = numActiveFeatures;
        return this;
    }

    public RegTreeConfig setMonotonicityType(String monotonicityType) {
        this.monotonicityType = monotonicityType;
        return this;
    }

    int getMaxNumLeaves() {
        return maxNumLeaves;
    }

    int getMinDataPerLeaf() {
        return minDataPerLeaf;
    }

    int getNumSplitIntervals() {
        return numSplitIntervals;
    }

    public int getNumActiveFeatures() {
        return numActiveFeatures;
    }

    public boolean isParallel() {
        return parallel;
    }

    public String getMonotonicityType() {
        return monotonicityType;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LibNLPCSharp.util.model
{

	public class ModelList<T> : AbstractList<T>, IObservable
	{

		////////////////////////////////////////////////////////////////
		// Constants
		////////////////////////////////////////////////////////////////

		////////////////////////////////////////////////////////////////
		// Variables
		////////////////////////////////////////////////////////////////

		private IObserver observer;

		////////////////////////////////////////////////////////////////
		// Constructors
		////////////////////////////////////////////////////////////////

		public ModelList()
		{
		}

		public ModelList(IObserver observer)
		{
			this.observer = observer;
		}

		////////////////////////////////////////////////////////////////
		// Properties
		////////////////////////////////////////////////////////////////

		public virtual IObserver Observer
		{
			get {
				return observer;
			}
			set {
				this.observer = value;
				foreach (T item in innerList) {
					if (item is IObservable) {
						IObservable hcf = (IObservable)item;
						hcf.Observer = observer;
					}
				}
			}
		}

		public override T this[int index]
		{
			get {
				return base[index];
			}
			set {
				if (!Util.Equals(innerList[index], value)) {
					innerList[index] = value;
					if (value is IObservable) {
						IObservable hcf = (IObservable)value;
						hcf.Observer = observer;
					}
					if (observer != null) observer.Notify();
				}
			}
		}

		////////////////////////////////////////////////////////////////
		// Methods
		////////////////////////////////////////////////////////////////

		public virtual void AddRange(IEnumerable<T> items)
		{
			if (observer != null) observer.SuspendEvents();
			foreach (T item in items) {
				Add(item);
			}
			if (observer != null) observer.ResumeEvents();
		}

		public override void Add(T item)
		{
			innerList.Add(item);
			if (item is IObservable) {
				IObservable hcf = (IObservable)item;
				hcf.Observer = observer;
			}
			if (observer != null) observer.Notify();
		}

		public override void Clear()
		{
			if (innerList.Count == 0)
				return;
			foreach (T item in innerList) {
				if (item is IObservable) {
					IObservable hcf = (IObservable)item;
					hcf.Observer = null;
				}
			}
			innerList.Clear();
			if (observer != null) observer.Notify();
		}

		public override void Insert(int index, T item)
		{
			innerList.Insert(index, item);
			if (item is IObservable) {
				IObservable hcf = (IObservable)item;
				hcf.Observer = observer;
			}
			if (observer != null) observer.Notify();
		}

		public override bool Remove(T item)
		{
			if (innerList.Remove(item)) {
				if (item is IObservable) {
					IObservable hcf = (IObservable)item;
					hcf.Observer = null;
				}
				if (observer != null) observer.Notify();
				return true;
			} else {
				return false;
			}
		}

		public override void RemoveAt(int index)
		{
			T item = innerList[index];
			if (item is IObservable) {
				IObservable hcf = (IObservable)item;
				hcf.Observer = null;
			}
			innerList.RemoveAt(index);
			if (observer != null) observer.Notify();
		}

	}

}


text:
// Task 2.1
//--------------------------------

// The OakStreaming constructor is available as a global variable

/* ### Write code here ### */

//---------------------------------

var theSharedYjsArray = null;
var streamSource = false;

console.log("This is task 2");

window.handleFiles = function (files) {
   streamSource = true;

   // Task 2.2
   //--------------------------------------------------

   // files[0] contains the video file that has been selected by the user
   // webTorrent_trackers: [["wss://tracker.webtorrent.io"]]  specifies the WebTorrent trackers (which also function as signaling servers) that will by contacted
   // peer_upload_limit_multiplier: 1.5    specifies that each peer is not allowed to upload more than 1.5 times as much as it has downloaded.

   /* ### Write code here ### */

   //--------------------------------------------------

}

function addToSharedArray(streamInformationObject){
   if(theSharedArray !== null){
      theSharedArray.insert(0, [streamInformationObject]);
   } else {
      setTimeout(function(){addToSharedArray(streamInformationObject);},250);
   }
}

Y({
  db: {
    name: 'memory'
  },
  connector: {
    url : "http://gaudi.informatik.rwth-aachen.de:9914",
    name: 'webrtc',
    room: 'WebTorrent-Streaming-yeah'
  },
  share: {
     myArray : 'Array'
  }
}).then(function (y){
   theSharedYjsArray = y.share.myArray;

   theSharedYjsArray.observe(function(event){
      console.log("The following event-type was thrown: "+ event.type);
      console.log("The event object has more information:");
      console.log(event);
      if(!streamSource){

      // Task 2.3
      //--------------------------------------------------

      /* ### Write code here ### */

      //--------------------------------------------------

      }
   });
});


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GoldenLayout = void 0;
const resolved_config_1 = require("./config/resolved-config");
const external_error_1 = require("./errors/external-error");
const internal_error_1 = require("./errors/internal-error");
const i18n_strings_1 = require("./utils/i18n-strings");
const utils_1 = require("./utils/utils");
const virtual_layout_1 = require("./virtual-layout");
/** @public */
class GoldenLayout extends virtual_layout_1.VirtualLayout {
    /** @internal */
    constructor(configOrOptionalContainer, containerOrBindComponentEventHandler, unbindComponentEventHandler) {
        super(configOrOptionalContainer, containerOrBindComponentEventHandler, unbindComponentEventHandler, true);
        /** @internal */
        this._componentTypesMap = new Map();
        /** @internal */
        this._virtuableComponentMap = new Map();
        /** @internal */
        this._containerVirtualRectingRequiredEventListener = (container, width, height) => this.handleContainerVirtualRectingRequiredEvent(container, width, height);
        /** @internal */
        this._containerVirtualVisibilityChangeRequiredEventListener = (container, visible) => this.handleContainerVirtualVisibilityChangeRequiredEvent(container, visible);
        /** @internal */
        this._containerVirtualZIndexChangeRequiredEventListener = (container, logicalZIndex, defaultZIndex) => this.handleContainerVirtualZIndexChangeRequiredEvent(container, logicalZIndex, defaultZIndex);
        // we told VirtualLayout to not call init() (skipInit set to true) so that Golden Layout can initialise its properties before init is called
        if (!this.deprecatedConstructor) {
            this.init();
        }
    }
    /**
     * Register a new component type with the layout manager.
     *
     * @deprecated See {@link https://stackoverflow.com/questions/40922531/how-to-check-if-a-javascript-function-is-a-constructor}
     * instead use {@link (GoldenLayout:class).registerComponentConstructor}
     * or {@link (GoldenLayout:class).registerComponentFactoryFunction}
     */
    registerComponent(name, componentConstructorOrFactoryFtn, virtual = false) {
        if (typeof componentConstructorOrFactoryFtn !== 'function') {
            throw new external_error_1.ApiError('registerComponent() componentConstructorOrFactoryFtn parameter is not a function');
        }
        else {
            if (componentConstructorOrFactoryFtn.hasOwnProperty('prototype')) {
                const componentConstructor = componentConstructorOrFactoryFtn;
                this.registerComponentConstructor(name, componentConstructor, virtual);
            }
            else {
                const componentFactoryFtn = componentConstructorOrFactoryFtn;
                this.registerComponentFactoryFunction(name, componentFactoryFtn, virtual);
            }
        }
    }
    /**
     * Register a new component type with the layout manager.
     */
    registerComponentConstructor(typeName, componentConstructor, virtual = false) {
        if (typeof componentConstructor !== 'function') {
            throw new Error(i18n_strings_1.i18nStrings[1 /* PleaseRegisterAConstructorFunction */]);
        }
        const existingComponentType = this._componentTypesMap.get(typeName);
        if (existingComponentType !== undefined) {
            throw new external_error_1.BindError(`${i18n_strings_1.i18nStrings[3 /* ComponentIsAlreadyRegistered */]}: ${typeName}`);
        }
        this._componentTypesMap.set(typeName, {
            constructor: componentConstructor,
            factoryFunction: undefined,
            virtual,
        });
    }
    /**
     * Register a new component with the layout manager.
     */
    registerComponentFactoryFunction(typeName, componentFactoryFunction, virtual = false) {
        if (typeof componentFactoryFunction !== 'function') {
            throw new external_error_1.BindError('Please register a constructor function');
        }
        const existingComponentType = this._componentTypesMap.get(typeName);
        if (existingComponentType !== undefined) {
            throw new external_error_1.BindError(`${i18n_strings_1.i18nStrings[3 /* ComponentIsAlreadyRegistered */]}: ${typeName}`);
        }
        this._componentTypesMap.set(typeName, {
            constructor: undefined,
            factoryFunction: componentFactoryFunction,
            virtual,
        });
    }
    /**
     * Register a component function with the layout manager. This function should
     * return a constructor for a component based on a config.
     * This function will be called if a component type with the required name is not already registered.
     * It is recommended that applications use the {@link (VirtualLayout:class).getComponentEvent} and
     * {@link (VirtualLayout:class).releaseComponentEvent} instead of registering a constructor callback
     * @deprecated use {@link (GoldenLayout:class).registerGetComponentConstructorCallback}
     */
    registerComponentFunction(callback) {
        this.registerGetComponentConstructorCallback(callback);
    }
    /**
     * Register a callback closure with the layout manager which supplies a Component Constructor.
     * This callback should return a constructor for a component based on a config.
     * This function will be called if a component type with the required name is not already registered.
     * It is recommended that applications use the {@link (VirtualLayout:class).getComponentEvent} and
     * {@link (VirtualLayout:class).releaseComponentEvent} instead of registering a constructor callback
     */
    registerGetComponentConstructorCallback(callback) {
        if (typeof callback !== 'function') {
            throw new Error('Please register a callback function');
        }
        if (this._getComponentConstructorFtn !== undefined) {
            console.warn('Multiple component functions are being registered.  Only the final registered function will be used.');
        }
        this._getComponentConstructorFtn = callback;
    }
    getRegisteredComponentTypeNames() {
        const typeNamesIterableIterator = this._componentTypesMap.keys();
        return Array.from(typeNamesIterableIterator);
    }
    /**
     * Returns a previously registered component instantiator.  Attempts to utilize registered
     * component type by first, then falls back to the component constructor callback function (if registered).
     * If neither gets an instantiator, then returns `undefined`.
     * Note that `undefined` will return if config.componentType is not a string
     *
     * @param config - The item config
     * @public
     */
    getComponentInstantiator(config) {
        let instantiator;
        const typeName = resolved_config_1.ResolvedComponentItemConfig.resolveComponentTypeName(config);
        if (typeName !== undefined) {
            instantiator = this._componentTypesMap.get(typeName);
        }
        if (instantiator === undefined) {
            if (this._getComponentConstructorFtn !== undefined) {
                instantiator = {
                    constructor: this._getComponentConstructorFtn(config),
                    factoryFunction: undefined,
                    virtual: false,
                };
            }
        }
        return instantiator;
    }
    /** @internal */
    bindComponent(container, itemConfig) {
        let instantiator;
        const typeName = resolved_config_1.ResolvedComponentItemConfig.resolveComponentTypeName(itemConfig);
        if (typeName !== undefined) {
            instantiator = this._componentTypesMap.get(typeName);
        }
        if (instantiator === undefined) {
            if (this._getComponentConstructorFtn !== undefined) {
                instantiator = {
                    constructor: this._getComponentConstructorFtn(itemConfig),
                    factoryFunction: undefined,
                    virtual: false,
                };
            }
        }
        let result;
        if (instantiator !== undefined) {
            const virtual = instantiator.virtual;
            // handle case where component is obtained by name or component constructor callback
            let componentState;
            if (itemConfig.componentState === undefined) {
                componentState = undefined;
            }
            else {
                // make copy
                componentState = utils_1.deepExtendValue({}, itemConfig.componentState);
            }
            let component;
            const componentConstructor = instantiator.constructor;
            if (componentConstructor !== undefined) {
                component = new componentConstructor(container, componentState, virtual);
            }
            else {
                const factoryFunction = instantiator.factoryFunction;
                if (factoryFunction !== undefined) {
                    component = factoryFunction(container, componentState, virtual);
                }
                else {
                    throw new internal_error_1.AssertError('LMBCFFU10008');
                }
            }
            if (virtual) {
                if (component === undefined) {
                    throw new internal_error_1.UnexpectedUndefinedError('GLBCVCU988774');
                }
                else {
                    const virtuableComponent = component;
                    const componentRootElement = virtuableComponent.rootHtmlElement;
                    if (componentRootElement === undefined) {
                        throw new external_error_1.BindError(`${i18n_strings_1.i18nStrings[5 /* VirtualComponentDoesNotHaveRootHtmlElement */]}: ${typeName}`);
                    }
                    else {
                        utils_1.ensureElementPositionAbsolute(componentRootElement);
                        this.container.appendChild(componentRootElement);
                        this._virtuableComponentMap.set(container, virtuableComponent);
                        container.virtualRectingRequiredEvent = this._containerVirtualRectingRequiredEventListener;
                        container.virtualVisibilityChangeRequiredEvent = this._containerVirtualVisibilityChangeRequiredEventListener;
                        container.virtualZIndexChangeRequiredEvent = this._containerVirtualZIndexChangeRequiredEventListener;
                    }
                }
            }
            result = {
                virtual: instantiator.virtual,
                component,
            };
        }
        else {
            // Use getComponentEvent
            result = super.bindComponent(container, itemConfig);
        }
        return result;
    }
    /** @internal */
    unbindComponent(container, virtual, component) {
        const virtuableComponent = this._virtuableComponentMap.get(container);
        if (virtuableComponent === undefined) {
            super.unbindComponent(container, virtual, component);
        }
        else {
            const componentRootElement = virtuableComponent.rootHtmlElement;
            if (componentRootElement === undefined) {
                throw new internal_error_1.AssertError('GLUC77743', container.title);
            }
            else {
                this.container.removeChild(componentRootElement);
                this._virtuableComponentMap.delete(container);
            }
        }
    }
    fireBeforeVirtualRectingEvent(count) {
        this._goldenLayoutBoundingClientRect = this.container.getBoundingClientRect();
        super.fireBeforeVirtualRectingEvent(count);
    }
    /** @internal */
    handleContainerVirtualRectingRequiredEvent(container, width, height) {
        const virtuableComponent = this._virtuableComponentMap.get(container);
        if (virtuableComponent === undefined) {
            throw new internal_error_1.UnexpectedUndefinedError('GLHCSCE55933');
        }
        else {
            const rootElement = virtuableComponent.rootHtmlElement;
            if (rootElement === undefined) {
                throw new external_error_1.BindError(i18n_strings_1.i18nStrings[4 /* ComponentIsNotVirtuable */] + ' ' + container.title);
            }
            else {
                const containerBoundingClientRect = container.element.getBoundingClientRect();
                const left = containerBoundingClientRect.left - this._goldenLayoutBoundingClientRect.left;
                rootElement.style.left = utils_1.numberToPixels(left);
                const top = containerBoundingClientRect.top - this._goldenLayoutBoundingClientRect.top;
                rootElement.style.top = utils_1.numberToPixels(top);
                utils_1.setElementWidth(rootElement, width);
                utils_1.setElementHeight(rootElement, height);
            }
        }
    }
    /** @internal */
    handleContainerVirtualVisibilityChangeRequiredEvent(container, visible) {
        const virtuableComponent = this._virtuableComponentMap.get(container);
        if (virtuableComponent === undefined) {
            throw new internal_error_1.UnexpectedUndefinedError('GLHCVVCRE55934');
        }
        else {
            const rootElement = virtuableComponent.rootHtmlElement;
            if (rootElement === undefined) {
                throw new external_error_1.BindError(i18n_strings_1.i18nStrings[4 /* ComponentIsNotVirtuable */] + ' ' + container.title);
            }
            else {
                utils_1.setElementDisplayVisibility(rootElement, visible);
            }
        }
    }
    /** @internal */
    handleContainerVirtualZIndexChangeRequiredEvent(container, logicalZIndex, defaultZIndex) {
        const virtuableComponent = this._virtuableComponentMap.get(container);
        if (virtuableComponent === undefined) {
            throw new internal_error_1.UnexpectedUndefinedError('GLHCVZICRE55935');
        }
        else {
            const rootElement = virtuableComponent.rootHtmlElement;
            if (rootElement === undefined) {
                throw new external_error_1.BindError(i18n_strings_1.i18nStrings[4 /* ComponentIsNotVirtuable */] + ' ' + container.title);
            }
            else {
                rootElement.style.zIndex = defaultZIndex;
            }
        }
    }
}
exports.GoldenLayout = GoldenLayout;
//# sourceMappingURL=golden-layout.js.map


text:
namespace boost {
namespace beast {
namespace detail {

struct temporary_buffer
{
    temporary_buffer() = default;
    temporary_buffer(temporary_buffer const&) = delete;
    temporary_buffer& operator=(temporary_buffer const&) = delete;

    ~temporary_buffer() noexcept
    {
        deallocate(data_);
    }

    BOOST_BEAST_DECL
    void
    append(string_view s);

    BOOST_BEAST_DECL
    void
    append(string_view s1, string_view s2);

    string_view
    view() const noexcept
    {
        return {data_, size_};
    }

    bool
    empty() const noexcept
    {
        return size_ == 0;
    }

private:
    BOOST_BEAST_DECL
    void
    unchecked_append(string_view s);

    BOOST_BEAST_DECL
    void
    grow(std::size_t n);

    void
    deallocate(char* data) noexcept
    {
        if (data != buffer_)
            delete[] data;
    }

    char buffer_[4096];
    char* data_ = buffer_;
    std::size_t capacity_ = sizeof(buffer_);
    std::size_t size_ = 0;
};

} // detail
} // beast
} // boost

#ifdef BOOST_BEAST_HEADER_ONLY
#include <boost/beast/core/detail/impl/temporary_buffer.ipp>
#endif

#endif


text:
<?php

namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * The path to the "home" route for your application.
     *
     * This is used by Laravel authentication to redirect users after login.
     *
     * @var string
     */
    public const HOME = '/profile';

    /**
     * Returns the relative URL to the home of the user
     *
     * @return string Relative URL
     */

    public static function home()
    {
        if( config( 'app.shop_registration' ) ) {
            return '/admin';
        }

        return airoute( 'aimeos_shop_account' );
    }

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        $this->configureRateLimiting();

        $this->routes(function () {
            Route::prefix('api')
                ->middleware('api')
                ->group(base_path('routes/api.php'));

            Route::middleware('web')
                ->group(base_path('routes/web.php'));
        });
    }

    /**
     * Configure the rate limiters for the application.
     *
     * @return void
     */
    protected function configureRateLimiting()
    {
        RateLimiter::for('api', function (Request $request) {
            return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
        });
    }
}


text:
namespace Highcharts
{
    using System.Drawing;

    public class SeriesPoint : Series
    {
        private readonly SolidBrush pointBrush = new SolidBrush(Color.Black);

        public SeriesPoint() : this("")
        { }

        public SeriesPoint(string name) : base(name)
        { }

        protected override void OnPaint(Graphics g, Rectangle clipRectangle)
        {
            pointBrush.Color = color;

            var pointRadius = collection.chart.circleRadius;
            var valueRange = GetValueRange();
            var xStep = GetXStep();

            for (float dataIterator = 0; dataIterator < data.Count; dataIterator += pointInterval)
            {
                int dataIndex = (int) dataIterator;

                double currentValue = data[dataIndex];

                float currentValueX = GetXFromIndex(dataIndex, xStep, clipRectangle) - pointRadius;
                float currentValueY = GetYFromValue(currentValue, valueRange, clipRectangle) - pointRadius;

                g.FillEllipse(pointBrush, currentValueX, currentValueY, pointRadius * 2, pointRadius * 2);

                SeriesPaint.PaintHoveredValueRect(this, g, currentValueX, currentValueY, xStep);
            }
        }

        protected override void OnPaintIcon(Graphics g, Rectangle clipRectangle)
        {
            pointBrush.Color = color;

            g.FillEllipse(pointBrush,  clipRectangle.Left + 4, clipRectangle.Top + 8, 8, 8);
        }
    }
}


text:
import React from 'react';
import { mount, shallow } from 'enzyme';
import Textarea from '../TextArea';

describe('Textarea', () => {
  describe('should render as expected', () => {
    const wrapper = mount(<Textarea id="testing" className="extra-class" />);

    const textarea = wrapper.find('textarea');

    describe('textarea', () => {
      it('renders a textarea', () => {
        expect(textarea.length).toEqual(1);
      });

      it('has the expected classes', () => {
        expect(textarea.hasClass('bx--text-area')).toEqual(true);
      });

      it('applies extra classes specified via className', () => {
        expect(textarea.hasClass('extra-class')).toEqual(true);
      });

      it('should set rows as expected', () => {
        expect(textarea.props().rows).toEqual(4);
        wrapper.setProps({ rows: 10 });
        expect(textarea.props().rows).toEqual(10);
      });

      it('should set cols as expected', () => {
        expect(textarea.props().cols).toEqual(50);
        wrapper.setProps({ cols: 200 });
        expect(textarea.props().cols).toEqual(200);
      });

      it('should set disabled as expected', () => {
        expect(textarea.props().disabled).toEqual(false);
        wrapper.setProps({ disabled: true });
        expect(textarea.props().disabled).toEqual(true);
      });

      it('should set placeholder as expected', () => {
        expect(textarea.props().placeholder).toEqual('Hint text here');
        wrapper.setProps({ placeholder: 'Type here' });
        expect(textarea.props().placeholder).toEqual('Type here');
      });

      it('should set value as expected', () => {
        wrapper.setProps({ value: 'value set' });
        expect(textarea.props().value).toEqual('value set');
      });

      it('should set defaultValue as expected', () => {
        wrapper.setProps({ defaultValue: 'default value' });
        expect(textarea.props().defaultValue).toEqual('default value');
      });
    });

    describe('label', () => {
      wrapper.setProps({ labelText: 'testLabel' });
      const renderedLabel = wrapper.find('label');

      it('renders a label', () => {
        expect(renderedLabel.length).toEqual(1);
      });

      it('label has expected text', () => {
        expect(renderedLabel.text()).toEqual('testLabel');
      });

      it('has the expected classes', () => {
        expect(renderedLabel.hasClass('bx--label')).toEqual(true);
      });
    });
  });

  describe('events', () => {
    describe('disabled textarea', () => {
      const onClick = jest.fn();
      const onChange = jest.fn();

      const wrapper = shallow(
        <Textarea id="test" onClick={onClick} onChange={onChange} disabled />
      );

      const textarea = wrapper.find('textarea');

      it('should not invoke onClick when textarea is clicked', () => {
        textarea.simulate('click');
        expect(onClick).not.toBeCalled();
      });

      it('should not invoke onChange', () => {
        textarea.simulate('change');
        expect(onChange).not.toBeCalled();
      });
    });

    describe('enabled textarea', () => {
      const onClick = jest.fn();
      const onChange = jest.fn();
      const eventObject = {
        target: { value: 'test' }
      };

      const wrapper = shallow(
        <Textarea id="test" onClick={onClick} onChange={onChange} />
      );

      const textarea = wrapper.find('textarea');

      it('should invoke onClick when textarea is clicked', () => {
        textarea.simulate('click');
        expect(onClick).toBeCalled();
      });

      it('should invoke onChange when textarea value is changed', () => {
        textarea.simulate('change', eventObject);
        expect(onChange).toBeCalledWith(eventObject);
      });
    });
  });
});


text:
#ifndef TREEMODEL_H
#define TREEMODEL_H

enum ItemFixedState {
    Movable,
    Fixed
};

#if defined(QT_CORE_LIB)
// Use Qt classes
#include <QAbstractItemModel>
#include <QModelIndex>
#include <QVariant>
#include <QObject>
#if defined(QT_GUI_LIB)
#include <QBrush>
#endif

#include "ustring.h"
#include "ubytearray.h"
#include "basetypes.h"
#include "types.h"
#include "treeitem.h"

#define UModelIndex QModelIndex
#else
// Use own implementation
#include "ustring.h"
#include "ubytearray.h"
#include "basetypes.h"
#include "types.h"
#include "treeitem.h"

class TreeModel;

class UModelIndex
{
    friend class TreeModel;

public:
    inline UModelIndex() : r(-1), c(-1), i(0), m(0) {}
    // compiler-generated copy/move ctors/assignment operators are fine!
    inline int row() const { return r; }
    inline int column() const { return c; }
    inline uint64_t internalId() const { return i; }
    inline void *internalPointer() const { return reinterpret_cast<void*>(i); }
    inline UModelIndex parent() const;
    inline UModelIndex child(int row, int column) const;
    inline CBString data(int role) const;
    inline const TreeModel *model() const { return m; }
    inline bool isValid() const { return (r >= 0) && (c >= 0) && (m != 0); }
    inline bool operator==(const UModelIndex &other) const { return (other.r == r) && (other.i == i) && (other.c == c) && (other.m == m); }
    inline bool operator!=(const UModelIndex &other) const { return !(*this == other); }
    inline bool operator<(const UModelIndex &other) const
    {
        return  r <  other.r
            || (r == other.r && (c <  other.c
            || (c == other.c && (i <  other.i
            || (i == other.i && m < other.m)))));
    }

private:
    inline UModelIndex(int arow, int acolumn, void *ptr, const TreeModel *amodel)
        : r(arow), c(acolumn), i(reinterpret_cast<uint64_t>(ptr)), m(amodel) {}
    inline UModelIndex(int arow, int acolumn, uint64_t id, const TreeModel *amodel)
        : r(arow), c(acolumn), i(id), m(amodel) {}
    int r, c;
    uint64_t i;
    const TreeModel *m;
};
#endif

#if defined(QT_CORE_LIB)
class TreeModel : public QAbstractItemModel
{
private:
    TreeItem *rootItem;
    bool markingEnabledFlag;

public:
    QVariant data(const UModelIndex &index, int role) const;
    Qt::ItemFlags flags(const UModelIndex &index) const;
    QVariant headerData(int section, Qt::Orientation orientation,
        int role = Qt::DisplayRole) const;
    TreeModel(QObject *parent = 0) : QAbstractItemModel(parent), markingEnabledFlag(true) {
        rootItem = new TreeItem(0, Types::Root, 0, UString(), UString(), UString(), UByteArray(), UByteArray(), UByteArray(), true, false);
    }

#else
#define emit

class TreeModel
{
private:
    TreeItem *rootItem;
    bool markingEnabledFlag;

    void dataChanged(const UModelIndex &, const UModelIndex &) {}
    void layoutAboutToBeChanged() {}
    void layoutChanged() {}

public:
    UString data(const UModelIndex &index, int role) const;
    UString headerData(int section, int orientation, int role = 0) const;

    TreeModel() : markingEnabledFlag(false) {
        rootItem = new TreeItem(0, Types::Root, 0, UString(), UString(), UString(), UByteArray(), UByteArray(), UByteArray(), TRUE, FALSE);
    }

    bool hasIndex(int row, int column, const UModelIndex &parent = UModelIndex()) const {
        if (row < 0 || column < 0)
            return false;
        return row < rowCount(parent) && column < columnCount(parent);
    }

    UModelIndex createIndex(int row, int column, void *data) const { return UModelIndex(row, column, data, this); }
#endif

    ~TreeModel() {
        delete rootItem;
    }

    bool markingEnabled() { return markingEnabledFlag; }
    void setMarkingEnabled(const bool enabled);

    UModelIndex index(int row, int column, const UModelIndex &parent = UModelIndex()) const;
    UModelIndex parent(const UModelIndex &index) const;
    int rowCount(const UModelIndex &parent = UModelIndex()) const;
    int columnCount(const UModelIndex &parent = UModelIndex()) const;

    UINT8 action(const UModelIndex &index) const;
    void setAction(const UModelIndex &index, const UINT8 action);

    UINT32 base(const UModelIndex &index) const;
    UINT32 offset(const UModelIndex &index) const;
    void setOffset(const UModelIndex &index, const UINT32 offset);

    UINT8 type(const UModelIndex &index) const;
    void setType(const UModelIndex &index, const UINT8 type);

    UINT8 subtype(const UModelIndex &index) const;
    void setSubtype(const UModelIndex &index, const UINT8 subtype);

    UString name(const UModelIndex &index) const;
    void setName(const UModelIndex &index, const UString &name);

    UString text(const UModelIndex &index) const;
    void setText(const UModelIndex &index, const UString &text);

    UString info(const UModelIndex &index) const;
    void setInfo(const UModelIndex &index, const UString &info);
    void addInfo(const UModelIndex &index, const UString &info, const bool append = TRUE);

    bool fixed(const UModelIndex &index) const;
    void setFixed(const UModelIndex &index, const bool fixed);

    bool compressed(const UModelIndex &index) const;
    void setCompressed(const UModelIndex &index, const bool compressed);

    UByteArray uncompressedData(const UModelIndex &index) const;
    bool hasEmptyUncompressedData(const UModelIndex &index) const;
    void setUncompressedData(const UModelIndex &index, const UByteArray &ucdata);

    UINT8 marking(const UModelIndex &index) const;
    void setMarking(const UModelIndex &index, const UINT8 marking);

    UByteArray header(const UModelIndex &index) const;
    bool hasEmptyHeader(const UModelIndex &index) const;

    UByteArray body(const UModelIndex &index) const;
    bool hasEmptyBody(const UModelIndex &index) const;

    UByteArray tail(const UModelIndex &index) const;
    bool hasEmptyTail(const UModelIndex &index) const;

    UByteArray parsingData(const UModelIndex &index) const;
    bool hasEmptyParsingData(const UModelIndex &index) const;
    void setParsingData(const UModelIndex &index, const UByteArray &pdata);

    UModelIndex addItem(const UINT32 offset, const UINT8 type, const UINT8 subtype,
        const UString & name, const UString & text, const UString & info,
        const UByteArray & header, const UByteArray & body, const UByteArray & tail,
        const ItemFixedState fixed,
        const UModelIndex & parent = UModelIndex(), const UINT8 mode = CREATE_MODE_APPEND);

    UModelIndex findParentOfType(const UModelIndex & index, UINT8 type) const;
    UModelIndex findLastParentOfType(const UModelIndex & index, UINT8 type) const;
    UModelIndex findByBase(UINT32 base) const;
};

#if defined(QT_CORE_LIB)
// Nothing required here
#else
inline UModelIndex UModelIndex::parent() const { return m ? m->parent(*this) : UModelIndex(); }
inline UModelIndex UModelIndex::child(int row, int column) const { return m ? m->index(row, column, *this) : UModelIndex(); }
inline UString UModelIndex::data(int role) const { return m ? m->data(*this, role) : UString(); }
#endif

#endif // TREEMODEL_H


text:
import httplib, urllib
from threading import Thread

from django.db import models
from django.db.models.signals import post_save

from resources.models import Resource
from facilities.models import Facility
from domain.models import Domain

class MasterIndex(models.Model):
    resource = models.ForeignKey(Resource)
    facility = models.ForeignKey(Facility, null=True, blank=True)

    # to keep master index separate within domains.
    domain = models.ForeignKey(Domain)

    class Meta:
        verbose_name_plural = 'Master Indexies'

    def __unicode__(self):
        return '%s is now at %s' % (self.resource, self.facility)

    def save(self, **kwargs):
        # modifed save to replace or add new resource allocations
        # add a filter for domain.
        MasterIndex.objects.filter(resource=self.resource).delete()
        super(MasterIndex, self).save(**kwargs)

def update_masterindex(sender, instance, created, **kwargs):
    MasterIndex(resource = instance,
                facility = instance.facility,
                domain = instance.facility.domain,
                ).save()

# signal to trigger masterindex update each time a Resource is saved
post_save.connect(update_masterindex, sender=Resource)


text:
for dir in ~/.config/dotfiles/shell/plugins/*; do
  if [[ -f "$dir/profile.zsh" ]]; then
    source "$dir/profile.zsh"
  fi
done


text:
package com.ctrip.platform.dal.dao.dialet.mysql;

import com.ctrip.platform.dal.dao.helper.AbstractDalParser;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.LinkedHashMap;
import java.util.Map;

public class PersonParser extends AbstractDalParser<Person> {
	public static final String DATABASE_NAME = "dao_test";
	public static final String TABLE_NAME = "Person";
	private static final String[] COLUMNS = new String[]{
		"ID",
		"Address",
		"Telephone",
		"Name",
		"Age",
		"Gender",
		"Birth",
		"PartmentID",
	};

	private static final String[] PRIMARY_KEYS = new String[]{
		"ID",
	};

	private static final int[] COLUMN_TYPES = new int[]{
		Types.INTEGER,
		Types.VARCHAR,
		Types.VARCHAR,
		Types.VARCHAR,
		Types.INTEGER,
		Types.INTEGER,
		Types.TIMESTAMP,
		Types.INTEGER,
	};

	public PersonParser() {
		super(DATABASE_NAME, TABLE_NAME, COLUMNS, PRIMARY_KEYS, COLUMN_TYPES);
	}

	@Override
	public Person map(ResultSet rs, int rowNum) throws SQLException {
		Person pojo = new Person();

		pojo.setID(rs.getInt("ID"));
		pojo.setAddress((String)rs.getObject("Address"));
		pojo.setTelephone((String)rs.getObject("Telephone"));
		pojo.setName((String)rs.getObject("Name"));
		pojo.setAge(rs.getInt("Age"));
		pojo.setGender(rs.getInt("Gender"));
		pojo.setBirth((Timestamp)rs.getObject("Birth"));
		pojo.setPartmentID(rs.getInt("PartmentID"));

		return pojo;
	}

	@Override
	public boolean isAutoIncrement() {
		return true;
	}

	@Override
	public Number getIdentityValue(Person pojo) {
		return pojo.getID();
	}

	@Override
	public Map<String, ?> getPrimaryKeys(Person pojo) {
		Map<String, Object> primaryKeys = new LinkedHashMap<String, Object>();

		primaryKeys.put("ID", pojo.getID());

		return primaryKeys;
	}

	@Override
	public Map<String, ?> getFields(Person pojo) {
		Map<String, Object> map = new LinkedHashMap<String, Object>();

		map.put("ID", pojo.getID());
		map.put("Address", pojo.getAddress());
		map.put("Telephone", pojo.getTelephone());
		map.put("Name", pojo.getName());
		map.put("Age", pojo.getAge());
		map.put("Gender", pojo.getGender());
		map.put("Birth", pojo.getBirth());
		map.put("PartmentID", pojo.getPartmentID());

		return map;
	}
}