text:
/****************************************************************************
 * kernel/environ/env_putenv.c
 *
 *   Copyright (C) 2007-2009, 2011 Gregory Nutt. All rights reserved.
 *   Author: Gregory Nutt <gnutt@nuttx.org>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name NuttX nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

/****************************************************************************
 * Included Files
 ****************************************************************************/

#include <tinyara/config.h>

#ifndef CONFIG_DISABLE_ENVIRON

#include <stdlib.h>
#include <sched.h>
#include <string.h>
#include <errno.h>

#include <tinyara/kmalloc.h>

/****************************************************************************
 * Private Data
 ****************************************************************************/

/****************************************************************************
 * Public Functions
 ****************************************************************************/

/****************************************************************************
 * Name: putenv
 *
 * Description:
 *   The putenv() function adds or changes the value of environment variables.
 *   The argument string is of the form name=value. If name does not already
 *   exist in  the  environment, then string is added to the environment. If
 *   name does exist, then the value of name in the environment is changed to
 *   value.
 *
 * Parameters:
 *   name=value string describing the environment setting to add/modify
 *
 * Return Value:
 *   Zero on sucess
 *
 * Assumptions:
 *   Not called from an interrupt handler
 *
 ****************************************************************************/

int putenv(FAR const char *string)
{
	char *pname;
	char *pequal;
	int ret = OK;

	/* Verify that a string was passed */

	if (!string) {
		ret = EINVAL;
		goto errout;
	}

	/* Parse the name=value string */

	pname = strdup(string);
	if (!pname) {
		ret = ENOMEM;
		goto errout;
	}

	pequal = strchr(pname, '=');
	if (pequal) {
		/* Then let setenv do all of the work */

		*pequal = '\0';
		ret = setenv(pname, pequal + 1, TRUE);
	}

	kmm_free(pname);
	return ret;

errout:
	set_errno(ret);
	return ERROR;
}

#endif							/* CONFIG_DISABLE_ENVIRON */


text:
set( LOMSE_VERSION_MAJOR 0 )
set( LOMSE_VERSION_MINOR 30 )
set( LOMSE_VERSION_PATCH 0 )

# build version string for installer name
set( LOMSE_PACKAGE_VERSION "${LOMSE_VERSION_MAJOR}.${LOMSE_VERSION_MINOR}.${LOMSE_VERSION_PATCH}" )
set( LOMSE_VERSION "${LOMSE_PACKAGE_VERSION}" )
set( LOMSE_VERSION_LONG "${LOMSE_VERSION}-nogit" )

message (STATUS "  Lomse version        = '${LOMSE_VERSION}'")
message (STATUS "  Lomse version string = '${LOMSE_PACKAGE_VERSION}'")

if (EXISTS ${LOMSE_ROOT_DIR}/.git)
  find_package (Git)
  if (NOT GIT_FOUND)
    message(SEND_ERROR "Git package not found." )
  else()
    # get sha1 and dirty status directly from git
    execute_process(COMMAND "${GIT_EXECUTABLE}" log -1 --format=%h
      WORKING_DIRECTORY "${LOMSE_ROOT_DIR}"
      OUTPUT_VARIABLE LOMSE_VERSION_BUILD
      OUTPUT_STRIP_TRAILING_WHITESPACE)
    execute_process(COMMAND "${GIT_EXECUTABLE}" describe --tags --long --dirty
      WORKING_DIRECTORY "${LOMSE_ROOT_DIR}"
      OUTPUT_VARIABLE LOMSE_VERSION_GIT
      OUTPUT_STRIP_TRAILING_WHITESPACE)
    message (STATUS "  version git    = '${LOMSE_VERSION_GIT}'")
    if ( ${LOMSE_VERSION_GIT} MATCHES "-dirty$" )
      set (LOMSE_VERSION_BUILD "${LOMSE_VERSION_BUILD}-dirty")
    endif()
    if (NOT ".${LOMSE_VERSION_BUILD}" STREQUAL "." )
      set(LOMSE_VERSION_LONG "${LOMSE_PACKAGE_VERSION}+${LOMSE_VERSION_BUILD}")
    else()
      set(LOMSE_VERSION_LONG "${LOMSE_PACKAGE_VERSION}")
    endif()
  endif()
endif()
message (STATUS "  Lomse version long   = '${LOMSE_VERSION_LONG}'" )

# define a header file to pass version information to source code
configure_file(
    "${LOMSE_ROOT_DIR}/lomse_version.h.cmake"
    "${CMAKE_BINARY_DIR}/lomse_version.h"
)

redpajama_set_name: RedPajamaGithub


text:
#ifndef OPENSIM_PSIM_PARAMETER_VALUE_H_
#define OPENSIM_PSIM_PARAMETER_VALUE_H_

#include <OpenSim/Common/Object.h>
#include <OpenSim/Common/Set.h>

#include "osimPSimDLL.h"

using namespace OpenSim;

namespace OpenSim {
/**
 * Stores the value of a parameter. This value is *not* scaled.
 * That is, it could be used directly in the model, and is not suited to be
 * used directly in the optimization. The name of the PSimParameterValue object
 * must match the name of a PSimParameter; otherwise, the value might be ignored.
 * TODO help detect unused values.
 */
class OSIMPSIM_API PSimParameterValue : public Object
{
OpenSim_DECLARE_CONCRETE_OBJECT(PSimParameterValue, Object);
public:

    /// @name Property declarations
    /// @{
    OpenSim_DECLARE_PROPERTY(value, double, "Value of the PSimParameter.")
    /// @}

    PSimParameterValue() {
        constructProperties();
    }

private:
    void constructProperties() {
        constructProperty_value(0);
    }

};

// TODO do I need "typename"?
// TODO for serialization, make this a class? or just register it?
typedef typename OpenSim::Set<OpenSim::PSimParameterValue> PSimParameterValueSet;

} // namespace OpenSim
#endif // OPENSIM_PSIM_PARAMETER_VALUE_H_


text:
One should think of `Who` as a web user with no clue what the "DOM" is. It is the average user, incapable of opening the console to track down the buttons they would like. `Who` is simple, and can only perform difficult tasks the same way as any other simple person, by pointing, clicking, and typing their way to victory.

#### Before getting started, a word on finding elements
##### findByPartial and caseSensitive
When `Who` utilizes a method that scans for text on the page, he will always have two options: `findByPartial` and `caseSensitive`. Both of these options default to `false`, and can always be overridden. Using `findByPartial` means that any text you are trying to match, be it a `label` or `placeholderText`, does not have to be an exact match. That means searching for "WIZARD" with the option `findByPartial` set to `true` would match a string such as "A wizard is never late, Frodo Baggins". This works because `caseSensitive` defaults to `false` as well, however, simply setting `caseSensitive` to `true` would cause the example to fail.

##### text, label and placeholderText
When searching for an element on page, the `text` option refers to the inner text of the element `Who` is looking for. This is useful when looking for elements such as `<div>`s, `<li>`s, `<span>`s, etc.

Another common element of text searching with `Who` is will be `label` and `placeholderText`. When `Who` searches by `label`, the approach is to look for a label on screen with inner text matching the `label` option. Once `Who` has located that label, the input that label is `for` is returned.

Inputs don't always have labels however, and in that case, `Who` has a backup. Using `placeholderText` will allow Who to track down any input that has a placeholder string that matches the `placeholderText` option.

