text:
package de.otto.jsonhome.registry.controller;

import de.otto.jsonhome.registry.store.Registry;
import org.testng.annotations.Test;

import java.util.Map;

import static de.otto.jsonhome.registry.controller.RegistryConverter.jsonToRegistry;
import static de.otto.jsonhome.registry.controller.RegistryConverter.registryToJson;
import static de.otto.jsonhome.registry.fixture.RegistryFixture.doubleEntryRegistry;
import static de.otto.jsonhome.registry.fixture.RegistryFixture.registryLiveWithSingleLinkTo;
import static java.net.URI.create;
import static org.testng.Assert.assertEquals;

/**
 * @author Guido Steinacker
 * @since 09.02.13
 */
public class RegistryConverterTest {

    @Test
    public void shouldConvertRegistryWithSingleEntry() {
        // given:
        final Map<String, Object> linksMap = registryLiveWithSingleLinkTo("foo");
        // when:
        final Registry registry = jsonToRegistry(linksMap);
        // then:
        assertEquals(registryToJson(create("http://example.org"), registry), linksMap);
    }

    @Test
    public void shouldConvertRegistryWithMultipleEntries() {
        // given:
        final Map<String, Object> linksMap = doubleEntryRegistry();
        // when:
        final Registry registry = jsonToRegistry(linksMap);
        // then:
        assertEquals(registryToJson(create("http://example.org"), registry), linksMap);
    }
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE401_Memory_Leak__twoIntsStruct_realloc_62b.cpp
Label Definition File: CWE401_Memory_Leak.c.label.xml
Template File: sources-sinks-62b.tmpl.cpp
*/
/*
 * @description
 * CWE: 401 Memory Leak
 * BadSource: realloc Allocate data using realloc()
 * GoodSource: Allocate data on the stack
 * Sinks:
 *    GoodSink: call free() on data
 *    BadSink : no deallocation of data
 * Flow Variant: 62 Data flow: data flows using a C++ reference from one function to another in different source files
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

namespace CWE401_Memory_Leak__twoIntsStruct_realloc_62
{

#ifndef OMITBAD

void badSource(twoIntsStruct * &data)
{
    /* POTENTIAL FLAW: Allocate memory on the heap */
    data = (twoIntsStruct *)realloc(data, 100*sizeof(twoIntsStruct));
    if (data == NULL) {exit(-1);}
    /* Initialize and make use of data */
    data[0].intOne = 0;
    data[0].intTwo = 0;
    printStructLine(&data[0]);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B() uses the GoodSource with the BadSink */
void goodG2BSource(twoIntsStruct * &data)
{
    /* FIX: Use memory allocated on the stack with ALLOCA */
    data = (twoIntsStruct *)ALLOCA(100*sizeof(twoIntsStruct));
    /* Initialize and make use of data */
    data[0].intOne = 0;
    data[0].intTwo = 0;
    printStructLine(&data[0]);
}

/* goodB2G() uses the BadSource with the GoodSink */
void goodB2GSource(twoIntsStruct * &data)
{
    /* POTENTIAL FLAW: Allocate memory on the heap */
    data = (twoIntsStruct *)realloc(data, 100*sizeof(twoIntsStruct));
    if (data == NULL) {exit(-1);}
    /* Initialize and make use of data */
    data[0].intOne = 0;
    data[0].intTwo = 0;
    printStructLine(&data[0]);
}

#endif /* OMITGOOD */

} /* close namespace */

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Sylius\Component\Addressing\Model;

use Sylius\Component\Resource\Model\ResourceInterface;
use Sylius\Component\Resource\Model\TimestampableInterface;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
interface AddressInterface extends TimestampableInterface, ResourceInterface
{
    /**
     * @return string
     */
    public function getFirstName();

    /**
     * @param string $firstName
     */
    public function setFirstName($firstName);

    /**
     * @return string
     */
    public function getLastName();

    /**
     * @param string $lastName
     */
    public function setLastName($lastName);

    /**
     * @return string
     */
    public function getPhoneNumber();

    /**
     * @param string $phoneNumber
     */
    public function setPhoneNumber($phoneNumber);

    /**
     * @return string
     */
    public function getCompany();

    /**
     * @param string $company
     */
    public function setCompany($company);

    /**
     * @return string
     */
    public function getCountryCode();

    /**
     * @param string $countryCode
     */
    public function setCountryCode($countryCode = null);

    /**
     * @return string
     */
    public function getProvinceCode();

    /**
     * @param string $provinceCode
     */
    public function setProvinceCode($provinceCode = null);

    /**
     * @return string
     */
    public function getStreet();

    /**
     * @param string $street
     */
    public function setStreet($street);

    /**
     * @return string
     */
    public function getCity();

    /**
     * @param string $city
     */
    public function setCity($city);

    /**
     * @return string
     */
    public function getPostcode();

    /**
     * @param string $postcode
     */
    public function setPostcode($postcode);
}


text:
      <form name="newThingForm"
          ng-submit="validateAndAddToModel(newThing.name)"
          ng-class="{'has-error': newThingName.$invalid || modalError}"
          novalidate>

          <button type="button" class="close" ng-click="$hide()">×</button>

              this  already exists!

                New  name

              <input type="text"
                name="newThingName"
                ng-model="newThing.name"
                id="newThingName-{{thingName}}"
                cask-focus="inputNewThingName_{{thingName}}"
                class="form-control"
                required />

          <button type="submit"
            ng-disabled="newThingForm.$invalid"
            class="btn btn-primary"
          >Add</button>

      </form>


text:
<?php namespace Develpr\Tests;

class RequestSignerTest extends AbstractSignatureTest
{
	public function test_blah(){
		$this->assertTrue(true);
	}
}


text:
if ! uname -m | egrep -q "i686|x86_64"; then
  echo "Only x86 architectures are currently supported" >&2
  exit
fi

# Install first the default Linux build deps.
"$(dirname "${BASH_SOURCE[0]}")/install-build-deps.sh" \
    --no-syms --no-arm --no-chromeos-fonts --no-nacl --no-prompt

# The temporary directory used to store output of update-java-alternatives
TEMPDIR=$(mktemp -d)
cleanup() {
  local status=${?}
  trap - EXIT
  rm -rf "${TEMPDIR}"
  exit ${status}
}
trap cleanup EXIT

sudo apt-get update

# Fix deps
sudo apt-get -f install

# Install deps
# This step differs depending on what Ubuntu release we are running
# on since the package names are different, and Sun's Java must
# be installed manually on late-model versions.

# common
sudo apt-get -y install checkstyle lighttpd python-pexpect xvfb x11-utils

# Few binaries in the Android SDK require 32-bit libraries on the host.
sudo apt-get -y install lib32z1 g++-multilib

sudo apt-get -y install ant

# Install openjdk and openjre 7 stuff
sudo apt-get -y install openjdk-7-jre openjdk-7-jdk

# Switch version of Java to openjdk 7.
# Some Java plugins (e.g. for firefox, mozilla) are not required to build, and
# thus are treated only as warnings. Any errors in updating java alternatives
# which are not '*-javaplugin.so' will cause errors and stop the script from
# completing successfully.
if ! sudo update-java-alternatives -s java-1.7.0-openjdk-amd64 \
           >& "${TEMPDIR}"/update-java-alternatives.out
then
  # Check that there are the expected javaplugin.so errors for the update
  if grep 'javaplugin.so' "${TEMPDIR}"/update-java-alternatives.out >& \
      /dev/null
  then
    # Print as warnings all the javaplugin.so errors
    echo 'WARNING: java-6-sun has no alternatives for the following plugins:'
    grep 'javaplugin.so' "${TEMPDIR}"/update-java-alternatives.out
  fi
  # Check if there are any errors that are not javaplugin.so
  if grep -v 'javaplugin.so' "${TEMPDIR}"/update-java-alternatives.out \
      >& /dev/null
  then
    # If there are non-javaplugin.so errors, treat as errors and exit
    echo 'ERRORS: Failed to update alternatives for java-6-sun:'
    grep -v 'javaplugin.so' "${TEMPDIR}"/update-java-alternatives.out
    exit 1
  fi
fi

echo "install-build-deps-android.sh complete."


text:
This program was for a CS college course. The lab was given the pet name "Monster" by my professor because of it's challenging nature, she said.

The program is basically a obstacle course demonstrating various programming abilities and use of good logic like input validation etc.

There are 7 different functions that the program can do and these are:

1) Average a set of non-negative numbers - You will be prompted to continuously enter numbers until you enter a number which is less than zero. The average of the numbers you entered will be printed after.

2) Enter a number in a given range - You will be prompted to enter a start and an end range and then a number in the range you entered. The program is written in such a way to make the case where your start is larger than your end impossible.

3) Enter a letter - Pretty straight forward. The program will make sure you enter a letter.

4) Enter an integer - Also very straight forward. The program will check the input before accepting it (or crashing).

5) Enter a prime number - You will be prompted to input a prime number and the program will validate that it is indeed prime.

6) Classify a number as deficient, perfect, or abundant. A number is deficient when the sum of all it's factors is less than the number itself, perfect when the sum of the factors equal the number and abundant when the sum of the factors is greater than the number. This is of course not including the number itself in the sum of the factors.

7) Prints the ASCII table with customizable formatting. You can choose the number of columns you want and the program takes care of the rest.


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center_vertical"
    android:gravity="center_vertical"
    android:paddingLeft="10dip"
    android:paddingRight="10dip" >

    <LinearLayout
        android:id="@+id/notify_linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:orientation="horizontal" >

        <LinearLayout
            android:id="@+id/notify_linearLayout2"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center_vertical" >

            <ImageView
                android:id="@+id/noitfy_icon"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5.0dp"
                android:layout_marginRight="10.0dp" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/notify_linearLayout3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dip"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/notify_text"
                style="@style/NotificationTitle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="2dip"
                android:ellipsize="end"
                android:singleLine="true" />

            <RelativeLayout
                android:id="@+id/RelativeLayout01"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >

                <TextView
                    android:id="@+id/notify_state"
                    style="@style/NotificationText"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentLeft="true"
                    android:layout_marginLeft="2dip"
                    android:singleLine="true" />

                <TextView
                    android:id="@+id/notify_speed"
                    style="@style/NotificationText"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:singleLine="true" />
            </RelativeLayout>
        </LinearLayout>
    </LinearLayout>

    <ProgressBar
        android:id="@+id/notify_processbar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/notify_linearLayout1" />

