text:
package org.abratuhi.mavendepbuilder;

import org.abratuhi.mavendepbuilder.model.JavaClass;
import org.abratuhi.mavendepbuilder.model.Project;
import org.junit.jupiter.api.Test;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Set;
import java.util.TreeSet;

import static org.junit.jupiter.api.Assertions.*;

/**
 * @author Alexei Bratuhin
 */
public class MavenDependencyBuilderTest {

	@Test
	public void testProjectEquals() {
		Project p1 = new Project(1, "project", new HashMap<>(), new TreeSet<>(), true, false);
		Project p2 = new Project(2, "project", new HashMap<>(), null, false, false);
		assertEquals(p1, p2);
	}

	@Test
	public void testProjectNotEquals() {
		Project p1 = new Project(1, "project1", new HashMap<>(), null, false, false);
		Project p2 = new Project(1, "project2", new HashMap<>(), null, false, false);
		assertNotEquals(p1, p2);
	}

	@Test
	void testVisitDirectory() throws IOException {
		MavenDependencyBuilder mdb = new MavenDependencyBuilder();
		Set<Project> projects = mdb.visitDirectory(new File("src/test/resources/payara-issue-959-deps-0"));
		assertEquals(4, projects.size());
	}

	@Test
	void testVisitJavaClass() throws IOException {
		MavenDependencyBuilder mdb = new MavenDependencyBuilder();
		JavaClass javaClass = mdb.visitJavaClass(new File("src/test/resources/payara-issue-959-deps-0/payara-issue-959-ejb/src/main/java/org/abratuhi/payara/issue959/PayaraIssue959Impl.java"));
		assertNotNull(javaClass);
		assertEquals("org.abratuhi.payara.issue959.PayaraIssue959Impl", javaClass.getName());
		assertEquals("org.abratuhi.payara.issue959", javaClass.getPakkage());
		assertEquals(4, javaClass.getImports().size());
	}

	@Test
	void testVisitExcludedDirectory() throws IOException {
		MavenDependencyBuilder mdb = new MavenDependencyBuilder(Set.of("payara-issue-959-deps-0"));
		Set<Project> projects = mdb.visitDirectory(new File("src/test/resources/payara-issue-959-deps-0"));
		assertNotNull(projects);
		assertTrue(projects.isEmpty());
	}

	@Test
	public void testVisitParentInDependencies() throws IOException {
		MavenDependencyBuilder mdb = new MavenDependencyBuilder();
		Set<Project> projects = mdb.visitDirectory(new File("src/test/resources/payara-issue-959-deps-1"));
		assertNotNull(projects);
		Project projectApi = projects.stream().filter(project -> project.getName().contains("api")).findFirst().orElse(null);
		assertNotNull(projectApi);
		assertTrue(projectApi.getDependencies().containsKey("org.abratuhi:payara-issue-959"));
	}
}


text:
<?php

namespace Respect\Config;

use ReflectionClass;

class Instantiator
{
    const MODE_DEPENDENCY = false;
    const MODE_FACTORY = 'new';

    protected $instance;
    protected $reflection;
    protected $constructor = array();
    protected $className;
    protected $params = array();
    protected $staticMethodCalls = array();
    protected $methodCalls = array();
    protected $propertySetters = array();
    protected $mode = self::MODE_DEPENDENCY;

    public function __construct($className)
    {
        if (false !== stripos($className, ' ')) {
            list($mode, $className) = explode(' ', $className, 2);
            $this->mode = $mode;
        }
        $this->reflection = new ReflectionClass($className);
        $this->constructor = $this->findConstructorParams($this->reflection);
        $this->className = $className;
    }

    public function getMode()
    {
        return $this->mode;
    }

    public function __invoke()
    {
        return call_user_func_array(array($this, 'getInstance'), func_get_args());
    }

    public function getClassName()
    {
        return $this->className;
    }

    public function getInstance($forceNew = false)
    {
        if ($this->mode == static::MODE_FACTORY) {
            $this->instance = null;
        }

        if ($this->instance && !$forceNew) {
            return $this->instance;
        }

        $className     = $this->className;
        $staticMethods = count($this->staticMethodCalls);
        foreach ($this->staticMethodCalls as $methodCalls) {
            $this->performMethodCalls(
                $className,
                $methodCalls,
                function ($result) use ($className, &$instance, $staticMethods) {
                    if ($result instanceof $className || ($staticMethods == 1 && is_object($result))) {
                        $instance = $result;
                    }
                }
            );
        }

        $constructor     = $this->reflection->getConstructor();
        $hasConstructor  = ($constructor) ? $constructor->isPublic() : false;
        if (empty($instance)) {
            if (empty($this->constructor) || !$hasConstructor) {
                $instance = new $className();
            } else {
                $instance = $this->reflection->newInstanceArgs(
                    $this->cleanupParams($this->constructor)
                );
            }
        }

        foreach ($this->propertySetters as $property => $value) {
            $instance->{$property} = $this->lazyLoad($value);
        }

        foreach ($this->methodCalls as $methodCalls) {
            $this->performMethodCalls($instance, $methodCalls);
        }

        return $this->instance = $instance;
    }

    public function getParam($name)
    {
        return $this->params[$name];
    }

    public function setInstance($instance)
    {
        $this->instance = $instance;
    }

    public function setParam($name, $value)
    {
        $value = $this->processValue($value);

        if ($this->matchStaticMethod($name)) {
            $this->staticMethodCalls[] = array($name, $value);
        } elseif ($this->matchConstructorParam($name)) {
            $this->constructor[$name] = $value;
        } elseif ($this->matchFullConstructor($name, $value)) {
            $this->constructor = $value;
        } elseif ($this->matchMethod($name)) {
            $this->methodCalls[] = array($name, $value);
        } else {
            $this->propertySetters[$name] = $value;
        }

        $this->params[$name] = $value;
    }

    public function getParams()
    {
        return $this->params;
    }

    protected function cleanupParams(array $params)
    {
        while (null === end($params)) {
            unset($params[key($params)]);
        }

        foreach ($params as &$p) {
            $p = $this->lazyLoad($p);
        }

        return $params;
    }

    protected function lazyLoad($value)
    {
        return $value instanceof self ? $value->getInstance() : $value;
    }

    protected function findConstructorParams(ReflectionClass $class)
    {
        $params = array();
        $constructor = $class->getConstructor();

        if (!$constructor) {
            return array();
        }

        foreach ($constructor->getParameters() as $param) {
            $params[$param->getName()] = $param->isDefaultValueAvailable() ?
                $param->getDefaultValue() : null;
        }

        return $params;
    }

    protected function processValue($value)
    {
        if (is_array($value)) {
            foreach ($value as $valueKey => $subValue) {
                $value[$valueKey] = $this->processValue($subValue);
            }
        }

        return $value;
    }

    protected function matchConstructorParam($name)
    {
        return array_key_exists($name, $this->constructor);
    }

    protected function matchFullConstructor($name, &$value)
    {
        return $name == '__construct'
        || ($name == $this->className && stripos($this->className, '\\'));
    }

    protected function matchMethod($name)
    {
        return $this->reflection->hasMethod($name);
    }

    protected function matchStaticMethod($name)
    {
        return $this->reflection->hasMethod($name)
        && $this->reflection->getMethod($name)->isStatic();
    }