_Also, feel free to checkout the [demo site](http://globusonline.github.io/whojs/)._

---

### clearsInput
##### Params
```
options = {
	label : STRING,
	placeholderText : STRING,
	caseSensitive : BOOL [default:false],
	findByPartial : BOOL [default:false]
}
```
This method allows `Who` to clear out any text in an input field or textarea.

### clicksButton
##### Params
```
options = {
	text : STRING [required],
	caseSensitive : BOOL [default:false],
	findByPartial : BOOL [default:false]
}
```
This method will simulate a click on any button type (`<button>`, `<input[type=button]>`, `<input[type=submit]>`) on a matching element.

### clicksCheckbox
##### Params
```
options = {
	label : STRING [required],
	caseSensitive : BOOL [default:false],
	findByPartial : BOOL [default:false]
}
```
This method provides a shortcut for clicking on a `<input[type="checkbox']>` element that matches the `label` option.

### clicksElement
##### Params
```
options = {
	text : STRING,
	type : STRING,
	query : STRING,
	label : STRING,
	placeholderText : STRING,
	caseSensitive : BOOL [default:false],
	findByPartial : BOOL [default:false]
}
```
This method will simulate a click on an element on the page, based on a small set of `options`. If a user specifies `text` and `type`, then `clicksElement` will search the DOM for an element of that `type` containing the `text` specified. If the user specifies the `label`, then `clicksElement` will look for the input `for` that label. This is useful for triggering events on `focus` or on `blur`. Finally, when the above methods are not enough, it is possible to specify a `query` parameter, that is entered in the same syntax as jQuery (`#` for IDs, `.` for class names, etc). With the `query` parameter specified, you can click any element on the page, at the cost of Who clarity.

### clicksLink
##### Params
```
options = {
	text : STRING [required],
	caseSensitive : BOOL [default:false],
	findByPartial : BOOL [default:false]
}
```
`clicksLink` is a wrapper around the `clicksElement` function that allows someone to more concisely click on an `<a>`nchor by simply passing the text of the link they would like to click.

### clicksRadio
##### Params
```
options = {
	label : STRING [required],
	caseSensitive : BOOL [default:false],
	findByPartial : BOOL [default:false]
}
```
This method allows `Who` to click on radio button with a label inner text matching the `label` option.

### hoversOver
##### Params
```
options = {
	text : STRING,
	type : STRING,
	query : STRING,
	label : STRING,
	caseSensitive : BOOL [default:false],
	findByPartial : BOOL [default:false]
}
```
`hoversOver` is a method that allows `Who` to hover over any element on the page and trigger it's `mouseover` events.

### passesTime
##### Params
```
options = {
	ms : STRING [required],
	thenWho : FUNCTION,
	whileWaiting : FUNCTION
}
```
This method is extremely useful for simulating a period of time in which `Who` is not actively moving about the page, but may be scanning it, or reading other information. For example, if `Who` has clicked a link and is waiting for an AJAX response. To set the amount of time Who should wait, simply set `ms` as the number of milliseconds you would like `Who` to wait. By default, this method will continuously return `false` while Who is waiting, and once Who is no longer waiting, the method returns `true`. However, these methods are both overridable. To alter what happens when Who is waiting, override the method `whileWaiting`, and to override the successfully finished waiting method, use `thenWho`.

### readsFormValue
##### Params
```
options = {
	label : STRING,
	placeholderText : STRING,
	caseSensitive : BOOL [default:false],
	findByPartial : BOOL [default:false]
}
```

This method allows for `Who` to read from any value field in a form, be it a `checkbox`, `radio`, `input`, or `textarea`. To retrieve this form value, one must simply pass a `label` option with the inner text of the label `for` that input.

### resetContext
##### Params
```
None
```
Resets the DOM context of Who, to the default DOM element: `body`.

### seesElement
##### Params
```
options = {
    text : STRING,
    type : STRING,
    query : STRING,
    label : STRING,
    placeholderText : STRING,
    caseSensitive : BOOL [default:false],
    findByPartial : BOOL [default:false]
}
```
`seesElement` allows `Who` to report `true` if a certain element is visible on screen, and `false` if not.

### seesElWithPlaceholderText
##### Params
```
options = {
	placeholderText : STRING,
	visible : BOOL [default:false],
	caseSensitive : BOOL [default:false],
	findByPartial : BOOL [default:false]
}
```
`seesElWithPlaceholderText` allows `Who` to report `true` if an input with matching `placeholderText` is found on screen, and `false` if not.

### seesElementWithText
##### Params
```
options = {
	text : STRING,
	type : STRING,
	visible : BOOL [default:false],
	caseSensitive : BOOL [default:false],
	findByPartial : BOOL [default:false]
}
```
This method gives `Who` the ability to quickly locate an element on screen with a given string as it's contents. By setting the `type` of the element, we determine what type of element we are looking for. The `text` option, is the option that must match the inner text of the element we are looking for. By default, this method looks for elements that are currently `visible` on screen, however, flipping the option to `false`, will allow Who to find hidden elements.

### seesImages
##### Params
```
None
```
`seesImage` allows `Who` to report `true` if an image is visible in context on screen, and `false` if not.

### selectsFromDropdown
```
options = {
	label : STRING,
	optionText : STRING,
	caseSensitive : BOOL [default:false],
	findByPartial : BOOL [default:false]
}
```
`selectsFromDropdown` allows `Who` to select an `<option>` from a `<select>` box on screen. `Who` uses the input that matches the `label` option, and matches the the `<option>` by

### setContext
##### Params
```
context = STRING
```
Sets the location in the DOM where Who will be active. The parameter `context` is a query string (i.e `#new-container` or `.other-new-guy`).

### typesValueIntoForm
##### Params
```
options = {
	label : STRING,
	text : STRING,
	caseSensitive : BOOL [default:false],
	findByPartial : BOOL [default:false]
}
```

This method simulates a keystroke-by-keystroke entering of information into a form field. To find the correct input, use the `label` parameter, which matches the inner text of the label for that field, and is mapped by the `label`'s `for` attribute.  `findByPartial` rules apply. The `text` option refers to the text that Who will actually be typing in.

### typesEnterKey
```
options = {
	label : STRING,
	placeholderText : STRING,
	caseSensitive : BOOL [default:false],
	findByPartial : BOOL [default:false]
}
```
`typesEnterKey` gives `Who` the ability to recreate an enter key stroke with the focus on the matching `<input>`.


text:
var TemplateEngine = require('../../models/templateEngine');
var TemplateBlock = require('../../models/templateBlock');

var renderTemplate = require('../render');
var postRender = require('../postRender');

describe('postRender', function() {
    var testPost;
    var engine = TemplateEngine.create({
        blocks: [
            TemplateBlock.create('lower', function(blk) {
                return blk.body.toLowerCase();
            }),
            TemplateBlock.create('prefix', function(blk) {
                return {
                    body: '_' + blk.body + '_',
                    post: function() {
                        testPost = true;
                    }
                };
            })
        ]
    });

    it('should correctly replace block', function() {
        return renderTemplate(engine, 'README.md', 'Hello {% lower %}Samy{% endlower %}')
        .then(function(output) {
            expect(output.getContent()).toMatch(/Hello \{\{\-([\S]+)\-\}\}/);
            expect(output.getBlocks().size).toBe(1);

            return postRender(engine, output);
        })
        .then(function(result) {
            expect(result).toBe('Hello samy');
        });
    });

    it('should correctly replace blocks', function() {
        return renderTemplate(engine, 'README.md', 'Hello {% lower %}Samy{% endlower %}{% prefix %}Pesse{% endprefix %}')
        .then(function(output) {
            expect(output.getContent()).toMatch(/Hello \{\{\-([\S]+)\-\}\}\{\{\-([\S]+)\-\}\}/);
            expect(output.getBlocks().size).toBe(2);
            return postRender(engine, output);
        })
        .then(function(result) {
            expect(result).toBe('Hello samy_Pesse_');
            expect(testPost).toBe(true);
        });
    });

});


text:
#include <Modules/Legacy/Converters/ConvertMatrixToString.h>
#include <Core/Algorithms/Legacy/Converter/ConvertMatrixToString.h>

#include <Core/Datatypes/Matrix.h>
#include <Core/Datatypes/DenseMatrix.h>
// ReSharper disable once CppUnusedIncludeDirective
#include <Core/Datatypes/String.h>
#include <Core/Datatypes/DatatypeFwd.h>
#include <Core/Datatypes/MatrixTypeConversions.h>

using namespace SCIRun;
using namespace SCIRun::Modules;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Modules::Converters;

ConvertMatrixToString::ConvertMatrixToString() : Module(ModuleLookupInfo("ConvertMatrixToString","Converters","SCIRun"),false)
{
	INITIALIZE_PORT(InputMatrix);
	INITIALIZE_PORT(ResultString);
}

void ConvertMatrixToString::execute()
{
	auto input_matrix = getRequiredInput(InputMatrix);

	auto output = algo().run(withInputData((InputMatrix,input_matrix)));

	sendOutputFromAlgorithm(ResultString, output);
}


text:
@interface UserModel : BaseModel

// 除了userDescription 不能直接用数据的key ,因为与系统字符冲突. 所以使用kvc解析出userModel

@property(nonatomic,copy)NSString *idstr;           //字符串型的用户UID
@property(nonatomic,copy)NSString *screen_name;     //用户昵称
@property(nonatomic,copy)NSString *name;            //友好显示名称
@property(nonatomic,copy)NSString *location;        //用户所在地
@property(nonatomic,copy)NSString *userDescription;     //用户个人描述
@property(nonatomic,copy)NSString *url;             //用户博客地址
@property(nonatomic,copy)NSString * profile_image_url;  //用户头像地址,50×50像素
@property(nonatomic,copy)NSString * avatar_large;  //用户大头像地址
@property(nonatomic,copy)NSString * gender;             //性别,m:男、f:女、n:未知
@property(nonatomic,strong)NSNumber * followers_count;    //粉丝数
@property(nonatomic,strong)NSNumber * friends_count;   //关注数
@property(nonatomic,strong)NSNumber * statuses_count;   //微博数
@property(nonatomic,strong)NSNumber * favourites_count;   //收藏数
@property(nonatomic,strong)NSNumber * verified;   //是否是微博认证用户,即加V用户,true:是,false:否

@end


text:
package org.jetbrains.builtInWebServer;

import com.intellij.openapi.options.ConfigurableUi;
import com.intellij.ui.PortField;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.ide.BuiltInServerBundle;

import javax.swing.*;

class BuiltInServerConfigurableUi implements ConfigurableUi<BuiltInServerOptions> {
  private JPanel mainPanel;

  private PortField builtInServerPort;
  private JCheckBox builtInServerAvailableExternallyCheckBox;
  private JCheckBox allowUnsignedRequestsCheckBox;
  private JLabel portLabel;

  BuiltInServerConfigurableUi() {
    portLabel.setLabelFor(builtInServerPort);
    builtInServerPort.setMin(1024);
    builtInServerPort.addChangeListener(e -> {
      boolean isEnabled = builtInServerPort.getNumber() < BuiltInServerOptions.DEFAULT_PORT;
      builtInServerAvailableExternallyCheckBox.setEnabled(isEnabled);
      builtInServerAvailableExternallyCheckBox
        .setToolTipText(isEnabled ? null : BuiltInServerBundle.message("checkbox.tooltip.can.t.be.enabled.for.default.port"));
    });
  }

  @Override
  @NotNull
  public JComponent getComponent() {
    return mainPanel;
  }

  @Override
  public boolean isModified(@NotNull BuiltInServerOptions settings) {
    return builtInServerPort.getNumber() != settings.builtInServerPort ||
           builtInServerAvailableExternallyCheckBox.isSelected() != settings.builtInServerAvailableExternally ||
           allowUnsignedRequestsCheckBox.isSelected() != settings.allowUnsignedRequests;
  }

  @Override
  public void apply(@NotNull BuiltInServerOptions settings) {
    boolean builtInServerPortChanged = settings.builtInServerPort != builtInServerPort.getNumber() || settings.builtInServerAvailableExternally != builtInServerAvailableExternallyCheckBox.isSelected();
    settings.allowUnsignedRequests = allowUnsignedRequestsCheckBox.isSelected();
    if (builtInServerPortChanged) {
      settings.builtInServerPort = builtInServerPort.getNumber();
      settings.builtInServerAvailableExternally = builtInServerAvailableExternallyCheckBox.isSelected();

      BuiltInServerOptions.onBuiltInServerPortChanged();
    }
  }

  @Override
  public void reset(@NotNull BuiltInServerOptions settings) {
    builtInServerPort.setNumber(settings.builtInServerPort);
    builtInServerAvailableExternallyCheckBox.setSelected(settings.builtInServerAvailableExternally);
    allowUnsignedRequestsCheckBox.setSelected(settings.allowUnsignedRequests);
  }
}


text:
package test;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(value=RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE_USE, ElementType.PARAMETER, ElementType.METHOD, ElementType.TYPE})
@interface ScalacDoesNotGetMe {}

class J<@ScalacDoesNotGetMe X> {
  public int f = (new S()).foo();
}


text:
import {Component} from '@angular/core';
import {FormBuilder} from '@angular/forms';

/** @title Fixed sidenav */
@Component({
  selector: 'sidenav-fixed-example',
  templateUrl: 'sidenav-fixed-example.html',
  styleUrls: ['sidenav-fixed-example.css'],
})
export class SidenavFixedExample {
  options = this._formBuilder.group({
    bottom: 0,
    fixed: false,
    top: 0,
  });

  constructor(private _formBuilder: FormBuilder) {}

  shouldRun = /(^|.)(stackblitz|webcontainer).(io|com)$/.test(window.location.host);
}