</RelativeLayout>


text:
using SimpleSharpDependencyInjection.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SimpleSharpDependencyInjection.Exceptions
{
	public class InvalidDependencyObjectTypeException : SimpleSharpDependencyInjectionException
	{
		public InvalidDependencyObjectTypeException(Type t, DependencyObjectType current, DependencyObjectType required)
			: base(string.Format("Class: {0} is of object-type: '{0}', while '{2}' is required", t, current, required))
		{ }
	}
}


text:
import {observable, isObservable, observe, unobserve} from '@nx-js/observer-util';

const time = observable({seconds: 10});
let check: boolean = isObservable(time);
const logger = observe(() => console.log(time.seconds));
unobserve(logger);

// $FlowExpectedError
const errorLogger = observe(time);

// $FlowExpectedError
const errorTime = observable(2);


text:
function h = hypotenuse(a, b)
% h = hypotenuse of a right triangle with square sides = a, b

h = sqrt(a^2 + b^2);


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>ActiveModel::AttributeMethods</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" href="../../css/reset.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../css/main.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../css/github.css" type="text/css" media="screen" />

            Ruby on Rails 4.0.0

            Module
            ActiveModel::AttributeMethods

/usr/local/rvm/gems/ruby-2.0.0-p0/gems/activemodel-4.0.0/lib/active_model/attribute_methods.rb

Active Model Attribute Methods

ActiveModel::AttributeMethods provides a way to add prefixes
and suffixes to your methods as well as handling the creation of
ActiveRecord::Base-like class methods such as
table_name.

The requirements to implement ActiveModel::AttributeMethods
are to:

include ActiveModel::AttributeMethods in your class.

Call each of its method you want to add, such as
attribute_method_suffix or
attribute_method_prefix.

Call define_attribute_methods after the other methods are
called.

Define the various generic _attribute methods that you have
declared.

Define an attributes method, see below.

A minimal implementation could be:

class Person
  include ActiveModel::AttributeMethods

  attribute_method_affix  prefix: 'reset_', suffix: '_to_default!'
  attribute_method_suffix '_contrived?'
  attribute_method_prefix 'clear_'
  define_attribute_methods :name

  attr_accessor :name

  def attributes
    {'name' => @name}
  end

  private

  def attribute_contrived?(attr)
    true
  end

  def clear_attribute(attr)
    send("#{attr}=", nil)
  end

  def reset_attribute_to_default!(attr)
    send("#{attr}=", 'Default Name')
  end
end

Note that whenever you include ActiveModel::AttributeMethods
in your class, it requires you to implement an attributes
method which returns a hash with each attribute name in your model as hash
key and the attribute value as hash value.

Hash keys must be strings.

Namespace

          MODULE
          ActiveModel::AttributeMethods::ClassMethods

Methods

A

                attribute_missing

M

                method_missing

R

                respond_to?,

                respond_to_without_attributes?

Constants

            NAME_COMPILABLE_REGEXP
            =
            /\A[a-zA-Z_]\w*[!?=]?\z/

            CALL_COMPILABLE_REGEXP
            =
            /\A[a-zA-Z_]\w*[!?]?\z/

Instance Public methods

              attribute_missing(match, *args, &block)

            Link

attribute_missing is like method_missing, but for
attributes. When method_missing is called we check to see if
there is a matching attribute method. If so, we tell
attribute_missing to dispatch the attribute. This method can
be overloaded to customize the behavior.

                Source:
                show

# File /usr/local/rvm/gems/ruby-2.0.0-p0/gems/activemodel-4.0.0/lib/active_model/attribute_methods.rb, line 444
def attribute_missing(match, *args, &block)
  __send__(match.target, match.attr_name, *args, &block)
end

              method_missing(method, *args, &block)

            Link

Allows access to the object attributes, which are held in the hash returned
by attributes, as though they were first-class methods. So a
Person class with a name attribute can for
example use Person#name and Person#name= and
never directly use the attributes hash – except for multiple assigns with
ActiveRecord::Base#attributes=.

It's also possible to instantiate related objects, so a
Client class belonging to the clients table with
a master_id foreign key can instantiate master through
Client#master.

                Source:
                show

# File /usr/local/rvm/gems/ruby-2.0.0-p0/gems/activemodel-4.0.0/lib/active_model/attribute_methods.rb, line 431
def method_missing(method, *args, &block)
  if respond_to_without_attributes?(method, true)
    super
  else
    match = match_attribute_method?(method.to_s)
    match ? attribute_missing(match, *args, &block) : super
  end
end

              respond_to?(method, include_private_methods = false)

            Link

              Also aliased as: respond_to_without_attributes?

                Source:
                show

# File /usr/local/rvm/gems/ruby-2.0.0-p0/gems/activemodel-4.0.0/lib/active_model/attribute_methods.rb, line 452
def respond_to?(method, include_private_methods = false)
  if super
    true
  elsif !include_private_methods && super(method, true)
    # If we're here then we haven't found among non-private methods
    # but found among all methods. Which means that the given method is private.
    false
  else
    !match_attribute_method?(method.to_s).nil?
  end
end

              respond_to_without_attributes?(method, include_private_methods = false)

            Link

A Person instance with a name attribute can ask
person.respond_to?(:name),
person.respond_to?(:name=), and
person.respond_to?(:name?) which will all return
true.


text:
Change Log
--------

v0.1.13
 - Fix test for $pristine state

v0.1.12
 - Fix ngModel setPristine call when $setViewValue(null) in init

v0.1.11
 - Update package description

v0.1.10
 - Update bower and npm keywords for better search visibility

v0.1.9
 - Rename preprocessor to parser
 - Custom parser can return a promise
 - Removed `base64Converter` service. There are better base64 libraries already available for base64 conversion

v0.1.8
 - To update premature npm publish. Will deprecate `v0.1.7`

v0.1.7
 - Support preprocessor handlers
 - Added `base64Converter` service

