text:
package ch.iserver.ace.collaboration.jupiter.server.document;

public class GapTextStore implements TextStore {

	private int highWatermark;

	private int lowWatermark;

	private int gapStart = -1;

	private int gapEnd = -1;

	private char[] content = new char[0];

	public GapTextStore() {
		this(30, 200);
	}

	public GapTextStore(int lowWatermark, int highWatermark) {
		if (!(lowWatermark < highWatermark)) {
			throw new IllegalArgumentException("lowWatermark must be smaller than highWatermark");
		}
		this.lowWatermark = lowWatermark;
		this.highWatermark = highWatermark;
	}

	/**
	 * Adjusts the gap so that is at the right offset and capable of handling
	 * the addition of a specified number of characters without having to be
	 * shifted. The sizeHint represents the range that will be
	 * filled afterwards. If the gap is already at the right offset, it must
	 * only be resized if it will be no longer between the low and high
	 * watermark. However, on delete (sizeHint < 0) at the edges of the gap,
	 * the gap is only enlarged.
	 *
	 * @param offset
	 *            the offset at which the change happens
	 * @param sizeHint
	 *            the number of character which will be inserted
	 */
	private void adjustGap(int offset, int sizeHint) {
		if (offset == gapStart) {
			int size = (gapEnd - gapStart) - sizeHint;
			if (lowWatermark <= size && size <= highWatermark)
				return;
		}

		moveAndResizeGap(offset, sizeHint);
	}

	/**
	 * Moves the gap to the specified offset and adjust its size to the
	 * anticipated change size. The given size represents the expected range of
	 * the gap that will be filled after the gap has been moved. Thus the gap is
	 * resized to actual size + the specified size and moved to the given
	 * offset.
	 *
	 * @param offset
	 *            the offset where the gap is moved to
	 * @param size
	 *            the anticipated size of the change
	 */
	private void moveAndResizeGap(int offset, int size) {
		char[] newContent = null;
		int oldSize = gapEnd - gapStart;
		int newSize = highWatermark + size;

		if (newSize < 0) {
			if (oldSize > 0) {
				newContent = new char[content.length - oldSize];
				System.arraycopy(content, 0, newContent, 0, gapStart);
				System.arraycopy(content, gapEnd, newContent, gapStart, newContent.length - gapStart);
				content = newContent;
			}
			gapStart = gapEnd = offset;
			return;
		}

		newContent = new char[content.length + (newSize - oldSize)];

		int newGapStart = offset;
		int newGapEnd = newGapStart + newSize;

		if (oldSize == 0) {
			System.arraycopy(content, 0, newContent, 0, newGapStart);
			System.arraycopy(content, newGapStart, newContent, newGapEnd, newContent.length - newGapEnd);
		} else if (newGapStart < gapStart) {
			int delta = gapStart - newGapStart;
			System.arraycopy(content, 0, newContent, 0, newGapStart);
			System.arraycopy(content, newGapStart, newContent, newGapEnd, delta);
			System.arraycopy(content, gapEnd, newContent, newGapEnd + delta, content.length - gapEnd);
		} else {
			int delta = newGapStart - gapStart;
			System.arraycopy(content, 0, newContent, 0, gapStart);
			System.arraycopy(content, gapEnd, newContent, gapStart, delta);
			System.arraycopy(content, gapEnd + delta, newContent, newGapEnd, newContent.length - newGapEnd);
		}

		content = newContent;
		gapStart = newGapStart;
		gapEnd = newGapEnd;
	}

	/*
	 * @see ch.iserver.ace.text.ITextStore#getText(int, int)
	 */
	public String getText(int offset, int length) {
		int end = offset + length;

		if (content == null)
			return ""; //$NON-NLS-1$

		if (end <= gapStart)
			return new String(content, offset, length);

		if (gapStart < offset) {
			int gapLength = gapEnd - gapStart;
			return new String(content, offset + gapLength, length);
		}

		StringBuffer buf = new StringBuffer();
		buf.append(content, offset, gapStart - offset);
		buf.append(content, gapEnd, end - gapStart);
		return buf.toString();
	}

	/*
	 * @see org.eclipse.jface.text.ITextStore#getLength()
	 */
	public int getLength() {
		int length = gapEnd - gapStart;
		return (content.length - length);
	}

	/*
	 * @see org.eclipse.jface.text.ITextStore#replace(int, int,
	 *      java.lang.String)
	 */
	public void replace(int offset, int length, String text) {
		int textLength = (text == null ? 0 : text.length());

		// handle delete at the edges of the gap
		if (textLength == 0) {
			if (offset <= gapStart && offset + length >= gapStart
					&& gapStart > -1 && gapEnd > -1) {
				length -= gapStart - offset;
				gapStart = offset;
				gapEnd += length;
				return;
			}
		}

		// move gap
		adjustGap(offset + length, textLength - length);

		// overwrite
		int min = Math.min(textLength, length);
		for (int i = offset, j = 0; i < offset + min; i++, j++) {
			content[i] = text.charAt(j);
		}

		if (length > textLength) {
			// enlarge the gap
			gapStart -= (length - textLength);
		} else if (textLength > length) {
			// shrink gap
			gapStart += (textLength - length);
			for (int i = length; i < textLength; i++)
				content[offset + i] = text.charAt(i);
		}
	}

}


text:
import { IVirtualBackground } from './reducer';

export interface IVirtualBackgroundOptions extends IVirtualBackground {
    enabled: boolean;
    url?: string;
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.camel.component.jms;

import javax.jms.ConnectionFactory;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;
import static org.apache.camel.component.jms.JmsComponent.jmsComponentAutoAcknowledge;

/**
 * @version
 */
public class JmsComponentTest extends CamelTestSupport {

    protected String componentName = "activemq123";
    protected JmsEndpoint endpoint;

    @Test
    public void testComponentOptions() throws Exception {
        String reply = template.requestBody("activemq123:queue:hello?requestTimeout=5000", "Hello World", String.class);
        assertEquals("Bye World", reply);

        assertEquals(true, endpoint.isAcceptMessagesWhileStopping());
        assertEquals(true, endpoint.isAlwaysCopyMessage());
        assertEquals(1, endpoint.getAcknowledgementMode());
        assertEquals(true, endpoint.isAutoStartup());
        assertEquals(1, endpoint.getCacheLevel());
        assertEquals("foo", endpoint.getClientId());
        assertEquals(2, endpoint.getConcurrentConsumers());
        assertEquals(true, endpoint.isDeliveryPersistent());
        assertEquals(true, endpoint.isExplicitQosEnabled());
        assertEquals(20, endpoint.getIdleTaskExecutionLimit());
        assertEquals(5, endpoint.getMaxConcurrentConsumers());
        assertEquals(90, endpoint.getMaxMessagesPerTask());
        assertEquals(3, endpoint.getPriority());
        assertEquals(5000, endpoint.getReceiveTimeout());
        assertEquals(9000, endpoint.getRecoveryInterval());
        assertEquals(3000, endpoint.getTimeToLive());
        assertEquals(true, endpoint.isTransacted());
        assertEquals(15000, endpoint.getTransactionTimeout());
    }

    protected CamelContext createCamelContext() throws Exception {
        CamelContext camelContext = super.createCamelContext();

        ConnectionFactory connectionFactory = CamelJmsTestHelper.createConnectionFactory();
        JmsComponent comp = jmsComponentAutoAcknowledge(connectionFactory);

        comp.setAcceptMessagesWhileStopping(true);
        comp.setAlwaysCopyMessage(true);
        comp.setAcknowledgementMode(1);
        comp.setAutoStartup(true);
        comp.setCacheLevel(1);
        comp.setClientId("foo");
        comp.setConcurrentConsumers(2);
        comp.setDeliveryPersistent(true);
        comp.setExplicitQosEnabled(true);
        comp.setIdleTaskExecutionLimit(20);
        comp.setMaxConcurrentConsumers(5);
        comp.setMaxMessagesPerTask(90);
        comp.setPriority(3);
        comp.setReceiveTimeout(5000);
        comp.setRecoveryInterval(9000);
        comp.setTimeToLive(3000);
        comp.setTransacted(true);
        comp.setTransactionTimeout(15000);

        camelContext.addComponent(componentName, comp);

        endpoint = (JmsEndpoint) comp.createEndpoint("queue:hello");

        return camelContext;
    }

    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            public void configure() throws Exception {
                from(endpoint).transform(constant("Bye World"));
            }
        };
    }
}


text:
package filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.bean.User;
import utils.MyUtils;

/**
 * Servlet Filter implementation class UserFilter
 */
@WebFilter("/AdminFilter")
public class AdminFilter implements Filter {

    /**
     * Default constructor.
     */
    public AdminFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;

		User user = MyUtils.getSessionLogin(httpRequest);
		if (user == null || !user.getRole()) {
			httpResponse.sendRedirect(httpRequest.getContextPath() + "/login");
			return;
		}

		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}


text:
<!DOCTYPE html>
<meta charset="utf-8">
<title>CSS Grid Layout Test: 'float' has no effect on grid items</title>
<link rel="author" title="Manuel Rego Casasnovas" href="mailto:rego@igalia.com">
<link rel="reviewer" title="Gérard Talbot" href="http://www.gtalbot.org/BrowserBugsSection/css21testsuite/">
<link rel="help" href="http://www.w3.org/TR/css-grid-1/#grid-containers" title="3.1 Establishing Grid Containers">
<link rel="help" href="http://www.w3.org/TR/CSS21/visuren.html#float-position" title="9.5.1 Positioning the float">
<link rel="match" href="../../reference/ref-filled-green-100px-square.xht">

Test passes if there is a filled green square and no red.


text:
// Copyright (c) 2020-2021 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <banman.h>
#include <chainparams.h>
#include <consensus/consensus.h>
#include <net.h>
#include <net_processing.h>
#include <protocol.h>
#include <scheduler.h>
#include <script/script.h>
#include <streams.h>
#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
#include <test/fuzz/util.h>
#include <test/util/mining.h>
#include <test/util/net.h>
#include <test/util/setup_common.h>
#include <test/util/validation.h>
#include <txorphanage.h>
#include <util/memory.h>
#include <validationinterface.h>
#include <version.h>

#include <atomic>
#include <cassert>
#include <chrono>
#include <cstdint>
#include <iosfwd>
#include <iostream>
#include <memory>
#include <string>

namespace {
const TestingSetup* g_setup;
} // namespace