text:
{-# LANGUAGE FlexibleContexts      #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes            #-}
module Copy.Conduit where

import           Conduit
import qualified Data.ByteString               as S
import           Data.ByteString.Lazy.Internal (defaultChunkSize)
import           Data.ByteVector               (fromByteVector)
import           Data.Conduit.Combinators      (vectorBuilder)
import           System.IO                     (Handle)

run :: Handle -> Handle -> IO ()
run inH outH =
    (sourceHandle inH :: Producer IO S.ByteString)
        $$ vectorBuilder defaultChunkSize mapM_CE
        =$ mapC fromByteVector
        =$ sinkHandle outH


text:
package kerio.connect.admin.common;

public class ManipulationError {

  String               id;         ///< entity KId, can be user, group, alias, ML...
  LocalizableMessage   errorMessage;

  public ManipulationError() {

  }

  public String getId() {
    return id;
  }

  public void setId(String id) {
    this.id = id;
  }

  public LocalizableMessage getErrorMessage() {
    return errorMessage;
  }

  public void setErrorMessage(LocalizableMessage errorMessage) {
    this.errorMessage = errorMessage;
  }

}


text:
package at.alladin.rmbt.qos.testserver.entity;

public interface Observable {

	/**
	 *
	 * @return
	 */
	public boolean isHealthy();

	/**
	 *
	 * @return
	 */
	public String getStatusMessage();
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>boost/python/enum.hpp</title>
<link rel="stylesheet" href="../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../index.html" title="Boost.Python Reference Manual">
<link rel="up" href="../high_level_components.html" title="Chapter 2. High Level Components">
<link rel="prev" href="boost_python_docstring_options_h.html" title="boost/python/docstring_options.hpp">
<link rel="next" href="boost_python_errors_hpp.html" title="boost/python/errors.hpp">

boost/python/enum.hpp

Introduction

Class
        template enum_

Class
        template enum_ constructors

Class
        template enum_ modifier functions

Example

Introduction

          <boost/python/enum.hpp> defines the interface through which users
          expose their C++ enumeration types to Python. It declares the enum_ class template, which is parameterized
          on the enumeration type being exposed.

Class
        template enum_

          Creates a Python class derived from Python's int
          type which is associated with the C++ type passed as its first parameter.

namespace boost { namespace python
{
  template <class T>
  class enum_ : public object
  {
    enum_(char const* name, char const* doc = 0);
    enum_<T>& value(char const* name, T);
    enum_<T>& export_values();
  };
}}

Class
        template enum_ constructors

enum_(char const* name, char const* doc=0);

Requires

                name is an ntbs which conforms to Python's
                identifier
                naming rules.

Effects

                Constructs an enum_
                object holding a Python extension type derived from int which is named name.
                The named attribute of the current
                scope is bound to the new extension type.

Class
        template enum_ modifier functions

enum_<T>& value(char const* name, T x);

Requires

                name is an ntbs which conforms to Python's
                identifier
                naming rules.

Effects

                adds an instance of the wrapped enumeration type with value x to
                the type's dictionary as the named attribute.

Returns

                *this

enum_<T>& export_values();

Effects

                sets attributes in the current
                scope with the same names and values as all enumeration values
                exposed so far by calling value().

Returns

                *this

Example

          C++ module definition

#include <boost/python/enum.hpp>
#include <boost/python/def.hpp>
#include <boost/python/module.hpp>

using namespace boost::python;

enum color { red = 1, green = 2, blue = 4 };

color identity_(color x) { return x; }

BOOST_PYTHON_MODULE(enums)
{
  enum_<color>("color")
    .value("red", red)
    .value("green", green)
    .export_values()
    .value("blue", blue)
    ;

  def("identity", identity_);
}

          Interactive Python:

>>> from enums import *

>>> identity(red)
enums.color.red

>>> identity(color.red)
enums.color.red

>>> identity(green)
enums.color.green

>>> identity(color.green)
enums.color.green

>>> identity(blue)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'blue' is not defined

>>> identity(color.blue)
enums.color.blue

>>> identity(color(1))
enums.color.red

>>> identity(color(2))
enums.color.green

>>> identity(color(3))
enums.color(3)

>>> identity(color(4))
enums.color.blue

>>> identity(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: bad argument type for built-in operation

Copyright © 2002-2005, 2015 David Abrahams, Stefan Seefeld

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt


text:
from __future__ import absolute_import, unicode_literals
from base import GAETestCase
from datetime import datetime, date
from decimal import Decimal
from lesson_app.lesson_model import Lesson
from routes.lessons.edit import index, save
from mommygae import mommy
from tekton.gae.middleware.redirect import RedirectResponse

class IndexTests(GAETestCase):
    def test_success(self):
        lesson = mommy.save_one(Lesson)
        template_response = index(lesson.key.id())
        self.assert_can_render(template_response)

class EditTests(GAETestCase):
    def test_success(self):
        lesson = mommy.save_one(Lesson)
        old_properties = lesson.to_dict()
        redirect_response = save(lesson.key.id(), description='description_string', title='title_string')
        self.assertIsInstance(redirect_response, RedirectResponse)
        edited_lesson = lesson.key.get()
        self.assertEquals('description_string', edited_lesson.description)
        self.assertEquals('title_string', edited_lesson.title)
        self.assertNotEqual(old_properties, edited_lesson.to_dict())

    def test_error(self):
        lesson = mommy.save_one(Lesson)
        old_properties = lesson.to_dict()
        template_response = save(lesson.key.id())
        errors = template_response.context['errors']
        self.assertSetEqual(set(['description', 'title']), set(errors.keys()))
        self.assertEqual(old_properties, lesson.key.get().to_dict())
        self.assert_can_render(template_response)


text:
package spew

import (
	"fmt"
	"io"
	"reflect"
	"sort"
	"strconv"
	"unsafe"
)

// reflectValue mirrors the struct layout of the reflect package Value type.
var reflectValue struct {
	typ  unsafe.Pointer
	val  unsafe.Pointer
	flag uintptr
}

// flagIndir indicates whether the value field of a reflect.Value is the actual
// data or a pointer to the data.
const flagIndir = 1 << 1

// unsafeReflectValue converts the passed reflect.Value into a one that bypasses
// the typical safety restrictions preventing access to unaddressable and
// unexported data.  It works by digging the raw pointer to the underlying
// value out of the protected value and generating a new unprotected (unsafe)
// reflect.Value to it.
//
// This allows us to check for implementations of the Stringer and error
// interfaces to be used for pretty printing ordinarily unaddressable and
// inaccessible values such as unexported struct fields.
func unsafeReflectValue(v reflect.Value) (rv reflect.Value) {
	indirects := 1
	vt := v.Type()
	upv := unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + unsafe.Offsetof(reflectValue.val))
	rvf := *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + unsafe.Offsetof(reflectValue.flag)))
	if rvf&flagIndir != 0 {
		vt = reflect.PtrTo(v.Type())
		indirects++
	}

	pv := reflect.NewAt(vt, upv)
	rv = pv
	for i := 0; i < indirects; i++ {
		rv = rv.Elem()
	}
	return rv
}

// Some constants in the form of bytes to avoid string overhead.  This mirrors
// the technique used in the fmt package.
var (
	panicBytes            = []byte("(PANIC=")
	plusBytes             = []byte("+")
	iBytes                = []byte("i")
	trueBytes             = []byte("true")
	falseBytes            = []byte("false")
	interfaceBytes        = []byte("(interface {})")
	commaNewlineBytes     = []byte(",\n")
	newlineBytes          = []byte("\n")
	openBraceBytes        = []byte("{")
	openBraceNewlineBytes = []byte("{\n")
	closeBraceBytes       = []byte("}")
	asteriskBytes         = []byte("*")
	colonBytes            = []byte(":")
	colonSpaceBytes       = []byte(": ")
	openParenBytes        = []byte("(")
	closeParenBytes       = []byte(")")
	spaceBytes            = []byte(" ")
	pointerChainBytes     = []byte("->")
	nilAngleBytes         = []byte("<nil>")
	maxNewlineBytes       = []byte("<max depth reached>\n")
	maxShortBytes         = []byte("<max>")
	circularBytes         = []byte("<already shown>")
	circularShortBytes    = []byte("<shown>")
	invalidAngleBytes     = []byte("<invalid>")
	openBracketBytes      = []byte("[")
	closeBracketBytes     = []byte("]")
	percentBytes          = []byte("%")
	precisionBytes        = []byte(".")
	openAngleBytes        = []byte("<")
	closeAngleBytes       = []byte(">")
	openMapBytes          = []byte("map[")
	closeMapBytes         = []byte("]")
)

// hexDigits is used to map a decimal value to a hex digit.
var hexDigits = "0123456789abcdef"

// catchPanic handles any panics that might occur during the handleMethods
// calls.
func catchPanic(w io.Writer, v reflect.Value) {
	if err := recover(); err != nil {
		w.Write(panicBytes)
		fmt.Fprintf(w, "%v", err)
		w.Write(closeParenBytes)
	}
}

// handleMethods attempts to call the Error and String methods on the underlying
// type the passed reflect.Value represents and outputes the result to Writer w.
//
// It handles panics in any called methods by catching and displaying the error
// as the formatted value.
func handleMethods(cs *ConfigState, w io.Writer, v reflect.Value) (handled bool) {
	// We need an interface to check if the type implements the error or
	// Stringer interface.  However, the reflect package won't give us an
	// interface on certain things like unexported struct fields in order
	// to enforce visibility rules.  We use unsafe to bypass these restrictions
	// since this package does not mutate the values.
	if !v.CanInterface() {
		v = unsafeReflectValue(v)
	}

	// Choose whether or not to do error and Stringer interface lookups against
	// the base type or a pointer to the base type depending on settings.
	// Technically calling one of these methods with a pointer receiver can
	// mutate the value, however, types which choose to satisify an error or
	// Stringer interface with a pointer receiver should not be mutating their
	// state inside these interface methods.
	var viface interface{}
	if !cs.DisablePointerMethods {
		if !v.CanAddr() {
			v = unsafeReflectValue(v)
		}
		viface = v.Addr().Interface()
	} else {
		if v.CanAddr() {
			v = v.Addr()
		}
		viface = v.Interface()
	}

	// Is it an error or Stringer?
	switch iface := viface.(type) {
	case error:
		defer catchPanic(w, v)
		if cs.ContinueOnMethod {
			w.Write(openParenBytes)
			w.Write([]byte(iface.Error()))
			w.Write(closeParenBytes)
			w.Write(spaceBytes)
			return false
		}

		w.Write([]byte(iface.Error()))
		return true

	case fmt.Stringer:
		defer catchPanic(w, v)
		if cs.ContinueOnMethod {
			w.Write(openParenBytes)
			w.Write([]byte(iface.String()))
			w.Write(closeParenBytes)
			w.Write(spaceBytes)
			return false
		}
		w.Write([]byte(iface.String()))
		return true
	}
	return false
}

// printBool outputs a boolean value as true or false to Writer w.
func printBool(w io.Writer, val bool) {
	if val {
		w.Write(trueBytes)
	} else {
		w.Write(falseBytes)
	}
}

// printInt outputs a signed integer value to Writer w.
func printInt(w io.Writer, val int64, base int) {
	w.Write([]byte(strconv.FormatInt(val, base)))
}

// printUint outputs an unsigned integer value to Writer w.
func printUint(w io.Writer, val uint64, base int) {
	w.Write([]byte(strconv.FormatUint(val, base)))
}

// printFloat outputs a floating point value using the specified precision,
// which is expected to be 32 or 64bit, to Writer w.
func printFloat(w io.Writer, val float64, precision int) {
	w.Write([]byte(strconv.FormatFloat(val, 'g', -1, precision)))
}

// printComplex outputs a complex value using the specified float precision
// for the real and imaginary parts to Writer w.
func printComplex(w io.Writer, c complex128, floatPrecision int) {
	r := real(c)
	w.Write(openParenBytes)
	w.Write([]byte(strconv.FormatFloat(r, 'g', -1, floatPrecision)))
	i := imag(c)
	if i >= 0 {
		w.Write(plusBytes)
	}
	w.Write([]byte(strconv.FormatFloat(i, 'g', -1, floatPrecision)))
	w.Write(iBytes)
	w.Write(closeParenBytes)
}