v0.1.6
 - Fix for [browserify](http://browserify.org)

v0.1.5
 - Fixed `maxsize` and `minsize` validator for single file selection

v0.1.4
 - Fix bower.json

v0.1.3
 - Refactor test config files
 - Test gainst number of angular versions, and fix errors for angular v1.2.10
 - Removed custom `required` validator. Angular's default `require` validator works well

v0.1.2
 - Move all validators to `ngModel.$parsers`, it's more angular way
 - Added unit tests

v0.1.1
 - Remove the use of singleton file reader instance. Each file is read by respective file reader.
 - FileReader event handlers receive new set of arguments `(Event, FileReader, File, FileList, FileObjects, FileObject)`.
 - Added `on-change` event.
 - Added sourcemap.

V0.1.0
 - Support for multiple file selection
 - Support for file reader event handlers
 - Added validations
 - Removed `base-sixty-four-image` and `base-sixty-four-image-placeholder` directives


text:
package org.openhds.webservice;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

public class CacheResponseWriter {

    public static void writeResponse(File fileToWrite, HttpServletResponse response) throws IOException {
        if (!fileToWrite.exists()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }

        response.setStatus(HttpServletResponse.SC_OK);

        InputStream is = null;
        try {
            is = new BufferedInputStream(new FileInputStream(fileToWrite));
            IOUtils.copy(is, response.getOutputStream());
        } finally {
            if (is != null) {
                IOUtils.closeQuietly(is);
            }
        }
    }
}


text:
package org.openspaces.admin.gsa;

import com.gigaspaces.grid.gsa.GSProcessOptions;

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

/**
 * {@link org.openspaces.admin.lus.LookupService} process options to be started by the
 * {@link org.openspaces.admin.gsa.GridServiceAgent}.
 *
 * @author kimchy
 * @see org.openspaces.admin.gsa.GridServiceAgent#startGridService(LookupServiceOptions)
 */
public class LookupServiceOptions {

    private final List<String> vmInputArguments = new ArrayList<String>();

    private boolean overrideVmInputArguments = false;

    private boolean useScript = false;

    private final Map<String, String> environmentVariables = new HashMap<String, String>();

    /**
     * Constructs a new lookup service options. By default will use JVM process execution.
     */
    public LookupServiceOptions() {
    }

    /**
     * Will cause the {@link org.openspaces.admin.lus.LookupService} to be started using a script
     * and not a pure Java process.
     */
    public LookupServiceOptions useScript() {
        this.useScript = true;
        return this;
    }

    /**
     * Will cause JVM options added using {@link #vmInputArgument(String)} to override all the vm arguments
     * that the JVM will start by default with.
     */
    public LookupServiceOptions overrideVmInputArguments() {
        overrideVmInputArguments = true;
        return this;
    }

    /**
     * Will add a JVM level argument when the process is executed using pure JVM. For example, the memory
     * can be controlled using <code>-Xmx512m</code>.
     */
    public LookupServiceOptions vmInputArgument(String vmInputArgument) {
        vmInputArguments.add(vmInputArgument);
        return this;
    }

    /**
     * Sets an environment variable that will be passed to forked process.
     */
    public LookupServiceOptions environmentVariable(String name, String value) {
        environmentVariables.put(name, value);
        return this;
    }

    /**
     * Returns the agent process options that represents what was set on this LUS options.
     */
    public GSProcessOptions getOptions() {
        GSProcessOptions options = new GSProcessOptions("lus");
        options.setUseScript(useScript);
        if (overrideVmInputArguments) {
            options.setVmInputArguments(vmInputArguments.toArray(new String[vmInputArguments.size()]));
        } else {
            options.setVmAppendableInputArguments(vmInputArguments.toArray(new String[vmInputArguments.size()]));
        }
        options.setEnvironmentVariables(environmentVariables);
        return options;
    }
}


text:
@implementation RedState

- (instancetype)initWithComponent:(BarrierComponent*)barrier
{
  self = [super init];
  if (self) {
    self.barrierComponent = barrier;
  }
  return self;
}

-(void)didEnterWithPreviousState:(GKState *)previousState
{
  [super didEnterWithPreviousState:previousState];

  Player* player = (Player*)self.barrierComponent.entity;
  player.barrierComponent.color = [UIColor redColor];
  player.animationComponent.shape.fillColor = player.barrierComponent.color;
  player.barrierComponent.shape.fillColor = player.barrierComponent.color;
  player.barrierComponent.shape.physicsBody.categoryBitMask = redBarrierCategory;
  player.barrierComponent.shape.physicsBody.contactTestBitMask = redEnemyCategory;

}

@end


text:
function OnInterceptor(
  $httpProvider,
  jwtOptionsProvider,
  RestangularProvider) {

  'ngInject';

  console.log('ASHDKJHIUQHWIUEHQW');

  localStorage.removeItem('publicToken');

  // TODO: melhorar o interceptador da resposta...
  RestangularProvider.addResponseInterceptor(function (data, operation, what, url, response, deferred) {
    if (operation == "getList") {
      var responseData = response.data;
      if (responseData.total == undefined) return responseData.data;
      var newResponse = responseData.data;
      newResponse.total = responseData.total;

      return newResponse;
        //return { pagingInfo: responseData.paginginfo, data: responseData.result };
    }
    if (operation != "get") {
        //var item = { status: response.status };
        //feedBackFactory.showFeedBack(item);
    }

    return response.data;
  });

}

export default OnInterceptor;


text:
using System.Collections.Generic;

namespace DisasterRecoveryAPI.Models.ViewModels
{
    public class BuildingDetailsViewModel
    {
        public int Id { get; set; }
        public int YearBuilt { get; set; }
        public string Address { get; set; }
        public string PostCode { get; set; }
        public string County { get; set; }
        public string Country { get; set; }
        public UserViewModel Manager { get; set; }
    }

    public class BuildingOccupantsViewModel
    {
        public int BuildingId;
        public List<UserViewModel> Occupants;
    }
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace XenAPI
{
    /// <summary>
    /// Management of remote authentication services
    /// First published in XenServer 5.5.
    /// </summary>
    public partial class Auth : XenObject<Auth>
    {
        public Auth()
        {
        }

        /// <summary>
        /// Creates a new Auth from a Proxy_Auth.
        /// </summary>
        /// <param name="proxy"></param>
        public Auth(Proxy_Auth proxy)
        {
            this.UpdateFromProxy(proxy);
        }

        /// <summary>
        /// Updates each field of this instance with the value of
        /// the corresponding field of a given Auth.
        /// </summary>
        public override void UpdateFrom(Auth update)
        {
        }

        internal void UpdateFromProxy(Proxy_Auth proxy)
        {
        }

        public Proxy_Auth ToProxy()
        {
            Proxy_Auth result_ = new Proxy_Auth();
            return result_;
        }

        /// <summary>
        /// Creates a new Auth from a Hashtable.
        /// Note that the fields not contained in the Hashtable
        /// will be created with their default values.
        /// </summary>
        /// <param name="table"></param>
        public Auth(Hashtable table) : this()
        {
            UpdateFrom(table);
        }

        /// <summary>
        /// Given a Hashtable with field-value pairs, it updates the fields of this Auth
        /// with the values listed in the Hashtable. Note that only the fields contained
        /// in the Hashtable will be updated and the rest will remain the same.
        /// </summary>
        /// <param name="table"></param>
        public void UpdateFrom(Hashtable table)
        {
        }

        public bool DeepEquals(Auth other)
        {
            if (ReferenceEquals(null, other))
                return false;
            if (ReferenceEquals(this, other))
                return true;

            return false;
        }

        internal static List<Auth> ProxyArrayToObjectList(Proxy_Auth[] input)
        {
            var result = new List<Auth>();
            foreach (var item in input)
                result.Add(new Auth(item));

            return result;
        }

        public override string SaveChanges(Session session, string opaqueRef, Auth server)
        {
            if (opaqueRef == null)
            {
                System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
                return "";
            }
            else
            {
              throw new InvalidOperationException("This type has no read/write properties");
            }
        }
        /// <summary>
        /// This call queries the external directory service to obtain the subject_identifier as a string from the human-readable subject_name
        /// First published in XenServer 5.5.
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="_subject_name">The human-readable subject_name, such as a username or a groupname</param>
        public static string get_subject_identifier(Session session, string _subject_name)
        {
            if (session.JsonRpcClient != null)
                return session.JsonRpcClient.auth_get_subject_identifier(session.opaque_ref, _subject_name);
            else
                return (string)session.proxy.auth_get_subject_identifier(session.opaque_ref, _subject_name ?? "").parse();
        }

        /// <summary>
        /// This call queries the external directory service to obtain the user information (e.g. username, organization etc) from the specified subject_identifier
        /// First published in XenServer 5.5.
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="_subject_identifier">A string containing the subject_identifier, unique in the external directory service</param>
        public static Dictionary<string, string> get_subject_information_from_identifier(Session session, string _subject_identifier)
        {
            if (session.JsonRpcClient != null)
                return session.JsonRpcClient.auth_get_subject_information_from_identifier(session.opaque_ref, _subject_identifier);
            else
                return Maps.convert_from_proxy_string_string(session.proxy.auth_get_subject_information_from_identifier(session.opaque_ref, _subject_identifier ?? "").parse());
        }

        /// <summary>
        /// This calls queries the external directory service to obtain the transitively-closed set of groups that the the subject_identifier is member of.
        /// First published in XenServer 5.5.
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="_subject_identifier">A string containing the subject_identifier, unique in the external directory service</param>
        public static string[] get_group_membership(Session session, string _subject_identifier)
        {
            if (session.JsonRpcClient != null)
                return session.JsonRpcClient.auth_get_group_membership(session.opaque_ref, _subject_identifier);
            else
                return (string [])session.proxy.auth_get_group_membership(session.opaque_ref, _subject_identifier ?? "").parse();
        }
    }
}


text:
/* Includes ------------------------------------------------------------------*/
#include "lib/USB_lib/inc/usb_lib.h"

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/*  The number of current endpoint, it will be used to specify an endpoint */
 u8	EPindex;
/*  The number of current device, it is an index to the Device_Table */
/* u8	Device_no; */
/*  Points to the DEVICE_INFO structure of current device */
/*  The purpose of this register is to speed up the execution */
DEVICE_INFO *pInformation;
/*  Points to the DEVICE_PROP structure of current device */
/*  The purpose of this register is to speed up the execution */
DEVICE_PROP *pProperty;
/*  Temporary save the state of Rx & Tx status. */
/*  Whenever the Rx or Tx state is changed, its value is saved */
/*  in this variable first and will be set to the EPRB or EPRA */
/*  at the end of interrupt process */
u16	SaveState ;
u16  wInterrupt_Mask;
DEVICE_INFO	Device_Info;
USER_STANDARD_REQUESTS  *pUser_Standard_Requests;

/* Extern variables ----------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/

/*******************************************************************************
* Function Name  : USB_Init
* Description    : USB system initialization
* Input          : None.
* Output         : None.
* Return         : None.
*******************************************************************************/
void USB_Init(void)
{
  pInformation = &Device_Info;
  pInformation->ControlState = 2;
  pProperty = &Device_Property;
  pUser_Standard_Requests = &User_Standard_Requests;
  /* Initialize devices one by one */
  pProperty->Init();
}

/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/


text:
#ifndef __Nimble_EventEmitter_H__
#define __Nimble_EventEmitter_H__

#include "Globals.h"

NIMBLE_BEGIN

    namespace detail {

        //! Event listener subscribtion
        class Listener {
        public:

            virtual         ~Listener( void ) {}

            //! Emits event to listener.
            virtual void    notify( const void* e ) = 0;
        };

        //! Event listener with a type.
        template<typename T>
        class EventListener : public Listener {
        public:

            //! Callback function type.
            typedef cClosure<void(const T&)> Callback;

                            //! Constructs EventListener instance.
                            EventListener( const Callback& callback )
                                : m_callback( callback ) {}

            //! Compares this listener with a callback.
            bool            operator == ( const Callback& callback ) const { return m_callback == callback; }

            //! Calls a callback function with a casted event.
            virtual void    notify( const void* e ) { m_callback( *reinterpret_cast<const T*>( e ) ); }

        private:

            //! Callback function.
            Callback        m_callback;
        };
    } // namespace detail

    //! Event emitter class is used for dispatching strong typed global events.
    class EventEmitter {
    public:

        virtual    ~EventEmitter( void ) {}

        //! Callback type wrapper.
        template<typename TEvent>
        struct Callback {
            //! Callback type alias.
            typedef typename detail::EventListener<TEvent>::Callback Type;
        };

        //! Subscribes to an event of type TEvent.
        template<typename TEvent>
        void subscribe( const typename Callback<TEvent>::Type& callback );

        //! Unsubscribes from an event of type TEvent.
        template<typename TEvent>
        void unsubscribe( const typename Callback<TEvent>::Type& callback );

        //! Emits a global event.
        template<typename TEvent>
        void notify( const TEvent& e );

    #ifdef NIMBLE_CPP11_ENABLED
        //! Constructs and emits a new event instance.
        template<typename TEvent, typename ... TArgs>
        void notify( const TArgs& ... args );
    #endif  /*  NIMBLE_CPP11_ENABLED    */

    private:

        //! Array of listeners.
        typedef Array< UPtr<detail::Listener> > Listeners;

        //! Listener container type.
        typedef Map<TypeIdx, Listeners> Subscribers;

        //! Array of array of listeners.
        Subscribers    m_subscribers;
    };

    // ** EventEmitter::subscribe
    template<typename TEvent>
    inline void EventEmitter::subscribe( const typename Callback<TEvent>::Type& callback )
    {
        TypeIdx idx = TypeIndex<TEvent>::idx();

        if( m_subscribers.count( idx ) == 0 ) {
            m_subscribers[idx] = Listeners();
        }

        m_subscribers[idx].push_back( new detail::EventListener<TEvent>( callback ) );
    }

    // ** EventEmitter::unsubscribe
    template<typename TEvent>
    inline void EventEmitter::unsubscribe( const typename Callback<TEvent>::Type& callback )
    {
        TypeIdx idx = TypeIndex<TEvent>::idx();

        if( m_subscribers.count( idx ) == 0 ) {
            return;
        }

        typedef detail::EventListener<TEvent> EventListenerType;
        Listeners& listeners = m_subscribers[idx];

        for( Listeners::iterator i = listeners.begin(); i != listeners.end(); )
        {
            EventListenerType& listener = *static_cast<EventListenerType*>( i->get() );
            if( listener == callback ) {
                i = listeners.erase( i );
            } else {
                ++i;
            }
        }
    }

    // ** EventEmitter::notify
    template<typename TEvent>
    inline void EventEmitter::notify( const TEvent& e )
    {
        TypeIdx idx = TypeIndex<TEvent>::idx();
        Subscribers::iterator i = m_subscribers.find( idx );

        if( i == m_subscribers.end() ) {
            return;
        }

        for( u32 j = 0; j < ( u32 )i->second.size(); j++ ) {
            i->second[j]->notify( &e );
        }
    }

#ifdef NIMBLE_CPP11_ENABLED

    // ** EventEmitter::notify
    template<typename TEvent, typename ... TArgs>
    inline void EventEmitter::notify( const TArgs& ... args )
    {
        TEvent e( args... );
        notify( e );
    }

#endif    /*    NIMBLE_CPP11_ENABLED    */

    //! Event emitter class used for injection.
    template<typename TBase>
    class InjectEventEmitter : public TBase {
    public:

                                    //! Constructs InjectEventEmitter instance by passing arguments to TBase's constructor.
                                    template<typename ... TArgs>
                                    InjectEventEmitter( TArgs ... args )
                                        : TBase( args... ) {}

        //! Subscribes to an event of type TEvent.
        template<typename TEvent>
        void                        subscribe( const typename EventEmitter::Callback<TEvent>::Type& callback ) { m_eventEmitter.subscribe<TEvent>( callback ); }

        //! Unsubscribes from an event of type TEvent.
        template<typename TEvent>
        void                        unsubscribe( const typename EventEmitter::Callback<TEvent>::Type& callback ) { m_eventEmitter.unsubscribe<TEvent>( callback ); }

        //! Constructs and emits a new event instance.
        template<typename TEvent, typename ... TArgs>
        void                        notify( const TArgs& ... args ) { m_eventEmitter.notify<TEvent, TArgs...>( args... ); }

    protected:

        EventEmitter                m_eventEmitter;    //!< Event emitter instance.
    };

    //namespace detail {

    //    //! Event interface
    //    class IQueuedEvent {
    //    public:

    //        virtual            ~IQueuedEvent( void ) {}
    //        virtual void    emit( EventEmitter& emitter ) = 0;
    //    };

    //    //! Typed event.
    //    template<typename T>
    //    class QueuedEvent : public IQueuedEvent {
    //    public:

    //                        //! Constructs a QueuedEvent instance.
    //                        QueuedEvent( const T& e )
    //                            : m_event( e ) {}

    //        //! Emits an event.
    //        virtual void    emit( EventEmitter& emitter ) { emitter.emit( m_event ); }

    //    private:

    //        //! Stored event data.
    //        T                m_event;
    //    };

    //    //! Event queue is used for cross-thread event emitting.
    //    class EventQueue {
    //    public:

    //        //! Queues a new event.
    //        template<typename T>
    //        void            queue( const T& e );

    //        //! Emits all queued events.
    //        void            emit( EventEmitter& emitter );

    //    private:

    //        //! Queued events.
    //        Array<IQueuedEvent*>    m_events;
    //    };

    //    // ** EventQueue::queue
    //    template<typename T>
    //    inline void EventQueue::queue( const T& e )
    //    {
    //    //    m_events.push_back( new QueuedEvent( e ) );
    //    }

    //    // ** EventQueue::emit
    //    inline void EventQueue::emit( EventEmitter& emitter )
    //    {
    //        for( u32 i = 0, n = m_events.size(); i < n; i++ ) {
    //            m_events[i]->emit( emitter );
    //            delete m_events[i];
    //        }

    //        m_events.clear();
    //    }

    //} // namespace detail

NIMBLE_END

#endif    /*    !__Nimble_EventEmitter_H__    */


text:
class Course::Admin::Assessments::CategoriesController < Course::Admin::Controller
  load_and_authorize_resource :category,
                              through: :course,
                              through_association: :assessment_categories,
                              class: Course::Assessment::Category.name
  add_breadcrumb :index, :course_admin_assessments_path

  def new
  end

  def create
    if @category.save
      redirect_to course_admin_assessments_path(current_course),
                  success: t('.success', title: @category.title)
    else
      render 'new'
    end
  end

  def destroy
    if @category.destroy
      redirect_to course_admin_assessments_path(current_course),
                  success: t('.success', title: @category.title)
    else
      redirect_to course_admin_assessments_path(current_course),
                  danger: t('.failure', error: @category.errors.full_messages.to_sentence)
    end
  end

  private

  def category_params
    params.require(:category).permit(:title, :weight)
  end
end


text:
<?php
/**
 * wallee SDK
 *
 * This library allows to interact with the wallee payment service.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Wallee\Sdk\Model;

use \ArrayAccess;
use \Wallee\Sdk\ObjectSerializer;

/**
 * AbstractCustomerAddressActive model
 *
 * @category    Class
 * @package     Wallee\Sdk
 * @author      customweb GmbH
 * @license     http://www.apache.org/licenses/LICENSE-2.0 Apache License v2
 */
class AbstractCustomerAddressActive implements ModelInterface, ArrayAccess
{
    const DISCRIMINATOR = null;

    /**
      * The original name of the model.
      *
      * @var string
      */
    protected static $swaggerModelName = 'Abstract.CustomerAddress.Active';

    /**
      * Array of property to type mappings. Used for (de)serialization
      *
      * @var string[]
      */
    protected static $swaggerTypes = [
        'address' => '\Wallee\Sdk\Model\CustomerPostalAddressCreate',
        'address_type' => '\Wallee\Sdk\Model\CustomerAddressType'
    ];

    /**
      * Array of property to format mappings. Used for (de)serialization
      *
      * @var string[]
      */
    protected static $swaggerFormats = [
        'address' => null,
        'address_type' => null
    ];

    /**
     * Array of attributes where the key is the local name,
     * and the value is the original name
     *
     * @var string[]
     */
    protected static $attributeMap = [
        'address' => 'address',
        'address_type' => 'addressType'
    ];

    /**
     * Array of attributes to setter functions (for deserialization of responses)
     *
     * @var string[]
     */
    protected static $setters = [
        'address' => 'setAddress',
        'address_type' => 'setAddressType'
    ];

    /**
     * Array of attributes to getter functions (for serialization of requests)
     *
     * @var string[]
     */
    protected static $getters = [
        'address' => 'getAddress',
        'address_type' => 'getAddressType'
    ];

    /**
     * Associative array for storing property values
     *
     * @var mixed[]
     */
    protected $container = [];

    /**
     * Constructor
     *
     * @param mixed[] $data Associated array of property values
     *                      initializing the model
     */
    public function __construct(array $data = null)
    {

        $this->container['address'] = isset($data['address']) ? $data['address'] : null;

        $this->container['address_type'] = isset($data['address_type']) ? $data['address_type'] : null;

    }

    /**
     * Show all the invalid properties with reasons.
     *
     * @return array invalid properties with reasons
     */
    public function listInvalidProperties()
    {
        $invalidProperties = [];

        return $invalidProperties;
    }

    /**
     * Array of property to type mappings. Used for (de)serialization
     *
     * @return array
     */
    public static function swaggerTypes()
    {
        return self::$swaggerTypes;
    }

    /**
     * Array of property to format mappings. Used for (de)serialization
     *
     * @return array
     */
    public static function swaggerFormats()
    {
        return self::$swaggerFormats;
    }

    /**
     * Array of attributes where the key is the local name,
     * and the value is the original name
     *
     * @return array
     */
    public static function attributeMap()
    {
        return self::$attributeMap;
    }

    /**
     * Array of attributes to setter functions (for deserialization of responses)
     *
     * @return array
     */
    public static function setters()
    {
        return self::$setters;
    }

    /**
     * Array of attributes to getter functions (for serialization of requests)
     *
     * @return array
     */
    public static function getters()
    {
        return self::$getters;
    }

    /**
     * The original name of the model.
     *
     * @return string
     */
    public function getModelName()
    {
        return self::$swaggerModelName;
    }

    /**
     * Validate all the properties in the model
     * return true if all passed
     *
     * @return bool True if all properties are valid
     */
    public function valid()
    {
        return count($this->listInvalidProperties()) === 0;
    }

    /**
     * Gets address
     *
     * @return \Wallee\Sdk\Model\CustomerPostalAddressCreate
     */
    public function getAddress()
    {
        return $this->container['address'];
    }

    /**
     * Sets address
     *
     * @param \Wallee\Sdk\Model\CustomerPostalAddressCreate $address
     *
     * @return $this
     */
    public function setAddress($address)
    {
        $this->container['address'] = $address;

        return $this;
    }

    /**
     * Gets address_type
     *
     * @return \Wallee\Sdk\Model\CustomerAddressType
     */
    public function getAddressType()
    {
        return $this->container['address_type'];
    }

    /**
     * Sets address_type
     *
     * @param \Wallee\Sdk\Model\CustomerAddressType $address_type
     *
     * @return $this
     */
    public function setAddressType($address_type)
    {
        $this->container['address_type'] = $address_type;

        return $this;
    }

    /**
     * Returns true if offset exists. False otherwise.
     *
     * @param integer $offset Offset
     *
     * @return boolean
     */
    #[\ReturnTypeWillChange]
    public function offsetExists($offset)
    {
        return isset($this->container[$offset]);
    }

    /**
     * Gets offset.
     *
     * @param integer $offset Offset
     *
     * @return mixed
     */
    #[\ReturnTypeWillChange]
    public function offsetGet($offset)
    {
        return isset($this->container[$offset]) ? $this->container[$offset] : null;
    }

    /**
     * Sets value based on offset.
     *
     * @param integer $offset Offset
     * @param mixed   $value  Value to be set
     *
     * @return void
     */
    #[\ReturnTypeWillChange]
    public function offsetSet($offset, $value)
    {
        if (is_null($offset)) {
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }

    /**
     * Unsets offset.
     *
     * @param integer $offset Offset
     *
     * @return void
     */
    #[\ReturnTypeWillChange]
    public function offsetUnset($offset)
    {
        unset($this->container[$offset]);
    }

    /**
     * Gets the string presentation of the object
     *
     * @return string
     */
    public function __toString()
    {
        if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
            return json_encode(
                ObjectSerializer::sanitizeForSerialization($this),
                JSON_PRETTY_PRINT
            );
        }

        return json_encode(ObjectSerializer::sanitizeForSerialization($this));
    }
}


text:
package com.weatherNotes.conf;

import com.weatherNotes.common.Defines;
import com.weatherNotes.conf.security.SecurityConfig;
import com.weatherNotes.utils.LoggingAspect;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@EnableWebMvc
@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
@EnableJpaRepositories(basePackages = Defines.Packages.REPOISTORY_PACKAGE)
@EnableTransactionManagement
@Import({SecurityConfig.class})
@ComponentScan(basePackages = "com")
@PropertySource(name = Defines.Statics.APPLICATION_PROPERTIES,
        value = {Defines.Statics.PROP_FILE_PATH},
        ignoreResourceNotFound = false)
public class ApplicationConfig extends WebMvcConfigurerAdapter {

    @Autowired
    private ConfigurableEnvironment env;

    @Bean
    public LoggingAspect loggingAspect() {
        return new LoggingAspect();
    }

    @Bean()
    public DataSource dataSource() {

        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(env.getProperty(Defines.DataSource.DB_DRIVER_CLASS));
        dataSource.setUrl(env.getProperty(Defines.DataSource.DB_URL));
        dataSource.setUsername(env.getProperty(Defines.DataSource.DB_USERNAME));
        dataSource.setPassword(env.getProperty(Defines.DataSource.DB_PASSWORD));
        return dataSource;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource());
        em.setPackagesToScan(Defines.Packages.MODEL_PACKAGE);
        em.setJpaProperties(this.additionalProperties());
        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);

        return em;
    }

    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(emf);

        return transactionManager;
    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
        return new PersistenceExceptionTranslationPostProcessor();
    }

    Properties additionalProperties() {
        Properties properties = new Properties();
        properties.setProperty(Defines.Hibernate.DIALECT, env.getProperty(Defines.Hibernate.DIALECT));
        properties.setProperty(Defines.Hibernate.CONN_POOL_SIZE, env.getProperty(Defines.Hibernate.CONN_POOL_SIZE));
        properties.setProperty(Defines.Hibernate.SHOW_SQL, env.getProperty(Defines.Hibernate.SHOW_SQL));
        properties.setProperty(Defines.Hibernate.HBM2DDL_AUTO, env.getProperty(Defines.Hibernate.HBM2DDL_AUTO));
        properties.setProperty(Defines.Hibernate.SESSION_CONTEX_CLASS, env.getProperty(Defines.Hibernate.SESSION_CONTEX_CLASS));

        return properties;
    }

    @Bean
    public ViewResolver viewResolver() {

        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix(env.getProperty(Defines.ViewResolver.PREFIX));
        viewResolver.setSuffix(env.getProperty(Defines.ViewResolver.SUFIX));
        return viewResolver;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // Static ressources from both WEB-INF
        registry
                .addResourceHandler(env.getProperty(Defines.ResourceHandler.RESOURCE_HANDLER))
                .addResourceLocations(env.getProperty(Defines.ResourceHandler.RESOURCE_LOCATIONS))
                .setCachePeriod(Integer.parseInt(env.getProperty(Defines.ResourceHandler.RESOURCES_CACHE_PERIOD)));

    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Bean
    public MessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename(Defines.Statics.VALIDATION_MSG_FILE_NAME);
        return messageSource;
    }
}