size_t& GetNumMsgTypes()
{
    static size_t g_num_msg_types{0};
    return g_num_msg_types;
}
#define FUZZ_TARGET_MSG(msg_type)                                            \
    struct msg_type##_Count_Before_Main {                                    \
        msg_type##_Count_Before_Main()                                       \
        {                                                                    \
            ++GetNumMsgTypes();                                              \
        }                                                                    \
    } const static g_##msg_type##_count_before_main;                         \
    FUZZ_TARGET_INIT(process_message_##msg_type, initialize_process_message) \
    {                                                                        \
        fuzz_target(buffer, #msg_type);                                      \
    }

void initialize_process_message()
{
    Assert(GetNumMsgTypes() == getAllNetMessageTypes().size()); // If this fails, add or remove the message type below

    static const auto testing_setup = MakeNoLogFileContext<const TestingSetup>();
    g_setup = testing_setup.get();
    for (int i = 0; i < 2 * COINBASE_MATURITY; i++) {
        MineBlock(g_setup->m_node, CScript() << OP_TRUE);
    }
    SyncWithValidationInterfaceQueue();
}

void fuzz_target(FuzzBufferType buffer, const std::string& LIMIT_TO_MESSAGE_TYPE)
{
    FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());

    ConnmanTestMsg& connman = *(ConnmanTestMsg*)g_setup->m_node.connman.get();
    TestChainState& chainstate = *(TestChainState*)&g_setup->m_node.chainman->ActiveChainstate();
    SetMockTime(1610000000); // any time to successfully reset ibd
    chainstate.ResetIbd();

    const std::string random_message_type{fuzzed_data_provider.ConsumeBytesAsString(CMessageHeader::COMMAND_SIZE).c_str()};
    if (!LIMIT_TO_MESSAGE_TYPE.empty() && random_message_type != LIMIT_TO_MESSAGE_TYPE) {
        return;
    }
    CNode& p2p_node = *ConsumeNodeAsUniquePtr(fuzzed_data_provider).release();

    const bool successfully_connected{fuzzed_data_provider.ConsumeBool()};
    p2p_node.fSuccessfullyConnected = successfully_connected;
    connman.AddTestNode(p2p_node);
    g_setup->m_node.peerman->InitializeNode(&p2p_node);
    FillNode(fuzzed_data_provider, p2p_node, /* init_version */ successfully_connected);

    const auto mock_time = ConsumeTime(fuzzed_data_provider);
    SetMockTime(mock_time);

    // fuzzed_data_provider is fully consumed after this call, don't use it
    CDataStream random_bytes_data_stream{fuzzed_data_provider.ConsumeRemainingBytes<unsigned char>(), SER_NETWORK, PROTOCOL_VERSION};
    try {
        g_setup->m_node.peerman->ProcessMessage(p2p_node, random_message_type, random_bytes_data_stream,
                                                GetTime<std::chrono::microseconds>(), std::atomic<bool>{false});
    } catch (const std::ios_base::failure&) {
    }
    {
        LOCK(p2p_node.cs_sendProcessing);
        g_setup->m_node.peerman->SendMessages(&p2p_node);
    }
    SyncWithValidationInterfaceQueue();
    LOCK2(::cs_main, g_cs_orphans); // See init.cpp for rationale for implicit locking order requirement
    g_setup->m_node.connman->StopNodes();
}

FUZZ_TARGET_INIT(process_message, initialize_process_message) { fuzz_target(buffer, ""); }
FUZZ_TARGET_MSG(addr);
FUZZ_TARGET_MSG(addrv2);
FUZZ_TARGET_MSG(block);
FUZZ_TARGET_MSG(blocktxn);
FUZZ_TARGET_MSG(cfcheckpt);
FUZZ_TARGET_MSG(cfheaders);
FUZZ_TARGET_MSG(cfilter);
FUZZ_TARGET_MSG(cmpctblock);
FUZZ_TARGET_MSG(feefilter);
FUZZ_TARGET_MSG(filteradd);
FUZZ_TARGET_MSG(filterclear);
FUZZ_TARGET_MSG(filterload);
FUZZ_TARGET_MSG(getaddr);
FUZZ_TARGET_MSG(getblocks);
FUZZ_TARGET_MSG(getblocktxn);
FUZZ_TARGET_MSG(getcfcheckpt);
FUZZ_TARGET_MSG(getcfheaders);
FUZZ_TARGET_MSG(getcfilters);
FUZZ_TARGET_MSG(getdata);
FUZZ_TARGET_MSG(getheaders);
FUZZ_TARGET_MSG(headers);
FUZZ_TARGET_MSG(inv);
FUZZ_TARGET_MSG(mempool);
FUZZ_TARGET_MSG(merkleblock);
FUZZ_TARGET_MSG(notfound);
FUZZ_TARGET_MSG(ping);
FUZZ_TARGET_MSG(pong);
FUZZ_TARGET_MSG(sendaddrv2);
FUZZ_TARGET_MSG(sendcmpct);
FUZZ_TARGET_MSG(sendheaders);
FUZZ_TARGET_MSG(tx);
FUZZ_TARGET_MSG(verack);
FUZZ_TARGET_MSG(version);
FUZZ_TARGET_MSG(wtxidrelay);


text:
FROM nginx:alpine

RUN apk add bash --no-cache
ADD entrypoint.sh /entrypoint.sh
ADD dist /usr/share/nginx/html
ENTRYPOINT [ "/bin/bash", "/entrypoint.sh" ]


text:
<?php

/* Magic Methods are methods built into PHP which aids in class usage. These methods always use TWO underscores like so "__".
The most popular are: */

// __contruct(): the constructor of a class.
// __set($property, $value): The "__set()" method will be called when setting a member variable of a class.
// __get(): The "__get()" method will be called when getting a member variable of a class.
// __call($funName, $arguments): The "__call()" method will be called when an undefined or inaccessible method is called.
// __toString(): The "__toString()" method will be called when using echo method to print an object directly.

// Find more here with simple examples: https://www.tutorialdocs.com/article/16-php-magic-methods.html

// Example

class Collection implements
  Countable,
  JsonSerializable
{
  // Default properties
  protected $items = [];

  // Magic method
  public function __set($key)
  {
    $this->set($key, $value);
  }

  // Magic method
  public function __get($value)
  {
    return $this->get($value);
  }

  // Magic method. "__callStatic" is bassically the same for static methods
  public function __call($func, $args)
  {
    return $func . ' has been called with arguments' . implode(', ', $args);
  }

  // Magic method
  public function __toString()
  {
    return $this->jsonSerialize();
  }

  public function add($value)
  {
    $this->items[] = $value;
  }

  public function set($key, $value)
  {
    $this->items[$key] = $value;
  }

  public function get($key)
  {
    return array_key_exists($key, $this->items) ? $this->items[$key] : null;
  }

  // interface method
  public function jsonSerialize()
  {
    return json_encode($this->items);
  }

  // interface method
  public function count()
  {
    return count($this->items);
  }

  public function all()
  {
    return $this->items;
  }

}

// Instantiate class
$c = new Collection();

// Normal methods
$c->add('foo');
$c->add('bar');

// __set(): Setting a property, but is overwritten by the "__set" magic method, and thereby doing what we have defined instead.
$c->john = 'doe';
// will return the array with "john => doe"
print_r( $c->all() );

// __get(): Will return "doe"
echo $c->get('john');
// This with "__get" magic method will also work
echo $c->john

 // __call(): Will try to call function if not defined
 echo $c->hello('world');

 // __toString(): Will return an output of the class if defined
echo $c;


text:
<?php
require 'PHPMailerAutoload.php';

/**
 * Class die voor mail functionaliteit zorgt.
 *
 * @package CheckJeStress
 */
class Mailer {

  /**
   * Constructs the object
   *
   * @param array $config het deel van het configuratiebestand dat met de SMTP
   * server te maken heeft
   */
  function __construct($config) {
    $this->config = $config;
    $this->mail = new PHPMailer;
    $this->mail->SMTPDebug = 0; // Enable verbose debug output
  }

  /**
   * De PHPMailer instance van deze class
   */
  var $mail;

  /**
   * De array met gegevens betreffende de SMTP server
   */
  private $config;

  /**
   * Stuurt een mail.
   *
   * @param array $recipients de e-mailadresse van de personen naar wie de mail
   * gestuurd moet worden
   * @param string $subject het onderwerp van de e-mail
   * @param string $message het bericht zelf
   */
  function sendMail($recipients, $subject, $html_message, $non_html_message) {
    $this->configure();

    foreach ($recipients as $recipient) {
      $this->mail->addAddress($recipient);
      $this->mail->addReplyTo($recipient);
    }

    //$mail->addCC('cc@example.com');
    //$mail->addBCC('bcc@example.com');
    //$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
    //$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

    $this->mail->isHTML(true);
    $this->mail->Subject = $subject;
    $this->mail->Body = $html_message; /* Body containing HTML */
    $this->mail->AltBody = $non_html_message;

    if(!$this->mail->send()) {
      throw new MailException('Message could not be sent. Mailer Error: ' . $this->mail->ErrorInfo);
    }
  }

  /**
   * Haalt waarden uit de configuratie voor gebruik bij het verbinden met de
   * mailserver.
   */
  private function configure() {
    $this->mail->isSMTP();
    $this->mail->Host = $config['host'];
    $this->mail->Port = $config['port'];
    /* Enable TLS encryption, `ssl` also accepted */
    $this->mail->SMTPSecure = $config['secure'];
    $this->mail->SMTPAuth = $config['auth'];
    $this->mail->Username = $config['username'];
    $this->mail->Password = $config['password'];

    $this->mail->setFrom($config['admin-email'], 'CheckJeStress');
  }

}

/**
 * Thrown if een mail niet verstuurd kon worden.
 *
 * @package CheckJeStress
 */
class MailException extends Exception {
}


text:
package com.tomgibara.hashing;

import java.math.BigInteger;

final class SizedIntHasher<T> extends SizedHasher<T> {

	SizedIntHasher(Hashing<T> hashing, HashSize newSize) {
		super(hashing, newSize);
	}

	@Override
	public int intHashValue(T value) {
		int h = hashing.intHashValue(value);
		return isSmaller ? newSize.mapInt(h) : h;
	}

	@Override
	int sizedIntValue(HashCode code) {
		int h = code.intValue();
		return isSmaller ? newSize.mapInt(h) : h;
	}

	@Override
	long sizedLongValue(HashCode code) {
		long h = code.longValue();
		return isSmaller ? newSize.mapLong(h) : h;
	}

	@Override
	BigInteger sizedBigValue(HashCode code) {
		BigInteger h = code.bigValue();
		return isSmaller ? newSize.mapBig(h) : h;
	}

	@Override
	byte[] sizedBytesValue(HashCode code) {
		byte[] h = code.bytesValue();
		return isSmaller ? newSize.mapBytes(h) : h;
	}

}


text:
from msrest.serialization import Model

class DeploymentLb(Model):
    """
    Deployment operation parameters.

    Variables are only populated by the server, and will be ignored when
    sending a request.

    :ivar uri: URI referencing the template. Default value:
     "https://azuresdkci.blob.core.windows.net/templatehost/CreateLb_2016-07-19/azuredeploy.json"
     .
    :vartype uri: str
    :param content_version: If included it must match the ContentVersion in
     the template.
    :type content_version: str
    :ivar _artifacts_location: Container URI of of the template. Default
     value:
     "https://azuresdkci.blob.core.windows.net/templatehost/CreateLb_2016-07-19"
     .
    :vartype _artifacts_location: str
    :param backend_pool_name: Name of load balancer backend pool.
    :type backend_pool_name: str
    :param dns_name_type: Associate VMs with a public IP address to a DNS
     name. Possible values include: 'none', 'new'. Default value: "none" .
    :type dns_name_type: str or :class:`dnsNameType
     <lbcreationclient.models.dnsNameType>`
    :param frontend_ip_name: Name of the frontend IP configuration. Default
     value: "LoadBalancerFrontEnd" .
    :type frontend_ip_name: str
    :param load_balancer_name: Name for load balancer.
    :type load_balancer_name: str
    :param location: Location for load balancer resource.
    :type location: str
    :param private_ip_address: Static private IP address to use.
    :type private_ip_address: str
    :param private_ip_address_allocation: Private IP address allocation
     method. Possible values include: 'dynamic', 'static'. Default value:
     "dynamic" .
    :type private_ip_address_allocation: str or
     :class:`privateIpAddressAllocation
     <lbcreationclient.models.privateIpAddressAllocation>`
    :param public_ip_address: Name or ID of the public IP address to use.
    :type public_ip_address: str
    :param public_ip_address_allocation: Public IP address allocation method.
     Possible values include: 'dynamic', 'static'. Default value: "dynamic" .
    :type public_ip_address_allocation: str or
     :class:`publicIpAddressAllocation
     <lbcreationclient.models.publicIpAddressAllocation>`
    :param public_ip_address_type: Type of Public IP Address to associate
     with the load balancer. Possible values include: 'none', 'new',
     'existingName', 'existingId'. Default value: "new" .
    :type public_ip_address_type: str or :class:`publicIpAddressType
     <lbcreationclient.models.publicIpAddressType>`
    :param public_ip_dns_name: Globally unique DNS Name for the Public IP
     used to access the Virtual Machine (new public IP only).
    :type public_ip_dns_name: str
    :param subnet: The subnet name or ID to associate with the load balancer.
     Cannot be used in conjunction with a Public IP.
    :type subnet: str
    :param subnet_address_prefix: The subnet address prefix in CIDR format
     (new subnet only). Default value: "10.0.0.0/24" .
    :type subnet_address_prefix: str
    :param subnet_type: Use new, existing or no subnet. Possible values
     include: 'none', 'new', 'existingName', 'existingId'. Default value:
     "none" .
    :type subnet_type: str or :class:`subnetType
     <lbcreationclient.models.subnetType>`
    :param tags: Tags object.
    :type tags: object
    :param virtual_network_name: The VNet name containing the subnet. Cannot
     be used in conjunction with a Public IP.
    :type virtual_network_name: str
    :param vnet_address_prefix: The virtual network IP address prefix in CIDR
     format (new subnet only). Default value: "10.0.0.0/16" .
    :type vnet_address_prefix: str
    :ivar mode: Gets or sets the deployment mode. Default value:
     "Incremental" .
    :vartype mode: str
    """

    _validation = {
        'uri': {'required': True, 'constant': True},
        '_artifacts_location': {'required': True, 'constant': True},
        'load_balancer_name': {'required': True},
        'mode': {'required': True, 'constant': True},
    }

    _attribute_map = {
        'uri': {'key': 'properties.templateLink.uri', 'type': 'str'},
        'content_version': {'key': 'properties.templateLink.contentVersion', 'type': 'str'},
        '_artifacts_location': {'key': 'properties.parameters._artifactsLocation.value', 'type': 'str'},
        'backend_pool_name': {'key': 'properties.parameters.backendPoolName.value', 'type': 'str'},
        'dns_name_type': {'key': 'properties.parameters.dnsNameType.value', 'type': 'dnsNameType'},
        'frontend_ip_name': {'key': 'properties.parameters.frontendIpName.value', 'type': 'str'},
        'load_balancer_name': {'key': 'properties.parameters.loadBalancerName.value', 'type': 'str'},
        'location': {'key': 'properties.parameters.location.value', 'type': 'str'},
        'private_ip_address': {'key': 'properties.parameters.privateIpAddress.value', 'type': 'str'},
        'private_ip_address_allocation': {'key': 'properties.parameters.privateIpAddressAllocation.value', 'type': 'privateIpAddressAllocation'},
        'public_ip_address': {'key': 'properties.parameters.publicIpAddress.value', 'type': 'str'},
        'public_ip_address_allocation': {'key': 'properties.parameters.publicIpAddressAllocation.value', 'type': 'publicIpAddressAllocation'},
        'public_ip_address_type': {'key': 'properties.parameters.publicIpAddressType.value', 'type': 'publicIpAddressType'},
        'public_ip_dns_name': {'key': 'properties.parameters.publicIpDnsName.value', 'type': 'str'},
        'subnet': {'key': 'properties.parameters.subnet.value', 'type': 'str'},
        'subnet_address_prefix': {'key': 'properties.parameters.subnetAddressPrefix.value', 'type': 'str'},
        'subnet_type': {'key': 'properties.parameters.subnetType.value', 'type': 'subnetType'},
        'tags': {'key': 'properties.parameters.tags.value', 'type': 'object'},
        'virtual_network_name': {'key': 'properties.parameters.virtualNetworkName.value', 'type': 'str'},
        'vnet_address_prefix': {'key': 'properties.parameters.vnetAddressPrefix.value', 'type': 'str'},
        'mode': {'key': 'properties.mode', 'type': 'str'},
    }

    uri = "https://azuresdkci.blob.core.windows.net/templatehost/CreateLb_2016-07-19/azuredeploy.json"

    _artifacts_location = "https://azuresdkci.blob.core.windows.net/templatehost/CreateLb_2016-07-19"

    mode = "Incremental"

    def __init__(self, load_balancer_name, content_version=None, backend_pool_name=None, dns_name_type="none", frontend_ip_name="LoadBalancerFrontEnd", location=None, private_ip_address=None, private_ip_address_allocation="dynamic", public_ip_address=None, public_ip_address_allocation="dynamic", public_ip_address_type="new", public_ip_dns_name=None, subnet=None, subnet_address_prefix="10.0.0.0/24", subnet_type="none", tags=None, virtual_network_name=None, vnet_address_prefix="10.0.0.0/16"):
        self.content_version = content_version
        self.backend_pool_name = backend_pool_name
        self.dns_name_type = dns_name_type
        self.frontend_ip_name = frontend_ip_name
        self.load_balancer_name = load_balancer_name
        self.location = location
        self.private_ip_address = private_ip_address
        self.private_ip_address_allocation = private_ip_address_allocation
        self.public_ip_address = public_ip_address
        self.public_ip_address_allocation = public_ip_address_allocation
        self.public_ip_address_type = public_ip_address_type
        self.public_ip_dns_name = public_ip_dns_name
        self.subnet = subnet
        self.subnet_address_prefix = subnet_address_prefix
        self.subnet_type = subnet_type
        self.tags = tags
        self.virtual_network_name = virtual_network_name
        self.vnet_address_prefix = vnet_address_prefix


text:
package com.oneops.sensor.util;

import com.oneops.cms.cm.domain.CmsCI;
import com.oneops.cms.cm.service.CmsCmProcessor;
import com.oneops.ops.CiOpsProcessor;
import com.oneops.ops.dao.OpsEventDao;
import com.oneops.sensor.thresholds.Threshold;
import com.oneops.sensor.thresholds.ThresholdsDao;
import org.apache.log4j.Logger;
import rx.schedulers.Schedulers;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import static com.oneops.sensor.Sensor.READ_ROWCOUNT;

public class SensorTools {
    private CmsCmProcessor cmProcessor;
    private ThresholdsDao tsDao;
    private OpsEventDao opsEventDao;
    private CiOpsProcessor coProcessor;

    private static Logger logger = Logger.getLogger(SensorTools.class);

    public void setCmProcessor(CmsCmProcessor cmProcessor) {
        this.cmProcessor = cmProcessor;
    }

    public void setTsDao(ThresholdsDao tsDao) {
        this.tsDao = tsDao;
    }

    public void setOpsEventDao(OpsEventDao opsEventDao) {
        this.opsEventDao = opsEventDao;
    }

    public void setCoProcessor(CiOpsProcessor coProcessor) {
        this.coProcessor = coProcessor;
    }

    /**
     * Validate all the threshold statements.
     */
    public void validateThresholds() {
        final CountDownLatch latch = new CountDownLatch(1);
        tsDao.getAllThreshold(READ_ROWCOUNT).subscribeOn(Schedulers.io())
                .subscribe(this::processThreshold,
                        (t) -> {
                            latch.countDown();
                            logger.error("Error while processing the thresholds", t);
                            throw new RuntimeException(t);
                        }, () -> {
                            latch.countDown();
                            logger.info("Completed the threshold validation.");
                        });
        try {
            latch.await(15, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            logger.error("Error while validating the threshold", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * Processs each threshold.
     *
     * @param tr {@link Threshold}
     */
    private void processThreshold(Threshold tr) {
        List<Long> bomCiIds = tsDao.getManifestCiIds(tr.getManifestId());
        List<CmsCI> bomCIs = cmProcessor.getCiByIdListNaked(bomCiIds);

        Set<Long> bomCiIdsSet = new HashSet<>();
        for (CmsCI bomCi : bomCIs) {
            bomCiIdsSet.add(bomCi.getCiId());
        }
        // Mow lets check maped cassnadra CiIds with CMS ciIds
        int remainingBomsCount = 0;
        for (Long mapedCiId : bomCiIds) {
            if (!bomCiIdsSet.contains(mapedCiId)) {
                logger.warn("Found orphan ciId = " + mapedCiId + " it is not in cms but in the map, will remove");
                opsEventDao.removeCi(mapedCiId);
                coProcessor.removeManifestMap(mapedCiId, tr.getManifestId());
                logger.info("Removing ciId = " + mapedCiId + " from the manifest map");
            } else {
                remainingBomsCount++;
            }
        }
        if (remainingBomsCount == 0) {
            // No boms left need to clean up the thresholds
            logger.error("No instances for this manifet id found in CMS, manifestId = " + tr.getManifestId() + ", the threshold " + tr.getSource() + " will be removed");
            tsDao.removeManifestThreshold(tr.getManifestId(), tr.getSource());
        }
    }
}


text:
package org.oscm.internal.vo;

import org.oscm.internal.vo.BaseVO;

/**
 * Represents the definition of a service role for a technical service.
 *
 */
public class VORoleDefinition extends BaseVO {

    private static final long serialVersionUID = -5036106045991442656L;

    private String roleId;

    private String name;

    private String description;

    /**
     * Retrieves the identifier of the service role.
     *
     * @return the role ID
     */
    public String getRoleId() {
        return roleId;
    }

    /**
     * Sets the identifier of the service role.
     *
     * @param roleId
     *            the role ID
     */
    public void setRoleId(String roleId) {
        this.roleId = roleId;
    }

    /**
     * Retrieves the name of the service role.
     *
     * @return the role name
     */
    public String getName() {
        return name;
    }

    /**
     * Sets the name of the service role.
     *
     * @param name
     *            the role name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * Retrieves the text describing the service role.
     *
     * @return the role description
     */
    public String getDescription() {
        return description;
    }

    /**
     * Sets the text describing the service role.
     *
     * @param description
     *            the role description
     */
    public void setDescription(String description) {
        this.description = description;
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project-private xmlns="http://www.netbeans.org/ns/project-private/1">
    <editor-bookmarks xmlns="http://www.netbeans.org/ns/editor-bookmarks/2" lastBookmarkId="0"/>
    <open-files xmlns="http://www.netbeans.org/ns/projectui-open-files/2">
        <group>
            <file>file:/C:/xampp/htdocs/geovalores/application/models/InicioModel.php</file>
            <file>file:/C:/xampp/htdocs/geovalores/application/controllers/Publicadas.php</file>
            <file>file:/C:/xampp/htdocs/geovalores/application/models/LoginSuperModel.php</file>
            <file>file:/C:/xampp/htdocs/geovalores/application/views/headeradministrador.php</file>
            <file>file:/C:/xampp/htdocs/geovalores/application/views/prueba.php</file>
            <file>file:/C:/xampp/htdocs/geovalores/application/views/header.php</file>
            <file>file:/C:/xampp/htdocs/geovalores/application/views/visitas.php</file>
            <file>file:/C:/xampp/htdocs/geovalores/application/models/DBModel.php</file>
            <file>file:/C:/xampp/htdocs/geovalores/application/controllers/Administrador.php</file>
        </group>
    </open-files>
</project-private>


text: package finspace


text:
CharacterCardRepo::CharacterCardRepo(std::string fileLocation) : _fileLocation(fileLocation)
{}

Deck<CharacterCard> CharacterCardRepo::GetCharacterCards() const
{
	Deck<CharacterCard> deck;

	ifstream input(_fileLocation);
	for (std::string line; getline(input, line); )
	{
		auto explodedString = Explode(";", line);
		if (explodedString.size() == 2)
			deck.Add(CharacterCard(std::stoi(explodedString[0]), explodedString[1], NONE, true));
		else if(explodedString.size() == 3)
		{
			Alignment alignment = NONE;
			if (explodedString[2] == "geel") alignment = YELLOW;
			else if (explodedString[2] == "rood") alignment = RED;
			else if (explodedString[2] == "groen") alignment = GREEN;
			else if (explodedString[2] == "blauw") alignment = BLUE;
			deck.Add(CharacterCard(std::stoi(explodedString[0]), explodedString[1], alignment, true));
		}
	}
	return deck;
}

CharacterCardRepo::~CharacterCardRepo()
{
}


text:
package eu.liveandgov.wp1.serialization.impl;

import eu.liveandgov.wp1.data.impl.Proximity;
import eu.liveandgov.wp1.serialization.SerializationCommons;

import java.util.Scanner;

/**
 *
Serialization of the proximity item

 * Created by Lukas Härtel on 08.02.14.
 */
public class ProximitySerialization extends AbstractSerialization<Proximity> {
    /**
     * The one instance of the serialization
     */
    public static final ProximitySerialization PROXIMITY_SERIALIZATION = new ProximitySerialization();

    /**
     * Hidden constructor
     */
    protected ProximitySerialization() {
    }

    @Override
    protected void serializeRest(StringBuilder stringBuilder, Proximity proximity) {
        SerializationCommons.appendString(stringBuilder, proximity.key);
        stringBuilder.append(SerializationCommons.SLASH);
        stringBuilder.append(proximity.in);
        stringBuilder.append(SerializationCommons.SLASH);
        SerializationCommons.appendString(stringBuilder, proximity.of);

    }

    @Override
    protected Proximity deSerializeRest(String type, long timestamp, String device, Scanner scanner) {
        scanner.useDelimiter(SerializationCommons.SLASH_SEMICOLON_SEPARATED);

        final String key = SerializationCommons.nextString(scanner);
        final Boolean in = scanner.nextBoolean();
        final String of = SerializationCommons.nextString(scanner);

        return new Proximity(timestamp, device, key, in, of);
    }
}


text:
package io.reactors

abstract class DataBuffer {
  /** Clears the contents of the data buffer.
   */
  def clear(): Unit

  /** The writing end of the buffer.
   */
  def output: Data

  /** The reading end of the buffer.
   */
  def input: Data

  /** Indicates whether this buffer has bytes available to read.
   */
  def hasMore: Boolean

  /** Optionally flushes the contents of this data buffer, depending on the semantics.
   */
  def flush(): Unit = {
  }
}

object DataBuffer {
  def streaming(batchSize: Int): DataBuffer = new Linked(batchSize)

  private[reactors] class Linked(val initialBatchSize: Int) extends DataBuffer {
    private[reactors] var rawOutput = allocateData(initialBatchSize)
    private[reactors] var rawInput = rawOutput

    protected[reactors] def allocateData(minNextSize: Int): LinkedData = {
      new LinkedData(this, math.max(initialBatchSize, minNextSize))
    }

    protected[reactors] def deallocateData(old: LinkedData) = {
    }

    protected[reactors] def onWriteNext(old: LinkedData): Unit = {
      rawOutput = old.next
    }

    protected[reactors] def onReadNext(old: LinkedData): Unit = {
      rawInput = old.next
    }

    def clear(): Unit = {
      rawOutput = allocateData(initialBatchSize)
      rawInput = rawOutput
    }

    def output: Data = rawOutput

    def input: Data = rawInput

    def hasMore: Boolean = {
      rawInput == rawOutput && rawInput.remainingReadSize == 0
    }
  }

  private[reactors] class LinkedData(
    private var rawBuffer: Linked,
    rawArray: Array[Byte]
  ) extends Data(rawArray, 0, 0) {
    private[reactors] var next: LinkedData = null

    def this(buffer: Linked, requestedBatchSize: Int) =
      this(buffer, new Array[Byte](requestedBatchSize))

    def buffer: Linked = rawBuffer

    private[reactors] def buffer_=(sb: Linked) = rawBuffer = sb

    def writeNext(minNextSize: Int): Data = {
      next = buffer.allocateData(minNextSize)
      val result = next
      buffer.onWriteNext(this)
      result
    }

    def readNext(): Data = {
      val result = next
      if (result != null) {
        buffer.onReadNext(this)
        buffer.deallocateData(this)
      }
      // After this point, the `Data` object is potentially deallocated
      // and must not be used again.
      result
    }

    def fullByteString: String = {
      var curr = buffer.rawInput
      var s = ""
      while (curr != null) {
        s += curr.byteString + "\n -> "
        curr = curr match {
          case linked: DataBuffer.LinkedData => linked.next
          case _ => null
        }
      }
      s
    }
  }
}


text:
namespace {

// The WebDialogDelegate that specifies what the MD Feedback dialog will look
// like.
class MdFeedbackDialogDelegate : public ui::WebDialogDelegate {
 public:
  MdFeedbackDialogDelegate() {}
  ~MdFeedbackDialogDelegate() override {}

  ui::ModalType GetDialogModalType() const override {
    return ui::MODAL_TYPE_SYSTEM;
  }

  base::string16 GetDialogTitle() const override {
    return l10n_util::GetStringUTF16(IDS_MD_FEEDBACK_DIALOG_TITLE);
  }

  GURL GetDialogContentURL() const override {
    return GURL(chrome::kChromeUIFeedbackURL);
  }

  void GetWebUIMessageHandlers(
      std::vector<content::WebUIMessageHandler*>* handlers) const override {}

  void GetDialogSize(gfx::Size* size) const override {
    // TODO(apacible): Update when WebUI sizing behavior is finalized.
    size->SetSize(400, 600);
  }

  std::string GetDialogArgs() const override {
    return std::string();
  }

  void OnDialogClosed(const std::string& json_retval) override {
    delete this;
  }

  void OnCloseContents(
      content::WebContents* source, bool* out_close_dialog) override {}

  bool ShouldShowDialogTitle() const override {
    return false;
  }

  bool HandleContextMenu(const content::ContextMenuParams& params) override {
    // Do not show the contextual menu.
    return true;
  }
};

}  // namespace

// static
MdFeedbackDialogController* MdFeedbackDialogController::GetInstance() {
  return base::Singleton<MdFeedbackDialogController>::get();
}

void MdFeedbackDialogController::Show(
    content::BrowserContext* browser_context) {
  // TODO(apacible): Platform dependent implementations.
#if !defined(OS_MACOSX)
  // TODO(apacible): If a feedback dialog is already open, bring that dialog
  // to the front rather than creating a new dialog.
  chrome::ShowWebDialog(nullptr, browser_context,
      new MdFeedbackDialogDelegate());
#endif  // !defined(OS_MACOSX)
}

MdFeedbackDialogController::MdFeedbackDialogController() {}


text:
@interface LJNewViewController ()

@end

@implementation LJNewViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // 设置导航栏标题
    self.navigationItem.titleView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"MainTitle"]];

    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImage:@"MainTagSubIcon" highlightedImage:@"MainTagSubIconClick" target:self action:@selector(newButtonClick)];

    // 设置背景颜色
   self.view.backgroundColor =  LJGlobalBg;
}

- (void)newButtonClick
{
    LJLogFunc;
}
@end


text:
@interface BraintreeDemoDropInViewController () <PKPaymentAuthorizationViewControllerDelegate>

@property (nonatomic, strong) BTUIKPaymentOptionCardView *paymentMethodTypeIcon;
@property (nonatomic, strong) UILabel *paymentMethodTypeLabel;
@property (nonatomic, strong) UILabel *cartLabel;
@property (nonatomic, strong) UILabel *itemLabel;
@property (nonatomic, strong) UILabel *priceLabel;
@property (nonatomic, strong) UILabel *paymentMethodHeaderLabel;
@property (nonatomic, strong) UIButton *dropInButton;
@property (nonatomic, strong) UIButton *purchaseButton;
@property (nonatomic, strong) UISegmentedControl *dropinThemeSwitch;
@property (nonatomic, strong) NSString *authorizationString;
@property (nonatomic) BOOL useApplePay;
@property (nonatomic, strong) BTPaymentMethodNonce *selectedNonce;
@end

@implementation BraintreeDemoDropInViewController

- (instancetype)initWithAuthorization:(NSString *)authorization {
    if (self = [super initWithAuthorization:authorization]) {

        self.authorizationString = authorization;
    }
    return self;
}

- (void) updatePaymentMethod:(BTPaymentMethodNonce*)paymentMethodNonce {
    self.paymentMethodTypeLabel.hidden = paymentMethodNonce == nil;
    self.paymentMethodTypeIcon.hidden = paymentMethodNonce == nil;
    if (paymentMethodNonce != nil) {
        BTUIKPaymentOptionType paymentMethodType = [BTUIKViewUtil paymentOptionTypeForPaymentInfoType:paymentMethodNonce.type];
        self.paymentMethodTypeIcon.paymentOptionType = paymentMethodType;
        [self.paymentMethodTypeLabel setText:paymentMethodNonce.localizedDescription];
    }
    [self updatePaymentMethodConstraints];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.cartLabel = [[UILabel alloc] init];
    [self.cartLabel setText:@"CART"];
    self.cartLabel.font = [UIFont systemFontOfSize:[UIFont smallSystemFontSize]];
    [self.cartLabel setTextColor:[UIColor grayColor]];
    self.cartLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.cartLabel];

    self.itemLabel = [[UILabel alloc] init];
    [self.itemLabel setText:@"1 Sock"];
    self.itemLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.itemLabel];

    self.priceLabel = [[UILabel alloc] init];
    [self.priceLabel setText:@"$100"];
    self.priceLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.priceLabel];

    self.paymentMethodHeaderLabel = [[UILabel alloc] init];
    [self.paymentMethodHeaderLabel setText:@"PAYMENT METHODS"];
    [self.paymentMethodHeaderLabel setTextColor:[UIColor grayColor]];
    self.paymentMethodHeaderLabel.font = [UIFont systemFontOfSize:[UIFont smallSystemFontSize]];
    self.paymentMethodHeaderLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.paymentMethodHeaderLabel];

    self.dropInButton = [[UIButton alloc] init];
    [self.dropInButton setTitle:@"Select Payment Method" forState:UIControlStateNormal];
    [self.dropInButton setTitleColor:self.view.tintColor forState:UIControlStateNormal];
    self.dropInButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.dropInButton addTarget:self action:@selector(tappedToShowDropIn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.dropInButton];

    self.purchaseButton = [[UIButton alloc] init];
    [self.purchaseButton setTitle:@"Complete Purchase" forState:UIControlStateNormal];
    [self.purchaseButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.purchaseButton setTitleColor:[[UIColor whiteColor] colorWithAlphaComponent:0.8] forState:UIControlStateHighlighted];
    self.purchaseButton.backgroundColor = self.view.tintColor;
    self.purchaseButton.translatesAutoresizingMaskIntoConstraints = NO;

    [self.purchaseButton addTarget:self action:@selector(purchaseButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    self.purchaseButton.layer.cornerRadius = 4.0;
    [self.view addSubview:self.purchaseButton];

    self.paymentMethodTypeIcon = [BTUIKPaymentOptionCardView new];
    self.paymentMethodTypeIcon.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.paymentMethodTypeIcon];
    self.paymentMethodTypeIcon.hidden = YES;

    self.paymentMethodTypeLabel = [[UILabel alloc] init];
    self.paymentMethodTypeLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.paymentMethodTypeLabel];
    self.paymentMethodTypeLabel.hidden = YES;

    self.dropinThemeSwitch = [[UISegmentedControl alloc] initWithItems:@[@"Light Theme", @"Dark Theme"]];
    self.dropinThemeSwitch.translatesAutoresizingMaskIntoConstraints = NO;
    self.dropinThemeSwitch.selectedSegmentIndex = 0;
    [self.view addSubview:self.dropinThemeSwitch];

    [self updatePaymentMethodConstraints];

    self.progressBlock(@"Fetching customer's payment methods...");
    self.useApplePay = NO;

    [BTDropInResult fetchDropInResultForAuthorization:self.authorizationString handler:^(BTDropInResult * _Nullable result, NSError * _Nullable error) {
        if (error) {
            self.progressBlock([NSString stringWithFormat:@"Error: %@", error.localizedDescription]);
            NSLog(@"Error: %@", error);
        } else {
            if (result.paymentOptionType == BTUIKPaymentOptionTypeApplePay) {
                self.progressBlock(@"Ready for checkout...");
                [self setupApplePay];
            } else {
                self.useApplePay = NO;
                self.selectedNonce = result.paymentMethod;
                self.progressBlock(@"Ready for checkout...");
                [self updatePaymentMethod:self.selectedNonce];
            }
        }
    }];
}