    protected function performMethodCalls($class, array $methodCalls, $resultCallback = null)
    {
        list($methodName, $calls) = $methodCalls;
        $resultCallback = $resultCallback ?: function () {

        };

        foreach ($calls as $arguments) {
            if (is_array($arguments)) {
                $resultCallback(call_user_func_array(
                    array($class, $methodName),
                    $this->cleanUpParams($arguments)
                ));
            } elseif (!is_null($arguments)) {
                $resultCallback(call_user_func(array($class, $methodName), $this->lazyLoad($arguments)));
            } else {
                $resultCallback(call_user_func(array($class, $methodName)));
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.semagrow.plan.querygraph;

import org.eclipse.rdf4j.query.algebra.ValueExpr;

/**
 * Created by angel on 23/6/2016.
 */
public class FilterPredicate extends QueryPredicate {

    public FilterPredicate(ValueExpr valueExpr) {
        this.valueExpr = valueExpr;
    }

    private ValueExpr valueExpr;

}


text:
require 'jsduck/logger'

module JsDuck
  module Process

    # Reports bugs and problems in documentation
    class Lint
      attr_accessor :relations

      def initialize(relations)
        @relations = relations
      end

      # Runs the linter
      def process_all!
        warn_unnamed
        warn_optional_params
        warn_duplicate_params
        warn_duplicate_members
        warn_singleton_statics
        warn_empty_enums
      end

      # print warning for each member or parameter with no name
      def warn_unnamed
        each_member do |member|
          if !member[:name] || member[:name] == ""
            warn(:name_missing, "Unnamed #{member[:tagname]}", member)
          end
          (member[:params] || []).each do |p|
            if !p[:name] || p[:name] == ""
              warn(:name_missing, "Unnamed parameter", member)
            end
          end
        end
      end

      # print warning for each non-optional parameter that follows an optional parameter
      def warn_optional_params
        each_member do |member|
          if member[:tagname] == :method
            optional_found = false
            member[:params].each do |p|
              if optional_found && !p[:optional]
                warn(:req_after_opt, "Optional param followed by regular param #{p[:name]}", member)
              end
              optional_found = optional_found || p[:optional]
            end
          end
        end
      end

      # print warnings for duplicate parameter names
      def warn_duplicate_params
        each_member do |member|
          params = {}
          (member[:params] || []).each do |p|
            if params[p[:name]]
              warn(:dup_param, "Duplicate parameter name #{p[:name]}", member)
            end
            params[p[:name]] = true
          end
        end
      end

      # print warnings for duplicate member names
      def warn_duplicate_members
        @relations.each do |cls|
          members = {:members => {}, :statics => {}}
          cls.all_local_members.each do |m|
            group = m[:static] ? :statics : :members
            type = m[:tagname]
            name = m[:name]
            hash = members[group][type] || {}
            if hash[name]
              warn(:dup_member, "Duplicate #{type} name #{name}", hash[name])
              warn(:dup_member, "Duplicate #{type} name #{name}", m)
            end
            hash[name] = m
            members[group][type] = hash
          end
        end
      end

      # Print warnings for static members in singleton classes
      def warn_singleton_statics
        @relations.each do |cls|
          if cls[:singleton]
            cls.find_members({:local => true, :static => true}).each do |m|
              warn(:sing_static, "Static members don't make sense in singleton class #{cls[:name]}", m)
            end
          end
        end
      end

      # print warnings for enums with no values
      def warn_empty_enums
        @relations.each do |cls|
          if cls[:enum] && cls[:members].length == 0
            warn(:enum, "Enum #{cls[:name]} defined without values in it", cls)
          end
        end
      end

      # Loops through all members of all classes
      def each_member(&block)
        @relations.each {|cls| cls.all_local_members.each(&block) }
      end

      # Prints warning + filename and linenumber from doc-context
      def warn(type, msg, member)
        Logger.warn(type, msg, member[:files][0])
      end

    end

  end
end


text:
class DebugSettings(object):
    DEBUG_TOOLBAR_ENABLED = False

    DEBUG_TOOLBAR_CONFIG = {
        'INTERCEPT_REDIRECTS': False,
        'SHOW_TOOLBAR_CALLBACK': lambda x: True,
        'HIDE_DJANGO_SQL': False,
    }

    # Empty for no logging
    # Don't use with SENTRY_DSN together, this will take prescendence
    # http://raven.readthedocs.org/en/latest/config/django.html
    RAVEN_CONFIG = {
        'dsn': '',  # http://public:secret@example.com/1
    }


text:
package org.pmg.jms.genclient;

import java.util.concurrent.Executor;
import javax.jms.JMSException;
import javax.jms.Message;

/**
 * Handles message routing and invokes state machine iteration
 * @author peter
 */
public interface Deliverable {

    public Executor getExecutor();
    public Routable handle(Message message) throws JMSException;
    public void setRoute(String route);
}


text:
@class ScreenshotDelegate;
// TODO(crbug.com/1045560): Refactor this class to not use
// BrowserInterfaceProvider when possible.
@protocol BrowserInterfaceProvider;

// ScreenshotDelegate provides methods for UIScreenshotServiceDelegate to create
// PDF content of the captured window scene.
@interface ScreenshotDelegate : NSObject <UIScreenshotServiceDelegate>

// Init the ScreenshotDelegate and set the `browserInterfaceProvider` to
// generate PDF screenshots from.
- (instancetype)initWithBrowserInterfaceProvider:
    (id<BrowserInterfaceProvider>)browserInterfaceProvider
    NS_DESIGNATED_INITIALIZER;

- (instancetype)init NS_UNAVAILABLE;

@end

#endif  // IOS_CHROME_BROWSER_SCREENSHOT_SCREENSHOT_DELEGATE_H_


text:
layout: default
modal-id: 8
date: 2013-10-20
img: abaa.png
alt: A Beard Across America
project-date: October 2013
project: A Beard Across America
siteurl: http://abeardacrossamerica.com
category: Wrote A Book
description: A Beard Across America is filled with inspiring and motivating stories that capture Beard's road-trip across America. Compiled of stories written to help readers look at something "impossible" and redefine it as not only achievable, but achievable a lot quicker than expected.

---


text:
package gov.nasa.ensemble.common;

import static fj.data.Option.*;
import static gov.nasa.ensemble.common.extension.ClassRegistry.*;

import java.util.List;

import fj.data.Option;

public class LazyProperties {

	private final static List<ILazyPropertiesProvider> providers = createInstances(ILazyPropertiesProvider.class);

	public static Option<String> getProperty(String key) {
		for (final ILazyPropertiesProvider provider : providers) {
			final Option<String> result = provider.getProperty(key);
			if (result.isSome())
				return result;
		}
		return none();
	}
}


text:
package org.switchyard.quickstarts.camel.sap.binding.composer;

import java.util.Map.Entry;
import java.util.Set;

import javax.activation.DataHandler;

import org.fusesource.camel.component.sap.SapSynchronousRfcDestinationEndpoint;
import org.fusesource.camel.component.sap.model.rfc.Structure;
import org.fusesource.camel.component.sap.model.rfc.Table;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.switchyard.Exchange;
import org.switchyard.Message;
import org.switchyard.component.camel.common.composer.CamelBindingData;
import org.switchyard.component.camel.common.composer.CamelMessageComposer;
import org.switchyard.quickstarts.camel.sap.binding.bean.FlightCustomerInfo;
import org.switchyard.quickstarts.camel.sap.binding.jaxb.BookFlightRequest;

/**
 * A MessageComposer for GetFlightCustomerListService.
 */
public class FlightCustomerInfoMessageComposer extends CamelMessageComposer {
    private static final Logger LOG = LoggerFactory.getLogger(FlightCustomerInfoMessageComposer.class);

    @Override
    public CamelBindingData decompose(Exchange exchange, CamelBindingData target) throws Exception {
        CamelBindingData response = super.decompose(exchange, target);

        // Get BOOK_FLIGHT Request JAXB Bean object.
        BookFlightRequest bookFlightRequest = exchange.getMessage().getContent(BookFlightRequest.class);

        // Create SAP Request object from target endpoint.
        SapSynchronousRfcDestinationEndpoint endpoint = target.getMessage().getExchange().getContext().getEndpoint("sap-srfc-destination:nplDest:BAPI_FLCUST_GETLIST", SapSynchronousRfcDestinationEndpoint.class);
        Structure request = endpoint.createRequest();

        // Add Customer Name to request if set
        if (bookFlightRequest.getCustomerName() != null && bookFlightRequest.getCustomerName().length() > 0) {
            request.put("CUSTOMER_NAME", bookFlightRequest.getCustomerName());
            if (LOG.isDebugEnabled()) {
                LOG.debug("Added CUSTOMER_NAME = '{}' to request", bookFlightRequest.getCustomerName());
            }
        } else {
            throw new Exception("No Customer Name");
        }

        // Put request object into body of exchange message.
        response.getMessage().setBody(request);
        return response;
    }

    @Override
    public Message compose(CamelBindingData source, Exchange exchange) throws Exception {
        Message response = exchange.createMessage();

        // map context properties
        getContextMapper().mapFrom(source, exchange.getContext(response));

        Set<String> attachements = source.getMessage().getAttachmentNames();
        if (!attachements.isEmpty()) {
            for (Entry<String, DataHandler> entry : source.getMessage().getAttachments().entrySet()) {
                response.addAttachment(entry.getKey(), entry.getValue().getDataSource());
            }
        }

        // Retrieve SAP response object from body of exchange message.
        Structure flightCustomerGetListResponse = source.getMessage().getBody(Structure.class);

        if (flightCustomerGetListResponse == null) {
            throw new Exception("No Flight Customer Get List Response");
        }

        // Check BAPI return parameter for errors
        @SuppressWarnings("unchecked")
        Table<Structure> bapiReturn = flightCustomerGetListResponse.get("RETURN", Table.class);
        Structure bapiReturnEntry = bapiReturn.get(0);
        if (!bapiReturnEntry.get("TYPE", String.class).equals("S")) {
            String message = bapiReturnEntry.get("MESSAGE", String.class);
            throw new Exception("BAPI call failed: " + message);
        }

        // Get customer list table from response object.
        @SuppressWarnings("unchecked")
        Table<? extends Structure> customerList = flightCustomerGetListResponse.get("CUSTOMER_LIST", Table.class);

        if (customerList == null || customerList.size() == 0) {
            throw new Exception("No Customer Info.");
        }

        // Get Flight Customer data from first row of table.
        Structure customer = customerList.get(0);

        // Create bean to hold Flight Customer data.
        FlightCustomerInfo flightCustomerInfo = new FlightCustomerInfo();

        // Get customer id from Flight Customer data and add to bean.
        String customerId = customer.get("CUSTOMERID", String.class);
        if (customerId != null) {
            flightCustomerInfo.setCustomerNumber(customerId);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Set customer number = '{}' in flight customer info", customerId);
            }
        }

        // Get customer name from Flight Customer data and add to bean.
        String customerName = customer.get("CUSTNAME", String.class);
        if (customerName != null) {
            flightCustomerInfo.setName(customerName);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Set customer name = '{}' in flight customer info", customerName);
            }
        }

        // Get customer form of address from Flight Customer data and add to bean.
        String formOfAddress = customer.get("FORM", String.class);
        if (formOfAddress != null) {
            flightCustomerInfo.setFormOfAddress(formOfAddress);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Set form of address = '{}' in flight customer info", formOfAddress);
            }
        }

        // Get customer street name from Flight Customer data and add to bean.
        String street = customer.get("STREET", String.class);
        if (street != null) {
            flightCustomerInfo.setStreet(street);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Set street = '{}' in flight customer info", street);
            }
        }

        // Get customer PO box from Flight Customer data and add to bean.
        String poBox = customer.get("POBOX", String.class);
        if (poBox != null) {
            flightCustomerInfo.setPoBox(poBox);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Set PO box = '{}' in flight customer info", poBox);
            }
        }