text:
package Mimic;

/**
 *
 * @author
 * Toni Harju
 */
public interface IMainEvents {

	public void onCreate();
	public void onDestroy();

	public void onUpdate();
	public void onRender();

}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title>BioEHS President Inaugural Address</title>
    <meta name="description" content="Zian "Zane" Liu - Bioengineer, synthetic biologist, regulatory consultant, STEM outreach organizer, political junkie, menswear enthusiast, fountain pen user, coffee addict, and more..." />

    <meta name="HandheldFriendly" content="True" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="shortcut icon" href="/assets/images/favicon.ico" >

    <link rel="stylesheet" type="text/css" href="/assets/css/screen.css" />
    <link rel="stylesheet" type="text/css"
          href="//fonts.googleapis.com/css?family=Merriweather:300,700,700italic,300italic|Open+Sans:700,400" />
    <link rel="stylesheet" type="text/css" href="/assets/css/syntax.css" />

    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.3.0/styles/default.min.css">

        <link rel="canonical" href="/" />
    <meta name="referrer" content="origin" />
    <link rel="next" href="/page2/" />

    <meta property="og:site_name" content="Zian "Zane" Liu" />
    <meta property="og:type" content="website" />
    <meta property="og:title" content="Zian "Zane" Liu" />
    <meta property="og:description" content="Bioengineer, synthetic biologist, regulatory consultant, STEM outreach organizer, political junkie, menswear enthusiast, fountain pen user, coffee addict, and more..." />
    <meta property="og:url" content="/" />
    <meta property="og:image" content="/assets/images/cover1.jpg" />

    <meta name="twitter:card" content="summary_large_image" />
    <meta name="twitter:title" content="Zian "Zane" Liu" />
    <meta name="twitter:description" content="Bioengineer, synthetic biologist, regulatory consultant, STEM outreach organizer, political junkie, menswear enthusiast, fountain pen user, coffee addict, and more..." />
    <meta name="twitter:url" content="/" />
    <meta name="twitter:image:src" content="/assets/images/cover1.jpg" />

    <meta name="generator" content="Jekyll 3.0.0" />
    <link rel="alternate" type="application/rss+xml" title="Zian "Zane" Liu" href="/feed.xml" />