- (void) setupApplePay {
    self.paymentMethodTypeLabel.hidden = NO;
    self.paymentMethodTypeIcon.hidden = NO;
    self.paymentMethodTypeIcon.paymentOptionType = BTUIKPaymentOptionTypeApplePay;
    [self.paymentMethodTypeLabel setText:@"Apple Pay"];
    self.useApplePay = YES;
    [self updatePaymentMethodConstraints];
}

#pragma mark Constraints

- (void)updatePaymentMethodConstraints {
    [self.view removeConstraints:self.view.constraints];

    NSDictionary *viewBindings = @{
                                   @"view": self,
                                   @"cartLabel": self.cartLabel,
                                   @"itemLabel": self.itemLabel,
                                   @"priceLabel": self.priceLabel,
                                   @"paymentMethodHeaderLabel": self.paymentMethodHeaderLabel,
                                   @"dropInButton": self.dropInButton,
                                   @"paymentMethodTypeIcon": self.paymentMethodTypeIcon,
                                   @"paymentMethodTypeLabel": self.paymentMethodTypeLabel,
                                   @"purchaseButton":self.purchaseButton,
                                   @"dropinThemeSwitch":self.dropinThemeSwitch
                                   };

    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[cartLabel]-|" options:0 metrics:nil views:viewBindings]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[purchaseButton]-|" options:0 metrics:nil views:viewBindings]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(20)-[cartLabel]-[itemLabel]-[paymentMethodHeaderLabel]" options:0 metrics:nil views:viewBindings]];

    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[itemLabel]-[priceLabel]-|" options:NSLayoutFormatAlignAllTop metrics:nil views:viewBindings]];

    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[paymentMethodHeaderLabel]-|" options:0 metrics:nil views:viewBindings]];

    if (!self.paymentMethodTypeIcon.hidden && !self.paymentMethodTypeLabel.hidden) {
        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[paymentMethodHeaderLabel]-[paymentMethodTypeIcon(29)]-[dropInButton]" options:0 metrics:nil views:viewBindings]];

        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[paymentMethodTypeIcon(45)]-[paymentMethodTypeLabel]" options:NSLayoutFormatAlignAllCenterY metrics:nil views:viewBindings]];
        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[dropInButton]-|" options:0 metrics:nil views:viewBindings]];
        [self.dropInButton setTitle:@"Change Payment Method" forState:UIControlStateNormal];
        self.purchaseButton.backgroundColor = self.view.tintColor;
        self.purchaseButton.enabled = YES;
    } else {
        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[paymentMethodHeaderLabel]-[dropInButton]" options:0 metrics:nil views:viewBindings]];

        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[dropInButton]-|" options:0 metrics:nil views:viewBindings]];
        [self.dropInButton setTitle:@"Add Payment Method" forState:UIControlStateNormal];
        self.purchaseButton.backgroundColor = [UIColor lightGrayColor];
        self.purchaseButton.enabled = NO;
    }

    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[dropInButton]-(20)-[purchaseButton]-(20)-[dropinThemeSwitch]" options:0 metrics:nil views:viewBindings]];

    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[dropinThemeSwitch]-|" options:0 metrics:nil views:viewBindings]];
}