// printHexPtr outputs a uintptr formatted as hexidecimal with a leading '0x'
// prefix to Writer w.
func printHexPtr(w io.Writer, p uintptr) {
	// Null pointer.
	num := uint64(p)
	if num == 0 {
		w.Write(nilAngleBytes)
		return
	}

	// Max uint64 is 16 bytes in hex + 2 bytes for '0x' prefix
	buf := make([]byte, 18)

	// It's simpler to construct the hex string right to left.
	base := uint64(16)
	i := len(buf) - 1
	for num >= base {
		buf[i] = hexDigits[num%base]
		num /= base
		i--
	}
	buf[i] = hexDigits[num]

	// Add '0x' prefix.
	i--
	buf[i] = 'x'
	i--
	buf[i] = '0'

	// Strip unused leading bytes.
	buf = buf[i:]
	w.Write(buf)
}

// valuesSorter implements sort.Interface to allow a slice of reflect.Value
// elements to be sorted.
type valuesSorter struct {
	values []reflect.Value
}

// Len returns the number of values in the slice.  It is part of the
// sort.Interface implementation.
func (s *valuesSorter) Len() int {
	return len(s.values)
}

// Swap swaps the values at the passed indices.  It is part of the
// sort.Interface implementation.
func (s *valuesSorter) Swap(i, j int) {
	s.values[i], s.values[j] = s.values[j], s.values[i]
}

// Less returns whether the value at index i should sort before the
// value at index j.  It is part of the sort.Interface implementation.
func (s *valuesSorter) Less(i, j int) bool {
	switch s.values[i].Kind() {
	case reflect.Bool:
		return !s.values[i].Bool() && s.values[j].Bool()
	case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
		return s.values[i].Int() < s.values[j].Int()
	case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
		return s.values[i].Uint() < s.values[j].Uint()
	case reflect.Float32, reflect.Float64:
		return s.values[i].Float() < s.values[j].Float()
	case reflect.String:
		return s.values[i].String() < s.values[j].String()
	case reflect.Uintptr:
		return s.values[i].Uint() < s.values[j].Uint()
	}
	return s.values[i].String() < s.values[j].String()
}

// sortValues is a generic sort function for native types: int, uint, bool,
// string and uintptr.  Other inputs are sorted according to their
// Value.String() value to ensure display stability.
func sortValues(values []reflect.Value) {
	if len(values) == 0 {
		return
	}
	sort.Sort(&valuesSorter{values})
}


text:
using System.Collections.Generic;
using JetBrains.Annotations;

namespace Archichect.Reading {
    public abstract class AbstractReaderFactory : IReaderFactory {
        [NotNull, ItemNotNull]
        public abstract IEnumerable<string> SupportedFileExtensions { get; }

        [NotNull]
        public abstract IDependencyReader CreateReader([NotNull] string fileName, bool needsOnlyItemTails, AbstractReadingContext readingContext);

        [NotNull]
        public abstract string GetHelp(bool detailedHelp, string filter);

        public abstract AbstractReadingContext CreateReadingContext();
    }
}


text:
@implementation LBNybusinessListTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];

    self.GoBt.layer.cornerRadius = 3;
    self.GoBt.clipsToBounds = YES;

    self.imagev.layer.cornerRadius = 3;
    self.imagev.clipsToBounds = YES;

    self.GoBt.layer.borderWidth = 1;
    self.GoBt.layer.borderColor = YYSRGBColor(55, 159, 72, 1).CGColor;

}

- (IBAction)GoPayEvent:(UIButton *)sender {

    if (self.returnGowhere) {
        self.returnGowhere(self.index);
    }
}

@end


text:
$:.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'double_bag_ftps'

require 'tmpdir'

HOST   = 'ftp.secureftp-test.com'
USR    = 'test'
PASSWD = 'test'


text:
import { Product32 } from "../../";

export = Product32;


text:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawerLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/root"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".MainActivity">

        <include
            android:id="@+id/toolbar"
            layout="@layout/layout_toolbar" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorPrimary"
            android:elevation="@dimen/toolbar_elevation"
            app:tabIndicatorColor="@android:color/white"
            app:tabMode="scrollable"
            app:tabSelectedTextColor="@android:color/white"
            app:tabTextColor="@android:color/white" />

        <android.support.v4.view.ViewPager
            android:id="@+id/viewPager"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </LinearLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/navigationView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:menu="@menu/drawer_menu" />
</android.support.v4.widget.DrawerLayout>


text:
We generally need to reference static resources in a template when developing projects.

When using the command `thinkjs` to create a project, it will automatically create the directory `www/static`, where specially stores JS, CSS, images and other static resources.

### Access Static Resources

After putting the static resources in `www/static`, you can reference them in a template by the following approaches.

#### Reference JS files in template

```html
<script src="/static/js/foo.js"></script>
```

#### Reference CSS files in template

```html
<link href="/static/css/foo.css" rel="stylesheet" />
```

#### Reference Image files in template

```html
<img src="/static/img/foo.png" alt="" >
```

### Static Resources Access Configuration

Judging whether the request is a static resource request, we use regular expression. The default configuration is as follows.

```js
export default {
  resource_on: true, // enable static resources resolution function
  resource_reg: /^(static\/|[^\/]+\.(?!js|html)\w+$)/, // regular expression for judging static resource request
}
```

You can modify the configuration file `src/common/config/config.js` according to your project requirements.

### Close Online Static Resources Access

After the project is online, it generally uses nginx or other WEB server as a angent. At this time, you can let nginx to directly handle the static resource requests. Thus, you could close the static resources access to improve performance.

Set the option `resource_on` to `false` in the configuration file `src/common/config/env/prodution.js` to close it. eg.

```js
export default {
  resource_on: false
}
```


text:
package com.purejadeite.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

/**
 * 値のチェック用ユーティリティです
 *
 * @author mitsuhiroseino
 *
 */
public class SimpleValidator {

	/**
	 * コンフィグの必須チェック
	 *
	 * @param config
	 *            コンフィグ
	 * @param persistence
	 *            必須項目名称
	 */
	public static void containsKey(Map<?, ?> map, Object[] keys) {
		List<String> errors = new ArrayList<>();
		for (Object key : keys) {
			if (key instanceof Object[]) {
				// or条件
				Object[] keyArray = (Object[]) key;
				boolean result = false;
				for (Object k : keyArray) {
					if (map.containsKey(k)) {
						result = true;
						break;
					}
				}
				if (!result) {
					errors.add(keyArray[0].toString());
				}
			} else {
				if (!map.containsKey(key)) {
					errors.add(key.toString());
				}
			}
		}
		if (!errors.isEmpty()) {
			String errorKeys = StringUtils.join(errors.toArray(), ",");
			throw new ValidationException(errorKeys + "に値を設定してください。");
		}
	}

}


text:
import { SelectedFiltersCounts } from "../ArtworkFilterContext"

export const getTotalSelectedFiltersCount = (
  selectedFiltersCounts: Partial<SelectedFiltersCounts> = {}
) => {
  return Object.values(selectedFiltersCounts).reduce(
    (total: number, curr: number) => total + curr,
    0
  )
}


text:
package iso20022

// Chain of parties involved in the settlement of a transaction, including receipts and deliveries, book transfers, treasury deals, or other activities, resulting in the movement of a security or amount of money from one account to another.
type SettlementParties36 struct {

	// First party in the settlement chain. In a plain vanilla settlement, it is the Central Securities Depository where the counterparty requests to receive the financial instrument or from where the counterparty delivers the financial instruments.
	Depository *PartyIdentification75 `xml:"Dpstry,omitempty"`

	// Party that, in a settlement chain interacts with the depository.
	Party1 *PartyIdentificationAndAccount106 `xml:"Pty1,omitempty"`

	// Party that, in a settlement chain interacts with the party 1.
	Party2 *PartyIdentificationAndAccount106 `xml:"Pty2,omitempty"`

	// Party that, in a settlement chain interacts with the party 2.
	Party3 *PartyIdentificationAndAccount106 `xml:"Pty3,omitempty"`

	// Party that, in a settlement chain interacts with the party 3.
	Party4 *PartyIdentificationAndAccount106 `xml:"Pty4,omitempty"`

	// Party that, in a settlement chain interacts with the party 4.
	Party5 *PartyIdentificationAndAccount106 `xml:"Pty5,omitempty"`
}

func (s *SettlementParties36) AddDepository() *PartyIdentification75 {
	s.Depository = new(PartyIdentification75)
	return s.Depository
}

func (s *SettlementParties36) AddParty1() *PartyIdentificationAndAccount106 {
	s.Party1 = new(PartyIdentificationAndAccount106)
	return s.Party1
}

func (s *SettlementParties36) AddParty2() *PartyIdentificationAndAccount106 {
	s.Party2 = new(PartyIdentificationAndAccount106)
	return s.Party2
}

func (s *SettlementParties36) AddParty3() *PartyIdentificationAndAccount106 {
	s.Party3 = new(PartyIdentificationAndAccount106)
	return s.Party3
}

func (s *SettlementParties36) AddParty4() *PartyIdentificationAndAccount106 {
	s.Party4 = new(PartyIdentificationAndAccount106)
	return s.Party4
}

func (s *SettlementParties36) AddParty5() *PartyIdentificationAndAccount106 {
	s.Party5 = new(PartyIdentificationAndAccount106)
	return s.Party5
}


text:
/* globals describe it expect */

import React from 'react'
import Enzyme from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
import ModalDialog from 'components/shared/modal-dialog'
import { pack } from "../../helpers/pack"

Enzyme.configure({adapter: new Adapter()})

describe('When I try to render a modal dialog', () => {

  it("should render without children", () => {
    const modalDialog = Enzyme.mount(<ModalDialog title="Test Dialog"/>);
    expect(modalDialog.html()).toBe(pack(`

            Test Dialog

    `));
  });

  it("should render with children", () => {
    const modalDialog = Enzyme.mount(<ModalDialog title="Test Dialog">
children here...
</ModalDialog>);
    expect(modalDialog.html()).toBe(pack(`

            Test Dialog

            children here...

    `));
  });

})


text:
var DefineMap = require("can-define/map/map");

foo();


text:
                <input data-dojo-type="dijit/form/TextBox" id="linkDisplayText"
                       value=""
                       data-dojo-props="trim:true"
                       name="linkDisplayText" />
                <input data-dojo-type="dijit/form/TextBox" id="isReadOnlyText"
                       type ="hidden"
                       value=""
                       data-dojo-props="trim:true"
                       name="isReadOnlyText" />

                <input data-dojo-type="dijit/form/TextBox" id="linkUrl"
                value="http://"
                data-dojo-props="trim:true, intermediateChanges:true"
                name="linkUrl" />

                <button data-dojo-type="dijit/form/Button" id="saveHyperlinkChangeButton" type="submit">Ok</button>
                <button data-dojo-type="dijit/form/Button" id="cancelHyperlinkChangeButton" data-dojo-id="cancelHyperlinkChangeButton">Cancel</button>