Menu

        Close

Home

About Zian

Resume

Projects

Leadership

Menswear Advice

Interests

Contact Me

Follow @chairmanzian

            Menu

BioEHS President Inaugural Address

            <time class="post-date" datetime="2014-12-12">12 Dec 2014</time>

                on

                       Leadership

I am honored and humbled to assume the Office of President of the Bioengineering Honor Society. For myself and on behalf of this club, I want to thank my predecessor for all she has done.

I want to recognize Anita for her role in the leadership, because she, not I, should have been the one becoming president today. Anita, you've given so much to this club - joy in a year as Social Chair and direction in a semester as EVP. We relied on you for each and every important project - two DWPs, the high school competition, a plethora of workshops, and countless socials. Your enthusiasm, your dependability, your natural and proven leadership - all these qualities made you the rock and backbone of BioEHS in this difficult time. I hope to be a worthy replacement of the great president you surely would have been.

For all of BioEHS - alumni, officers, members old and new - I want to apologize if this club has not lived up to your expectations. BioEHS needs to change after a year of stagnation, and it is the responsibility of this officer core to give the club the activation energy needed to revive it.

For we must make candidacy worthwhile to those who wish to join us, we must make membership meaningful for those who are a part of us, and we must make our actions useful for those around us.

My fellow bioengineers, fellow members of the Bioengineering Honor Society - the era of stagnation is over. Because today, the work to build a better BioEHS begins, and I hope to see all of you on the journey ahead.

Thank you, and good night!

                's Picture

Zian Liu

 Bioengineer, synthetic biologist, and medical device regulatory professional. Constantly caffeinated. Owner of way too many navy suits.

                     Silicon Valley
                     zane@chairmanzian.com

Share this post

                    Twitter

                    Facebook

                    Google+

Presidential Address to 2015 BioEHSC

_My speech at the opening ceremonies of the 2015 Bioengineering High School Competition, as prepared...

On Open Collars

I had the misfortune of running into a seemingly unsuccessful job interview at Starbucks today....

Zian "Zane" Liu © 2018

Proudly published with Jekyll using Jasper


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0">
<context>
    <name>main</name>
    <message>
        <source>Not authenticated</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <source>Would you like to sign in to Google for authentication?</source>
        <translation type="unfinished"></translation>
    </message>
</context>
<context>
    <name>o_auth</name>
    <message>
        <source>Successfully authenticated!</source>
        <translation type="unfinished"></translation>
    </message>
</context>
</TS>


text:
function Validate()
    {
        // Check for empty fields
        if(empty($_POST['name'])            ||
                empty($_POST['email'])      ||
                empty($_POST['phone'])      ||
                empty($_POST['message'])    ||
                !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)) {

                return false;
           }
        else
            return true;
    }