#pragma mark Button Handlers

- (void)purchaseButtonPressed {
    if (self.useApplePay) {

        PKPaymentRequest *paymentRequest = [[PKPaymentRequest alloc] init];
        paymentRequest.paymentSummaryItems = @[
                                               [PKPaymentSummaryItem summaryItemWithLabel:@"Socks" amount:[NSDecimalNumber decimalNumberWithString:@"100"]]
                                               ];
        paymentRequest.supportedNetworks = @[PKPaymentNetworkVisa, PKPaymentNetworkMasterCard, PKPaymentNetworkAmex, PKPaymentNetworkDiscover];
        paymentRequest.merchantCapabilities = PKMerchantCapability3DS;
        paymentRequest.currencyCode = @"USD";
        paymentRequest.countryCode = @"US";

        switch ([BraintreeDemoSettings currentEnvironment]) {
            case BraintreeDemoTransactionServiceEnvironmentSandboxBraintreeSampleMerchant:
                paymentRequest.merchantIdentifier = @"merchant.com.braintreepayments.sandbox.Braintree-Demo";
                break;
            case BraintreeDemoTransactionServiceEnvironmentProductionExecutiveSampleMerchant:
                paymentRequest.merchantIdentifier = @"merchant.com.braintreepayments.Braintree-Demo";
                break;
            case BraintreeDemoTransactionServiceEnvironmentCustomMerchant:
                self.progressBlock(@"Direct Apple Pay integration does not support custom environments in this Demo App");
                break;
        }

        PKPaymentAuthorizationViewController *viewController = [[PKPaymentAuthorizationViewController alloc] initWithPaymentRequest:paymentRequest];
        viewController.delegate = self;

        self.progressBlock(@"Presenting Apple Pay Sheet");
        [self presentViewController:viewController animated:YES completion:nil];
    } else {
        self.completionBlock(self.selectedNonce);
        self.transactionBlock();
    }
}