text:
"""
Variables are entry points in the shader that allow to upload CPU data to
the GPU. For OpenGL ES 2.0, there are mainly two types: uniforms and
attributes. The correspondance betwenn GPU and CPU data types is given in the
table below.

=========== ================== == ================== ==============
GLSL Type   GLSL/GL Type       #  GL elementary type Numpy type
=========== ================== == ================== ==============
float       gl.GL_FLOAT        1  gl.GL_FLOAT        np.float32
vec2        gl.GL_FLOAT_VEC2   2  gl.GL_FLOAT        np.float32
vec3        gl.GL_FLOAT_VEC3   3  gl.GL_FLOAT        np.float32
vec4        gl.GL_FLOAT_VEC4   4  gl.GL_FLOAT        np.float32
int         gl.GL_INT          1  gl.GL_INT          np.int32
ivec2       gl.GL_INT_VEC2     2  gl.GL_INT          np.int32
ivec3       gl.GL_INT_VEC3     3  gl.GL_INT          np.int32
ivec4       gl.GL_INT_VEC4     4  gl.GL_INT          np.int32
bool        gl.GL_BOOL         1  gl.GL_BOOL         np.bool
bvec2       gl.GL_BOOL_VEC2    2  gl.GL_BOOL         np.bool
bvec3       gl.GL_BOOL_VEC3    3  gl.GL_BOOL         np.bool
bvec4       gl.GL_BOOL_VEC4    4  gl.GL_BOOL         np.bool
mat2        gl.GL_FLOAT_MAT2   4  gl.GL_FLOAT        np.float32
mat3        gl.GL_FLOAT_MAT3   9  gl.GL_FLOAT        np.float32
mat4        gl.GL_FLOAT_MAT4   16 gl.GL_FLOAT        np.float32
sampler1D   gl.GL_SAMPLER_1D   1  gl.GL_UNSIGNED_INT np.uint32
sampler2D   gl.GL_SAMPLER_2D   1  gl.GL_UNSIGNED_INT np.uint32
sampler3D   gl.GL_SAMPLER_3D   1  gl.GL_UNSIGNED_INT np.uint32
samplerCube gl.GL_SAMPLER_CUBE 1  gl.GL_UNSIGNED_INT np.uint32
=========== ================== == ================== ==============

.. note::

   Most of the time, you don't need to directly manipulate such variables
   since they are created automatically when shader code is parsed.

**Example usage**

  .. code::

     vertex = '''
         attribute vec3 position;
         void main (void)
         {
             gl_Position = vec4(position, 1.0);
         } '''
     fragment = '''
         uniform vec4 color;
         void main(void)
         {
             gl_FragColor = color;
         } '''
     program = gloo.Program(vertex, fragment, count=4)
     # program["position"] type is Attribute
     # program["color"] type is Uniform
"""
import ctypes
import numpy as np

from glumpy import gl
from glumpy.log import log
from glumpy.gloo.globject import GLObject
from glumpy.gloo.array import VertexArray
from glumpy.gloo.buffer import VertexBuffer
from glumpy.gloo.texture import TextureCube
from glumpy.gloo.texture import Texture1D, Texture2D, Texture3D
from glumpy.gloo.texture import TextureFloat1D, TextureFloat2D, TextureFloat3D

# ------------------------------------------------------------- gl_typeinfo ---
gl_typeinfo = {
    gl.GL_FLOAT        : ( 1, gl.GL_FLOAT,        np.float32),
    gl.GL_FLOAT_VEC2   : ( 2, gl.GL_FLOAT,        np.float32),
    gl.GL_FLOAT_VEC3   : ( 3, gl.GL_FLOAT,        np.float32),
    gl.GL_FLOAT_VEC4   : ( 4, gl.GL_FLOAT,        np.float32),
    gl.GL_INT          : ( 1, gl.GL_INT,          np.int32),
    gl.GL_INT_VEC2     : ( 2, gl.GL_INT,          np.int32),
    gl.GL_INT_VEC3     : ( 3, gl.GL_INT,          np.int32),
    gl.GL_INT_VEC4     : ( 4, gl.GL_INT,          np.int32),
    gl.GL_BOOL         : ( 1, gl.GL_BOOL,         np.bool),
    gl.GL_BOOL_VEC2    : ( 2, gl.GL_BOOL,         np.bool),
    gl.GL_BOOL_VEC3    : ( 3, gl.GL_BOOL,         np.bool),
    gl.GL_BOOL_VEC4    : ( 4, gl.GL_BOOL,         np.bool),
    gl.GL_FLOAT_MAT2   : ( 4, gl.GL_FLOAT,        np.float32),
    gl.GL_FLOAT_MAT3   : ( 9, gl.GL_FLOAT,        np.float32),
    gl.GL_FLOAT_MAT4   : (16, gl.GL_FLOAT,        np.float32),
    gl.GL_SAMPLER_1D   : ( 1, gl.GL_UNSIGNED_INT, np.uint32),
    gl.GL_SAMPLER_2D   : ( 1, gl.GL_UNSIGNED_INT, np.uint32),
    gl.GL_SAMPLER_3D   : ( 1, gl.GL_UNSIGNED_INT, np.uint32),
    gl.GL_SAMPLER_CUBE : ( 1, gl.GL_UNSIGNED_INT, np.uint32)
}

# ---------------------------------------------------------- Variable class ---
class Variable(GLObject):
    """ A variable is an interface between a program and data """

    def __init__(self, program, name, gtype):
        """ Initialize the data into default state """

        # Make sure variable type is allowed (for ES 2.0 shader)
        if gtype not in [gl.GL_FLOAT,      gl.GL_FLOAT_VEC2,
                         gl.GL_FLOAT_VEC3, gl.GL_FLOAT_VEC4,
                         gl.GL_INT,        gl.GL_BOOL,
                         gl.GL_FLOAT_MAT2, gl.GL_FLOAT_MAT3,
                         gl.GL_FLOAT_MAT4, gl.GL_SAMPLER_1D,
                         gl.GL_SAMPLER_2D, gl.GL_SAMPLER_3D, gl.GL_SAMPLER_CUBE]:
            raise TypeError("Unknown variable type")

        GLObject.__init__(self)

        # Program this variable belongs to
        self._program = program

        # Name of this variable in the program
        self._name = name

        # Build dtype
        size, _, base = gl_typeinfo[gtype]
        self._dtype = (name,base,size)

        # GL type
        self._gtype = gtype

        # CPU data
        self._data = None

        # Whether this variable is active
        self._active = True

    @property
    def name(self):
        """ Variable name """

        return self._name

    @property
    def program(self):
        """ Program this variable belongs to """

        return self._program

    @property
    def gtype(self):
        """ Type of the underlying variable (as a GL constant) """

        return self._gtype

    @property
    def dtype(self):
        """ Equivalent dtype of the variable """

        return self._dtype

    @property
    def active(self):
        """ Whether this variable is active in the program """
        return self._active

    @active.setter
    def active(self, active):
        """ Whether this variable is active in the program """
        self._active = active

    @property
    def data(self):
        """ CPU data """

        return self._data

# ----------------------------------------------------------- Uniform class ---
class Uniform(Variable):
    """ A Uniform represents a program uniform variable. """

    _ufunctions = {
        gl.GL_FLOAT:        gl.glUniform1fv,
        gl.GL_FLOAT_VEC2:   gl.glUniform2fv,
        gl.GL_FLOAT_VEC3:   gl.glUniform3fv,
        gl.GL_FLOAT_VEC4:   gl.glUniform4fv,
        gl.GL_INT:          gl.glUniform1iv,
        gl.GL_BOOL:         gl.glUniform1iv,
        gl.GL_FLOAT_MAT2:   gl.glUniformMatrix2fv,
        gl.GL_FLOAT_MAT3:   gl.glUniformMatrix3fv,
        gl.GL_FLOAT_MAT4:   gl.glUniformMatrix4fv,
        gl.GL_SAMPLER_1D:   gl.glUniform1i,
        gl.GL_SAMPLER_2D:   gl.glUniform1i,
        gl.GL_SAMPLER_3D:   gl.glUniform1i,
        gl.GL_SAMPLER_CUBE: gl.glUniform1i
    }

    def __init__(self, program, name, gtype):
        """ Initialize the input into default state """

        Variable.__init__(self, program, name, gtype)
        size, _, dtype = gl_typeinfo[self._gtype]
        self._data = np.zeros(size, dtype)
        self._ufunction = Uniform._ufunctions[self._gtype]
        self._texture_unit = -1

    def set_data(self, data):
        """ Assign new data to the variable (deferred operation) """

        # Textures need special handling
        if self._gtype == gl.GL_SAMPLER_1D:

            if isinstance(data, Texture1D):
                self._data = data

            elif isinstance(self._data, Texture1D):
                #self._data.set_data(data)
                self._data[...] = data.reshape(self._data.shape)

            # Automatic texture creation if required
            else:
                data = np.array(data,copy=False)
                if data.dtype in [np.float16, np.float32, np.float64]:
                    self._data = data.astype(np.float32).view(Texture1D)
                else:
                    self._data = data.view(Texture1D)

        elif self._gtype == gl.GL_SAMPLER_2D:
            if isinstance(data, Texture2D):
                self._data = data
            elif isinstance(self._data, Texture2D):
                #self._data.set_data(data)
                self._data[...] = data.reshape(self._data.shape)

            # Automatic texture creation if required
            else:
                data = np.array(data,copy=False)
                if data.dtype in [np.float16, np.float32, np.float64]:
                    self._data = data.astype(np.float32).view(Texture2D)
                else:
                    self._data = data.view(Texture2D)

        elif self._gtype == gl.GL_SAMPLER_3D:
            if isinstance(data, Texture3D):
                self._data = data
            elif isinstance(self._data, Texture3D):
                #self._data.set_data(data)
                self._data[...] = data.reshape(self._data.shape)

            # Automatic texture creation if required
            else:
                data = np.array(data,copy=False)
                if data.dtype in [np.float16, np.float32, np.float64]:
                    self._data = data.astype(np.float32).view(Texture3D)
                else:
                    self._data = data.view(Texture3D)

        elif self._gtype == gl.GL_SAMPLER_CUBE:
            if isinstance(data, TextureCube):
                self._data = data
            elif isinstance(self._data, TextureCube):
                self._data[...] = data.reshape(self._data.shape)

            # Automatic texture creation if required
            else:
                data = np.array(data,copy=False)
                if data.dtype in [np.float16, np.float32, np.float64]:
                    self._data = data.astype(np.float32).view(TextureCube)
                else:
                    self._data = data.view(TextureCube)

        else:
            self._data[...] = np.array(data,copy=False).ravel()

        self._need_update = True

    def _activate(self):
        if self._gtype in (gl.GL_SAMPLER_1D, gl.GL_SAMPLER_2D, gl.GL_SAMPLER_3D, gl.GL_SAMPLER_CUBE):
            if self.data is not None:
                log.debug("GPU: Active texture is %d" % self._texture_unit)
                gl.glActiveTexture(gl.GL_TEXTURE0 + self._texture_unit)
                self.data.activate()

    def _update(self):

        # Check active status (mandatory)
        if not self._active:
            raise RuntimeError("Uniform variable is not active")

        # WARNING : Uniform are supposed to keep their value between program
        #           activation/deactivation (from the GL documentation). It has
        #           been tested on some machines but if it is not the case on
        #           every machine, we can expect nasty bugs from this early
        #           return

        # Matrices (need a transpose argument)
        if self._gtype in (gl.GL_FLOAT_MAT2, gl.GL_FLOAT_MAT3, gl.GL_FLOAT_MAT4):
            # OpenGL ES 2.0 does not support transpose
            transpose = False
            self._ufunction(self._handle, 1, transpose, self._data)

        # Textures (need to get texture count)
        elif self._gtype in (gl.GL_SAMPLER_1D, gl.GL_SAMPLER_2D, gl.GL_SAMPLER_3D, gl.GL_SAMPLER_CUBE):
            # texture = self.data
            log.debug("GPU: Activactin texture %d" % self._texture_unit)
            # gl.glActiveTexture(gl.GL_TEXTURE0 + self._unit)
            # gl.glBindTexture(texture.target, texture.handle)
            gl.glUniform1i(self._handle, self._texture_unit)

        # Regular uniform
        else:
            self._ufunction(self._handle, 1, self._data)

    def _create(self):
        """ Create uniform on GPU (get handle) """

        self._handle = gl.glGetUniformLocation(self._program.handle, self._name)