        // Get customer postal code from Flight Customer data and add to bean.
        String postalCode = customer.get("POSTCODE", String.class);
        if (postalCode != null) {
            flightCustomerInfo.setPostalCode(postalCode);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Set postal code = '{}' in flight customer info", postalCode);
            }
        }

        // Get customer city name from Flight Customer data and add to bean.
        String city = customer.get("CITY", String.class);
        if (city != null) {
            flightCustomerInfo.setCity(city);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Set city = '{}' in flight customer info", city);
            }
        }

        // Get customer country name from Flight Customer data and add to bean.
        String country = customer.get("COUNTR", String.class);
        if (country != null) {
            flightCustomerInfo.setCountry(country);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Set country = '{}' in flight customer info", country);
            }
        }

        // Get customer country ISO code from Flight Customer data and add to bean.
        String countryIso = customer.get("COUNTR_ISO", String.class);
        if (countryIso != null) {
            flightCustomerInfo.setCountryIso(countryIso);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Set iso country code = '{}' in flight customer info", countryIso);
            }
        }

        // Get customer region name from Flight Customer data and add to bean.
        String region = customer.get("REGION", String.class);
        if (region != null) {
            flightCustomerInfo.setRegion(region);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Set region = '{}' in flight customer info", region);
            }
        }

        // Get customer phone number from Flight Customer data and add to bean.
        String phone = customer.get("PHONE", String.class);
        if (phone != null) {
            flightCustomerInfo.setPhone(phone);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Set phone = '{}' in flight customer info", phone);
            }
        }

        // Get customer email from Flight Customer data and add to bean.
        String email = customer.get("EMAIL", String.class);
        if (email != null) {
            flightCustomerInfo.setEmail(email);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Set email = '{}' in flight customer info", email);
            }
        }

        // Put flight customer info bean
        response.setContent(flightCustomerInfo);
        return response;
    }

}


text:
package cn.xiexianbin.packages.alibaba.aliyun.oss;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.model.Bucket;
import com.aliyun.openservices.oss.model.CannedAccessControlList;
import cn.xiexianbin.packages.baidu.ueditor.upload.AsynUploaderThreader;

/**
 * Bucket是OSS上的命名空间,也是计费、权限控制、日志记录等高级功能的管理实体;Bucket名称在整个OSS服务中具有全局唯一性,且不能修改;
 * 存储在OSS上的每个Object必须都包含在某个Bucket中
 * 。一个应用,例如图片分享网站,可以对应一个或多个Bucket。一个用户最多可创建10个Bucket
 * ,但每个Bucket中存放的Object的数量和大小总和没有限制,用户不需要考虑数据的可扩展性。
 *
 * @author XieXianbin me@xiexianbin.cn
 */
public class BucketService {

	private static final Logger logger = LoggerFactory.getLogger(AsynUploaderThreader.class);

	/**
	 * 创建一个Bucket,如果创建成功,则返回新的Bucket

	 *
	 * Bucket命名规则:

	 * 只能包括小写字母,数字,短横线(-)

	 * 必须以小写字母或者数字开头

	 * 长度必须在3-63字节之间
	 *
	 * @param client OSSClient
	 * @param bucketName OSS bucket name
	 * @return OSS bucket
	 */
	public static Bucket create(OSSClient client, String bucketName) {
		Bucket bucket = client.createBucket(bucketName);
		return bucket;
	}

	/**
	 * 列出用户所有的Bucket

	 *
	 * @param client client
	 * @return buckets buckets
	 */
	public static List<Bucket> list(OSSClient client) {
		List<Bucket> buckets = client.listBuckets();
		return buckets;
	}

	/**
	 * 判断Bucket是否存在

	 *
	 * @param client client
	 * @param bucketName bucketName
	 * @return boolean exists
	 */
	public static boolean doesBucketExist(OSSClient client, String bucketName) {
		// 获取Bucket的存在信息
		boolean exists = client.doesBucketExist(bucketName);
		// 输出结果
		if (exists) {
			logger.debug("Bucket: " + bucketName + " is exists");
		} else {
			logger.debug("Bucket: " + bucketName + " is not exists");
		}
		return exists;
	}

	/**
	 * 删除Bucket

	 * 如果Bucket不为空(Bucket中有Object),则Bucket无法删除,必须清空Bucket后才能成功删除
	 *
	 * @param client client
	 * @param bucketName bucketName
	 */
	public static void delete(OSSClient client, String bucketName) {
		client.deleteBucket(bucketName);
	}

	/**
	 * Bucket权限控制
	 *
	 * public-read-write:
	 * 任何人(包括匿名访问)都可以对该bucket中的object进行上传、下载和删除操作;所有这些操作产生的费用由该bucket的创建者承担
	 * ,请慎用该权限。

	 * public-read: 只有该bucket的创建者可以对该bucket内的Object进行写操作(包括上传和删除);任何人(包括匿名访问)
	 * 可以对该bucket中的object进行读操作。

	 * private: 只有该bucket的创建者才可以访问此Bukcet。其他人禁止对此Bucket做任何操作。

	 *
	 * @param client client
	 * @param bucketName bucketName
	 * @param acl

	 * 			CannedAccessControlList是枚举类型,包含三个值: Private 、 PublicRead 、 PublicReadWrite ,它们分别对应相关权限
	 */
	public static void setBucketAcl(OSSClient client, String bucketName, CannedAccessControlList acl) {
		client.setBucketAcl(bucketName, acl);
	}

}


text:
package skadistats.clarity.decoder.unpacker;

import skadistats.clarity.decoder.bitstream.BitStream;

public class FloatDefaultUnpacker implements Unpacker<Float> {

    private final int bitCount;
    private final float minValue;
    private final float maxValue;
    private final float decodeMultiplier;

    public FloatDefaultUnpacker(int bitCount, float minValue, float maxValue) {
        this.bitCount = bitCount;
        this.minValue = minValue;
        this.maxValue = maxValue;
        this.decodeMultiplier = 1.0f / ((1 << bitCount) - 1);
    }

    @Override
    public Float unpack(BitStream bs) {
        float v = bs.readUBitInt(bitCount) * decodeMultiplier;
        return minValue + (maxValue - minValue) * v;
    }

}


text:
.app-welcome-features-different {
  background: url(../images/different.jpg) no-repeat center center fixed;

}
.app-welcome-features-open {
  background: url(../images/open.jpg) no-repeat center center fixed;

}
.app-welcome-features-massive {
  background: url(../images/massive.jpg) no-repeat center center fixed;

}
.app-welcome-features-lab {
  background: url(../images/lab.jpg) no-repeat center center fixed;

}
.app-welcome-features-explore {
  background: url(../images/explore.jpg) no-repeat center center fixed;

}
.app-welcome-content-text {
	background-color: #FFFFFF;
	padding: 5px;
}
.app-welcome-features-meem {
  background: url(../images/meem.jpg) no-repeat center center fixed;

}
.app-welcome-how-item.active-item {
	border-bottom: solid 4px #006DCC;
}
.app-welcome-how-item {
	border-bottom: solid 4px transparent;
}
.app-welcome-how-content {
	width : 100%;
	-webkit-background-size: cover;
  	-moz-background-size: cover;
  	-o-background-size: cover;
  	background-size: cover;
  	min-height: 700px;
}
.app-welcome-how-content .jumbotron {
	background-color: transparent;
}


text:
class FormatPauper < FormatVintage
  def format_pretty_name
    "Pauper"
  end

  def in_format?(card)
    return false if card.funny
    card.printings.each do |printing|
      next if @time and printing.release_date > @time
      next if @excluded_sets.include?(printing.set_code)
      return true if printing.rarity == "common" or printing.rarity == "basic"
    end
    false
  end
end


text:
#include "modules/drivers/canbus/sensor_gflags.h"

// System gflags
DEFINE_string(node_name, "chassis", "The chassis module name in proto");
DEFINE_string(hmi_name, "canbus", "Module name in HMI");

DEFINE_string(adapter_config_filename, "modules/canbus/conf/adapter.conf",
              "The adapter config file");

// data file
DEFINE_string(sensor_conf_file, "", "Sensor conf file");

// Canbus gflags
DEFINE_double(sensor_freq, 100,
              "Sensor feedback timer frequency -- 0 means event trigger.");

// System gflags
DEFINE_string(sensor_node_name, "", "Sensor node name.");


text:
package com.tvd12.ezyfox.database.mapservice;

public interface EzyPutValuesService<V> {

    void put(Iterable<V> values);
}


text:
import re
import requests
import json
from datetime import datetime
from sh import tail

'''
POST data should be of the form:
	{
		## REQUIRED ##
		'time' : <given as epoch>
		'remote_ip' :
		'host_ip' :
		'service': <ssh, telnet, http, ...>
		'type': <vector of attack, i.e. user/pass, reversemapping, etc...>
		'longitude': <longitude coordinates>
		'latitude': <latitiude coordinates>

		## OPTIONAL ##
		'remote_port' :
		'local port' :
		'username' :
		'password' :
		'client_specs' :
		'other' :

		... more from geo ip lookup (i.e. region, country, etc..)
		'city': <city>
		'region_name': <region>
	}

Here are the log entries we are looking for:

	Jul 17 22:34:11 honeypy sshd-22[8837]: IP: 131.252.50.27 PassLog: Username: keene Password: kmkm
	Jul 17 22:36:57 honeypy sshd-22[8866]: Attack From: 101.207.248.14; Client protocol version 2.0; client software version libssh2_1.8.1-20170115; Remote port:
	54538; Local port: 22
	Jul 17 05:33:17 honeypy sshd[1306]: reverse mapping checking getaddrinfo for 119.164.117.124.broad.wl.xj.dynamic.163data.com.cn [124.117.164.119] failed - POSSIBLE BREAK-IN ATTEMPT!
'''

'''
	Splits log-line to return details of attack (information outside of the time stamp)
	on success: returns 'Connection closed by...' from 'Jul 17 22:38:56 honeypy sshd-22[8892]: Connection closed'
	on failure: returns None
'''
def split_line(line):
	#simple rexex to match on the [ppid] element of the log
	split_regex = re.compile("\[\d+\]: ")
	split_line = split_regex.split(line)
	if(not split_line):
		return None
	else:
		return split_line[-1]