- (void)tappedToShowDropIn {
    BTDropInRequest *dropInRequest = [[BTDropInRequest alloc] init];
    // To test 3DS
    //dropInRequest.amount = @"10.00";
    //dropInRequest.threeDSecureVerification = YES;
    if (self.dropinThemeSwitch.selectedSegmentIndex == 0) {
        [BTUIKAppearance lightTheme];
    } else {
        [BTUIKAppearance darkTheme];
    }
    BTDropInController *dropIn = [[BTDropInController alloc] initWithAuthorization:self.authorizationString request:dropInRequest handler:^(BTDropInController * _Nonnull dropInController, BTDropInResult * _Nullable result, NSError * _Nullable error) {
        if (error) {
            self.progressBlock([NSString stringWithFormat:@"Error: %@", error.localizedDescription]);
            NSLog(@"Error: %@", error);
        } else if (result.isCancelled) {
            self.progressBlock(@"Cancelled🎲");
        } else {
            if (result.paymentOptionType == BTUIKPaymentOptionTypeApplePay) {
                self.progressBlock(@"Ready for checkout...");
                [self setupApplePay];
            } else {
                self.useApplePay = NO;
                self.selectedNonce = result.paymentMethod;
                self.progressBlock(@"Ready for checkout...");
                [self updatePaymentMethod:self.selectedNonce];
            }
        }
        [dropInController dismissViewControllerAnimated:YES completion:nil];
    }];

    [self presentViewController:dropIn animated:YES completion:nil];
}

#pragma mark PKPaymentAuthorizationViewControllerDelegate

- (void)paymentAuthorizationViewController:(__unused PKPaymentAuthorizationViewController *)controller
                   didSelectShippingMethod:(PKShippingMethod *)shippingMethod
                                completion:(void (^)(PKPaymentAuthorizationStatus, NSArray<PKPaymentSummaryItem *> * _Nonnull))completion
{
    PKPaymentSummaryItem *testItem = [PKPaymentSummaryItem summaryItemWithLabel:@"SOME ITEM" amount:[NSDecimalNumber decimalNumberWithString:@"10"]];
    if ([shippingMethod.identifier isEqualToString:@"fast"]) {
        completion(PKPaymentAuthorizationStatusSuccess,
                   @[
                     testItem,
                     [PKPaymentSummaryItem summaryItemWithLabel:@"SHIPPING" amount:shippingMethod.amount],
                     [PKPaymentSummaryItem summaryItemWithLabel:@"BRAINTREE" amount:[testItem.amount decimalNumberByAdding:shippingMethod.amount]],
                     ]);
    } else if ([shippingMethod.identifier isEqualToString:@"fail"]) {
        completion(PKPaymentAuthorizationStatusFailure, @[testItem]);
    } else {
        completion(PKPaymentAuthorizationStatusSuccess, @[testItem]);
    }
}

- (void)paymentAuthorizationViewController:(__unused PKPaymentAuthorizationViewController *)controller
                       didAuthorizePayment:(PKPayment *)payment
                                completion:(void (^)(PKPaymentAuthorizationStatus status))completion {
    self.progressBlock(@"Apple Pay Did Authorize Payment");
    BTAPIClient *client = [[BTAPIClient alloc] initWithAuthorization:self.authorizationString];
    BTApplePayClient *applePayClient = [[BTApplePayClient alloc] initWithAPIClient:client];
    [applePayClient tokenizeApplePayPayment:payment completion:^(BTApplePayCardNonce * _Nullable tokenizedApplePayPayment, NSError * _Nullable error) {
        if (error) {
            self.progressBlock(error.localizedDescription);
            completion(PKPaymentAuthorizationStatusFailure);
        } else {
            self.completionBlock(tokenizedApplePayPayment);
            completion(PKPaymentAuthorizationStatusSuccess);
        }
    }];
}

- (void)paymentAuthorizationViewControllerDidFinish:(PKPaymentAuthorizationViewController *)controller {
    [controller dismissViewControllerAnimated:YES completion:nil];
}

- (void)paymentAuthorizationViewControllerWillAuthorizePayment:(__unused PKPaymentAuthorizationViewController *)controller {
    self.progressBlock(@"Apple Pay will Authorize Payment");
}

@end


text:
using System.Numerics;

namespace SharpSteer2.Obstacles
{
	/// <summary>
	/// Obstacle: a pure virtual base class for an abstract shape in space, to be
	/// used with obstacle avoidance.
	/// </summary>
	public interface IObstacle
	{
        Vector3 SteerToAvoid(IVehicle v, float minTimeToCollision);

        float? NextIntersection(IVehicle vehicle);
	}
}


text:
package com.nec.healthpredictions.util;

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

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import com.nec.healthpredictions.entity.dto.Chart;
import com.nec.healthpredictions.entity.dto.ZoneCompare;
import com.nec.healthpredictions.entity.mapping.IllnessRisk;
import com.nec.healthpredictions.util.constant.Constants;

/**
 * Utility for Chart
 *
 * @author sondn
 */
public class ChartUtil {

	/** LESS THAN */
	public static final String LT = "<";

	/** GREATER THAN */
	public static final String GT = ">";

	/** LESS THAN OR EQUAL */
	public static final String LE = "<=";

	/** GREATER THAN OR EQUAL */
	public static final String GE = ">=";

	/**
	 * Get a list of ticks for graph (chart).
	 *
	 * @param simulation : value of simulation.
	 * @param yAxisScope : scope of RangeRisk.
	 * @param interval : interval of RangeRisk.
	 * @return list of yaxis values.
	 */
	public static List<Float> findYaxisValues(Float simulation, Float yAxisScope, Float interval) {
		Float yAxisMin = simulation - yAxisScope;
		Float yAxisMax = simulation + yAxisScope;
		yAxisMin = (float) ((float) Math.round(yAxisMin * 100d) / 100d);
		yAxisMax = (float) ((float) Math.round(yAxisMax * 100d) / 100d);

		List<Float> ticks = new ArrayList<Float>();
		do {
			ticks.add(yAxisMin);
			yAxisMin += interval;
		} while (yAxisMin < yAxisMax);

		return ticks;
	}

	/**
	 * Find array of riskNumberAdvice based on illnessRisks , used for CHG-001 screen.
	 *
	 * @author vuld
	 * @param illnessRisks : List of IllnessRisk.
	 * @return riskNumberAdvices calculated from List of IllnessRisk.
	 */
	public static Integer[] findRiskNumberAdvices(final List<IllnessRisk> illnessRisks) {
		if (CollectionUtils.isEmpty(illnessRisks)) {
			return null;
		}
		List<Integer> riskNumberAdvices = new ArrayList<Integer>();

		for (int i = 0; i < illnessRisks.size(); i++) {
			String iconOf3Year = illnessRisks.get(i).getIconOf3YearAgo();
			if (iconOf3Year.equals(Constants.ICON_YELLOW) || iconOf3Year.equals(Constants.ICON_RED)) {
				riskNumberAdvices.add(i);
			}
		}

		return riskNumberAdvices.toArray(new Integer[riskNumberAdvices.size()]);
	}

	// コード検証結果対応 開始
	// VuLD 2016/03/18
	// Dead Code: Obsolete