# --------------------------------------------------------- Attribute class ---
class Attribute(Variable):
    """ An Attribute represents a program attribute variable """

    _afunctions = {
        gl.GL_FLOAT:      gl.glVertexAttrib1f,
        gl.GL_FLOAT_VEC2: gl.glVertexAttrib2f,
        gl.GL_FLOAT_VEC3: gl.glVertexAttrib3f,
        gl.GL_FLOAT_VEC4: gl.glVertexAttrib4f
    }

    def __init__(self, program, name, gtype):
        """ Initialize the input into default state """

        Variable.__init__(self, program, name, gtype)

        # Number of elements this attribute links to (in the attached buffer)
        self._size = 0

        # Whether this attribure is generic
        self._generic = False

    def set_data(self, data):
        """ Assign new data to the variable (deferred operation) """

        isnumeric = isinstance(data, (float, int))

        # New vertex buffer
        if isinstance(data, (VertexBuffer,VertexArray)):
            self._data = data

        # We already have a vertex buffer
        elif isinstance(self._data, (VertexBuffer,VertexArray)):
            self._data[...] = data

        # Data is a tuple with size <= 4, we assume this designates a generate
        # vertex attribute.
        elif (isnumeric or (isinstance(data, (tuple, list)) and
                            len(data) in (1, 2, 3, 4) and
                            isinstance(data[0], (float, int)))):
            # Let numpy convert the data for us
            _, _, dtype = gl_typeinfo[self._gtype]
            self._data = np.array(data).astype(dtype)
            self._generic = True
            self._need_update = True
            self._afunction = Attribute._afunctions[self._gtype]
            return

        # For array-like, we need to build a proper VertexBuffer to be able to
        # upload it later to GPU memory.
        else: #lif not isinstance(data, VertexBuffer):
            name,base,count = self.dtype
            data = np.array(data,dtype=base,copy=False)
            data = data.ravel().view([self.dtype])
            # WARNING : transform data with the right type
            # data = np.array(data,copy=False)
            self._data = data.view(VertexBuffer)

        self._generic = False

    def _activate(self):
        if isinstance(self.data, (VertexBuffer, VertexArray)):
            self.data.activate()
            size, gtype, dtype = gl_typeinfo[self._gtype]
            stride = self.data.stride
            offset = ctypes.c_void_p(self.data.offset)
            gl.glEnableVertexAttribArray(self.handle)
            gl.glVertexAttribPointer(self.handle, size, gtype, gl.GL_FALSE, stride, offset)

    def _deactivate(self):
        if isinstance(self.data,VertexBuffer):
            self.data.deactivate()
            if self.handle >= 0:
                gl.glDisableVertexAttribArray(self.handle)
        elif isinstance(self.data,VertexArray):
            self.data.deactivate()

    def _update(self):
        """ Actual upload of data to GPU memory  """

        log.debug("GPU: Updating %s" % self.name)

        # Check active status (mandatory)
#        if not self._active:
#            raise RuntimeError("Attribute variable is not active")
#        if self._data is None:
#            raise RuntimeError("Attribute variable data is not set")

        # Generic vertex attribute (all vertices receive the same value)
        if self._generic:
            if self._handle >= 0:
                gl.glDisableVertexAttribArray(self._handle)
                self._afunction(self._handle, *self._data)

        # Regular vertex buffer
        elif self.handle >= 0:
            #if self._need_update:
            #    self.data._update()
            #    self._need_update = False

            # Get relevant information from gl_typeinfo
            size, gtype, dtype = gl_typeinfo[self._gtype]
            stride = self.data.stride

            # Make offset a pointer, or it will be interpreted as a small array
            offset = ctypes.c_void_p(self.data.offset)
            gl.glEnableVertexAttribArray(self.handle)
            gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.data.handle)
            gl.glVertexAttribPointer(self.handle, size, gtype,  gl.GL_FALSE, stride, offset)

    def _create(self):
        """ Create attribute on GPU (get handle) """

        self._handle = gl.glGetAttribLocation(self._program.handle, self.name)

    @property
    def size(self):
        """ Size of the underlying vertex buffer """

        if self._data is None:
            return 0
        return self._data.size

    def __len__(self):
        """ Length of the underlying vertex buffer """

        if self._data is None:
            return 0
        return len(self._data)


text:
//-----------------------------------------------------------------------
// <copyright file="Interpreter_Test.cs">
//     Copyright (c) Janis Fliegenschmidt
// </copyright>
//-----------------------------------------------------------------------

namespace Brainfuck.Tests.Interpreter.Core
{
    using Brainfuck.Interpreter.Core;
    using Brainfuck.Interpreter.Core.Exceptions;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using System;
    using System.Collections.Generic;

    /// <summary>
    /// Test class containing ByteInterpreter related tests.
    /// </summary>
    [TestClass]
    public class ByteInterpreter_Test
    {
        [TestMethod]
        public void SmokeTest()
        {
            IInterpreter<Byte> interpreter = new ByteInterpreter();

            try
            {
                interpreter.Execute(Instruction.ReadByte);
                Assert.Fail("Execute ReadByte should fail if no input event handler is bound!");
            }
            catch (NoInputSourceAvailableException)
            {
                // This is expected
            }
            catch (Exception)
            {
                Assert.Fail("Execute threw an unexpected exception!");
            }

            List<Byte> output = new List<Byte>();

            interpreter.OutputAvailable += (o) => output.Add(o);

            const int RUNS = 20;

            for (int i = 0; i < RUNS; i++)
            {
                interpreter.Execute(Instruction.IncrementValue);
                interpreter.Execute(Instruction.IncrementPointer);
            }

            for (int i = 0; i < RUNS; i++)
            {
                interpreter.Execute(Instruction.DecrementPointer);
            }

            interpreter.Execute(Instruction.BeginLoop);
            interpreter.Execute(Instruction.PrintByte);
            interpreter.Execute(Instruction.IncrementPointer);
            interpreter.Execute(Instruction.EndLoop);

            Assert.AreEqual(RUNS, output.Count);

            for (int i = 0; i < output.Count; i++)
            {
                Assert.AreEqual(1, output[i]);
            }
        }

        [TestMethod]
        public void StackOverflow()
        {
            try
            {
                IInterpreter interpreter = new ByteInterpreter();
                interpreter.Execute(Instruction.IncrementValue);
                interpreter.Execute(Instruction.BeginLoop);
                interpreter.Execute(Instruction.EndLoop);

                Assert.Fail("This should cause a stack overflow.");
            }
            catch (StackOverflowException)
            {
                // expected
            }
            catch
            {
                Assert.Fail("This should cause _nothing_ but a stack overflow.");
            }
        }
    }
}


text:
/*% SONLASTPOINTSTIME returns the time for which a read will terminate
%
% Implemented through SONLastPointsTime.dll
%
% TIME=SONGETADCDATA(FH, CHAN, ETIME, STIME, LPOINTS, BADC {, FILTERMASK})
%
%   INPUTS: FH SON File Handle
%           CHAN Channel number (1 to SONMaxChannels)
%           STIME Searches back from this time
%           ETIME stops search at this time (eTime must be less than sTime)
%           LPOINTS the number of points it is dsired to read
%           BADC ADCMark data will be treated as Adc if this set
%           FILTERMASK, if present, a filter mask
%
% Returns the time at which the read will end i.e. the time of the final data
% point or a negative error code
%
% ML 05/05
*/

#include <string.h>
#include <stdio.h>
#include <windows.h>
#include <matrix.h>
#include "mex.h"

#include "son.h"
#include "machine.h"
#include "SONDef.h"

HINSTANCE hinstLib;
BOOL fFreeResult;

// Calls the SON32.DLL  routine

TSTime _SONLastPointsTime(short fh,
                    WORD chan,
                    TSTime sTime,
                    TSTime eTime,
                    long lpoints,
                    BOOL bAdc,
                    TpFilterMask pFltMask)
{
    FARPROC SONLastPointsTime;
    TSTime ret;

    SONLastPointsTime=GetProcAddress(hinstLib, "SONLastPointsTime");
    if (SONLastPointsTime!=NULL){
        ret=(*SONLastPointsTime)(fh, chan, sTime, eTime, lpoints, bAdc, pFltMask);
        return ret;
    }
}

void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
{

    short   fh;
    WORD    chan;
    TSTime sTime, eTime, ResTime;
    TpSTime peTime;
    unsigned char *ptr;
    TpFilterMask    pFltMask=NULL;
    TFilterMask FilterMask;
    BOOL bAdc;
    long lpoints;

    int const dim[2]={1,1};
    int m;

    int GetFilterMask();

    if (nrhs<6)
        mexErrMsgTxt("SONGetADCData: Too few input arguments\n");

    //Get input arguments
    fh=mxGetScalar(prhs[0]);                   //File handle
    chan=mxGetScalar(prhs[1]);                 //Channel number
    sTime=mxGetScalar(prhs[2]);                //Start time for data search
    eTime=mxGetScalar(prhs[3]);                //End Time
    lpoints=mxGetScalar(prhs[4]);              //Number of points
    bAdc=mxGetScalar(prhs[5]);                 // If set, treat ADCMark data
                                               // as adc

    //Get and set up the filter mask
    if (nrhs==7 && mxIsStruct(prhs[7])==1){
        GetFilterMask(prhs[7], FilterMask);
        pFltMask=&FilterMask;
    }
    else
        pFltMask=NULL;

    //Load and get pointer to the library SON32.DLL//
    hinstLib = LoadLibrary(SON32);
    if (hinstLib == NULL){
        mexPrintf("%s not found",SON32);
        plhs[0]=mxCreateNumericArray(2, dim, mxINT32_CLASS, mxREAL);
        *mxGetPr(plhs[0])=SON_BAD_PARAM;
        return;
    }

    ResTime=_SONLastPointsTime(fh, chan, sTime, eTime, bAdc, lpoints, pFltMask);
    fFreeResult = FreeLibrary(hinstLib);

    plhs[0]=mxCreateNumericArray(2, dim, mxINT32_CLASS, mxREAL);
    peTime=mxGetData(plhs[0]);
    *peTime=ResTime;

}