function SendEmail($to = 'austinrf2918@yahoo.com')
    {
        if(Validate() == true) {
                $name           =   $_POST['name'];
                $email_address  =   $_POST['email'];
                $phone          =   $_POST['phone'];
                $message        =   $_POST['message'];

                // Create the email and send the message
                $email_subject  =   "Website Contact Form:  $name";
                $email_body     =   "You have received a new message from your website contact form.\n\n"."Here are the
                details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
                $headers        =   "From: noreply@tri-dev.com\n";
                $headers        .= "Reply-To: $email_address";
                // Send true on successful send.
                // Send false if failed
                return (mail($to,$email_subject,$email_body,$headers))? true: false;
            }
        else
            // Invalid inputs
            return 'err';
    }

    // Apply function(s). You will get true, false, or err
    $send   =   SendEmail();

    // On return, you can echo any result
    if($send == 'err')
        echo 'Invalid Fields.';
    elseif($send == false)
        echo 'An Error Occurred.';
    else
        echo 'Email Sent Successfully.';


text:
package com.lesfurets.maven.partial.core;

import static java.util.stream.Collectors.toSet;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.ResetCommand;
import org.junit.Before;
import org.junit.Test;

import com.lesfurets.maven.partial.mocks.LocalRepoMock;
import com.lesfurets.maven.partial.mocks.RepoTest;

public abstract class DifferentFilesTest extends RepoTest {

    private static final String REFS_HEADS_FEATURE_2 = "refs/heads/feature/2";
    private static final String HEAD = "HEAD";
    private static final String FETCH_FILE = "fetch-file";
    private static final String DEVELOP = "refs/heads/develop";
    private static final String REMOTE_DEVELOP = "refs/remotes/origin/develop";

    @Before
    public void before() throws Exception {
        super.init();
        localRepoMock = new LocalRepoMock(true);
    }

    @Test
    public void listIncludingOnlyUncommited() throws Exception {
        LOCAL_DIR.resolve("file5").toFile().createNewFile();
        getLocalRepoMock().getGit().add().addFilepattern(".").call();
        Property.untracked.setValue(Boolean.FALSE.toString());
        Property.uncommited.setValue(Boolean.TRUE.toString());
        assertTrue(getInstance().get().stream().anyMatch(p -> p.toString().contains("file5")));
    }

    @Test
    public void listIncludingOnlyUntracked() throws Exception {
        LOCAL_DIR.resolve("file5").toFile().createNewFile();
        Property.uncommited.setValue(Boolean.FALSE.toString());
        Property.untracked.setValue(Boolean.TRUE.toString());
        assertTrue(getInstance().get().stream().anyMatch(p -> p.toString().contains("file5")));
    }

    @Test
    public void listWithCheckout() throws Exception {
        getLocalRepoMock().getGit().reset().setRef(HEAD).setMode(ResetCommand.ResetType.HARD).call();
        getLocalRepoMock().getGit().reset().setRef(REFS_HEADS_FEATURE_2).setMode(ResetCommand.ResetType.HARD).call();
        Property.baseBranch.setValue(REFS_HEADS_FEATURE_2);
        getInstance().get();
        assertTrue(consoleOut.toString().contains("Checking out base branch refs/heads/feature/2"));
    }

    @Test
    public void list() throws Exception {
        final DifferentFiles differentFiles = getInstance();
        final Set<Path> expected = new HashSet<>(Arrays.asList(
                        Paths.get(LOCAL_DIR.toString(), "/child2", "subchild2", "src", "resources", "file2"),
                        Paths.get(LOCAL_DIR.toString(), "/child2", "subchild2", "src", "resources", "file22"),
                        Paths.get(LOCAL_DIR.toString() + "/child3","src", "resources", "file1"),
                        Paths.get(LOCAL_DIR.toString() + "/child4", "pom.xml")
        ));
        assertEquals(expected, differentFiles.get());
    }

    @Test
    public void listInSubdir() throws Exception {
        Path workDir = LOCAL_DIR.resolve("child2");
        final DifferentFiles differentFiles = getInstance();
        final Set<Path> expected = new HashSet<>(Arrays.asList(
                        workDir.resolve("subchild2").resolve("src").resolve("resources").resolve("file2"),
                        workDir.resolve("subchild2").resolve("src").resolve("resources").resolve("file22"),
                        workDir.resolve("..").resolve("child3").resolve("src").resolve("resources").resolve("file1").normalize(),
                        workDir.resolve("..").resolve("child4").resolve("pom.xml").normalize()
        ));
        assertEquals(expected, differentFiles.get());
    }

    @Test
    public void listComparedToMergeBase() throws Exception {
        getLocalRepoMock().getGit().reset().setRef(REFS_HEADS_FEATURE_2).setMode(ResetCommand.ResetType.HARD).call();
        getLocalRepoMock().getGit().checkout().setName(REFS_HEADS_FEATURE_2).call();
        getLocalRepoMock().getGit().reset().setRef(HEAD).setMode(ResetCommand.ResetType.HARD).call();
        Property.baseBranch.setValue(REFS_HEADS_FEATURE_2);
        Property.compareToMergeBase.setValue("true");
        assertTrue(getInstance().get().stream().collect(toSet()).contains(LOCAL_DIR.resolve("feature2-only-file.txt")));
        assertTrue(consoleOut.toString().contains("ee64b9b863d3d30b429459cb3ccfaeac67e4efa1"));
    }

    @Test
    public void fetch() throws Exception {
        Git remoteGit = localRepoMock.getRemoteRepo().getGit();
        remoteGit.reset().setRef(DEVELOP).setMode(ResetCommand.ResetType.HARD).call();
        remoteGit.checkout().setName(DEVELOP).call();
        remoteGit.getRepository().getDirectory().toPath().resolve(FETCH_FILE).toFile().createNewFile();
        remoteGit.add().addFilepattern(".").call();
        remoteGit.commit().setMessage(FETCH_FILE).call();
        assertEquals(FETCH_FILE, remoteGit.log().setMaxCount(1).call().iterator().next().getFullMessage());
        Property.fetchReferenceBranch.setValue(Boolean.TRUE.toString());
        Property.referenceBranch.setValue(REMOTE_DEVELOP);
        getInstance().get();
        Git localGit = localRepoMock.getGit();
        localGit.reset().setRef(REMOTE_DEVELOP).setMode(ResetCommand.ResetType.HARD).call();
        localGit.checkout().setName(REMOTE_DEVELOP).call();
        assertEquals(FETCH_FILE, localGit.log().setMaxCount(1).call().iterator().next().getFullMessage());
    }

    @Test
    public void fetchNonExistent() throws Exception {
        Git remoteGit = localRepoMock.getRemoteRepo().getGit();
        remoteGit.reset().setRef(DEVELOP).setMode(ResetCommand.ResetType.HARD).call();
        remoteGit.checkout().setName(DEVELOP).call();
        remoteGit.getRepository().getDirectory().toPath().resolve(FETCH_FILE).toFile().createNewFile();
        remoteGit.add().addFilepattern(".").call();
        remoteGit.commit().setMessage(FETCH_FILE).call();
        Git localGit = localRepoMock.getGit();
        localGit.branchDelete().setBranchNames(DEVELOP).call();
        localGit.branchDelete().setBranchNames(REMOTE_DEVELOP).call();
        assertEquals(FETCH_FILE, remoteGit.log().setMaxCount(1).call().iterator().next().getFullMessage());
        Property.fetchReferenceBranch.setValue(Boolean.TRUE.toString());
        Property.referenceBranch.setValue(REMOTE_DEVELOP);
        getInstance().get();
        localGit.reset().setRef(REMOTE_DEVELOP).setMode(ResetCommand.ResetType.HARD).call();
        localGit.checkout().setName(REMOTE_DEVELOP).call();
        assertEquals(FETCH_FILE, localGit.log().setMaxCount(1).call().iterator().next().getFullMessage());
    }

    private boolean filterIgnored(Path p) {
        return !p.toString().contains("target") && !p.toString().contains(".iml");
    }

    protected abstract DifferentFiles getInstance() throws Exception;

}


text:
var isDebug = false; // Set In Debug Mode to See Nerdy Details on Events
var maxPositiveDegWidth = 12; // Max Number Of Degrees in The Positive Direction (Y)
var maxPositiveDegHeight = 9; // Max Number Of Degrees in The Positive Direction (X)

var dd = document.getElementById('data-analysis'); // Adds Data Analysis Object To
var cards = document.getElementsByClassName('card'); // Select All Elements with class "card"

// Set Events On All Elements In "cards"
for (var i = 0; i < cards.length; i++) {
  var currentCard = cards[i]; // Gets CurrentCard

  currentCard.onmousemove = function (evt) {
    var target = evt.target || evt.srcElement; // Gets Element Based On Event

    target.style.webkitTransition = ""; // Reset Animation so event is fluid
    calculateWidth(evt, target); // Sends To Horizontal Tilt Calculator
    calculateHeight(evt, target); // Sends To Vertical Tilt Calculator

    if (isDebug) {
      dd.innerHTML = target.style.webkitTransform; // If in Debug Mode Page Will Display Rotation Degrees
    }
  }

  currentCard.onmouseout = function (evt) {
    var target = evt.target || evt.srcElement; // Gets Element Based On Event
    target.style.webkitTransition = "-webkit-transform 1s"; // Set Animation on Reset
    target.style.webkitTransform = "rotateY(0deg)"; // Reset Level Of Tilt
  }
}

function calculateWidth(evt, obj) {
  var maxDeg = maxPositiveDegWidth * 2; // Mutliples Postive Degrees by 2 to get Full Range
  var percent = (evt.layerX / obj.offsetWidth); // Gets the position of mouse in percent relative to current card
  var degreeOfTilt = ((maxDeg * percent) - maxPositiveDegWidth); // Calculates Degree of Tilt based on Percentage and Max Degree. Then minus the default max degrees to shift y-axis to the middle of the card
  obj.style.webkitTransform = "rotateY(" + degreeOfTilt + "deg)"; // Sets Degree of Tilt on y-axis
}