	/*
	@Deprecated
	public static String diagnoseLevelForWeight(Chart tempChart, Float simulation) {
		if (tempChart == null || simulation == null) {
			throw new IllegalArgumentException("ERROR");
		}

		// return diagnose level according to it's simulation value
		if (isBetweenForWeight(simulation, tempChart.getZoneColorLLimitLow(), tempChart.getZoneColorULimitLow())) {
			return Constants.DIAGNOSE_LEVEL_LOW;
		} else if (isBetweenForWeight(simulation, tempChart.getZoneColorLLimitMiddle(), tempChart.getZoneColorULimitMiddle())) {
			return Constants.DIAGNOSE_LEVEL_MIDDLE;
		} else if (isBetweenForWeight(simulation, tempChart.getZoneColorLLimitHigh(), tempChart.getZoneColorULimitHigh())) {
			return Constants.DIAGNOSE_LEVEL_HIGH;
		} else {
			// Throw exception 1.7.3
			throw new IllegalArgumentException("Error happened when Get Risk information");
		}
	}
	 */
	//コード検証結果対応 終了

	/**
	 * Get Diagnose level by condition.
	 *
	 * @author vuld
	 * @param tempChart : Chart that need to calculate diagnoseLevel.
	 * @param simulation : simulation value.
	 * @return diagnoseLevel calculated with zoneColors by simulation.
	 */
	public static String diagnoseLevel(Chart tempChart, Float simulation) {
		if (tempChart == null || simulation == null || tempChart.getZoneCompare() == null) {
			throw new IllegalArgumentException("Chart's object or simulation is null");
		}

		// Determine HIGH
		if (!Constants.RANGE_RISK_03.equals(tempChart.getType())) {
			if( isBetweenWithOperator(simulation, tempChart.getZoneColorLLimitHigh(), tempChart.getZoneColorULimitHigh(),
					tempChart.getZoneCompare().getlHighUpperOperator(), tempChart.getZoneCompare().getuHighLowerOperator())) {

				return Constants.DIAGNOSE_LEVEL_HIGH;
			}
		}

		// Determine LOW
		if (isBetweenWithOperator(simulation, tempChart.getZoneColorLLimitLow(), tempChart.getZoneColorULimitLow(),
				tempChart.getZoneCompare().getlLowOperator(), tempChart.getZoneCompare().getuLowOperator())) {

			return Constants.DIAGNOSE_LEVEL_LOW;
		}

		// Determine MIDDLE
		if (isBetweenWithOperator(simulation, tempChart.getZoneColorLLimitMiddle(), tempChart.getZoneColorULimitMiddle(),
				tempChart.getZoneCompare().getlMiddleOperator(), tempChart.getZoneCompare().getuMiddleOperator())) {

			return Constants.DIAGNOSE_LEVEL_MIDDLE;
		}

		// Determine SUB for element 1
		if (Constants.RANGE_RISK_01.equals(tempChart.getType())
				&& isBetweenWithOperator(simulation, tempChart.getZoneColorLLimitSub(), null,
						tempChart.getZoneCompare().getlSubOperator(), null)) {

			return tempChart.getZoneColorSubType();
		}

		/** in the end , if diagnoseLevel cannot be determined , throw exception */
		throw new IllegalArgumentException("Cannot determined diagnoseLevel for Chart: "
				+ tempChart.getType() + " , with Value: " + simulation);
	}

	/**
	 * reverse all operator of zoneCompare, ie: LT to GT or GT to LT.
	 *
	 * @author vuld
	 * @param zoneCompare : ZoneCompare of Chart need to reverse operator.
	 */
	public static void reverseOperator(ZoneCompare zoneCompare){
		if (zoneCompare != null) {
			zoneCompare.setlLowOperator(reverseOperator(zoneCompare.getlLowOperator()));
			zoneCompare.setuLowOperator(reverseOperator(zoneCompare.getuLowOperator()));
			zoneCompare.setlMiddleOperator(reverseOperator(zoneCompare.getlMiddleOperator()));
			zoneCompare.setuMiddleOperator(reverseOperator(zoneCompare.getuMiddleOperator()));
			zoneCompare.setlHighUpperOperator(reverseOperator(zoneCompare.getlHighUpperOperator()));
			zoneCompare.setuHighLowerOperator(reverseOperator(zoneCompare.getuHighLowerOperator()));
			zoneCompare.setlSubOperator(reverseOperator(zoneCompare.getlSubOperator()));
		}
	}

	/**
	 * reverse operator , ie: LT to GT or GT to LT.
	 *
	 * @param operator : operator want to reverse
	 * @return reversedOperator : value that already bean reversed from passed operator param
	 */
	private static String reverseOperator(String operator) {
		if (!StringUtils.isEmpty(operator)) {
			if (operator.equals(LT)) {
				return GT;
			} else if (operator.equals(GT)) {
				return LT;
			} else if (operator.equals(GE)) {
				return LE;
			} else if (operator.equals(LE)) {
				return GE;
			}
		}
		return null;
	}

	/**
	 * Check if simulation satisfied condition.
	 *
	 * @author vuld
	 * @param simulation : simulation value.
	 * @param low : low range risk.
	 * @param high : high range risk.
	 * @param lowOperator : operator used for compare with passed low param
	 * @param highOperator : operator used for compare with passed high param
	 * @return true if in range risk, otherwise return false.
	 */
	private static boolean isBetweenWithOperator(Float simulation, Float low, Float high, String lowOperator, String highOperator) {
		boolean flag = false;

		if (low != null && high != null && !StringUtils.isEmpty(lowOperator) && !StringUtils.isEmpty(highOperator)) {
			flag = (compareValue(low, simulation, lowOperator) == compareValue(high, simulation, highOperator));
		} else if (low != null && high == null && !StringUtils.isEmpty(lowOperator)) {
			flag = compareValue(low, simulation, lowOperator);
		} else if ((low == null || low == 0) && high != null && !StringUtils.isEmpty(highOperator)) {
			flag = compareValue(high, simulation, highOperator);
		}

		return flag;
	}

	/**
	 * return result of comparing 2 inputed value with operator.
	 *
	 * @param target : target that need to compare with.
	 * @param value : value used for compare.
	 * @param operator : operator using for compare.
	 * @return return true if valid, otherwise return false.
	 */
	private static boolean compareValue(Float target, Float value, String operator) {
		if (operator.equals(LT)) {
			return lessThan(target, value);
		}
		if (operator.equals(GT)) {
			return greaterThan(target, value);
		}
		if (operator.equals(LE)) {
			return lessThanOrEqual(target, value);
		}
		if (operator.equals(GE)) {
			return greaterThanOrEqual(target, value);
		}

		/** in the end , if operator is not defined yet , throw exception */
		throw new IllegalArgumentException("Error happened when compare with range risk,"
				+ " operator : " + operator + " is not defined ");
	}

	/**
	 * compare value less than target.
	 *
	 * @author vuld
	 * @param target : target that need to compare with.
	 * @param value : value used for compare.
	 * @return true if value less than target, otherwise return false
	 */
	private static boolean lessThan(Float target, Float value) {
		return value < target;
	}

	/**
	 * compare value greater than target.
	 *
	 * @author vuld
	 * @param target : target that need to compare with.
	 * @param value : value used for compare.
	 * @return true if value greater than target, otherwise return false.
	 */
	private static boolean greaterThan(Float target, Float value) {
		return value > target;
	}

	/**
	 * compare value less than or equal target.
	 *
	 * @author vuld
	 * @param target : target that need to compare with.
	 * @param value : value used for compare.
	 * @return true if value less than or equal target, otherwise return false.
	 */
	private static boolean lessThanOrEqual(Float target, Float value) {
		return value <= target;
	}

	/**
	 * compare value greater than or equal target.
	 *
	 * @author vuld
	 * @param target : target that need to compare with.
	 * @param value : value used for compare.
	 * @return true if value greater than or equal target, otherwise return false.
	 */
	private static boolean greaterThanOrEqual(Float target, Float value) {
		return value >= target;
	}

	// コード検証結果対応 開始
	// VuLD 2016/03/18
	// Dead Code: Unused Method

	/*
	@Deprecated
	private static boolean isBetween(Float simulation, Float low, Float high) {
		if (simulation == null) {
			return false;
		}

		boolean flag = false;

		if (low != null && high != null && simulation >= low && simulation < high) {
			flag = true;
		} else if (low != null && high == null && simulation >= low) {
			flag = true;
		} else if (low == null && high != null && simulation < high) {
			flag = true;
		}
		return flag;
	}

	@Deprecated
	private static boolean isBetweenNotEqualLow(Float simulation, Float low, Float high) {
		if (simulation == null) {
			return false;
		}

		boolean flag = false;

		if (low != null && high != null && simulation > low && simulation < high) {
			flag = true;
		} else if (low != null && high == null && simulation > low) {
			flag = true;
		} else if (low == null && high != null && simulation < high) {
			flag = true;
		}
		return flag;
	}
	 */
	//コード検証結果対応 終了

	// コード検証結果対応 開始
	// VuLD 2016/03/18
	// Dead Code: Obsolete

	/*
	@Deprecated
	private static boolean isBetweenForWeight(float simulation, Float low, Float high) {
		boolean flag = false;

		if (low != null && high != null && simulation >= low && simulation < high) {
			flag = true;
		} else if (low != null && high == null && simulation >= low) {
			flag = true;
		} else if (low == null && high != null && simulation < high) {
			flag = true;
		}
		return flag;
	}
	 */
	//コード検証結果対応 終了

}


text:
#ifndef TB_PLATFORM_COMPILER_LIBC_ATOMIC_H
#define TB_PLATFORM_COMPILER_LIBC_ATOMIC_H

/* //////////////////////////////////////////////////////////////////////////////////////
 * includes
 */
#include "prefix.h"
#include <stdatomic.h>

/* //////////////////////////////////////////////////////////////////////////////////////
 * macros
 */

#define TB_ATOMIC_RELAXED                               memory_order_relaxed
#define TB_ATOMIC_CONSUME                               memory_order_consume
#define TB_ATOMIC_ACQUIRE                               memory_order_acquire
#define TB_ATOMIC_RELEASE                               memory_order_release
#define TB_ATOMIC_ACQ_REL                               memory_order_acq_rel
#define TB_ATOMIC_SEQ_CST                               memory_order_seq_cst

#define tb_memory_barrier()                             atomic_thread_fence(memory_order_seq_cst)

#define TB_ATOMIC_FLAG_INIT                             ATOMIC_FLAG_INIT
#define tb_atomic_flag_test_and_set_explicit(a, mo)     atomic_flag_test_and_set_explicit(a, mo)
#define tb_atomic_flag_test_and_set(a)                  atomic_flag_test_and_set(a)
#ifdef atomic_flag_test_explicit
#   define tb_atomic_flag_test_explicit(a, mo)          atomic_flag_test_explicit(a, mo)
#else
#   define tb_atomic_flag_test_explicit(a, mo)          tb_atomic_flag_test_explicit_libc(a, mo)
#endif
#define tb_atomic_flag_test(a)                          tb_atomic_flag_test_explicit(a, memory_order_seq_cst)
#define tb_atomic_flag_test_noatomic(a)                 tb_atomic_flag_test_noatomic_libc(a)
#define tb_atomic_flag_clear_explicit(a, mo)            atomic_flag_clear_explicit(a, mo)
#define tb_atomic_flag_clear(a)                         atomic_flag_clear(a)

/* //////////////////////////////////////////////////////////////////////////////////////
 * inline implementation
 */
static __tb_inline__ tb_bool_t tb_atomic_flag_test_explicit_libc(tb_atomic_flag_t* a, tb_int_t mo)
{
    tb_assert(a);
    tb_assert_static(sizeof(tb_atomic_flag_t) == sizeof(unsigned char));
    return (tb_bool_t)atomic_load_explicit((__tb_volatile__ _Atomic unsigned char*)a, mo);
}
static __tb_inline__ tb_bool_t tb_atomic_flag_test_noatomic_libc(tb_atomic_flag_t* a)
{
    tb_assert(a);
    tb_assert_static(sizeof(tb_atomic_flag_t) == sizeof(unsigned char));
    return (tb_bool_t)*((__tb_volatile__ unsigned char*)a);
}

#endif