text:
<?php
# $Id$
# PHPlot test: Data label extended custom formatting - 2e, ohlc
# This is a parameterized test. See the script named at the bottom for details.
$plot_type = 'ohlc';
$data_type = 'data-data';
$ny = 1;
$dvls = False; // This plot & data type does not do Data Value Labels.
require 'dlexformat.php';


text:
/*
 * Jitsi, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package net.java.sip.communicator.impl.gui.lookandfeel;

import java.awt.event.*;

import javax.swing.tree.*;

import net.java.sip.communicator.impl.gui.main.contactlist.*;
import net.java.sip.communicator.impl.gui.main.contactlist.contactsource.*;
import net.java.sip.communicator.plugin.desktoputil.plaf.*;
import net.java.sip.communicator.service.gui.*;

/**
 * The <tt>ExtendedTreeUI</tt> is an extended implementation of the
 * <tt>SIPCommTreeUI</tt> specific for the gui implementation.
 */
public class ExtendedTreeUI
    extends SIPCommTreeUI
{
    /**
     * Do not select the <tt>ShowMoreContact</tt>.
     *
     * @param path the <tt>TreePath</tt> to select
     * @param event the <tt>MouseEvent</tt> that provoked the select
     */
    @Override
    protected void selectPathForEvent(TreePath path, MouseEvent event)
    {
        Object lastComponent = path.getLastPathComponent();

        // Open right button menu when right mouse is pressed.
        if (lastComponent instanceof ContactNode)
        {
            UIContact uiContact
                = ((ContactNode) lastComponent).getContactDescriptor();

            if (!(uiContact instanceof ShowMoreContact))
            {
                super.selectPathForEvent(path, event);
            }
        }
        else
            super.selectPathForEvent(path, event);
    }
}


text:
import { Debouncer } from '@polymer/polymer/lib/utils/debounce.js';
import { timeOut, animationFrame } from '@polymer/polymer/lib/utils/async.js';
import { GridElement } from '@vaadin/vaadin-grid/src/vaadin-grid.js';
import { ItemCache } from '@vaadin/vaadin-grid/src/vaadin-grid-data-provider-mixin.js';
import './gridConnector.js';

window.Vaadin.Flow.Legacy.Debouncer = Debouncer;
window.Vaadin.Flow.Legacy.timeOut = timeOut;
window.Vaadin.Flow.Legacy.animationFrame = animationFrame;
window.Vaadin.Flow.Legacy.GridElement = GridElement;
window.Vaadin.Flow.Legacy.ItemCache = ItemCache;


text:
<link rel="import" href="../polymer/polymer-element.html">

<dom-module id="intersection-observer-element">
	<template>
		<style>
			:host {
				display: block;
			}
		</style>
		<div id="slottedData">
			<slot></slot>
		</div>
	</template>

	<script>
		/**
		 * `intersection-observer-element`
		 * Reflects contained elements visibility in attributes
		 *
		 * @customElement
		 * @polymer
		 * @demo demo/index.html
		 */
		class IntersectionObserverElement extends Polymer.Element {
			static get is() {
				return 'intersection-observer-element';
			}

            static get properties() {
                return {
                    thresholds: {
                        type: Array,
                        value: [0.0, 0.25, 0.5, 0.75, 1.0]
                    },
                    rootMargin: {
                        type: String,
                        value: "0px"
                    },
                    visible: {
                        type: Boolean,
                        value: false,
                        reflectToAttribute: true,
                        readOnly: true,
                        notify: true
                    },
                    ratio: {
                        type: Number,
                        reflectToAttribute: true,
                        readOnly: true
                    },
                    visibleLimit: {
                        type: Number,
                        value: 0.5,
                        reflectToAttribute: true
                    }
                };
            }

			connectedCallback() {
				super.connectedCallback();

				this.observer = new IntersectionObserver(this.handleIntersectionCallback.bind(this), {
					root: document.rootElement,
					rootMargin: this.rootMargin,
					threshold: this.thresholds
				});

				this.observer.observe(this.$.slottedData);
			}

			handleIntersectionCallback(entries) {
				if (!document.hidden) {
					for (let entry of entries) {
						this._setRatio(Number(entry.intersectionRatio).toFixed(2));

						if (this.ratio > this.visibleLimit) {
							this._setVisible(true);
						} else {
							this._setVisible(false);
						}
					}
				} else {
					this._setVisible(false);
				}
			}
		}

		window.customElements.define(IntersectionObserverElement.is, IntersectionObserverElement);
	</script>
</dom-module>


text:
package org.sparkcommerce.common.payment.service;

import org.sparkcommerce.common.payment.dto.PaymentRequestDTO;
import org.sparkcommerce.common.payment.dto.PaymentResponseDTO;
import org.sparkcommerce.common.vendor.service.exception.PaymentException;

/**
 *
This API allows each module to provide its own implementation for rollback.
 * Each module needs to implement this if for some reason the checkout workflow fails
 * after payments have been finalized and the submitted transaction needs to rollback.

 *
 * @author Anand Dasari
 */
public interface PaymentGatewayRollbackService {

    public PaymentResponseDTO rollbackAuthorize(PaymentRequestDTO transactionToBeRolledBack) throws PaymentException;

    public PaymentResponseDTO rollbackCapture(PaymentRequestDTO transactionToBeRolledBack) throws PaymentException;

    public PaymentResponseDTO rollbackAuthorizeAndCapture(PaymentRequestDTO transactionToBeRolledBack) throws PaymentException;

    public PaymentResponseDTO rollbackRefund(PaymentRequestDTO transactionToBeRolledBack) throws PaymentException;

}


text:
using System.Threading.Tasks;
using WireMock.Settings;

namespace WireMock.ResponseProviders;

/// <summary>
/// The Response Provider interface.
/// </summary>
public interface IResponseProvider
{
    /// <summary>
    /// The provide response.
    /// </summary>
    /// <param name="mapping">The used mapping.</param>
    /// <param name="requestMessage">The request.</param>
    /// <param name="settings">The WireMockServerSettings.</param>
    /// <returns>The <see cref="ResponseMessage"/> including a new (optional) <see cref="IMapping"/>.</returns>
    Task<(IResponseMessage Message, IMapping? Mapping)> ProvideResponseAsync(IMapping mapping, IRequestMessage requestMessage, WireMockServerSettings settings);
}


text:
/*
  Module dependencies:

  - Express
  - Http (to run Express)
  - Body parser (to parse JSON requests)
  - Underscore (because it's cool)
  - Socket.IO (Note: we need a web server to attach Socket.IO to)

  It is a common practice to name the variables after the module name.
  Ex: http is the "http" module, express is the "express" module, etc.
  The only exception is Underscore, where we use, conveniently, an underscore.
  Oh, and "socket.io" is simply called io. Seriously, the rest should be named after its module name.
*/
var express = require("express")
  , app = express()
  , http = require("http").createServer(app)
  , bodyParser = require("body-parser")
  , io = require("socket.io").listen(http)
  , _ = require("underscore");

/*
  The list of participants in our chatroom.
  The format of each participant will be:
  {
    id: "sessionId",
    name: "participantName"
  }
*/
var participants = [];

/* Server config */

//Server's IP address
app.set("ipaddr", "0.0.0.0");

//Server's port number
app.set("port", 1377);

//Specify the views folder
app.set("views", __dirname + "/views");

//View engine is Jade
app.set("view engine", "jade");

//Specify where the static content is
app.use(express.static("public", __dirname + "/public"));

//Tells server to support JSON requests
app.use(bodyParser.json());

/* Server routing */

//Handle route "GET /", as in "http://localhost:8080/"
app.get("/", function(request, response) {

  //Render the view called "index"
  response.render("index");

});

//POST method to create a chat message
app.post("/message", function(request, response) {

  //The request body expects a param named "message"
  var message = request.body.message;

  //If the message is empty or wasn't sent it's a bad request
  if (_.isUndefined(message) || _.isEmpty(message.trim()))
  {
    return response.json(400, {error: "Message is invalid"});
  }

  //We also expect the sender's name with the message
  var name = request.body.name;

  //Let our chatroom know there was a new message
  io.sockets.emit("incomingMessage", {message: message, name: name});

  //Looks good, let the client know
  response.json(200, {message: "Message received"});

});

/* Socket.IO events */
io.on("connection", function(socket){

  /*
    When a new user connects to our server, we expect an event called "newUser"
    and then we'll emit an event called "newConnection" with a list of all
    participants to all connected clients
  */
  socket.on("newUser", function(data) {
    participants.push({id: data.id, name: data.name});
    io.sockets.emit("newConnection", {participants: participants});
  });

  /*
    When a user changes his name, we are expecting an event called "nameChange"
    and then we'll emit an event called "nameChanged" to all participants with
    the id and new name of the user who emitted the original message
  */
  socket.on("nameChange", function(data) {
    _.findWhere(participants, {id: socket.id}).name = data.name;
    io.sockets.emit("nameChanged", {id: data.id, name: data.name});
  });

  /*
    When a client disconnects from the server, the event "disconnect" is automatically
    captured by the server. It will then emit an event called "userDisconnected" to
    all participants with the id of the client that disconnected
  */
  socket.on("disconnect", function() {
    participants = _.without(participants,_.findWhere(participants, {id: socket.id}));
    io.sockets.emit("userDisconnected", {id: socket.id, sender:"system"});
  });

});

//Start the http server at port and IP defined before
http.listen(app.get("port"), app.get("ipaddr"), function() {
  console.log("Server up and running. Go to http://" + app.get("ipaddr") + ":" + app.get("port"));
});