function calculateHeight(evt, obj) {
  var maxDeg = maxPositiveDegHeight * 2; // Mutliples Postive Degrees by 2 to get Full Range
  var percent = (evt.layerY / obj.offsetHeight); // Gets the position of mouse in percent relative to current card
  var degreeOfTilt = (((maxDeg * percent) - maxPositiveDegWidth) * -1); // Calculates Degree of Tilt based on Percentage and Max Degree. Then minus the default max degrees to shift x-axis to the middle of the card
  obj.style.webkitTransform += " rotateX(" + degreeOfTilt + "deg)"; // Sets Degree of Tilt on x-axis
}


text:
from .essential import Essential

class Action(Essential):

    def __init__(self, app, id_):
        super().__init__(app, id_)
        self.running = True

    async def execute(self):
        self.logger.info('action_run')
        try:
            result = await self.run()
        except:
            self.logger.error('action_crash', exc_info=True)
            raise
        else:
            self.logger.info('action_end')
        finally:
            await self.cleanup()
        return result

    async def run(self):
        pass

    def stop(self):
        self.logger.info('action_stop')
        self.running = False

    async def cleanup(self):
        self.logger.info('action_cleanup')


text:
package com.capitalone.dashboard.collector;

import com.capitalone.dashboard.jenkins.*;
import com.capitalone.dashboard.model.quality.JunitXmlReport;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.mockito.Matchers.argThat;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.*;

public class HttpJenkinsClientTest {

    private RestTemplate mockRestTemplate;

    private HttpJenkinsClient testee;

    @Before
    public void setup() {
        mockRestTemplate = mock(RestTemplate.class);
        JenkinsSettings settings = new JenkinsSettings();
        settings.setJobDepth(3);
        testee = new HttpJenkinsClient(mockRestTemplate, settings);
    }

    @Test
    public void artifactsReturnedInJunitFormatOnlyForMatchingArtifacts() throws Exception {

        when(mockRestTemplate.exchange(argThat(is(equalTo(new URI("http://myBuildServer/myJob/lastSuccessfulBuild/artifact/mysubmodule/TEST-someSuite-test.xml")))), eq(HttpMethod.GET), eq(HttpEntity.EMPTY), eq(JunitXmlReport.class)))
                .thenReturn(ResponseEntity.ok().body(new JunitXmlReport()));

        JenkinsJob job = JenkinsJob.newBuilder()
                                   .jobName("myJob")
                                   .url("http://myBuildServer/myJob")
                                   .job(JenkinsJob.newBuilder().jobName("wibble").build())
                                   .lastSuccessfulBuild(JenkinsBuild.newBuilder()
                                       .artifact(Artifact.newBuilder()
                                           .fileName("TEST-someSuite-test.xml")
                                           .path("mysubmodule/TEST-someSuite-test.xml")
                                           .build())
                                       .artifact(Artifact.newBuilder()
                                           .fileName("this_does_not_match")
                                           .path("mysubmodule/this_does_not_match")
                                           .build())
                                       .build()).build();

        List<JunitXmlReport> xmlReports = testee.getLatestArtifacts(JunitXmlReport.class, job, Pattern.compile("TEST-.*-test\\.xml"));

        verify(mockRestTemplate).exchange(argThat(is(equalTo(new URI("http://myBuildServer/myJob/lastSuccessfulBuild/artifact/mysubmodule/TEST-someSuite-test.xml")))), eq(HttpMethod.GET), eq(HttpEntity.EMPTY), eq(JunitXmlReport.class));
        assertThat(xmlReports).size().isEqualTo(1);
    }

    @Test
    public void getJobsShouldReturnAListOfJobs() throws Exception {
        when(mockRestTemplate.exchange(eq(new URI("http://buildserver1/api/json?tree=jobs[name,url,lastSuccessfulBuild[timestamp,artifacts[*]],jobs[name,url,lastSuccessfulBuild[timestamp,artifacts[*]],jobs[name,url,lastSuccessfulBuild[timestamp,artifacts[*]]]]]")), eq(HttpMethod.GET), isNotNull(HttpEntity.class), eq(JobContainer.class)))
                .thenReturn(ResponseEntity.ok()
                    .body(JobContainer.newBuilder()
                        .job(JenkinsJob.newBuilder()
                            .jobName("job1")
                            .url("http://buildserver1/job1")
                            .build())
                        .build()));
        when(mockRestTemplate.exchange(eq(new URI("http://buildserver2/api/json?tree=jobs[name,url,lastSuccessfulBuild[timestamp,artifacts[*]],jobs[name,url,lastSuccessfulBuild[timestamp,artifacts[*]],jobs[name,url,lastSuccessfulBuild[timestamp,artifacts[*]]]]]")), eq(HttpMethod.GET), isNotNull(HttpEntity.class), eq(JobContainer.class)))
                .thenReturn(ResponseEntity.ok()
                    .body(JobContainer.newBuilder()
                        .job(JenkinsJob.newBuilder()
                            .jobName("job1")
                            .url("http://buildserver2/job1")
                            .build())
                        .build()));

        final List<JenkinsJob> jobs = testee.getJobs(Arrays.asList("http://buildserver1", "http://buildserver2"));

        verify(mockRestTemplate).exchange(eq(new URI("http://buildserver1/api/json?tree=jobs[name,url,lastSuccessfulBuild[timestamp,artifacts[*]],jobs[name,url,lastSuccessfulBuild[timestamp,artifacts[*]],jobs[name,url,lastSuccessfulBuild[timestamp,artifacts[*]]]]]")), eq(HttpMethod.GET), eq(HttpEntity.EMPTY), eq(JobContainer.class));
        verify(mockRestTemplate).exchange(eq(new URI("http://buildserver2/api/json?tree=jobs[name,url,lastSuccessfulBuild[timestamp,artifacts[*]],jobs[name,url,lastSuccessfulBuild[timestamp,artifacts[*]],jobs[name,url,lastSuccessfulBuild[timestamp,artifacts[*]]]]]")), eq(HttpMethod.GET), eq(HttpEntity.EMPTY), eq(JobContainer.class));
        assertThat(jobs).isNotNull();
        assertThat(jobs).hasSize(2);
        assertThat(jobs).extracting("url")
                        .containsExactlyInAnyOrder("http://buildserver1/job1", "http://buildserver2/job1");
    }

    @Test
    public void createsSecurityHeaderIfSetForJobs() throws Exception {
        JenkinsSettings settings = new JenkinsSettings();
        settings.setJobDepth(1);
        settings.setApiKey("api_Key");
        settings.setUsername("username");
        HttpJenkinsClient localTestee = new HttpJenkinsClient(mockRestTemplate, settings);

        when(mockRestTemplate.exchange(eq(new URI("http://buildserver1/api/json?tree=jobs[name,url,lastSuccessfulBuild[timestamp,artifacts[*]]]")), eq(HttpMethod.GET), any(HttpEntity.class), eq(JobContainer.class)))
                .thenReturn(ResponseEntity.ok()
                    .body(JobContainer.newBuilder()
                        .job(JenkinsJob.newBuilder()
                            .jobName("job1")
                            .url("http://buildserver1/job1")
                            .build())
                        .build()));

        //test
        localTestee.getJobs(Arrays.asList("http://buildserver1"));

        //verify
        ArgumentCaptor<HttpEntity> entityCaptor = ArgumentCaptor.forClass(HttpEntity.class);
        verify(mockRestTemplate).exchange(eq(new URI("http://buildserver1/api/json?tree=jobs[name,url,lastSuccessfulBuild[timestamp,artifacts[*]]]")), eq(HttpMethod.GET), entityCaptor
                .capture(), eq(JobContainer.class));

        HttpEntity capturedEntity = entityCaptor.getValue();
        byte[] encodedAuth = org.apache.commons.codec.binary.Base64.encodeBase64("username:api_Key".getBytes(StandardCharsets.US_ASCII));
        String authHeader = "Basic " + new String(encodedAuth);
        assertThat(capturedEntity.getHeaders().get(HttpHeaders.AUTHORIZATION).get(0)).isEqualTo(authHeader);
    }

    @Test
    public void createsSecurityHeaderIfSetForArtifacts() throws Exception {
        JenkinsSettings settings = new JenkinsSettings();
        settings.setApiKey("apiKey");
        settings.setUsername("name");
        settings.setJobDepth(1);
        HttpJenkinsClient localTestee = new HttpJenkinsClient(mockRestTemplate, settings);

        when(mockRestTemplate.exchange(argThat(is(equalTo(new URI("http://myBuildServer/myJob/lastSuccessfulBuild/artifact/mysubmodule/TEST-someSuite-test.xml")))), eq(HttpMethod.GET), any(HttpEntity.class), eq(JobContainer.class)))
                .thenReturn(ResponseEntity.ok().body(JobContainer.newBuilder().build()));

        //test
        final JenkinsJob jenkinsJob = JenkinsJob.newBuilder()
                                                .url("http://myBuildServer/myJob")
                                                .lastSuccessfulBuild(JenkinsBuild.newBuilder()
                                                    .artifact(Artifact.newBuilder()
                                                        .fileName("TEST-someSuite-test.xml")
                                                        .path("mysubmodule/TEST-someSuite-test.xml")
                                                        .build())
                                                    .build())
                                                .build();
        localTestee.getLatestArtifacts(JobContainer.class, jenkinsJob, Pattern.compile("TEST-.*-test\\.xml"));

        //verify
        ArgumentCaptor<HttpEntity> entityCaptor = ArgumentCaptor.forClass(HttpEntity.class);
        verify(mockRestTemplate).exchange(eq(new URI("http://myBuildServer/myJob/lastSuccessfulBuild/artifact/mysubmodule/TEST-someSuite-test.xml")), eq(HttpMethod.GET), entityCaptor
                .capture(), eq(JobContainer.class));

        HttpEntity capturedEntity = entityCaptor.getValue();
        byte[] encodedAuth = org.apache.commons.codec.binary.Base64.encodeBase64("name:apiKey".getBytes(StandardCharsets.US_ASCII));
        String authHeader = "Basic " + new String(encodedAuth);
        assertThat(capturedEntity.getHeaders().get(HttpHeaders.AUTHORIZATION).get(0)).isEqualTo(authHeader);
    }