'''
	Given a string of attack details, such as Attack From: 101.207.248.14, retrurns a
	dictionary of all attack details - both required and optional (*see specs at file header).
	Must be a valid line according to program header above.
	on success: returns a dicitonary of attack details, inclucing geo_ip information
	on failure: returns {}
'''
def map_event(line):
	#initial key-values
	event = {
		'time': datetime.now().timestamp(),
		'service': 'ssh',
	}

	if line.startswith('Attack From'):
		# example, Attack From: 131.252.50.27; Client protocol version 2.0; client software version OpenSSH_7.4; Remote port: 50597; Local port: 22
		raw_event = line.replace(';','').split(' ')
		event['remote_ip'] = raw_event[2]
		event['local_port'] =  raw_event[16]
		event['remote_port'] =  raw_event[13]
		event['description'] = 'protocol version {}; client software {}'.format(raw_event[6], raw_event[10])
		event['type'] = 'connect'
	elif line.startswith('IP'):
		# example, IP: 131.252.50.27 PassLog: Username: keene Password: kmkm
		raw_event = line.split(' ')
		event['remote_ip'] = raw_event[1]
		event['username'] = raw_event[4]
		#event['password'] = raw_event[6] if len(raw_event) > 6 else ' '
		#password could be raw
		event['password'] = line.split('Password: ')[-1]
		event['type'] = 'password'
	elif line.startswith('reverse mapping checking'):
		# example, reverse mapping checking getaddrinfo for host-79-165-2-209.qwerty.ru [79.165.2.209] failed ...
		raw_event = line.split(' ')
		event['remote_ip'] = re.sub('[\[\]]', '', raw_event[6])
		event['other'] = raw_event[5]
		event['type'] = 'reverse mapping'
	else:
		print('** details: {}\n'.format(_details))
		return {}

	# return all data if geo lookup was a success
	_remote_data = get_geo_data(event['remote_ip'], 'remote')
	if _remote_data != {}:
		event.update(_remote_data)
		return event
	else:
		print('failed to get event {}'.format(event))
		return {}

'''
	get geographic data from freegeoip.net/{format}/{IP_or_hostname} for the given IP
	*note, given <location> must be 'remote' or 'host'
	*note, it uses prepends 'host', 'remote' to the ip, longitidue, and

	returns {'ip' : <ip>, 'city': <city>, 'country', ... }
	returns {} on failure
'''
def get_geo_data(ip, location):
	event = {}
	try:
		#get geographic data from freegeoip.net/{format}/{IP_or_hostname}
		response = requests.get(url='http://www.freegeoip.net/json/{}'.format(ip))
		if response.status_code == 200:
			#prepends 'host_' or 'remote_' to each key on success
			for key, value in dict(response.json()).items():
				event[location + '_' + key] = value
	except Exception as err:
		print('Exception in get_geo_data(): {}\nResponse: {}'.format(err, response.text))
	# return empty dict on failure to lookup/thrown exception
	return event

'''
	iterates over log lines in tail -f like fashion
	posts all relevant attack information to the data store
'''
def main():
	## FILL IN DATA ##
	host_ip = 'XXX.XX.XXX.XXX'
	app_url = 'XXX.XXX.XX:8080/event'
	log_file = '/var/log/auth.log'

	host = get_geo_data(host_ip, 'host')
	host_data = {
		'host_ip': host['host_ip'],
		'host_longitude': host['host_longitude'],
		'host_latitude': host['host_latitude']
	}

	for line in tail('-f', log_file, _iter=True):
		# avoid wasting resources on invalid lines
		if 'IP' not in line and 'Attack From' not in line and 'reverse mapping' not in line:
			continue
		#strip endlines and split
		line = line.replace('\n','')
		details = split_line(line)
		if not details:
			continue

		# map raw data to a JSON post and deliver to data store (don't forget host data)
		event = map_event(details)
		if event != {}:
			event.update(host_data)
			try:
				resp = requests.post(url=app_url, data=json.dumps(event), headers={'Content-Type': 'application/json'})
			except Exception as e:
				print('Error sending payload to server\nPOST Body:{}\nException:{}'.format(event, e))

if __name__ == '__main__':
	main()


text:
package com.thoughtworks.go.config.policy;

import com.thoughtworks.go.config.DelegatingValidationContext;
import com.thoughtworks.go.config.ValidationContext;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;

import java.util.Arrays;
import java.util.List;

import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;

class AbstractDirectiveTest {
    @Nested
    class Validate {
        @Test
        void shouldAddErrorIfActionIsNotSet() {
            Directive directive = getDirective(null, "environment", "test-resource");

            directive.validate(rulesValidationContext(singletonList("view"), singletonList("environment")));

            assertThat(directive.errors()).hasSize(1);
            assertThat(directive.errors().get("action"))
                    .hasSize(1)
                    .contains("Invalid action, must be one of [view].");
        }

        @Test
        void shouldAddErrorIfActionIsSetToOtherThanAllowedActions() {
            Directive directive = getDirective("invalid", "environment", "test-resource");

            directive.validate(rulesValidationContext(singletonList("view"), singletonList("environment")));

            assertThat(directive.errors()).hasSize(1);

            assertThat(directive.errors().get("action"))
                    .hasSize(1)
                    .contains("Invalid action, must be one of [view].");
        }

        @Test
        void shouldNotAllowActionToHaveWildcard() {
            Directive directive = getDirective("*", "environment", "test-resource");

            directive.validate(rulesValidationContext(singletonList("view"), singletonList("environment")));

            assertThat(directive.errors()).hasSize(1);
            assertThat(directive.errors().on("action")).isEqualTo("Invalid action, must be one of [view].");
        }

        @Test
        void shouldAddErrorIfTypeIsNotSet() {
            Directive directive = getDirective("view", null, "test-resource");

            directive.validate(rulesValidationContext(singletonList("view"), singletonList("environment")));

            assertThat(directive.errors()).hasSize(1);
            assertThat(directive.errors().get("type"))
                    .hasSize(1)
                    .contains("Invalid type, must be one of [environment].");
        }

        @Test
        void shouldAddErrorIfTypeIsSetToOtherThanAllowedActions() {
            Directive directive = getDirective("view", "invalid", "test-resource");

            directive.validate(rulesValidationContext(singletonList("view"), singletonList("environment")));

            assertThat(directive.errors()).hasSize(1);

            assertThat(directive.errors().get("type"))
                    .hasSize(1)
                    .contains("Invalid type, must be one of [environment].");
        }

        @Test
        void shouldAllowTypeToHaveWildcard() {
            Directive directive = getDirective("view", "*", "test-resource");

            directive.validate(rulesValidationContext(singletonList("view"), singletonList("environment")));

            assertThat(directive.errors()).hasSize(0);
        }

        @Test
        void shouldNotFailWhenResourceIsEmpty() {
            Directive directive = getDirective("view", "elastic_agent_profile", null);

            directive.validate(rulesValidationContext(singletonList("view"), Arrays.asList("environment", "elastic_agent_profile")));

            assertThat(directive.errors()).hasSize(0);
        }

        @Test
        void shouldNotAddAnErrorForColonSeparatorOnElasticAgentProfileResource() {
            Directive directive = getDirective("view", "elastic_agent_profile", "test:resource");

            directive.validate(rulesValidationContext(singletonList("view"), Arrays.asList("environment", "elastic_agent_profile")));

            assertThat(directive.errors()).hasSize(0);
        }

        @Test
        void shouldAddErrorIfColonSeparatorIsSpecifiedAsResourceForAnyTypeApartFromElasticAgentProfile() {
            Directive directive = getDirective("view", "environment", "test:resource");

            directive.validate(rulesValidationContext(singletonList("view"), Arrays.asList("environment", "elastic_agent_profile")));

            assertThat(directive.errors()).hasSize(1);
            assertThat(directive.errors().get("resource"))
                    .hasSize(1)
                    .contains("Invalid resource, environment permissions can not contain ':' separator.");
        }

    }

    private ValidationContext rulesValidationContext(List<String> allowedAction, List<String> allowedType) {
        return new DelegatingValidationContext(null) {
            @Override
            public PolicyValidationContext getPolicyValidationContext() {
                return new PolicyValidationContext(allowedAction, allowedType);
            }
        };
    }

    Directive getDirective(String action, String type, String resource) {
        return new Allow(action, type, resource);
    }
}


text:
<!doctype html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Friends Timeline - Quantified Self Visualization Project</title>
    <link rel="stylesheet" href="css/foundation.css" />

Quantified Self - Visualization Project

Home

FRIENDS TIMELINE

Friends Timeline

Who I interacted with

Events


text:
package com.gdgand.rxjava.rxjavasample.fcm.token;

import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;

public class FCMTokenService extends FirebaseInstanceIdService {
    public static final String KEY_FCM_TOKEN = "fcm_token";
    private static final String TAG = "FCMTokenService";

    @Override
    public void onTokenRefresh() {
        super.onTokenRefresh();
        String fcmTokenId = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "onTokenRefresh() : Token : " + fcmTokenId);
        saveToken(fcmTokenId);
    }

    private void saveToken(String fcmTokenId) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        preferences.edit().putString(KEY_FCM_TOKEN, fcmTokenId).apply();

    }
}


text:
layout: chem370
title:  Data Processing and Lab Notebook Info
permalink: /archive/chem370-f2020/data-processing
---