text:
namespace IdmGenerateModels
{
    public class ReferenceToObjectTypeMap
    {
        public string AttrName { get; set; }
        public string ObjType { get; set; }
    }
}


text:
package org.apache.wicket.markup.html.markupId;

import org.apache.wicket.protocol.http.WebApplication;

/**
 * Application object for your web application. If you want to run this application without
 * deploying, run the Start class.
 *
 * @see com.mycompany.Start#main(String[])
 */
public class WicketApplication extends WebApplication
{
	/**
	 * Constructor
	 */
	public WicketApplication()
	{
	}

	/**
	 * @see org.apache.wicket.Application#getHomePage()
	 */
	@Override
	public Class<HomePage> getHomePage()
	{
		return HomePage.class;
	}

}


text:
using FbTk::StringUtil::removeFirstWhitespace;
using FbTk::StringUtil::toLower;
using std::string;

namespace FbTk {

namespace {

template <typename M>
M *addCommands(M *macro, const string &args, bool trusted) {
    std::string blah;
    std::vector<std::string> cmds;
    StringUtil::stringTokensBetween(cmds, args, blah, '{', '}');
    RefCount<Command<bool> > cmd(0);

    std::vector<std::string>::iterator it = cmds.begin(), it_end = cmds.end();
    for (; it != it_end; ++it) {
        cmd = CommandParser<bool>::instance().parse(*it, trusted);
        if (*cmd)
            macro->add(cmd);
    }

    if (macro->size() > 0)
        return macro;
    delete macro;
    return 0;
}

Command<bool> *parseLogicCommand(const string &command, const string &args,
                               bool trusted) {
    if (command == "not") {
        Command<bool> *boolcmd =
                CommandParser<bool>::instance().parse(args, trusted);
        if (!boolcmd)
            return 0;
        RefCount<Command<bool> > ref(boolcmd);
        return new NotCommand(ref);
    } else if (command == "and")
        return addCommands<AndCommand>(new AndCommand(), args, trusted);
    else if (command == "or")
        return addCommands<OrCommand>(new OrCommand(), args, trusted);
    else if (command == "xor")
        return addCommands<XorCommand>(new XorCommand(), args, trusted);
    return 0;
}

REGISTER_COMMAND_PARSER(not, parseLogicCommand, bool);
REGISTER_COMMAND_PARSER(and, parseLogicCommand, bool);
REGISTER_COMMAND_PARSER(or, parseLogicCommand, bool);
REGISTER_COMMAND_PARSER(xor, parseLogicCommand, bool);

}; // end anonymous namespace

Command<void> *IfCommand::parse(const std::string &command, const std::string &args,
                          bool trusted) {
    std::string blah;
    std::vector<std::string> cmds;
    RefCount<Command<bool> > cond(0);
    RefCount<Command<void> > t(0), f(0);

    StringUtil::stringTokensBetween(cmds, args, blah, '{', '}');
    if (cmds.size() < 2)
        return 0;

    cond = CommandParser<bool>::instance().parse(cmds[0], trusted);
    if (*cond == 0)
        return 0;

    t = CommandParser<void>::instance().parse(cmds[1], trusted);
    if (cmds.size() >= 3)
        f = CommandParser<void>::instance().parse(cmds[2], trusted);
    if (*t == 0 && *f == 0)
        return 0;

    return new IfCommand(cond, t, f);
}

REGISTER_COMMAND_PARSER(if, IfCommand::parse, void);
REGISTER_COMMAND_PARSER(cond, IfCommand::parse, void);

void OrCommand::add(RefCount<Command<bool> > &com) {
    m_commandlist.push_back(com);
}

size_t OrCommand::size() const {
    return m_commandlist.size();
}

bool OrCommand::execute() {
    for (size_t i=0; i < m_commandlist.size(); ++i) {
        if (m_commandlist[i]->execute())
            return true;
    }
    return false;
}

void AndCommand::add(RefCount<Command<bool> > &com) {
    m_commandlist.push_back(com);
}

size_t AndCommand::size() const {
    return m_commandlist.size();
}

bool AndCommand::execute() {
    for (size_t i=0; i < m_commandlist.size(); ++i) {
        if (!m_commandlist[i]->execute())
            return false;
    }
    return true;
}

void XorCommand::add(RefCount<Command<bool> > &com) {
    m_commandlist.push_back(com);
}

size_t XorCommand::size() const {
    return m_commandlist.size();
}

bool XorCommand::execute() {
    bool ret = false;
    for (size_t i=0; i < m_commandlist.size(); ++i)
        ret ^= m_commandlist[i]->execute();
    return ret;
}

} // end namespace FbTk


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="title_donate">Apoie O Desenvolvedor</string>
    <string name="summary_donate">Doar Bitcoin</string>
    <string name="error_donate">Endereço bitcoin não encontrado</string>
</resources>


text:
namespace Swisstalk.ORM.Transport
{
    public enum PacketType
    {
        None = 0,
        Atomic,
        Array,
        Dataset
    }

    public struct Packet
    {
        private readonly object payload;
        private readonly PacketType payloadType;

        public Packet(object payload, PacketType payloadType)
        {
            this.payload = payload;
            this.payloadType = payloadType;
        }

        public object Payload
        {
            get
            {
                return payload;
            }
        }

        public PacketType PayloadType
        {
            get
            {
                return payloadType;
            }
        }

        public T GetPayloadAs<T>()
        {
            return (T)payload;
        }
    }
}


text:
<?php

declare(strict_types=1);

namespace OpenCFP\Http\Controller;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Twig\Environment;

abstract class BaseController
{
    /**
     * @var Environment
     */
    protected $twig;

    /**
     * @var UrlGeneratorInterface
     */
    protected $urlGenerator;

    public function __construct(Environment $twig, UrlGeneratorInterface $urlGenerator)
    {
        $this->twig         = $twig;
        $this->urlGenerator = $urlGenerator;
    }

    /**
     * Generates a file for the user
     *
     * @param string $content
     * @param string $fileName
     *
     * @return Response
     */
    protected function export(string $content, string $fileName)
    {
        $response    = new Response($content);
        $disposition = $response->headers->makeDisposition(
            ResponseHeaderBag::DISPOSITION_ATTACHMENT,
            $fileName
        );
        $response->headers->set('Content-Disposition', $disposition);

        return $response;
    }

    /**
     * Generate an absolute url from a route name.
     *
     * @param string $route
     * @param array  $parameters
     *
     * @return string the generated URL
     */
    protected function url($route, $parameters = [])
    {
        return $this->urlGenerator->generate($route, $parameters, UrlGeneratorInterface::ABSOLUTE_URL);
    }

    /**
     * Returns a rendered Twig response.
     *
     * @param string $name    Twig template name
     * @param array  $context
     * @param int    $status
     *
     * @return Response
     */
    protected function render($name, array $context = [], $status = Response::HTTP_OK)
    {
        return new Response($this->twig->render($name, $context), $status);
    }

    /**
     * @param string $route  Route name to redirect to
     * @param int    $status
     *
     * @return RedirectResponse
     */
    protected function redirectTo($route, $status = Response::HTTP_FOUND)
    {
        return new RedirectResponse($this->url($route), $status);
    }
}


text:
package com.github.badoualy.telegram.tl.api.request;

import com.github.badoualy.telegram.tl.TLContext;
import com.github.badoualy.telegram.tl.api.TLAbsInputChannel;
import com.github.badoualy.telegram.tl.core.TLBool;
import com.github.badoualy.telegram.tl.core.TLMethod;
import com.github.badoualy.telegram.tl.core.TLObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import static com.github.badoualy.telegram.tl.StreamUtils.readInt;
import static com.github.badoualy.telegram.tl.StreamUtils.readTLObject;
import static com.github.badoualy.telegram.tl.StreamUtils.writeInt;
import static com.github.badoualy.telegram.tl.StreamUtils.writeTLObject;
import static com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_CONSTRUCTOR_ID;
import static com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_INT32;

/**
 * @author Yannick Badoual yann.badoual@gmail.com
 * @see http://github.com/badoualy/kotlogram
 */
public class TLRequestChannelsReadHistory extends TLMethod<TLBool> {

    public static final int CONSTRUCTOR_ID = 0xcc104937;

    protected TLAbsInputChannel channel;

    protected int maxId;

    private final String _constructor = "channels.readHistory#cc104937";

    public TLRequestChannelsReadHistory() {
    }

    public TLRequestChannelsReadHistory(TLAbsInputChannel channel, int maxId) {
        this.channel = channel;
        this.maxId = maxId;
    }

    @Override
    @SuppressWarnings({"unchecked", "SimplifiableConditionalExpression"})
    public TLBool deserializeResponse(InputStream stream, TLContext context) throws IOException {
        final TLObject response = readTLObject(stream, context);
        if (response == null) {
            throw new IOException("Unable to parse response");
        }
        if (!(response instanceof TLBool)) {
            throw new IOException(
                    "Incorrect response type, expected " + getClass().getCanonicalName() + ", found " + response
                            .getClass().getCanonicalName());
        }
        return (TLBool) response;
    }

    @Override
    public void serializeBody(OutputStream stream) throws IOException {
        writeTLObject(channel, stream);
        writeInt(maxId, stream);
    }

    @Override
    @SuppressWarnings({"unchecked", "SimplifiableConditionalExpression"})
    public void deserializeBody(InputStream stream, TLContext context) throws IOException {
        channel = readTLObject(stream, context, TLAbsInputChannel.class, -1);
        maxId = readInt(stream);
    }

    @Override
    public int computeSerializedSize() {
        int size = SIZE_CONSTRUCTOR_ID;
        size += channel.computeSerializedSize();
        size += SIZE_INT32;
        return size;
    }

    @Override
    public String toString() {
        return _constructor;
    }

    @Override
    public int getConstructorId() {
        return CONSTRUCTOR_ID;
    }

    public TLAbsInputChannel getChannel() {
        return channel;
    }

    public void setChannel(TLAbsInputChannel channel) {
        this.channel = channel;
    }

    public int getMaxId() {
        return maxId;
    }

    public void setMaxId(int maxId) {
        this.maxId = maxId;
    }
}


text:
package etcdserver

import "github.com/coreos/etcd/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus"

var (
	// TODO: with label in v3?
	proposeDurations = prometheus.NewSummary(prometheus.SummaryOpts{
		Name: "etcdserver_proposal_durations_milliseconds",
		Help: "The latency distributions of committing proposal.",
	})
	proposePending = prometheus.NewGauge(prometheus.GaugeOpts{
		Name: "etcdserver_pending_proposal_total",
		Help: "The total number of pending proposals.",
	})
	// This is number of proposal failed in client's view.
	// The proposal might be later got committed in raft.
	proposeFailed = prometheus.NewCounter(prometheus.CounterOpts{
		Name: "etcdserver_proposal_failed_total",
		Help: "The total number of failed proposals.",
	})
)

func init() {
	prometheus.MustRegister(proposeDurations)
	prometheus.MustRegister(proposePending)
	prometheus.MustRegister(proposeFailed)
}


text:
package org.apache.hadoop.yarn.server.nodemanager.webapp.dao;

import static org.apache.hadoop.yarn.util.StringHelper.join;
import static org.apache.hadoop.yarn.util.StringHelper.ujoin;

import javax.xml.bind.annotation.*;

import org.apache.hadoop.yarn.api.records.ContainerExitStatus;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.ContainerStatus;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.server.nodemanager.Context;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container;
import org.apache.hadoop.yarn.server.nodemanager.webapp.ContainerLogsUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

@XmlRootElement(name = "container")
@XmlAccessorType(XmlAccessType.FIELD)
public class ContainerInfo {

  protected String id;
  protected String state;
  protected int exitCode;
  protected String diagnostics;
  protected String user;
  protected long totalMemoryNeededMB;
  protected long totalVCoresNeeded;
  protected String containerLogsLink;
  protected String nodeId;
  @XmlTransient
  protected String containerLogsShortLink;
  @XmlTransient
  protected String exitStatus;

  protected List<String> containerLogFiles;

  public ContainerInfo() {
  } // JAXB needs this