    @Test
    public void swallowsMalformedURLsInArtefacts() throws Exception {
        JenkinsSettings settings = new JenkinsSettings();
        settings.setApiKey("apiKey");
        settings.setUsername("name");
        settings.setJobDepth(1);
        HttpJenkinsClient localTestee = new HttpJenkinsClient(mockRestTemplate, settings);

        //test
        final JenkinsJob jenkinsJob = JenkinsJob.newBuilder()
            .url("://myBuildServer/myJob")
            .lastSuccessfulBuild(JenkinsBuild.newBuilder()
                .artifact(Artifact.newBuilder()
                    .fileName("TEST-someSuite-test.xml")
                    .path("mysubmodule/TEST-someSuite-test.xml")
                    .build())
                .build())
            .build();
        localTestee.getLatestArtifacts(JobContainer.class, jenkinsJob, Pattern.compile("TEST-.*-test\\.xml"));

    }

    @Test
    public void swallowsMalformedURLsInJobs() throws Exception {
        this.testee.getJobs(Arrays.asList("://buildserver1"));

    }

}


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.camunda.bpm.engine.test.api.runtime.migration.util;

import org.camunda.bpm.engine.ProcessEngine;
import org.camunda.bpm.engine.test.api.runtime.migration.MigrationTestRule;
import org.camunda.bpm.engine.test.api.runtime.migration.ModifiableBpmnModelInstance;
import org.camunda.bpm.model.bpmn.BpmnModelInstance;

/**
 * @author Thorben Lindhauer
 *
 */
public class ConditionalEventFactory implements BpmnEventFactory {

  protected static final String VAR_CONDITION = "${any=='any'}";

  @Override
  public MigratingBpmnEventTrigger addBoundaryEvent(ProcessEngine engine, BpmnModelInstance modelInstance, String activityId, String boundaryEventId) {
    ModifiableBpmnModelInstance.wrap(modelInstance)
      .activityBuilder(activityId)
      .boundaryEvent(boundaryEventId)
        .condition(VAR_CONDITION)
      .done();

    ConditionalEventTrigger trigger = new ConditionalEventTrigger();
    trigger.engine = engine;
    trigger.variableName = "any";
    trigger.variableValue = "any";
    trigger.activityId = boundaryEventId;

    return trigger;
  }

  @Override
  public MigratingBpmnEventTrigger addEventSubProcess(ProcessEngine engine, BpmnModelInstance modelInstance, String parentId, String subProcessId, String startEventId) {
    ModifiableBpmnModelInstance.wrap(modelInstance)
      .addSubProcessTo(parentId)
      .id(subProcessId)
      .triggerByEvent()
      .embeddedSubProcess()
        .startEvent(startEventId)
        .condition(VAR_CONDITION)
      .subProcessDone()
      .done();

    ConditionalEventTrigger trigger = new ConditionalEventTrigger();
    trigger.engine = engine;
    trigger.variableName = "any";
    trigger.variableValue = "any";
    trigger.activityId = startEventId;

    return trigger;
  }

  protected static class ConditionalEventTrigger implements MigratingBpmnEventTrigger {

    protected ProcessEngine engine;
    protected String variableName;
    protected Object variableValue;
    protected String activityId;

    @Override
    public void trigger(String processInstanceId) {
      engine.getRuntimeService().setVariable(processInstanceId, variableName, variableValue);
    }

    @Override
    public void assertEventTriggerMigrated(MigrationTestRule migrationContext, String targetActivityId) {
      migrationContext.assertEventSubscriptionMigrated(activityId, targetActivityId, null);
    }

    @Override
    public MigratingBpmnEventTrigger inContextOf(String newActivityId) {
      ConditionalEventTrigger newTrigger = new ConditionalEventTrigger();
      newTrigger.activityId = newActivityId;
      newTrigger.engine = engine;
      newTrigger.variableName = variableName;
      newTrigger.variableValue = variableValue;
      return newTrigger;
    }

  }

}


text:
package com.hazelcast.test;

import com.hazelcast.logging.Logger;
import com.hazelcast.logging.LoggerFactory;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runner.RunWith;
import org.junit.runners.model.Statement;

import java.lang.reflect.Field;

/**
 * Fully isolates the shared global logging state for a test. Also provides
 * utilities which are useful while testing logging related things.
 */
public class IsolatedLoggingRule implements TestRule {

    public static final String LOGGING_TYPE_PROPERTY = "hazelcast.logging.type";
    public static final String LOGGING_CLASS_PROPERTY = "hazelcast.logging.class";

    public static final String LOGGING_TYPE_LOG4J = "log4j";
    public static final String LOGGING_TYPE_LOG4J2 = "log4j2";
    public static final String LOGGING_TYPE_SLF4J = "slf4j";
    public static final String LOGGING_TYPE_JDK = "jdk";
    public static final String LOGGING_TYPE_NONE = "none";

    private final Field loggerFactoryField;
    private final Field loggerFactoryClassOrTypeField;
    private final Field loggerFactoryLockField;

    public IsolatedLoggingRule() {
        loggerFactoryField = getLoggerField("loggerFactory");
        loggerFactoryClassOrTypeField = getLoggerField("loggerFactoryClassOrType");
        loggerFactoryLockField = getLoggerField("FACTORY_LOCK");
    }

    @Override
    public Statement apply(final Statement base, final Description description) {
        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                ensureSerialRunner(description);

                String oldLoggingType = System.getProperty(LOGGING_TYPE_PROPERTY);
                String oldLoggingClass = System.getProperty(LOGGING_CLASS_PROPERTY);

                System.clearProperty(LOGGING_TYPE_PROPERTY);
                System.clearProperty(LOGGING_CLASS_PROPERTY);

                LoggerFactory originalLoggerFactory = (LoggerFactory) loggerFactoryField.get(null);
                String originalLoggerFactoryClassOrType = (String) loggerFactoryClassOrTypeField.get(null);

                loggerFactoryField.set(null, null);
                loggerFactoryClassOrTypeField.set(null, null);

                try {
                    base.evaluate();
                } finally {
                    setOrClearProperty(LOGGING_TYPE_PROPERTY, oldLoggingType);
                    setOrClearProperty(LOGGING_CLASS_PROPERTY, oldLoggingClass);

                    loggerFactoryField.set(null, originalLoggerFactory);
                    loggerFactoryClassOrTypeField.set(null, originalLoggerFactoryClassOrType);
                }
            }
        };
    }

    public void setLoggingType(String type) {
        setOrClearProperty(LOGGING_TYPE_PROPERTY, type);
    }

    public void setLoggingClass(Class<? extends LoggerFactory> clazz) {
        setOrClearProperty(LOGGING_CLASS_PROPERTY, clazz == null ? null : clazz.getName());
    }

    public LoggerFactory getLoggerFactory() {
        try {
            return (LoggerFactory) loggerFactoryField.get(null);
        } catch (IllegalAccessException e) {
            throw new IllegalStateException(e);
        }
    }

    public void setLoggerFactory(LoggerFactory factory) {
        try {
            loggerFactoryField.set(null, factory);
        } catch (IllegalAccessException e) {
            throw new IllegalStateException(e);
        }
    }

    public Object getLoggerFactoryLock() {
        try {
            return loggerFactoryLockField.get(null);
        } catch (IllegalAccessException e) {
            throw new IllegalStateException(e);
        }
    }

    private void setOrClearProperty(String propertyName, String value) {
        if (value == null) {
            System.clearProperty(propertyName);
        } else {
            System.setProperty(propertyName, value);
        }
    }

    private Field getLoggerField(String name) {
        Field field;
        try {
            field = Logger.class.getDeclaredField(name);
        } catch (NoSuchFieldException e) {
            throw new IllegalStateException(name + " field not found");
        }
        field.setAccessible(true);
        return field;
    }

    private void ensureSerialRunner(Description description) {
        RunWith runWithAnnotation = description.getTestClass().getAnnotation(RunWith.class);
        Class runnerClass = runWithAnnotation == null ? null : runWithAnnotation.value();
        if (runnerClass == null || !HazelcastSerialClassRunner.class.isAssignableFrom(runnerClass)) {
            throw new IllegalStateException("Isolated logging may be achieved only when running a test using a serial runner. Use"
                    + " HazelcastSerialClassRunner or its subclass to run this test.");
        }
    }

}


text:
@class NSCalendar;
@class NSDate;
@class NSDateComponents;
@class NSError;
@class NSString;
@class NSTimeZone;

HOMEKIT_EXPORT_CLASS
@interface HMTimerTrigger : HMTrigger
- (instancetype)initWithName:(NSString*)name
                    fireDate:(NSDate*)fireDate
                    timeZone:(NSTimeZone*)timeZone
                  recurrence:(NSDateComponents*)recurrence
          recurrenceCalendar:(NSCalendar*)recurrenceCalendar STUB_METHOD;
@property (readonly, copy, nonatomic) NSDate* fireDate STUB_PROPERTY;
- (void)updateFireDate:(NSDate*)fireDate completionHandler:(void (^)(NSError*))completion STUB_METHOD;
@property (readonly, copy, nonatomic) NSDateComponents* recurrence STUB_PROPERTY;
- (void)updateRecurrence:(NSDateComponents*)recurrence completionHandler:(void (^)(NSError*))completion STUB_METHOD;
@property (readonly, copy, nonatomic) NSCalendar* recurrenceCalendar STUB_PROPERTY;
@property (readonly, copy, nonatomic) NSTimeZone* timeZone STUB_PROPERTY;
- (void)updateTimeZone:(NSTimeZone*)timeZone completionHandler:(void (^)(NSError*))completion STUB_METHOD;
@end