If you experience trouble with R or RStudio, you can use it on VCAT (Virtual Apps link on my.wcu.edu).  You will need to download the notebook templates from [GitHub](https://github.com/dr-fischer/instRumental/tree/master/inst/rmarkdown/templates).

We will focus heavily on analytical data processing throughout the semester.  You will be expected to process your data using the programming language R.  Although this may feel like computer science to some, programmatic data analysis is becoming an increasingly important part of analytical chemistry. (Remember, analytical chemistry is what analytical chemists do!)

You will undoubtedly encounter many error messages while coding this semester.  You will have to find the cause of the error and fix it before moving on.  It's likely you will feel lost, underprepared, and frustrated.  To help with this, I encourage you to follow the tutorials below.  If you get stuck, take a look at the *How to Get Help* section below.

# Data Processing Tutorials

Video tutorials for R, RStudio, and data processing methods.

# How to Get Help

- **R help:** Type `?function_name()` into the R prompt to learn about a function. For example, `?plot()` will bring up the help for the `plot()` function.
- **MS Teams Discussion:** Post your question to the general discussion channel in MS Teams.  This will be visible by the whole class.  If you know the answer to someone else's question, please answer it!  If no one knows the answer I'll weigh in.  By posting your question on MS Teams you allow the whole class to benefit and help keep me from answering the same question many times over.
- **Stack Overflow:** The [Stack Overflow](https://stackoverflow.com/questions/tagged/r) discussion board.  Often you can find Stack Overflow discussions that answer your question by using you favorite search engine (e.g. Google).
- **Each Other:** Please help each other!  I encourage collaboration.  Note that collaboratively helping each other does NOT mean sharing code verbatim.  Help others understand concepts and methods rather than providing an answer.
- **Email Me:** I can often help solve the problem via [email](mailto:dfischer@wcu.edu).  To the best extent possible, please take the following steps so that I can answer your question in an effective and timely manner:
  - *Be specific*.  I can't do much if you say "my code isn't working".  As Stack Exchange states, 'It doesn't work' isn't descriptive enough to help people understand your problem. Instead...tell other readers [i.e. your instructor] what the exact wording of the error message is, and which line of code is producing it"

  - *Explain what you've tried.*  I expect that you attempt to troubleshoot before contacting me.  Try to figure out what's occurring.  Try to re-create the error as a [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example).  As Stack Exchange suggests:

    > The more code there is to go through, the less likely people can find your problem. Streamline your example in one of two ways:
    > - Restart from scratch. Create a new program, adding in only what is needed to see the problem. Use simple, descriptive names for functions and variables – don't copy the names you're using in your existing code.
    > - Divide and conquer. If you're not sure what the source of the problem is, start removing code a bit at a time until the problem disappears – then add the last part back.

  I usually start with the second option and use the prior as a last resort.

  Please *do* ask for help when needed.  Although I want you to gain experience troubleshooting, I do not want you to spend hours focused on finding a single typo or rewriting your code multiple times!

  - *Include screen shots*.  A screen shot of RStudio showing your code, the error message, and your data is usually sufficient for me to understand what's going on.  If I need more information I'll ask you to send your code.

- See [Getting help with R](https://support.rstudio.com/hc/en-us/articles/200552336-Getting-Help-with-R) by RStudio for additional options.

# Data Processing tutorials

R video tutorials are available in the Lab channel of Chem 370 team in MS Teams.

<!-- # Lab Notebook Info

The lab manual contains the expectations for your lab notebooks along with good and bad examples.

- [Lab notebook guide]({{site.baseurl}}/archive/chem370-f2020/lab-manual/appendix-4-lab-notebook-guidelines.html)

## Example Lab Notebooks

- [Good Example]({{site.baseurl}}/archive/chem370-f2020/notebooks/good-example/) *Note: data processing in this example was done in the language Julia, not Octave.*
- [Bad Example]({{site.baseurl}}/archive/chem370-f2020/notebooks/bad-example/)  *Note: data processing in this example was done in the language Julia, not Octave.*
- [Bad Example 2]({{site.baseurl}}/archive/chem370-f2020/notebooks/bad-example-2/)  *Note: data processing in this example was done in the language Julia, not Octave.*   -->


text:
`Home`
`301 Index`

#### RegExp (patterns used to match character combinations in strings) - RegEx 101 - RegEx Cheatsheet
- Expression Literal
  - `/ab+c/g`
- Constructor Function
  - `new RegExp('ab+c', 'g')`
- `[abc]` - match precisely what you want (a|b|c)
- `\` - selects special character
- `^` - matches beginning of input (followed by selections)
- `$` - matches end of input
- `*` - matches the preceeding expression 0 or more times (`/bo*/` = `'b'` | `'booooo'`
- `+` - matches the preceeding expression 1 or more times (`/a+/`) = `'a'` | `'aaaaaa'`
- `?` - matches the preceeding expression 0 or 1 time (`/e?le?/`) = `'el'` | `'le'` | `'l'`
- `.` - matches any single character (`/.n/`) = `'on'` | `'an'`, EXCEPT: `'near'`
- `/(x)/` - matches x and remembers for later use. Called in the same instance with `\1` `\2` etc.. and called later, or in a .replace() method perhaps with `$1` `$2` etc..


text:
<component name="ProjectRunConfigurationManager">
  <configuration default="false" name="All tests" type="AndroidJUnit" factoryName="Android JUnit">
    <module name="app" />
    <extension name="coverage">
      <pattern>
        <option name="PATTERN" value="org.connectbot.*" />
        <option name="ENABLED" value="true" />
      </pattern>
    </extension>
    <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
    <option name="ALTERNATIVE_JRE_PATH" value="" />
    <option name="PACKAGE_NAME" value="" />
    <option name="MAIN_CLASS_NAME" value="" />
    <option name="METHOD_NAME" value="" />
    <option name="TEST_OBJECT" value="package" />
    <option name="VM_PARAMETERS" value="-ea" />
    <option name="PARAMETERS" value="" />
    <option name="WORKING_DIRECTORY" value="file://$MODULE_DIR$" />
    <option name="PASS_PARENT_ENVS" value="true" />
    <option name="TEST_SEARCH_SCOPE">
      <value defaultName="singleModule" />
    </option>
    <dir value="$PROJECT_DIR$/app/src/test" />
    <patterns />
    <method />
  </configuration>
</component>


text:
'use strict';

/**
 * @ngdoc function
 * @name tablepricingApp.controller:MainCtrl
 * @description
 * # MainCtrl
 * Controller of the tablepricingApp
 */
angular.module('tablepricingApp')
  .controller('MainCtrl', function ($scope, $http) {
    $scope.userColumns = {
      titleIndex: 'title',
      columns: [{
        text: 'User Code',
        dataIndex: 'uuid'
      },{
        text: 'User Name',
        iconCls: 'icon-user',
        dataIndex: 'name'
      },{
        text: 'Phone',
        dataIndex: 'phone'
      },{
        text: 'Create Date',
        filter: {
          type: 'date',
          format: 'yyyy-MM-dd'
        },
        dataIndex: 'createDate'
      }]
    };

    $scope.operation = {
      text: 'Go',
      cls: 'btn btn-info',
      iconCls: 'm-icon-swapright m-icon-white',
      handlers: {
        click: function(item){
          console.log(item);
        }
      }
    };

    $http.get('json/table-pricing.json')
      .success(function(response){
        $scope.store = response;
      })
      .error(function(er){
        console.log(er);
      });
  });


text:
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_saved_model.h"

#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/raw_ostream.h"
#include "mlir/IR/Attributes.h"  // TF:llvm-project
#include "mlir/IR/Builders.h"  // TF:llvm-project
#include "mlir/IR/Function.h"  // TF:llvm-project
#include "mlir/IR/Identifier.h"  // TF:llvm-project
#include "mlir/IR/Module.h"  // TF:llvm-project
#include "mlir/IR/OpImplementation.h"  // TF:llvm-project
#include "mlir/IR/StandardTypes.h"  // TF:llvm-project
#include "mlir/IR/SymbolTable.h"  // TF:llvm-project
#include "mlir/IR/TypeUtilities.h"  // TF:llvm-project
#include "mlir/Support/LogicalResult.h"  // TF:llvm-project
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_types.h"

namespace mlir {
namespace tf_saved_model {

//===----------------------------------------------------------------------===//
// Utilities
//===----------------------------------------------------------------------===//

static bool IsStrArrayAttr(Attribute attr) {
  auto array = attr.dyn_cast<ArrayAttr>();
  if (!array) return false;

  return llvm::all_of(array,
                      [](Attribute attr) { return attr.isa<StringAttr>(); });
}

//===----------------------------------------------------------------------===//
// TensorFlowSavedModelDialect Op's
//===----------------------------------------------------------------------===//

LogicalResult VerifyTensorTypesCompatible(Type t1, Type t2) {
  if (!t1.isa<TensorType>() || !t2.isa<TensorType>()) {
    return failure();
  }
  return verifyCompatibleShape(t1.cast<TensorType>(), t2.cast<TensorType>());
}

static LogicalResult Verify(GlobalTensorOp global_tensor) {
  if (failed(VerifyTensorTypesCompatible(
          global_tensor.type(), global_tensor.value().Attribute::getType()))) {
    return global_tensor.emitError() << "'type' and 'value' attributes should "
                                        "have compatible tensor types";
  }
  if (!global_tensor.is_mutable()) {
    if (!global_tensor.type().cast<TensorType>().hasStaticShape()) {
      return global_tensor.emitError()
             << "'type' attribute for immutable 'tf_saved_model.global_tensor' "
                "should have a static shape";
    }
  }
  return success();
}

#define GET_OP_CLASSES
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_saved_model.cc.inc"

//===----------------------------------------------------------------------===//
// TensorFlowSavedModelDialect Dialect
//===----------------------------------------------------------------------===//

TensorFlowSavedModelDialect::TensorFlowSavedModelDialect(MLIRContext *context)
    : Dialect(/*name=*/"tf_saved_model", context) {
  addOperations<
#define GET_OP_LIST
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_saved_model.cc.inc"
      >();
}

static LogicalResult VerifyIndexPath(Operation *op, NamedAttribute named_attr) {
  auto attr = named_attr.second.dyn_cast<ArrayAttr>();
  if (!attr) {
    return op->emitError()
           << "'tf_saved_model.index_path' attribute should be an ArrayAttr";
  }
  for (auto element : attr) {
    if (element.isa<StringAttr>()) {
      continue;
    }
    if (auto integer = element.dyn_cast<IntegerAttr>()) {
      if (integer.getValue().getBitWidth() == 64) {
        continue;
      }
    }
    return op->emitError() << "'tf_saved_model.index_path' elements should "
                              "be strings or 64-bit integers";
  }
  return mlir::success();
}

// Return true if `type` is a tensor of `!tf.resource`. This is the type that is
// used to represent mutable variables on exported functions' bound inputs.
static bool IsResourceVarType(Type type) {
  TensorType tensor_type = type.dyn_cast<TensorType>();
  if (!tensor_type) return false;
  return tensor_type.getElementType().isa<TF::ResourceType>();
}

LogicalResult TensorFlowSavedModelDialect::verifyRegionArgAttribute(
    Operation *op, unsigned region_index, unsigned arg_index,
    NamedAttribute named_attr) {
  if (named_attr.first == "tf_saved_model.bound_input") {
    if (!named_attr.second.isa<FlatSymbolRefAttr>()) {
      return op->emitError() << "'tf_saved_model.bound_input' attribute should "
                                "be a FlatSymbolRefAttr";
    }
    auto symbol_name = named_attr.second.cast<FlatSymbolRefAttr>().getValue();
    auto module = op->getParentOfType<ModuleOp>();
    auto global_tensor = module.lookupSymbol<GlobalTensorOp>(symbol_name);
    if (!global_tensor) {
      return op->emitError() << "'tf_saved_model.bound_input' attribute must "
                                "reference a valid symbol, got invalid symbol '"
                             << symbol_name << "'";
    }
    auto arg_type = cast<FuncOp>(op).getArgument(arg_index).getType();
    if (global_tensor.is_mutable()) {
      if (!IsResourceVarType(arg_type)) {
        return op->emitError()
               << "bound inputs for mutable 'tf_saved_model.global_tensor's "
                  "must be tensors of '!tf.resource'";
      }
    } else {
      if (arg_type != global_tensor.type()) {
        return op->emitError() << "bound input for immutable "
                                  "'tf_saved_model.global_tensor' must "
                                  "match the global tensor's type";
      }
    }
    return success();
  }
  if (named_attr.first == "tf_saved_model.index_path") {
    return VerifyIndexPath(op, named_attr);
  }

  return op->emitError() << "unknown tf_saved_model dialect arg attribute '"
                         << named_attr.first << "'";
}

LogicalResult TensorFlowSavedModelDialect::verifyRegionResultAttribute(
    Operation *op, unsigned region_index, unsigned result_index,
    NamedAttribute named_attr) {
  if (named_attr.first == "tf_saved_model.index_path") {
    return VerifyIndexPath(op, named_attr);
  }

  return op->emitError() << "unknown tf_saved_model dialect result attribute '"
                         << named_attr.first << "'";
}

static bool HasAnyTfSavedModelArgAttr(FuncOp func) {
  for (int i = 0, e = func.getNumArguments(); i < e; i++) {
    if (func.getArgAttr(i, "tf_saved_model.index_path") ||
        func.getArgAttr(i, "tf_saved_model.bound_input")) {
      return true;
    }
  }
  for (int i = 0, e = func.getNumResults(); i < e; i++) {
    if (func.getResultAttr(i, "tf_saved_model.index_path") ||
        func.getResultAttr(i, "tf_saved_model.bound_input")) {
      return true;
    }
  }
  return false;
}

static LogicalResult VerifySavedModelModule(
    ModuleOp module, TensorFlowSavedModelDialect *dialect) {
  auto exported_names_ident =
      Identifier::get("tf_saved_model.exported_names", dialect->getContext());
  // Check that there are no duplicated exported_names.
  DenseMap<StringRef, Operation *> exported_name_to_op;
  for (auto &op : module) {
    auto attr = op.getAttr(exported_names_ident);
    if (!attr) continue;
    // If this verifier is called before we verify the
    // 'tf_saved_model.exported_names' attribute, then it might be invalid.
    // Forward to the dialect's verification to establish that precondition.
    if (failed(dialect->verifyOperationAttribute(
            &op, {exported_names_ident, attr}))) {
      return failure();
    }
    for (auto str : attr.cast<ArrayAttr>()) {
      auto exported_name = str.cast<StringAttr>().getValue();
      auto p = exported_name_to_op.insert({exported_name, &op});
      if (!p.second) {
        return op.emitError()
            .append("duplicate exported name '", exported_name, "'")
            .attachNote(p.first->getSecond()->getLoc())
            .append("previously seen here");
      }
    }
  }
  for (auto func : module.getOps<FuncOp>()) {
    if (HasAnyTfSavedModelArgAttr(func)) {
      if (!IsExported(func)) {
        return func.emitError()
               << "can only apply 'tf_saved_model' argument attributes "
                  "to exported functions";
      }
    }
  }
  SymbolTable symbol_table(module);
  auto symbol_uses = SymbolTable::getSymbolUses(&module.getBodyRegion());
  if (!symbol_uses.hasValue()) {
    return module.emitError() << "modules with 'tf_saved_model.semantics' must "
                                 "have analyzable symbol uses";
  }
  for (auto symbol_use : *symbol_uses) {
    auto func = symbol_table.lookup<FuncOp>(
        symbol_use.getSymbolRef().cast<FlatSymbolRefAttr>().getValue());
    if (func && !GetExportedNames(func).empty()) {
      return symbol_use.getUser()
          ->emitError("exported function cannot be internally referenced")
          .attachNote(func.getLoc())
          .append("references this exported function");
    }
  }
  return success();
}

LogicalResult VerifyExportedFunc(FuncOp func) {
  bool reached_bound_inputs = false;
  for (int i = 0, e = func.getNumArguments(); i < e; i++) {
    if (func.getArgAttr(i, "tf_saved_model.bound_input")) {
      reached_bound_inputs = true;
      continue;
    }
    if (func.getArgAttr(i, "tf_saved_model.index_path")) {
      if (reached_bound_inputs) {
        return func.emitError()
               << "all 'tf_saved_model.index_path' arg attributes should "
                  "precede all 'tf_saved_model.bound_input' arg attributes";
      }
      continue;
    }
    return func.emitError()
           << "all arguments should have 'tf_saved_model.index_path' or "
              "'tf_saved_model.bound_input' attributes";
  }
  llvm::SmallDenseSet<StringRef, 8> unique_bound_inputs;
  for (int i = 0, e = func.getNumArguments(); i < e; i++) {
    if (auto attr = func.getArgAttrOfType<FlatSymbolRefAttr>(
            i, "tf_saved_model.bound_input")) {
      if (!unique_bound_inputs.insert(attr.getValue()).second) {
        return func.emitError()
               << "duplicate 'tf_saved_model.bound_input' binding";
      }
    }
  }

  for (int i = 0, e = func.getNumResults(); i < e; i++) {
    if (!func.getResultAttr(i, "tf_saved_model.index_path")) {
      return func.emitError() << "all results should have "
                                 "'tf_saved_model.index_path' attributes";
    }
  }

  return success();
}

LogicalResult TensorFlowSavedModelDialect::verifyOperationAttribute(
    Operation *op, NamedAttribute named_attr) {
  if (named_attr.first == "tf_saved_model.exported_names") {
    if (!isa<FuncOp>(op) && !isa<GlobalTensorOp>(op)) {
      return op->emitError() << "'tf_saved_model.exported_names' must be on a "
                                "'func' or 'tf_saved_model.global_tensor' op";
    }
    if (!IsStrArrayAttr(named_attr.second)) {
      return op->emitError()
             << "'tf_saved_model.exported_names' must be an array of strings";
    }
    if (!op->getParentOp()->getAttr("tf_saved_model.semantics")) {
      return op->emitError()
             << "'tf_saved_model.exported_names' must be on an op "
                "whose immediate parent has attribute "
                "'tf_saved_model.semantics'";
    }
    if (auto func = dyn_cast<FuncOp>(op)) {
      if (failed(VerifyExportedFunc(func))) {
        return failure();
      }
    }
    return success();
  }
  if (named_attr.first == "tf_saved_model.semantics") {
    auto module = dyn_cast<ModuleOp>(op);
    if (!module) {
      return op->emitError() << "'tf_saved_model.semantics' must "
                                "be on a module op";
    }
    return VerifySavedModelModule(module, this);
  }

  return op->emitError() << "unknown tf_saved_model dialect attribute '"
                         << named_attr.first << "'";
}

SmallVector<StringRef, 2> GetExportedNames(Operation *op) {
  SmallVector<StringRef, 2> ret;
  auto exported_names =
      op->getAttrOfType<ArrayAttr>("tf_saved_model.exported_names");
  if (exported_names) {
    for (auto name : exported_names) {
      ret.push_back(name.cast<StringAttr>().getValue());
    }
  }
  return ret;
}

bool IsExported(Operation *op) { return !GetExportedNames(op).empty(); }

bool HasTfSavedModelSemantics(ModuleOp module) {
  return module.getAttr("tf_saved_model.semantics") != nullptr;
}

GlobalTensorOp LookupBoundInput(FuncOp func, int arg_index,
                                const SymbolTable &symbol_table) {
  auto attr = func.getArgAttrOfType<FlatSymbolRefAttr>(
      arg_index, "tf_saved_model.bound_input");
  if (!attr) return nullptr;
  return symbol_table.lookup<GlobalTensorOp>(attr.getValue());
}

}  // namespace tf_saved_model
}  // namespace mlir


text:
<!doctype>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Hampton Restaurant Week</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <link rel="icon" type="image/x-icon" href="http://cartodb.github.io/odyssey.js/sandbox/favicon.png">
  <link rel="icon" type="image/png" href="http://cartodb.github.io/odyssey.js/sandbox/favicon.png">

  <link rel="stylesheet" href="http://cartodb-libs.global.ssl.fastly.net/cartodb.js/v3/themes/css/cartodb.css">
  <link rel="stylesheet" href="http://cartodb.github.io/odyssey.js/sandbox/css/slides.css">

    Title
    By Name using Odyssey.js


text:
var isNetworkConnected = true; // TODO: ネットワーク接続判定

// initialise Cloud User
if (Util.Settings.UseCloud.enable && isNetworkConnected)  {
    Util.User.loginBySavedSessionId();
}

// tabOpen event handler
function tabOpen(e) {
    // Android だったらアクションバーにメニューを表示する
    if (OS_ANDROID) {
        var activity: Ti.Android.Activity = $.index.getActivity();
        activity.onCreateOptionsMenu = function (evt) {

            // Add Button
            evt.menu.add({
                title: 'Add',
                icon: Ti.Android.R.drawable.ic_menu_edit,
                showAsAction: Ti.Android.SHOW_AS_ACTION_IF_ROOM
            }).addEventListener('click', () => $.tasks.openWindow('Add', 'addWin'));

            // User Button
            evt.menu.add({
                title: 'User',
                icon: Ti.Android.R.drawable.ic_lock_idle_charging,
                showAsAction: Ti.Android.SHOW_AS_ACTION_IF_ROOM
            }).addEventListener('click', () => $.tasks.openWindow('User', 'userWin'));

        };
        activity.invalidateOptionsMenu();
    } else {
        $.tasks.btnAdd.addEventListener('click',  () => $.tasks.openWindow('Add', 'addWin'));
        $.tasks.btnUser.addEventListener('click', () => $.tasks.openWindow('User', 'userWin'));
    }
}

// tabFocus event handler
function tabFocus(e) {
  // タブを切り替えたらそのタブをグローバルに参照できるようにする
  Alloy.Globals.currentTab = e.tab;
}

// close event handler
$.index.addEventListener('close', function() {
    $.destroy();
});

$.index.open();


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE78_OS_Command_Injection__wchar_t_console_w32_spawnlp_62b.cpp
Label Definition File: CWE78_OS_Command_Injection.strings.label.xml
Template File: sources-sink-62b.tmpl.cpp
*/
/*
 * @description
 * CWE: 78 OS Command Injection
 * BadSource: console Read input from the console
 * GoodSource: Fixed string
 * Sinks: w32_spawnlp
 *    BadSink : execute command with wspawnlp
 * Flow Variant: 62 Data flow: data flows using a C++ reference from one function to another in different source files
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

#ifdef _WIN32
#define COMMAND_INT_PATH L"%WINDIR%\\system32\\cmd.exe"
#define COMMAND_INT L"cmd.exe"
#define COMMAND_ARG1 L"/c"
#define COMMAND_ARG2 L"dir"
#define COMMAND_ARG3 data
#else /* NOT _WIN32 */
#include <unistd.h>
#define COMMAND_INT_PATH L"/bin/sh"
#define COMMAND_INT L"sh"
#define COMMAND_ARG1 L"ls"
#define COMMAND_ARG2 L"-la"
#define COMMAND_ARG3 data
#endif

namespace CWE78_OS_Command_Injection__wchar_t_console_w32_spawnlp_62
{

#ifndef OMITBAD

void badSource(wchar_t * &data)
{
    {
        /* Read input from the console */
        size_t dataLen = wcslen(data);
        /* if there is room in data, read into it from the console */
        if (100-dataLen > 1)
        {
            /* POTENTIAL FLAW: Read data from the console */
            if (fgetws(data+dataLen, (int)(100-dataLen), stdin) != NULL)
            {
                /* The next few lines remove the carriage return from the string that is
                 * inserted by fgetws() */
                dataLen = wcslen(data);
                if (dataLen > 0 && data[dataLen-1] == L'\n')
                {
                    data[dataLen-1] = L'\0';
                }
            }
            else
            {
                printLine("fgetws() failed");
                /* Restore NUL terminator if fgetws fails */
                data[dataLen] = L'\0';
            }
        }
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B() uses the GoodSource with the BadSink */
void goodG2BSource(wchar_t * &data)
{
    /* FIX: Append a fixed string to data (not user / external input) */
    wcscat(data, L"*.*");
}

#endif /* OMITGOOD */

} /* close namespace */


text:
<?php

namespace Endereco\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class HomeController extends AbstractActionController {

    public function indexAction() {
        return new ViewModel();
    }

    /**
     * action sobre
     * @return \Zend\View\Model\ViewModel
     */
    public function sobreAction()
    {
        return new ViewModel();
    }

}


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Collections;
using Microsoft.Build.Framework;
using Microsoft.Build.BuildEngine.Shared;

namespace Microsoft.Build.BuildEngine
{
    /// <summary>
    /// This class wraps BuildEventArgs and used for sending BuildEventArgs across the node boundary
    /// </summary>
    internal class NodeLoggingEvent
    {
        // Enumeration of logging event types, this is used to recreate the correct type on deserialization
        private enum LoggingEventType
        {
            CustomEvent = 0,
            BuildErrorEvent = 1,
            BuildFinishedEvent = 2,
            BuildMessageEvent = 3,
            BuildStartedEvent = 4,
            BuildWarningEvent = 5,
            ProjectFinishedEvent = 6,
            ProjectStartedEvent = 7,
            TargetStartedEvent = 8,
            TargetFinishedEvent = 9,
            TaskStartedEvent = 10,
            TaskFinishedEvent = 11,
            TaskCommandLineEvent = 12
        }

        #region Constructors
        /// <summary>
        /// This new constructor is required for custom serialization
        /// </summary>
        internal NodeLoggingEvent()
        {
        }
        /// <summary>
        /// Create an instance of this class wrapping given BuildEventArgs
        /// </summary>
        internal NodeLoggingEvent(BuildEventArgs eventToLog)
        {
           this.e = eventToLog;
        }
        #endregion

        #region Properties
        /// <summary>
        /// The BuildEventArgs wrapped by this class
        /// </summary>
        internal BuildEventArgs BuildEvent
        {
            get
            {
                return this.e;
            }
        }

        /// <summary>
        /// The ID of the central logger to which this event should be forwarded. By default
        /// all regular non-forwarded events are sent to all loggers registered on the parent.
        /// </summary>
        virtual internal int LoggerId
        {
            get
            {
                return 0;
            }
        }

        #endregion

        #region CustomSerializationToStream

        /// <summary>
        /// Converts a BuildEventArg into its associated enumeration Id.
        /// Any event which is a derrived event not in the predefined list will be
        /// considered a custom event and use .net serialization
        /// </summary>
        private LoggingEventType GetLoggingEventId(BuildEventArgs eventArg)
        {
            Type eventType = eventArg.GetType();
            if (eventType == typeof(BuildMessageEventArgs))
            {
                return LoggingEventType.BuildMessageEvent;
            }
            else if (eventType == typeof(TaskCommandLineEventArgs))
            {
                return LoggingEventType.TaskCommandLineEvent;
            }
            else if (eventType == typeof(ProjectFinishedEventArgs))
            {
                return LoggingEventType.ProjectFinishedEvent;
            }
            else if (eventType == typeof(ProjectStartedEventArgs))
            {
                return LoggingEventType.ProjectStartedEvent;
            }
            else if (eventType == typeof(TargetStartedEventArgs))
            {
                return LoggingEventType.TargetStartedEvent;
            }
            else if (eventType == typeof(TargetFinishedEventArgs))
            {
                return LoggingEventType.TargetFinishedEvent;
            }
            else if (eventType == typeof(TaskStartedEventArgs))
            {
                return LoggingEventType.TaskStartedEvent;
            }
            else if (eventType == typeof(TaskFinishedEventArgs))
            {
                return LoggingEventType.TaskFinishedEvent;
            }
            else if (eventType == typeof(BuildFinishedEventArgs))
            {
                return LoggingEventType.BuildFinishedEvent;
            }
            else if (eventType == typeof(BuildStartedEventArgs))
            {
                return LoggingEventType.BuildStartedEvent;
            }
            else if (eventType == typeof(BuildWarningEventArgs))
            {
                return LoggingEventType.BuildWarningEvent;
            }
            if (eventType == typeof(BuildErrorEventArgs))
            {
                return LoggingEventType.BuildErrorEvent;
            }
            else
            {
                return LoggingEventType.CustomEvent;
            }
        }

        /// <summary>
        /// Takes in a id (LoggingEventType as an int) and creates the correct specific logging class
        /// </summary>
        private BuildEventArgs GetBuildEventArgFromId(LoggingEventType id)
        {
            switch (id)
            {
                case LoggingEventType.BuildErrorEvent:
                    return new BuildErrorEventArgs(null, null, null, -1, -1, -1, -1, null, null, null);
                case LoggingEventType.BuildFinishedEvent:
                    return new BuildFinishedEventArgs(null, null, false);
                case LoggingEventType.BuildMessageEvent:
                    return new BuildMessageEventArgs(null, null, null, MessageImportance.Normal);
                case LoggingEventType.BuildStartedEvent:
                    return new BuildStartedEventArgs(null, null);
                case LoggingEventType.BuildWarningEvent:
                    return new BuildWarningEventArgs(null, null, null, -1, -1, -1, -1,null,null,null);
                case LoggingEventType.ProjectFinishedEvent:
                    return new ProjectFinishedEventArgs(null, null, null, false);
                case LoggingEventType.ProjectStartedEvent:
                    return new ProjectStartedEventArgs(-1, null, null, null, null, null, null, null);
                case LoggingEventType.TargetStartedEvent:
                    return new TargetStartedEventArgs(null, null, null, null, null);
                case LoggingEventType.TargetFinishedEvent:
                    return new TargetFinishedEventArgs(null, null, null, null, null, false);
                case LoggingEventType.TaskStartedEvent:
                    return new TaskStartedEventArgs(null, null, null, null, null);
                case LoggingEventType.TaskFinishedEvent:
                    return new TaskFinishedEventArgs(null, null, null, null, null, false);
                case LoggingEventType.TaskCommandLineEvent:
                    return new TaskCommandLineEventArgs(null, null, MessageImportance.Normal);
                default:
                    ErrorUtilities.VerifyThrow(false, "Should not get to the default of getBuildEventArgFromId ID:" + id);
                    return null;
            }
        }

        internal virtual void WriteToStream(BinaryWriter writer, Hashtable loggingTypeCache)
        {
            LoggingEventType id = GetLoggingEventId(e);
            writer.Write((byte)id);

            if (id != LoggingEventType.CustomEvent)
            {
                if (!loggingTypeCache.ContainsKey(id))
                {
                    Type eventType = e.GetType();
                    MethodInfo methodInfo = eventType.GetMethod("WriteToStream", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod);
                    loggingTypeCache.Add(id, methodInfo);
                }
                if (loggingTypeCache[id] != null)
                {
                    ((MethodInfo)loggingTypeCache[id]).Invoke(e, new object[] { writer });
                }
                else
                {
                    // The customer serialization methods are not availiable, default to .net serialization
                    writer.BaseStream.Position = writer.BaseStream.Position - 1;
                    writer.Write((byte)0);
                    binaryFormatter.Serialize(writer.BaseStream, e);
                }
            }
            else
            {
                writer.Write(e.GetType().Assembly.Location);
                binaryFormatter.Serialize(writer.BaseStream, e);
            }
        }

        internal virtual void CreateFromStream(BinaryReader reader, Hashtable loggingTypeCache)
        {
            LoggingEventType id = (LoggingEventType)reader.ReadByte();
            if (LoggingEventType.CustomEvent != id)
            {
                e = GetBuildEventArgFromId(id);
                if (!loggingTypeCache.Contains(id))
                {
                    Type eventType = e.GetType();
                    MethodInfo methodInfo = eventType.GetMethod("CreateFromStream", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod);
                    loggingTypeCache.Add(id, methodInfo);
                }

                int packetVersion = (Environment.Version.Major * 10) + Environment.Version.Minor;
                ((MethodInfo)loggingTypeCache[id]).Invoke(e, new object[] { reader, packetVersion });
            }
            else
            {
                string fileLocation = reader.ReadString();
                bool resolveAssembly = false;
                lock (lockObject)
                {
                    if (customEventsLoaded == null)
                    {
                        customEventsLoaded = new Hashtable(StringComparer.OrdinalIgnoreCase);
                        resolveAssembly = true;
                    }
                    else
                    {
                        if (!customEventsLoaded.Contains(fileLocation))
                        {
                            resolveAssembly = true;
                        }
                    }
                    // If we are to resolve the assembly add it to the list of assemblies resolved
                    if (resolveAssembly)
                    {
                        customEventsLoaded.Add(fileLocation, null);
                    }
                }
                    if (resolveAssembly)
                    {
                        resolver = new TaskEngineAssemblyResolver();
                        resolver.InstallHandler();
                        resolver.Initialize(fileLocation);
                    }
                    try
                    {
                        e = (BuildEventArgs)binaryFormatter.Deserialize(reader.BaseStream);
                    }
                    finally
                    {
                        if (resolveAssembly)
                        {
                            resolver.RemoveHandler();
                            resolver = null;
                        }
                    }

            }
        }
        #endregion

        #region Data
        // The actual event wrapped by this container class
        private BuildEventArgs e;
        // Just need one of each per app domain
        private static BinaryFormatter binaryFormatter = new BinaryFormatter();
        private TaskEngineAssemblyResolver resolver;
        private static Hashtable customEventsLoaded;
        private static object lockObject = new object();
        #endregion
    }

    /// <summary>
    /// This class is used to associate wrapped BuildEventArgs with a loggerId which
    /// identifies which central logger this event should be delivered to.
    /// </summary>
    internal class NodeLoggingEventWithLoggerId : NodeLoggingEvent
    {
        #region Constructors

        internal NodeLoggingEventWithLoggerId()
        {
        }
        /// <summary>
        /// Create a wrapper for a given event associated with a particular loggerId
        /// </summary>
        internal NodeLoggingEventWithLoggerId(BuildEventArgs eventToLog, int loggerId)
            :base(eventToLog)
        {
            this.loggerId = loggerId;
        }
        #endregion

        #region Properties
        /// <summary>
        /// The ID of the central logger to which this event should be forwarded
        /// </summary>
        internal override int LoggerId
        {
            get
            {
                return loggerId;
            }
        }
        #endregion

        #region CustomSerializationToStream

        internal override void WriteToStream(BinaryWriter writer, Hashtable loggingTypeCache)
        {
            base.WriteToStream(writer, loggingTypeCache);
            writer.Write((Int32)loggerId);
        }

        internal override void CreateFromStream(BinaryReader reader, Hashtable loggingTypeCache)
        {
            base.CreateFromStream(reader, loggingTypeCache);
            loggerId = reader.ReadInt32();
        }
        #endregion

        #region Data
        // The id of the central logger to which this event should be forwarded
        private int loggerId;
        #endregion
    }
}


text:
//
//  CLUVideoWriter.h
//  Clue
//
//  Created by Ahmed Sulaiman on 5/18/16.
//  Copyright © 2016 Ahmed Sulaiman. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
#import "CLUWritable.h"

/**
 `CLUVideoWriter` class which responsible for all writing and saving process for video stream from device's screen.
 Used with Video Module to record screen while report recording is active
 */
@interface CLUVideoWriter : NSObject <CLUWritable>

/**
 Size of final video. Depends on recorded view size
 */
@property (nonatomic, readonly) CGSize viewSize;

/**
 Current device's screen scale. To generate bitmap with correct size depending on scale
 */
@property (nonatomic, readonly) CGFloat scale;

/**
 URL of the final video file where Video Writer will save final recorded file
 */
@property (nonatomic, readonly) NSURL *outputURL;

/**
 Create new instance of Video Writer with scpecific output URL, view size and scale

 @param outputURL URL of the final video file where Video Writer will save final recorded file
 @param size Size of final video. Depends on recorded view size
 @param scale Current device's screen scale. To generate bitmap with correct size depending on scale
 @return New instance of Video Writer with configured properties
 */
- (instancetype)initWithOutputURL:(NSURL *)outputURL viewSize:(CGSize)size scale:(CGFloat)scale;

/**
 Append pixel buffer, current top view representation as a pixel buffer (See [UIView drawViewHierarchyInRect:afterScreenUpdates:] for drawing view Hierarchy on specific context) for specific timestamp

 @param pixelBuffer The `CVPixelBufferRef` to be appended.
 @param timestamp The presentation time for the pixel buffer to be appended.
 @return A BOOL value indicating success of appending the pixel buffer. If a result of NO is returned, clients can check the value of `[CLUVideoWriter status]` to determine whether the writing operation completed, failed, or was cancelled.

 @see -bitmapContextForPixelBuffer:
 */
- (BOOL)appendPixelBuffer:(CVPixelBufferRef)pixelBuffer forTimestamp:(CMTime)timestamp;

/**
 @return The status of writing samples to the receiver's output file.
 */
- (AVAssetWriterStatus)status;

/**
 Create `CGContextRef` Bitmap context with correct width, height, color space and bytes per row for specific pixel buffer

 @param pixelBuffer The empty `CVPixelBufferRef`
 @return `CGContextRef` Bitmap context on which client can draw view representation. (See [UIView drawViewHierarchyInRect:afterScreenUpdates:] to draw view on specific context)
 */
- (CGContextRef)bitmapContextForPixelBuffer:(CVPixelBufferRef *)pixelBuffer;

@end


text:
namespace testing {
namespace internal {

// Object that captures an output stream (stdout/stderr).
class CapturedStream {
 public:
  // The ctor redirects the stream to a temporary file.
  explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
    std::string temp_dir = ::testing::TempDir();

    // testing::TempDir() should return a directory with a path separator.
    // However, this rule was documented fairly recently, so we normalize across
    // implementations with and without a trailing path separator.
    if (temp_dir.back() != GTEST_PATH_SEP_[0])
      temp_dir.push_back(GTEST_PATH_SEP_[0]);

#if GTEST_OS_WINDOWS
    char temp_file_path[MAX_PATH + 1] = {'\0'};  // NOLINT
    const UINT success = ::GetTempFileNameA(temp_dir.c_str(), "gtest_redir",
                                            0,  // Generate unique file name.
                                            temp_file_path);
    GTEST_CHECK_(success != 0)
        << "Unable to create a temporary file in " << temp_dir;
    const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
    GTEST_CHECK_(captured_fd != -1)
        << "Unable to open temporary file " << temp_file_path;
    filename_ = temp_file_path;
#else
    std::string name_template = temp_dir + "gtest_captured_stream.XXXXXX";

    // mkstemp() modifies the string bytes in place, and does not go beyond the
    // string's length. This results in well-defined behavior in C++17.
    //
    // The const_cast is needed below C++17. The constraints on std::string
    // implementations in C++11 and above make assumption behind the const_cast
    // fairly safe.
    const int captured_fd = ::mkstemp(const_cast<char*>(name_template.data()));
    GTEST_CHECK_(captured_fd != -1)
        << "Failed to create tmp file " << name_template
        << " for test; does the test have write access to the directory?";
    filename_ = std::move(name_template);
#endif  // GTEST_OS_WINDOWS
    fflush(nullptr);
    dup2(captured_fd, fd_);
    close(captured_fd);
  }

  ~CapturedStream() { remove(filename_.c_str()); }

  std::string GetCapturedString() {
    if (uncaptured_fd_ != -1) {
      // Restores the original stream.
      fflush(nullptr);
      dup2(uncaptured_fd_, fd_);
      close(uncaptured_fd_);
      uncaptured_fd_ = -1;
    }

    FILE* const file = posix::FOpen(filename_.c_str(), "r");
    if (file == nullptr) {
      GTEST_LOG_(FATAL) << "Failed to open tmp file " << filename_
                        << " for capturing stream.";
    }
    const std::string content = ReadEntireFile(file);
    posix::FClose(file);
    return content;
  }

 private:
  const int fd_;  // A stream to capture.
  int uncaptured_fd_;
  // Name of the temporary file holding the stderr output.
  ::std::string filename_;

  GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
};

GTEST_DISABLE_MSC_DEPRECATED_POP_()

static CapturedStream* g_captured_stderr = nullptr;
static CapturedStream* g_captured_stdout = nullptr;

// Starts capturing an output stream (stdout/stderr).
static void CaptureStream(int fd,
                          const char* stream_name,
                          CapturedStream** stream) {
  if (*stream != nullptr) {
    GTEST_LOG_(FATAL) << "Only one " << stream_name
                      << " capturer can exist at a time.";
  }
  *stream = new CapturedStream(fd);
}

// Stops capturing the output stream and returns the captured string.
static std::string GetCapturedStream(CapturedStream** captured_stream) {
  const std::string content = (*captured_stream)->GetCapturedString();

  delete *captured_stream;
  *captured_stream = nullptr;

  return content;
}

// Starts capturing stdout.
void CaptureStdout() {
  CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
}

// Starts capturing stderr.
void CaptureStderr() {
  CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
}

// Stops capturing stdout and returns the captured string.
std::string GetCapturedStdout() {
  return GetCapturedStream(&g_captured_stdout);
}

// Stops capturing stderr and returns the captured string.
std::string GetCapturedStderr() {
  return GetCapturedStream(&g_captured_stderr);
}

}  // namespace internal
}  // namespace testing