  public ContainerInfo(final Context nmContext, final Container container) {
    this(nmContext, container, "", "", "");
  }

  public ContainerInfo(final Context nmContext, final Container container,
       String requestUri, String pathPrefix, String remoteUser) {

    this.id = container.getContainerId().toString();
    this.nodeId = nmContext.getNodeId().toString();
    ContainerStatus containerData = container.cloneAndGetContainerStatus();
    this.exitCode = containerData.getExitStatus();
    this.exitStatus =
        (this.exitCode == ContainerExitStatus.INVALID) ?
            "N/A" : String.valueOf(exitCode);
    this.state = container.getContainerState().toString();
    this.diagnostics = containerData.getDiagnostics();
    if (this.diagnostics == null || this.diagnostics.isEmpty()) {
      this.diagnostics = "";
    }

    this.user = container.getUser();
    Resource res = container.getResource();
    if (res != null) {
      this.totalMemoryNeededMB = res.getMemory();
      this.totalVCoresNeeded = res.getVirtualCores();
    }
    this.containerLogsShortLink = ujoin("containerlogs", this.id,
        container.getUser());

    if (requestUri == null) {
      requestUri = "";
    }
    if (pathPrefix == null) {
      pathPrefix = "";
    }
    this.containerLogsLink = join(requestUri, pathPrefix,
        this.containerLogsShortLink);
    this.containerLogFiles =
        getContainerLogFiles(container.getContainerId(), remoteUser, nmContext);
  }

  public String getId() {
    return this.id;
  }

  public String getNodeId() {
    return this.nodeId;
  }

  public String getState() {
    return this.state;
  }

  public int getExitCode() {
    return this.exitCode;
  }

  public String getExitStatus() {
    return this.exitStatus;
  }

  public String getDiagnostics() {
    return this.diagnostics;
  }

  public String getUser() {
    return this.user;
  }

  public String getShortLogLink() {
    return this.containerLogsShortLink;
  }

  public String getLogLink() {
    return this.containerLogsLink;
  }

  public long getMemoryNeeded() {
    return this.totalMemoryNeededMB;
  }

  public long getVCoresNeeded() {
    return this.totalVCoresNeeded;
  }

  public List<String> getContainerLogFiles() {
    return this.containerLogFiles;
  }

  private List<String> getContainerLogFiles(ContainerId id, String remoteUser,
      Context nmContext) {
    List<String> logFiles = new ArrayList<>();
    try {
      List<File> logDirs =
          ContainerLogsUtils.getContainerLogDirs(id, remoteUser, nmContext);
      for (File containerLogsDir : logDirs) {
        File[] logs = containerLogsDir.listFiles();
        if (logs != null) {
          for (File log : logs) {
            if (log.isFile()) {
              logFiles.add(log.getName());
            }
          }
        }
      }
    } catch (Exception ye) {
      return logFiles;
    }
    return logFiles;
  }

}


text:
package com.brain.jd.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.brain.jd.R;
import com.brain.jd.domain.RProductListBean;
import com.bumptech.glide.Glide;

import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

/**
 * @author : Brian
 * @date : 2017/7/19
 */

public class ProductListViewAdapter extends JDBaseAdapter<RProductListBean.RProductInfoBean> {

    public ProductListViewAdapter(Context ctx) {
        super(ctx);
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = View.inflate(mContext, R.layout.product_lv_item, null);
            holder = new ViewHolder();
            x.view().inject(holder, convertView);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        RProductListBean.RProductInfoBean rProductInfoBean = mData.get(position);

        Glide.with(mContext)
                .load(rProductInfoBean.getIconUrl())
                .into(holder.product_iv);

        holder.name_tv.setText(rProductInfoBean.getName());
        holder.price_tv.setText("" + (int) rProductInfoBean.getPrice() + "");
        holder.commrate_tv.setText(rProductInfoBean.getCommentCount());
        return convertView;
    }

    static class ViewHolder{
        @ViewInject(R.id.product_iv)
        ImageView product_iv;

        @ViewInject(R.id.name_tv)
        TextView name_tv;

        @ViewInject(R.id.commrate_tv)
        TextView commrate_tv;

        @ViewInject(R.id.price_tv)
        TextView price_tv;

        @ViewInject(R.id.shop_car_iv)
        ImageView shop_car_iv;
    }
}


text:
layout: post
title: Developing environment
description: "The choice of developing environment"
modified: 2015-12-13
---

I didn't write anything about the developing environment that I was planning to use in the former blogpost, because I hadn't decided which one to use then. I've decided to go for JetBrains WebStorm. The license is free for students and all you need is a valid student e-mail address. More information could be found here: https://www.jetbrains.com/student/

I'm dreaming of a nice, fancy blog, but then I realize I have to prioritize my time. I could spend a lot of time to setting up a blog or I could add a not-so-fancy textfile to the blog repository in my GitHub account... My decision is to use the textfile version even if it hurts a bit, but my experience tells me to spend my time on Javascript, React and Redux instead.

I think it's a bit frustrating not to have a WYSIWYG tool for writing md-files. But I found one that I think works pretty well. I case you haven't tried, here it is: http://dillinger.io

>Dillinger is a cloud-enabled, mobile-ready, offline-storage, AngularJS powered HTML5 Markdown editor.


text:
<?php
/**
 * Message translations.
 *
 * This file is automatically generated by 'yii message' command.
 * It contains the localizable messages extracted from source code.
 * You may modify this file by translating the extracted messages.
 *
 * Each array element represents the translation (value) of a message (key).
 * If the value is empty, the message is considered as not translated.
 * Messages that no longer need translation will have their translations
 * enclosed between a pair of '@@' marks.
 *
 * Message string can be used with plural forms format. Check i18n section
 * of the guide for details.
 *
 * NOTE: this file must be saved in UTF-8 encoding.
 */
return [
    'An error occured while creating folder "{folder}" on server "{host}"' => '',
    'Could change mode (to "{mode}") of file "{file}" on server "{host}"' => '',
    'Could not delete file "{file}" on server "{host}"' => '',
    'Could not get modification time of file "{file}" on server "{host}"' => '',
    'Could not get size of file "{file}" on server "{host}"' => '',
    'Could not go to "{folder}" on server "{host}"' => '',
    'Could not login to SFTP server "{host}" on port "{port}" with user "{user}" using RSA key.' => '',
    'Could not login to SFTP server "{host}" on port "{port}" with user "{user}".' => '',
    'Could not login to SFTP server "{host}" on port "{port}" without username.' => '',
    'Could not put file "{local_file}" on "{remote_file}" on server "{host}"' => '',
    'Could not read folder "{folder}" on server "{host}"' => '',
    'Could not rename file "{oldname}" to "{newname}" on server "{host}"' => '',
    'Could not synchronously get file "{remote_file}" from server "{host}"' => '',
    '{keyType} key file "{keyFile}" could not be read.' => '',
    '{keyType} key file "{keyFile}" does not exists.' => '',
];


text:
<?xml version="1.0" encoding="UTF-8"?>
<CustomObjectTranslation xmlns="http://soap.sforce.com/2006/04/metadata">
    <layouts>
        <layout>EDA Incident Layout</layout>
        <sections>
            Champs

Fields

        </sections>
        <sections>
            Liens personnalisés

Custom Links

        </sections>
    </layouts>
</CustomObjectTranslation>


text:
using System;
using System.Xml.Serialization;

namespace Aop.Api.Domain
{
    /// <summary>
    /// AlipayPcreditLoanApplyQueryModel Data Structure.
    /// </summary>
    [Serializable]
    public class AlipayPcreditLoanApplyQueryModel : AopObject
    {
        /// <summary>
        /// 贷款申请单号,借呗客户申请贷款时系统生成的全局唯一业务流水号
        /// </summary>
        [XmlElement("loan_apply_no")]
        public string LoanApplyNo { get; set; }
    }
}


text:
from tastypie import fields
from tastypie.resources import ModelResource

from school import models

import datetime

class BehaviourResource(ModelResource):
    class Meta:
        queryset = models.Behaviour.objects.all()
        resource_name = 'behaviour'
        excludes = ['id']

class PointResource(ModelResource):
    behaviour = fields.ForeignKey(BehaviourResource, 'behaviour', full=True, null=True, blank=True)
    class Meta:
        queryset = models.Point.objects.all()
        resource_name = 'behaviour'
        fields = ['behaviour']

class AttendanceResource(ModelResource):
    point = fields.ToManyField(PointResource, 'point_set', full=True, null=True, blank=True)
    class Meta:
        queryset = models.Attendance.objects.all()
        resource_name = 'attendance'
        excludes = ['id']

def attendance_set(bundle):
    try:
        date = datetime.date(year=int(bundle.request.GET['year']), month=int(bundle.request.GET['month']), day=int(bundle.request.GET['day']))
    except (KeyError, ValueError) as e:
        date = datetime.date.today()
    return bundle.obj.attendance_set.filter(date=date)

class UserResource(ModelResource):

    attendances = fields.ToManyField(AttendanceResource, attendance_set, full=True, null=True, blank=True)
    class Meta:
        queryset = models.User.objects.all()
        resource_name = 'user'
        fields = ['first_name', 'last_name', 'username']


text:
/*
 * XYLineAndShapeRendererWithHighlight.java
 *
 * Created on February 13, 2008, 3:39 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.opensim.view.functionEditor;

import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;

/**
 *
 * @author Ayman
 */
public abstract class XYLineAndShapeRendererWithHighlight extends XYLineAndShapeRenderer {

    /** Creates a new instance of XYLineAndShapeRendererWithHighlight */
    public XYLineAndShapeRendererWithHighlight() {
    }
    abstract public void highlightNode(int function, int point) ;

    abstract public void unhighlightNode(int function, int point) ;

}


text:
<?php
/**
 * PHP Version 5.6
 * @category Library
 * @package ChangeLog
 * @author Emlyn West <emlyn.west@gmail.gom>
 * @license MIT http://opensource.org/licenses/MIT
 * @link https://github.com/emlynwest/changelog
 */

namespace ChangeLog\IO;

use ChangeLog\AbstractIO;
use InvalidArgumentException;
use Milo\Github\Api;
use Milo\Github\OAuth\Token;

abstract class AbstractGitHubIO extends AbstractIO
{

	/**
	 * @var Api
	 */
	protected $api;

	/**
	 * Gets an active connection to the GitHub api.
	 *
	 * @return Api
	 */
	protected function getApi()
	{
		if ($this->api === null)
		{
			$this->createApiInstance();
		}

		return $this->api;
	}

	/**
	 * Creates a new instance of the API library to use later.
	 *
	 * @throws InvalidArgumentException
	 */
	protected function createApiInstance()
	{
		$configToken = $this->getConfig('token');

		if ($configToken === null)
		{
			throw new InvalidArgumentException('API token has not been set in the config.');
		}

		$token = new Token($configToken);
		$this->api = new Api();
		$this->api->setToken($token);
	}

}


text:
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from '../../services/auth.service';

@Injectable()
export class LoginGuard implements CanActivate {
    private dashboardRoute = '/dashboard';

    constructor(private authService: AuthService, private router: Router) {}

    canActivate(): boolean {
        if (!this.authService.loggedIn()) { return true; }

        this.router.navigate([this.dashboardRoute]);
        return false;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2008 The Android Open Source Project

     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.
-->

<!--
    TODO: Use localizable string resources instead of hard-coded strings
    once Search Manager is enhanced to allow them.
-->
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:icon="@drawable/ic_tab_contacts"
    android:label="@string/contactsList"
    android:hint="@string/searchHint"
    android:searchMode="queryRewriteFromText"

    android:searchSuggestAuthority="contacts"
    android:searchSuggestIntentAction="android.provider.Contacts.SEARCH_SUGGESTION_CLICKED"
    android:searchSuggestIntentData="content://contacts/people"
>

    <!-- allow green action key for search-bar and per-suggestion clicks -->
    <actionkey
        android:keycode="KEYCODE_CALL"
        android:queryActionMsg="call"
        android:suggestActionMsg="call"
    />

</searchable>