text:
import { Component, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'aui-field-with-cdk-autosize',
  templateUrl: './field-with-cdk-autosize.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class FieldWithCdkAutosizeComponent { }


text:
package acme;

public interface iTinyToon {
  void hello();
  void hi();
}


text:
package org.mamute.providers;

import java.net.URL;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.validation.ValidatorFactory;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.hbm2ddl.SchemaUpdate;
import org.mamute.meta.MamuteMetaInformation;
import org.mamute.model.*;
import org.mamute.model.interfaces.Flaggable;
import org.mamute.model.watch.Watcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import br.com.caelum.vraptor.environment.Environment;

@ApplicationScoped
public class MamuteDatabaseConfiguration {
	public static final String DATABASE_PROPERTY = "mamute.database";
	private static final Logger LOGGER = LoggerFactory
			.getLogger(MamuteDatabaseConfiguration.class);

	private final Environment env;
	private final ValidatorFactory vf;
	private final MamuteMetaInformation meta;
	private Configuration cfg;

	/**
	 * @deprecated CDI eyes only
	 */
	public MamuteDatabaseConfiguration() {
		this(null, null, null);
	}

	@Inject
	public MamuteDatabaseConfiguration(Environment env, ValidatorFactory vf, MamuteMetaInformation meta) {
		this.env = env;
		this.vf = vf;
		this.meta = meta;
	}

	@PostConstruct
	public void init(){
		String db = System.getProperty(DATABASE_PROPERTY);
		String hibernateCfg;

		if(db == null || db.equals("mysql")) {
			hibernateCfg = "/hibernate.cfg.xml";
		}else {
			hibernateCfg = "/hibernate-"+db+".cfg.xml";
		}

		URL xml = env.getResource(hibernateCfg);
		LOGGER.info("Loading hibernate xml from " + xml);

		cfg = new Configuration().configure(xml);

		if (this.vf != null) {
			Map<Object, Object> properties = cfg.getProperties();
			properties.put("javax.persistence.validation.factory", this.vf);
		}

		String url = System.getenv("JDBC_URL");
		if (url != null) {
			String user = System.getenv("USER");
			String password = System.getenv("PASSWORD");

			LOGGER.info("reading database config from environment: " + url);
			cfg.setProperty("hibernate.connection.url", url);
			cfg.setProperty("hibernate.connection.username", user);
			cfg.setProperty("hibernate.connection.password", password);

		}

		cfg.addAnnotatedClass(User.class);
		cfg.addAnnotatedClass(Question.class);
		cfg.addAnnotatedClass(AnswerInformation.class);
		cfg.addAnnotatedClass(Answer.class);
		cfg.addAnnotatedClass(Tag.class);
		cfg.addAnnotatedClass(Vote.class);
		cfg.addAnnotatedClass(Comment.class);
		cfg.addAnnotatedClass(QuestionInformation.class);
		cfg.addAnnotatedClass(Flag.class);
		cfg.addAnnotatedClass(LoginMethod.class);
		cfg.addAnnotatedClass(UserSession.class);
		cfg.addAnnotatedClass(Watcher.class);
		cfg.addAnnotatedClass(ReputationEvent.class);
		cfg.addAnnotatedClass(News.class);
		cfg.addAnnotatedClass(NewsInformation.class);
		cfg.addAnnotatedClass(NewsletterSentLog.class);
		cfg.addAnnotatedClass(TagPage.class);
		cfg.addAnnotatedClass(Attachment.class);

	}

	public Map<Object, Object> getProperties() {
		return cfg.getProperties();
	}

	public void addAnnotatedClass(Class<?> clazz) {
		if(meta != null && Flaggable.class.isAssignableFrom(clazz)){
			meta.add((Class<? extends Flaggable>) clazz);
		}
		cfg.addAnnotatedClass(clazz);
	}

	public SessionFactory buildSessionFactory() {
		ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
		return cfg.buildSessionFactory(serviceRegistry);
	}

	public SchemaExport getSchema() {
		return new SchemaExport(cfg);
	}

	public SchemaUpdate getSchemaUpdate() {
		return new SchemaUpdate(cfg);
	}

}


text:
<?php

final class PhabricatorAuthOneTimeLoginTemporaryTokenType
  extends PhabricatorAuthTemporaryTokenType {

  const TOKENTYPE = 'login:onetime';

  public function getTokenTypeDisplayName() {
    return pht('One-Time Login');
  }

  public function getTokenReadableTypeName(
    PhabricatorAuthTemporaryToken $token) {
    return pht('One-Time Login Token');
  }

  public function isTokenRevocable(PhabricatorAuthTemporaryToken $token) {
    return true;
  }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AppleseedMemberInvite
{
    public static class Extensions
    {
        public static string AppleseedMemberInviteResource(this UrlHelper urlHelper, string resourceName)
        {
            var areaName = (string)urlHelper.RequestContext.RouteData.DataTokens["area"];
            return urlHelper.Action("Index", "Resource", new { resourceName = resourceName, area = areaName });
        }
    }
}


text:
import Key from 'input/keyboard/Key.js';

export default function ALT () {

    return Key(18, 'ALT');

}


text:
layout: default
---

{{ site.data.home[page.lang].showcase.title }}

{{ site.data.home[page.lang].showcase.caption }}

  {{ site.data.home[page.lang].content }}

{{ content }}


text:
package org.wso2.carbon.esb.mediator.test.smooks;

import org.apache.axiom.om.util.AXIOMUtil;
import org.apache.commons.io.FileUtils;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.authenticator.stub.LoginAuthenticationExceptionException;
import org.wso2.esb.integration.common.utils.common.ServerConfigurationManager;
import org.wso2.esb.integration.common.clients.registry.ResourceAdminServiceClient;
import org.wso2.carbon.automation.engine.annotations.ExecutionEnvironment;
import org.wso2.carbon.automation.engine.annotations.SetEnvironment;
import org.wso2.carbon.endpoint.stub.types.EndpointAdminEndpointAdminException;
import org.wso2.esb.integration.common.utils.ESBIntegrationTest;

import javax.activation.DataHandler;
import javax.xml.stream.XMLStreamException;
import java.io.File;
import java.io.IOException;
import java.net.URL;

public class SmooksIntegrationTestCase extends ESBIntegrationTest {

    private ResourceAdminServiceClient resourceAdminServiceClient;
    private ServerConfigurationManager serverConfigurationManager;
    private boolean isProxyDeployed = false;

    @BeforeClass(alwaysRun = true)
    public void setEnvironment() throws Exception {

        super.init();
        serverConfigurationManager = new ServerConfigurationManager(context);
        serverConfigurationManager.applyConfiguration(new File(getClass().getResource(File.separator + "artifacts" + File.separator + "ESB" + File.separator + "synapseconfig" + File.separator + "smooks" + File.separator + "axis2.xml").getPath()));
        super.init();
        loadESBConfigurationFromClasspath(File.separator + "artifacts" + File.separator + "ESB" + File.separator + "synapseconfig" + File.separator + "smooks" + File.separator + "smooks_synapse.xml");

        resourceAdminServiceClient = new ResourceAdminServiceClient
                (contextUrls.getBackEndUrl(), context.getContextTenant().getContextUser().getUserName(), context.getContextTenant().getContextUser().getPassword());

        uploadResourcesToConfigRegistry();
        addSmooksProxy();
        addSmooksSequence();
    }

    @AfterClass(alwaysRun = true)
    public void close() throws Exception {
        try {
            if (isProxyDeployed) {
                deleteProxyService("SmooksProxy");
            }
            resourceAdminServiceClient.deleteResource("/_system/config/smooks_config.xml");
        } finally {
            cleanup();
            Thread.sleep(3000);
            serverConfigurationManager.restoreToLastConfiguration();
            resourceAdminServiceClient = null;
            serverConfigurationManager = null;

        }
    }

    @SetEnvironment(executionEnvironments = {ExecutionEnvironment.STANDALONE})
    @Test(groups = {"wso2.esb"}, description = "Sending a Large File To Smooks Mediator")
    public void testSendingToSmooks() throws IOException, EndpointAdminEndpointAdminException,
                                             LoginAuthenticationExceptionException,
                                             XMLStreamException, InterruptedException {

        File afile = new File(getClass().getResource(File.separator + "artifacts" + File.separator + "ESB" + File.separator + "synapseconfig" + File.separator + "smooks" + File.separator + "person.csv").getPath());
        File bfile = new File(getClass().getResource(File.separator + "artifacts" + File.separator + "ESB" + File.separator + "synapseconfig" + File.separator + "smooks" + File.separator).getPath() + "test" + File.separator + "in" + File.separator + "person.csv");

        FileUtils.copyFile(afile, bfile);
        Thread.sleep(40000);

        File outfile = new File(getClass().getResource(File.separator + "artifacts" + File.separator + "ESB" + File.separator + "synapseconfig" + File.separator + "smooks" + File.separator).getPath() + "test" + File.separator + "out" + File.separator + "Out.xml");

        String smooksOut = FileUtils.readFileToString(outfile);
        Assert.assertTrue(smooksOut.contains("<csv-record number=\"160\"><firstname>Andun</firstname><lastname>Sameera</lastname><gender>Male</gender><age>4</age><country>SriLanka</country></csv-record>"));

    }

    private void uploadResourcesToConfigRegistry() throws Exception {
        resourceAdminServiceClient.addResource(
                "/_system/config/smooks_config.xml", "application/xml", "xml files",
                new DataHandler(new URL("file:///" + getClass().getResource(
                        "/artifacts/ESB/synapseconfig/smooks/smooks_config.xml").getPath())));
    }

    private void addSmooksProxy() throws Exception {

        addProxyService(AXIOMUtil.stringToOM("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                                             "<proxy xmlns=\"http://ws.apache.org/ns/synapse\" name=\"SmooksProxy\" transports=\"vfs\" startOnLoad=\"true\">\n" +
                                             "    <target inSequence=\"Smooks\"/>\n" +
                                             "    <parameter name=\"transport.PollInterval\">15</parameter>\n" +
                                             "    <parameter name=\"transport.vfs.FileURI\">file://" + getClass().getResource(File.separator + "artifacts" + File.separator + "ESB" + File.separator + "synapseconfig" + File.separator + "smooks" + File.separator).getPath() + "test" + File.separator + "in" + File.separator + "</parameter>\n" +
                                             "    <parameter name=\"transport.vfs.FileNamePattern\">.*\\.csv</parameter>\n" +
                                             "    <parameter name=\"transport.vfs.ContentType\">text/plain</parameter>\n" +
                                             "</proxy>"));
        isProxyDeployed = true;
    }

    private void addSmooksSequence()
            throws Exception {
        addSequence(AXIOMUtil.stringToOM("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                                         "<sequence xmlns=\"http://ws.apache.org/ns/synapse\" name=\"Smooks\">\n" +
                                         "    <log level=\"full\"/>\n" +
                                         "    <smooks config-key=\"conf:/smooks_config.xml\">\n" +
                                         "        <input type=\"text\"/>\n" +
                                         "        <output type=\"xml\"/>\n" +
                                         "    </smooks>\n" +
                                         "    <property name=\"OUT_ONLY\" value=\"true\"/>\n" +
                                         "    <send>\n" +
                                         "        <endpoint name=\"FileEpr\">\n" +
                                         "            <address uri=\"vfs:file://" + getClass().getResource(File.separator + "artifacts" + File.separator + "ESB" + File.separator + "synapseconfig" + File.separator + "smooks" + File.separator).getPath() + "test" + File.separator + "out" + File.separator + "Out.xml\" format=\"soap11\"/>\n" +
                                         "        </endpoint>\n" +
                                         "    </send>\n" +
                                         "    <log level=\"full\"/>\n" +
                                         "</sequence>"));
    }

}


text:
using Konves.KScript.Expressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;

namespace Konves.KScript.UnitTests
{
	[TestClass]
	public class NotExpressionTestFixture
	{
		[TestCategory(nameof(NotExpression))]
		[TestMethod]
		public void TestEvaluate()
		{
			DoTestEvaluate(new TrueExpression(), false);
			DoTestEvaluate(new FalseExpression(), true);
		}

		private void DoTestEvaluate(IExpression expr, bool expected)
		{
			// Arrange
			IExpression expression = new NotExpression(expr);

			// Act
			bool result = expression.Evaluate(null);

			// Assert
			Assert.AreEqual(expected, result);
		}

		private class TrueExpression : IExpression
		{
			public bool Evaluate(IDictionary<string, object> state)
			{
				return true;
			}
		}

		private class FalseExpression : IExpression
		{
			public bool Evaluate(IDictionary<string, object> state)
			{
				return false;
			}
		}
	}
}