cly-react

last 1 chrome version
last 1 firefox version
last 1 safari version

{'repo_name': 'Countly/countly-sdk-web', 'stars': '136', 'repo_language': 'JavaScript', 'file_name': 'clear.html', 'mime_type': 'text/html', 'hash': -4023836883961654970, 'source_dataset': 'data'}


/*
 * Copyright 2002-2019 the original author or authors.
 *
 * 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
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.integration.jms.config;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.lang.reflect.Method;
import java.util.Properties;

import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.Queue;
import javax.jms.Session;

import org.junit.Test;

import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.NotReadablePropertyException;
import org.springframework.beans.factory.parsing.BeanDefinitionParsingException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.expression.Expression;
import org.springframework.integration.core.MessagingTemplate;
import org.springframework.integration.endpoint.EventDrivenConsumer;
import org.springframework.integration.endpoint.PollingConsumer;
import org.springframework.integration.handler.ExpressionEvaluatingMessageProcessor;
import org.springframework.integration.handler.advice.AbstractRequestHandlerAdvice;
import org.springframework.integration.history.MessageHistory;
import org.springframework.integration.jms.JmsOutboundGateway;
import org.springframework.integration.jms.StubMessageConverter;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.integration.test.util.TestUtils;
import org.springframework.jms.listener.DefaultMessageListenerContainer;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.SubscribableChannel;
import org.springframework.messaging.support.GenericMessage;

/**
 * @author Jonas Partner
 * @author Oleg Zhurakousky
 * @author Mark Fisher
 * @author Gary Russell
 */
public class JmsOutboundGatewayParserTests {

	private static volatile int adviceCalled;

	@Test
	public void testWithDeliveryPersistentAttribute() {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
				"jmsOutboundGatewayWithDeliveryPersistent.xml", this.getClass());
		EventDrivenConsumer endpoint = (EventDrivenConsumer) context.getBean("jmsGateway");
		DirectFieldAccessor accessor = new DirectFieldAccessor(endpoint);
		JmsOutboundGateway gateway = (JmsOutboundGateway) accessor.getPropertyValue("handler");
		accessor = new DirectFieldAccessor(gateway);
		int deliveryMode = (Integer) accessor.getPropertyValue("deliveryMode");
		assertThat(deliveryMode).isEqualTo(DeliveryMode.PERSISTENT);
		assertThat(TestUtils.getPropertyValue(gateway, "async", Boolean.class)).isTrue();
		DefaultMessageListenerContainer container = TestUtils.getPropertyValue(gateway, "replyContainer",
				DefaultMessageListenerContainer.class);
		assertThat(TestUtils.getPropertyValue(container, "concurrentConsumers")).isEqualTo(4);
		assertThat(TestUtils.getPropertyValue(container, "maxConcurrentConsumers")).isEqualTo(5);
		assertThat(TestUtils.getPropertyValue(container, "maxMessagesPerTask")).isEqualTo(10);
		assertThat(TestUtils.getPropertyValue(container, "receiveTimeout")).isEqualTo(2000L);
		Object recoveryInterval;
		try {
			recoveryInterval = TestUtils.getPropertyValue(container, "recoveryInterval");
		}
		catch (NotReadablePropertyException e) {
			recoveryInterval = TestUtils.getPropertyValue(container, "backOff.interval");
		}
		assertThat(recoveryInterval).isEqualTo(10000L);

		assertThat(TestUtils.getPropertyValue(container, "idleConsumerLimit")).isEqualTo(7);
		assertThat(TestUtils.getPropertyValue(container, "idleTaskExecutionLimit")).isEqualTo(2);
		assertThat(TestUtils.getPropertyValue(container, "cacheLevel")).isEqualTo(3);
		assertThat(container.isSessionTransacted()).isTrue();
		assertThat(TestUtils.getPropertyValue(container, "taskExecutor")).isSameAs(context.getBean("exec"));
		assertThat(TestUtils.getPropertyValue(gateway, "idleReplyContainerTimeout")).isEqualTo(1234000L);
		context.close();
	}

	@Test
	public void testAdvised() {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
				"jmsOutboundGatewayWithDeliveryPersistent.xml", this.getClass());
		EventDrivenConsumer endpoint = (EventDrivenConsumer) context.getBean("advised");
		JmsOutboundGateway gateway = TestUtils.getPropertyValue(endpoint, "handler", JmsOutboundGateway.class);
		assertThat(TestUtils.getPropertyValue(gateway, "async", Boolean.class)).isFalse();
		gateway.handleMessage(new GenericMessage<String>("foo"));
		assertThat(adviceCalled).isEqualTo(1);
		assertThat(TestUtils.getPropertyValue(gateway, "replyContainer.sessionAcknowledgeMode")).isEqualTo(3);
		context.close();
	}

	@Test
	public void testDefault() {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
				"jmsOutboundGatewayWithConverter.xml", this.getClass());
		PollingConsumer endpoint = (PollingConsumer) context.getBean("jmsGateway");
		DirectFieldAccessor accessor = new DirectFieldAccessor(endpoint);
		JmsOutboundGateway gateway = (JmsOutboundGateway) accessor.getPropertyValue("handler");
		accessor = new DirectFieldAccessor(gateway);
		MessageConverter converter = (MessageConverter) accessor.getPropertyValue("messageConverter");
		assertThat(converter instanceof StubMessageConverter).as("Wrong message converter").isTrue();
		context.close();
	}

	@Test
	public void gatewayWithOrder() {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
				"jmsOutboundGatewayWithOrder.xml", this.getClass());
		EventDrivenConsumer endpoint = (EventDrivenConsumer) context.getBean("jmsGateway");
		DirectFieldAccessor accessor = new DirectFieldAccessor(
				new DirectFieldAccessor(endpoint).getPropertyValue("handler"));
		Object order = accessor.getPropertyValue("order");
		assertThat(order).isEqualTo(99);
		assertThat(accessor.getPropertyValue("requiresReply")).isEqualTo(Boolean.TRUE);
		context.close();
	}

	@Test
	public void gatewayWithDest() {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
				"jmsOutboundGatewayReplyDestOptions.xml", this.getClass());
		EventDrivenConsumer endpoint = (EventDrivenConsumer) context.getBean("jmsGatewayDest");
		DirectFieldAccessor accessor = new DirectFieldAccessor(endpoint);
		JmsOutboundGateway gateway = (JmsOutboundGateway) accessor.getPropertyValue("handler");
		accessor = new DirectFieldAccessor(gateway);
		assertThat(accessor.getPropertyValue("replyDestination")).isSameAs(context.getBean("replyQueue"));
		context.close();
	}

	@Test
	public void gatewayWithDestName() {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
				"jmsOutboundGatewayReplyDestOptions.xml", this.getClass());
		EventDrivenConsumer endpoint = (EventDrivenConsumer) context.getBean("jmsGatewayDestName");
		DirectFieldAccessor accessor = new DirectFieldAccessor(endpoint);
		JmsOutboundGateway gateway = (JmsOutboundGateway) accessor.getPropertyValue("handler");
		accessor = new DirectFieldAccessor(gateway);
		assertThat(accessor.getPropertyValue("replyDestinationName")).isEqualTo("replyQueueName");
		context.close();
	}

	@Test
	public void gatewayWithDestExpression() throws Exception {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
				"jmsOutboundGatewayReplyDestOptions.xml", this.getClass());
		EventDrivenConsumer endpoint = (EventDrivenConsumer) context.getBean("jmsGatewayDestExpression");
		DirectFieldAccessor accessor = new DirectFieldAccessor(endpoint);
		JmsOutboundGateway gateway = (JmsOutboundGateway) accessor.getPropertyValue("handler");
		ExpressionEvaluatingMessageProcessor<?> processor = TestUtils.getPropertyValue(gateway, "replyDestinationExpressionProcessor",
				ExpressionEvaluatingMessageProcessor.class);
		Expression expression = TestUtils.getPropertyValue(gateway, "replyDestinationExpressionProcessor.expression",
				Expression.class);
		assertThat(expression.getExpressionString()).isEqualTo("payload");
		Message<?> message = MessageBuilder.withPayload("foo").build();
		assertThat(processor.processMessage(message)).isEqualTo("foo");

		Method method = JmsOutboundGateway.class.getDeclaredMethod("determineReplyDestination", Message.class, Session.class);
		method.setAccessible(true);

		Session session = mock(Session.class);
		Queue queue = mock(Queue.class);
		when(session.createQueue("foo")).thenReturn(queue);
		Destination replyQ = (Destination) method.invoke(gateway, message, session);
		assertThat(replyQ).isSameAs(queue);
		context.close();
	}

	@Test
	public void gatewayWithDestBeanRefExpression() {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
				"jmsOutboundGatewayReplyDestOptions.xml", this.getClass());
		EventDrivenConsumer endpoint = (EventDrivenConsumer) context.getBean("jmsGatewayDestExpressionBeanRef");
		DirectFieldAccessor accessor = new DirectFieldAccessor(endpoint);
		JmsOutboundGateway gateway = (JmsOutboundGateway) accessor.getPropertyValue("handler");
		ExpressionEvaluatingMessageProcessor<?> processor = TestUtils.getPropertyValue(gateway, "replyDestinationExpressionProcessor",
				ExpressionEvaluatingMessageProcessor.class);
		Expression expression = TestUtils.getPropertyValue(gateway, "replyDestinationExpressionProcessor.expression",
				Expression.class);
		assertThat(expression.getExpressionString()).isEqualTo("@replyQueue");
		assertThat(processor.processMessage(null)).isSameAs(context.getBean("replyQueue"));
		context.close();
	}

	@Test
	public void gatewayWithDestAndDestExpression() {
		try {
			new ClassPathXmlApplicationContext(
				"jmsOutboundGatewayReplyDestOptions-fail.xml", this.getClass()).close();
			fail("Exception expected");
		}
		catch (BeanDefinitionParsingException e) {
			assertThat(e.getMessage().startsWith("Configuration problem: Only one of the " +
					"'replyQueue', 'reply-destination-name', or 'reply-destination-expression' attributes is allowed" +
					"."))
					.isTrue();
		}
	}

	@Test
	public void gatewayMaintainsReplyChannelAndInboundHistory() {
		ActiveMqTestUtils.prepare();
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
				"gatewayMaintainsReplyChannel.xml", this.getClass());
		SampleGateway gateway = context.getBean("gateway", SampleGateway.class);
		SubscribableChannel jmsInput = context.getBean("jmsInput", SubscribableChannel.class);
		MessageHandler handler = message -> {
			MessageHistory history = MessageHistory.read(message);
			assertThat(history).isNotNull();
			Properties componentHistoryRecord = TestUtils.locateComponentInHistory(history, "inboundGateway", 0);
			assertThat(componentHistoryRecord).isNotNull();
			assertThat(componentHistoryRecord.get("type")).isEqualTo("jms:inbound-gateway");
			MessagingTemplate messagingTemplate = new MessagingTemplate();
			messagingTemplate.setDefaultDestination((MessageChannel) message.getHeaders().getReplyChannel());
			messagingTemplate.send(message);
		};
		jmsInput.subscribe(handler);
		String result = gateway.echo("hello");
		assertThat(result).isEqualTo("hello");
		JmsOutboundGateway gw1 = context.getBean("chain1$child.gateway.handler", JmsOutboundGateway.class);
		MessageChannel out = TestUtils.getPropertyValue(gw1, "outputChannel", MessageChannel.class);
		assertThat(out.getClass().getSimpleName()).isEqualTo("ReplyForwardingMessageChannel");
		JmsOutboundGateway gw2 = context.getBean("chain2$child.gateway.handler", JmsOutboundGateway.class);
		out = TestUtils.getPropertyValue(gw2, "outputChannel", MessageChannel.class);
		assertThat(out.getClass().getName()).contains("MessageHandlerChain$");
		context.close();
	}

	@Test
	public void gatewayWithDefaultPubSubDomain() {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
				"jmsOutboundGatewayWithPubSubSettings.xml", this.getClass());
		EventDrivenConsumer endpoint = (EventDrivenConsumer) context.getBean("defaultGateway");
		DirectFieldAccessor accessor = new DirectFieldAccessor(
				new DirectFieldAccessor(endpoint).getPropertyValue("handler"));
		assertThat((Boolean) accessor.getPropertyValue("requestPubSubDomain")).isFalse();
		assertThat((Boolean) accessor.getPropertyValue("replyPubSubDomain")).isFalse();
		context.close();
	}

	@Test
	public void gatewayWithExplicitPubSubDomainTrue() {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
				"jmsOutboundGatewayWithPubSubSettings.xml", this.getClass());
		EventDrivenConsumer endpoint = (EventDrivenConsumer) context.getBean("pubSubDomainGateway");
		DirectFieldAccessor accessor = new DirectFieldAccessor(
				new DirectFieldAccessor(endpoint).getPropertyValue("handler"));
		assertThat((Boolean) accessor.getPropertyValue("requestPubSubDomain")).isTrue();
		assertThat((Boolean) accessor.getPropertyValue("replyPubSubDomain")).isTrue();
		context.close();
	}

	public interface SampleGateway {

		String echo(String value);

	}

	public static class SampleService {

		public String echo(String value) {
			return value.toUpperCase();
		}

	}

	public static class FooAdvice extends AbstractRequestHandlerAdvice {

		@Override
		protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) {
			adviceCalled++;
			return null;
		}

	}

}

{'repo_name': 'spring-projects/spring-integration', 'stars': '1054', 'repo_language': 'Java', 'file_name': 'CacheListeningMessageProducerTests.java', 'mime_type': 'text/x-java', 'hash': -2396740802394371583, 'source_dataset': 'data'}


// This file was autogenerated by print_selective_registration_header.py
#ifndef OPS_TO_REGISTER
#define OPS_TO_REGISTER

    namespace {
      constexpr const char* skip(const char* x) {
        return (*x) ? (*x == ' ' ? skip(x + 1) : x) : x;
      }

      constexpr bool isequal(const char* x, const char* y) {
        return (*skip(x) && *skip(y))
                   ? (*skip(x) == *skip(y) && isequal(skip(x) + 1, skip(y) + 1))
                   : (!*skip(x) && !*skip(y));
      }

      template<int N>
      struct find_in {
        static constexpr bool f(const char* x, const char* const y[N]) {
          return isequal(x, y[0]) || find_in<N - 1>::f(x, y + 1);
        }
      };

      template<>
      struct find_in<0> {
        static constexpr bool f(const char* x, const char* const y[]) {
          return false;
        }
      };
    }  // end namespace
    constexpr const char* kNecessaryOpKernelClasses[] = {
"BinaryOp< CPUDevice, functor::add<float>>",
"BinaryOp< CPUDevice, functor::add<int32>>",
"AddNOp< CPUDevice, float>",
"ReductionOp<CPUDevice, bool, Eigen::internal::AndReducer>",
"AssertOp",
"AvgPoolingOp<CPUDevice, float>",
"BiasOp<CPUDevice, float>",
"CpuCastOp",
"ConcatV2Op<CPUDevice, ::tensorflow::int32>",
"ConcatV2Op<CPUDevice, float>",
"ConstantOp",
//"Conv2DOp<CPUDevice, float>",
"Conv2DUsingGemmOp< float, Im2ColConvFunctor<float, float, float, FastGemmFunctor<float, float, float>>>",
"DepthwiseConv2dNativeOp<CPUDevice, float>",
"CropAndResizeOp<CPUDevice, float>",
"DequantizeOp<CPUDevice, quint8>",
"EnterOp",
"BinaryOp< CPUDevice, functor::equal_to<int32>>",
"ExitOp",
"UnaryOp< CPUDevice, functor::exp<float>>",
"ExpandDimsOp",
"FillOp<CPUDevice, ::tensorflow::int32>",
"FillOp<CPUDevice, float>",
"GatherOp<CPUDevice, float, int32>",
"BinaryOp< CPUDevice, functor::greater<float>>",
"BinaryOp< CPUDevice, functor::greater<int32>>",
"BinaryOp< CPUDevice, functor::greater_equal<int32>>",
"IdentityOp",
"BinaryOp< CPUDevice, functor::less<int32>>",
"BinaryOp<CPUDevice, functor::logical_and>",
"LoopCondOp",
"MatMulOp<CPUDevice, float, false >",
"ReductionOp<CPUDevice, ::tensorflow::int32, Eigen::internal::MaxReducer<::tensorflow::int32>>",
"MaxPoolingOp<CPUDevice, float>",
"BinaryOp< CPUDevice, functor::maximum<float>>",
"ReductionOp<CPUDevice, float, Eigen::internal::MeanReducer<float>>",
"MergeOp",
"BinaryOp< CPUDevice, functor::minimum<float>>",
"BinaryOp< CPUDevice, functor::minimum<int32>>",
"BinaryOp< CPUDevice, functor::mul<float>>",
"BinaryOp< CPUDevice, functor::mul<int32>>",
"NextIterationOp",
"NoOp",
"NonMaxSuppressionOp<CPUDevice>",
"PackOp<CPUDevice, ::tensorflow::int32>",
"PackOp<CPUDevice, float>",
"PadOp<CPUDevice, float>",
"PlaceholderOp",
"RangeOp<::tensorflow::int32>",
"RankOp",
"BinaryOp< CPUDevice, functor::div<float>>",
"ReluOp<CPUDevice, float>",
"Relu6Op<CPUDevice, float>",
"ReshapeOp",
"ResizeBilinearOp<CPUDevice, float>",
"UnaryOp< CPUDevice, functor::round<float>>",
"UnaryOp< CPUDevice, functor::rsqrt<float>>",
"ShapeOp<int32>",
"UnaryOp< CPUDevice, functor::sigmoid<float>>",
"SizeOp<int32>",
"SliceOp<CPUDevice, ::tensorflow::int32>",
"SliceOp<CPUDevice, float>",
"SoftmaxOp<CPUDevice, float>",
"SplitOpCPU<float>",
"UnaryOp< CPUDevice, functor::sqrt<float>>",
"SqueezeOp",
"StridedSliceOp<CPUDevice, ::tensorflow::int32>",
"StridedSliceOp<CPUDevice, float>",
"BinaryOp< CPUDevice, functor::sub<float>>",
"BinaryOp< CPUDevice, functor::sub<int32>>",
"SwitchOp",
"TensorArrayPackOrGatherOp<CPUDevice, float, false >",
"TensorArrayReadOp<CPUDevice, float>",
"TensorArrayUnpackOrScatterOp<CPUDevice, float, false >",
"TensorArraySizeOp",
"TensorArrayOp",
"TensorArrayWriteOp<CPUDevice, float>",
"TileOp<CPUDevice>",
"TopK<CPUDevice, float>",
"TransposeCpuOp",
"UnpackOp<CPUDevice, ::tensorflow::int32>",
"UnpackOp<CPUDevice, float>",
"WhereCPUOp",
"ZerosLikeOp< CPUDevice, float>",
"RecvOp",
"SendOp",
};
#define SHOULD_REGISTER_OP_KERNEL(clz) (find_in<sizeof(kNecessaryOpKernelClasses) / sizeof(*kNecessaryOpKernelClasses)>::f(clz, kNecessaryOpKernelClasses))

constexpr inline bool ShouldRegisterOp(const char op[]) {
  return false
     || isequal(op, "Add")
     || isequal(op, "AddN")
     || isequal(op, "All")
     || isequal(op, "Assert")
     || isequal(op, "AvgPool")
     || isequal(op, "BiasAdd")
     || isequal(op, "Cast")
     || isequal(op, "ConcatV2")
     || isequal(op, "Const")
     || isequal(op, "Conv2D")
     || isequal(op, "DepthwiseConv2dNative")
     || isequal(op, "CropAndResize")
     || isequal(op, "Dequantize")
     || isequal(op, "Enter")
     || isequal(op, "Equal")
     || isequal(op, "Exit")
     || isequal(op, "Exp")
     || isequal(op, "ExpandDims")
     || isequal(op, "Fill")
     || isequal(op, "Gather")
     || isequal(op, "Greater")
     || isequal(op, "GreaterEqual")
     || isequal(op, "Identity")
     || isequal(op, "Less")
     || isequal(op, "LogicalAnd")
     || isequal(op, "LoopCond")
     || isequal(op, "MatMul")
     || isequal(op, "Max")
     || isequal(op, "MaxPool")
     || isequal(op, "Maximum")
     || isequal(op, "Mean")
     || isequal(op, "Merge")
     || isequal(op, "Minimum")
     || isequal(op, "Mul")
     || isequal(op, "NextIteration")
     || isequal(op, "NoOp")
     || isequal(op, "NonMaxSuppression")
     || isequal(op, "Pack")
     || isequal(op, "Pad")
     || isequal(op, "Placeholder")
     || isequal(op, "Range")
     || isequal(op, "Rank")
     || isequal(op, "RealDiv")
     || isequal(op, "Relu")
     || isequal(op, "Relu6")
     || isequal(op, "Reshape")
     || isequal(op, "ResizeBilinear")
     || isequal(op, "Rsqrt")
     || isequal(op, "Round")
     || isequal(op, "Shape")
     || isequal(op, "Sigmoid")
     || isequal(op, "Size")
     || isequal(op, "Slice")
     || isequal(op, "Softmax")
     || isequal(op, "Split")
     || isequal(op, "Sqrt")
     || isequal(op, "Squeeze")
     || isequal(op, "StridedSlice")
     || isequal(op, "Sub")
     || isequal(op, "Switch")
     || isequal(op, "TensorArrayGatherV3")
     || isequal(op, "TensorArrayReadV3")
     || isequal(op, "TensorArrayScatterV3")
     || isequal(op, "TensorArraySizeV3")
     || isequal(op, "TensorArrayV3")
     || isequal(op, "TensorArrayWriteV3")
     || isequal(op, "Tile")
     || isequal(op, "TopKV2")
     || isequal(op, "Transpose")
     || isequal(op, "Unpack")
     || isequal(op, "Where")
     || isequal(op, "ZerosLike")
     || isequal(op, "_Recv")
     || isequal(op, "_Send")
  ;
}
#define SHOULD_REGISTER_OP(op) ShouldRegisterOp(op)

#define SHOULD_REGISTER_OP_GRADIENT false
#endif

{'repo_name': 'JieHe96/iOS_Tensorflow_ObjectDetection_Example', 'stars': '125', 'repo_language': 'C++', 'file_name': 'contents.xcworkspacedata', 'mime_type': 'text/xml', 'hash': -2173658444097746474, 'source_dataset': 'data'}


//  (C) Copyright 2009-2011 Frederic Bron.
//
//  Use, modification and distribution are subject to the Boost Software License,
//  Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt).
//
//  See http://www.boost.org/libs/type_traits for most recent version including documentation.

#ifndef BOOST_TT_HAS_EQUAL_TO_HPP_INCLUDED
#define BOOST_TT_HAS_EQUAL_TO_HPP_INCLUDED

#define BOOST_TT_TRAIT_NAME has_equal_to
#define BOOST_TT_TRAIT_OP ==
#define BOOST_TT_FORBIDDEN_IF\
   ::boost::type_traits::ice_or<\
      /* Lhs==pointer and Rhs==fundamental */\
      ::boost::type_traits::ice_and<\
         ::boost::is_pointer< Lhs_noref >::value,\
         ::boost::is_fundamental< Rhs_nocv >::value\
      >::value,\
      /* Rhs==pointer and Lhs==fundamental */\
      ::boost::type_traits::ice_and<\
         ::boost::is_pointer< Rhs_noref >::value,\
         ::boost::is_fundamental< Lhs_nocv >::value\
      >::value,\
      /* Lhs==pointer and Rhs==pointer and Lhs!=base(Rhs) and Rhs!=base(Lhs) and Lhs!=void* and Rhs!=void* */\
      ::boost::type_traits::ice_and<\
         ::boost::is_pointer< Lhs_noref >::value,\
         ::boost::is_pointer< Rhs_noref >::value,\
         ::boost::type_traits::ice_not<\
            ::boost::type_traits::ice_or<\
               ::boost::is_base_of< Lhs_noptr, Rhs_noptr >::value,\
               ::boost::is_base_of< Rhs_noptr, Lhs_noptr >::value,\
               ::boost::is_same< Lhs_noptr, Rhs_noptr >::value,\
               ::boost::is_void< Lhs_noptr >::value,\
               ::boost::is_void< Rhs_noptr >::value\
            >::value\
         >::value\
      >::value\
   >::value

#include <boost/type_traits/detail/has_binary_operator.hpp>

#undef BOOST_TT_TRAIT_NAME
#undef BOOST_TT_TRAIT_OP
#undef BOOST_TT_FORBIDDEN_IF

#endif

{'repo_name': 'pmoulon/CMVS-PMVS', 'stars': '743', 'repo_language': 'C++', 'file_name': 'libgfx-license.html', 'mime_type': 'text/html', 'hash': -5132781217108877706, 'source_dataset': 'data'}


array [1..21] of int: Formula = [1, 2, 3, 1, 2, -3, 1, -2, 3, 1, -2, -3, -1, 2, 3, -1, 2, -3, -1, -2, 3];
var bool: BOOL____00001 :: is_defined_var :: var_is_introduced;
var bool: BOOL____00002 :: is_defined_var :: var_is_introduced;
var bool: BOOL____00004 :: is_defined_var :: var_is_introduced;
array [1..3] of var bool: assignment :: output_array([1..3]);
constraint array_bool_or([BOOL____00004, BOOL____00001, assignment[2]], true);
constraint array_bool_or([BOOL____00004, assignment[1], BOOL____00002], true);
constraint array_bool_or([BOOL____00004, assignment[1], assignment[2]], true);
constraint array_bool_or([assignment[3], BOOL____00001, BOOL____00002], true);
constraint array_bool_or([assignment[3], BOOL____00001, assignment[2]], true);
constraint array_bool_or([assignment[3], assignment[1], BOOL____00002], true);
constraint array_bool_or([assignment[3], assignment[1], assignment[2]], true);
constraint bool_eq_reif(assignment[1], false, BOOL____00001) :: defines_var(BOOL____00001);
constraint bool_eq_reif(assignment[2], false, BOOL____00002) :: defines_var(BOOL____00002);
constraint bool_eq_reif(assignment[3], false, BOOL____00004) :: defines_var(BOOL____00004);
solve satisfy;

{'repo_name': 'google/or-tools', 'stars': '5864', 'repo_language': 'C++', 'file_name': 'WAE_GAU1.TEST_54.vbp', 'mime_type': 'text/plain', 'hash': 626704966312220108, 'source_dataset': 'data'}


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

raise RuntimeError( "I am a very naughty boy" )

{'repo_name': 'ImageEngine/cortex', 'stars': '391', 'repo_language': 'C++', 'file_name': 'Doxyfile', 'mime_type': 'text/plain', 'hash': -7007870662628939329, 'source_dataset': 'data'}


// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.media.router.cast.remoting;

import android.support.annotation.Nullable;
import android.support.v7.media.MediaRouter;

import org.chromium.base.Log;
import org.chromium.base.VisibleForTesting;
import org.chromium.chrome.browser.media.router.ChromeMediaRouter;
import org.chromium.chrome.browser.media.router.FlingingController;
import org.chromium.chrome.browser.media.router.MediaRoute;
import org.chromium.chrome.browser.media.router.MediaRouteManager;
import org.chromium.chrome.browser.media.router.MediaRouteProvider;
import org.chromium.chrome.browser.media.router.MediaSink;
import org.chromium.chrome.browser.media.router.MediaSource;
import org.chromium.chrome.browser.media.router.cast.BaseMediaRouteProvider;
import org.chromium.chrome.browser.media.router.cast.CastSession;
import org.chromium.chrome.browser.media.router.cast.ChromeCastSessionManager;
import org.chromium.chrome.browser.media.router.cast.CreateRouteRequest;

/**
 * A {@link MediaRouteProvider} implementation for media remote playback.
 */
// Migrated to CafRemotingMediaRouteProvider. See https://crbug.com/711860.
public class RemotingMediaRouteProvider extends BaseMediaRouteProvider {
    private static final String TAG = "MediaRemoting";

    private int mPendingNativeRequestId;
    private MediaRoute mPendingMediaRoute;

    /**
     * @return Initialized {@link RemotingMediaRouteProvider} object.
     */
    public static RemotingMediaRouteProvider create(MediaRouteManager manager) {
        return new RemotingMediaRouteProvider(ChromeMediaRouter.getAndroidMediaRouter(), manager);
    }

    @Override
    protected MediaSource getSourceFromId(String sourceId) {
        return RemotingMediaSource.from(sourceId);
    }

    @Override
    protected ChromeCastSessionManager.CastSessionLaunchRequest createSessionLaunchRequest(
            MediaSource source, MediaSink sink, String presentationId, String origin, int tabId,
            boolean isIncognito, int nativeRequestId) {
        return new CreateRouteRequest(source, sink, presentationId, origin, tabId, isIncognito,
                nativeRequestId, this, CreateRouteRequest.RequestedCastSessionType.REMOTE, null);
    }

    @Override
    public void joinRoute(
            String sourceId, String presentationId, String origin, int tabId, int nativeRequestId) {
        mManager.onRouteRequestError(
                "Remote playback doesn't support joining routes", nativeRequestId);
    }

    @Override
    public void closeRoute(String routeId) {
        MediaRoute route = mRoutes.get(routeId);
        if (route == null) return;

        if (mSession == null) {
            mRoutes.remove(routeId);
            mManager.onRouteTerminated(routeId);
            return;
        }

        ChromeCastSessionManager.get().stopApplication();
    }

    @Override
    public void detachRoute(String routeId) {
        mRoutes.remove(routeId);
    }

    @Override
    public void sendStringMessage(String routeId, String message) {
        Log.e(TAG, "Remote playback does not support sending messages");
    }

    @VisibleForTesting
    RemotingMediaRouteProvider(MediaRouter androidMediaRouter, MediaRouteManager manager) {
        super(androidMediaRouter, manager);
    }

    @Override
    public void onSessionEnded() {
        if (mSession == null) return;

        for (String routeId : mRoutes.keySet()) mManager.onRouteTerminated(routeId);
        mRoutes.clear();

        mSession = null;

        if (mAndroidMediaRouter != null) {
            mAndroidMediaRouter.selectRoute(mAndroidMediaRouter.getDefaultRoute());
        }
    }

    @Override
    public void onSessionStarting(ChromeCastSessionManager.CastSessionLaunchRequest launchRequest) {
        CreateRouteRequest request = (CreateRouteRequest) launchRequest;
        MediaSink sink = request.getSink();
        MediaSource source = request.getSource();

        // Calling mManager.onRouteCreated() too early causes some issues. If we call it here
        // directly, getMediaController() might be called before onSessionStarted(), which causes
        // the FlingingRenderer's creation to fail. Instead, save the route and request ID, and only
        // signal the route as having been created when onSessionStarted() is called.
        mPendingMediaRoute =
                new MediaRoute(sink.getId(), source.getSourceId(), request.getPresentationId());
        mPendingNativeRequestId = request.getNativeRequestId();
    }

    private void clearPendingRoute() {
        mPendingMediaRoute = null;
        mPendingNativeRequestId = 0;
    }

    @Override
    public void onSessionStarted(CastSession session) {
        super.onSessionStarted(session);

        // Continued from onSessionStarting()
        mRoutes.put(mPendingMediaRoute.id, mPendingMediaRoute);
        mManager.onRouteCreated(mPendingMediaRoute.id, mPendingMediaRoute.sinkId,
                mPendingNativeRequestId, this, true);

        clearPendingRoute();
    }

    @Override
    public void onSessionStartFailed() {
        super.onSessionStartFailed();

        mManager.onRouteRequestError(
                "Failure to start RemotingCastSession", mPendingNativeRequestId);

        clearPendingRoute();
    };

    @Override
    @Nullable
    public FlingingController getFlingingController(String routeId) {
        // We cannot return a FlingingController if we don't have a session.
        if (mSession == null) return null;

        // Don't return controllers for stale routes.
        if (!mRoutes.containsKey(routeId)) return null;

        // RemotePlayback does not support joining routes, which means we only
        // have a single route active at a time. If we have a a valid CastSession
        // and the route ID is current, this means that the given |mSession|
        // corresponds to the route ID, and it is ok to return the FlingingController.
        return mSession.getFlingingController();
    }
}

{'repo_name': 'kuoruan/Chromium-Android', 'stars': '224', 'repo_language': 'Java', 'file_name': 'autofill_assistant_chip_assistive_bg.xml', 'mime_type': 'text/xml', 'hash': 1110071219160670915, 'source_dataset': 'data'}


package com.mashibing.transformer.mr.inbound;

import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
import org.apache.hadoop.hbase.filter.Filter;
import org.apache.hadoop.hbase.filter.FilterList;
import org.apache.hadoop.hbase.filter.SingleColumnValueFilter;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.log4j.Logger;

import com.mashibing.common.EventLogConstants;
import com.mashibing.common.EventLogConstants.EventEnum;
import com.mashibing.transformer.model.dim.StatsInboundDimension;
import com.mashibing.transformer.model.value.map.TextsOutputValue;
import com.mashibing.transformer.model.value.reduce.InboundReduceValue;
import com.mashibing.transformer.mr.TransformerBaseRunner;

/**
 * 计算活跃用户和总会话的入口类
 *
 * @author 马士兵教育
 *
 */
public class InboundRunner extends TransformerBaseRunner {
    private static final Logger logger = Logger.getLogger(InboundRunner.class);

    public static void main(String[] args) {
        InboundRunner runner = new InboundRunner();
        runner.setupRunner("inbound", InboundRunner.class, InboundMapper.class, InboundReducer.class, StatsInboundDimension.class, TextsOutputValue.class, StatsInboundDimension.class, InboundReduceValue.class);
        try {
            runner.startRunner(args);
        } catch (Exception e) {
            logger.error("执行异常", e);
            throw new RuntimeException("执行异常", e);
        }
    }

    @Override
    protected Filter fetchHbaseFilter() {
        FilterList list = new FilterList();
        String[] columns = new String[] { EventLogConstants.LOG_COLUMN_NAME_REFERRER_URL, // 前一个页面的url
                EventLogConstants.LOG_COLUMN_NAME_UUID, // uuid
                EventLogConstants.LOG_COLUMN_NAME_SESSION_ID, // 会话id
                EventLogConstants.LOG_COLUMN_NAME_PLATFORM, // 平台名称
                EventLogConstants.LOG_COLUMN_NAME_SERVER_TIME, // 服务器时间
                EventLogConstants.LOG_COLUMN_NAME_EVENT_NAME // 事件名称
        };
        list.addFilter(this.getColumnFilter(columns));
        list.addFilter(new SingleColumnValueFilter(InboundMapper.family, Bytes.toBytes(EventLogConstants.LOG_COLUMN_NAME_EVENT_NAME), CompareOp.EQUAL, Bytes.toBytes(EventEnum.PAGEVIEW.alias)));
        return list;
    }

}

{'repo_name': 'bjmashibing/BigDataArchitect', 'stars': '101', 'repo_language': 'Java', 'file_name': 'data.txt', 'mime_type': 'text/plain', 'hash': 2558283715485923224, 'source_dataset': 'data'}


placeholder folder for SAMM presentations.

First version to create for presenting SAMMv2 at Global AppSec Tel Aviv in May 2019.

{'repo_name': 'OWASP/samm', 'stars': '263', 'repo_language': 'JavaScript', 'file_name': 'v-security-testing.md', 'mime_type': 'text/plain', 'hash': -9047413101769831776, 'source_dataset': 'data'}


/* { dg-do run } */

int v, x;

__attribute__((noipa)) void
foo (int *a)
{
  #pragma omp for simd lastprivate (conditional: x) schedule(simd: static) if (simd: 0)
  for (int i = 0; i < 128; i++)
    if (a[i])
      x = a[i];
}

__attribute__((noipa)) void
bar (int *a, int *b)
{
  #pragma omp for simd lastprivate (conditional: x, v) schedule(static, 16) simdlen(1)
  for (int i = 16; i < 128; ++i)
    {
      if (a[i])
	x = a[i];
      if (b[i])
	v = b[i] + 10;
    }
}

__attribute__((noipa)) void
baz (int *a)
{
  #pragma omp for simd lastprivate (conditional: x) schedule(simd: dynamic, 16) if (0)
  for (int i = 0; i < 128; i++)
    if (a[i])
      x = a[i] + 5;
}

int
main ()
{
  int a[128], b[128], i;
  for (i = 0; i < 128; i++)
    {
      a[i] = ((i % 11) == 2) ? i + 10 : 0;
      asm volatile ("" : "+g" (i));
      b[i] = ((i % 13) == 5) ? i * 2 : 0;
    }
  #pragma omp parallel
  foo (a);
  if (x != 133)
    __builtin_abort ();
  x = -3;
  #pragma omp parallel
  bar (b, a);
  if (x != 244 || v != 143)
    __builtin_abort ();
  #pragma omp parallel
  baz (b);
  if (x != 249)
    __builtin_abort ();
  return 0;
}

{'repo_name': 'gcc-mirror/gcc', 'stars': '3986', 'repo_language': 'C', 'file_name': 'epiphany.opt', 'mime_type': 'text/plain', 'hash': 4211260708110924097, 'source_dataset': 'data'}


// run

// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

// Make sure the compiler knows that DUFFCOPY clobbers X0

import "fmt"

//go:noinline
func f(x float64) float64 {
	// y is allocated to X0
	y := x + 5
	// marshals z before y.  Marshaling z
	// calls DUFFCOPY.
	return g(z, y)
}

//go:noinline
func g(b [64]byte, y float64) float64 {
	return y
}

var z [64]byte

func main() {
	got := f(5)
	if got != 10 {
		panic(fmt.Sprintf("want 10, got %f", got))
	}
}

{'repo_name': 'golang/go', 'stars': '74444', 'repo_language': 'Go', 'file_name': 'codewalk.css', 'mime_type': 'text/x-asm', 'hash': 106009563396144238, 'source_dataset': 'data'}


#pragma once

namespace BulletSharp
{
	ref class ManifoldPoint;
	ref class CollisionObject;

#ifdef BT_CALLBACKS_ARE_EVENTS
	public delegate void ContactDestroyedEventHandler(Object^ userPersistantData);
	public delegate void ContactProcessedEventHandler(ManifoldPoint^ cp, CollisionObject^ body0, CollisionObject^ body1);
#else
	public delegate bool ContactDestroyed(Object^ userPersistantData);
	public delegate bool ContactProcessed(ManifoldPoint^ cp, CollisionObject^ body0, CollisionObject^ body1);
#endif

	public value struct PersistentManifold
	{
	internal:
		btPersistentManifold* _native;

		PersistentManifold(btPersistentManifold* native);

#ifdef BT_CALLBACKS_ARE_EVENTS
		static ContactDestroyedEventHandler^ _contactDestroyed;
		static ContactProcessedEventHandler^ _contactProcessed;

	public:
		static event ContactDestroyedEventHandler^ ContactDestroyed
		{
			void add(ContactDestroyedEventHandler^ callback);
			void remove(ContactDestroyedEventHandler^ callback);
		}
		static event ContactProcessedEventHandler^ ContactProcessed
		{
			void add(ContactProcessedEventHandler^ callback);
			void remove(ContactProcessedEventHandler^ callback);
		}
#else
		static ContactDestroyed^ _contactDestroyed;
		static ContactProcessed^ _contactProcessed;

	public:
		static property ContactDestroyed^ ContactDestroyed
		{
			::ContactDestroyed^ get();
			void set(::ContactDestroyed^ value);
		}

		static property ContactProcessed^ ContactProcessed
		{
			::ContactProcessed^ get();
			void set(::ContactProcessed^ value);
		}
#endif
/*
		PersistentManifold();
		PersistentManifold(CollisionObject^ body0, CollisionObject^ body1, int __unnamed2,
			btScalar contactBreakingThreshold, btScalar contactProcessingThreshold);
*/
		int AddManifoldPoint(ManifoldPoint^ newPoint, bool isPredictive);
		int AddManifoldPoint(ManifoldPoint^ newPoint);
		void ClearManifold();
		void ClearUserCache(ManifoldPoint^ pt);
		virtual bool Equals(Object^ obj) override;
		int GetCacheEntry(ManifoldPoint^ newPoint);
		virtual int GetHashCode() override;
		ManifoldPoint^ GetContactPoint(int index);
		void RefreshContactPoints(Matrix trA, Matrix trB);
		void RemoveContactPoint(int index);
		void ReplaceContactPoint(ManifoldPoint^ newPoint, int insertIndex);
		void SetBodies(CollisionObject^ body0, CollisionObject^ body1);
		bool ValidContactDistance(ManifoldPoint^ pt);
		static bool operator== (PersistentManifold value1, PersistentManifold value2);
		static bool operator!= (PersistentManifold value1, PersistentManifold value2);

		property CollisionObject^ Body0
		{
			CollisionObject^ get();
		}

		property CollisionObject^ Body1
		{
			CollisionObject^ get();
		}

		property int CompanionIDA
		{
			int get();
			void set(int value);
		}

		property int CompanionIDB
		{
			int get();
			void set(int value);
		}

		property btScalar ContactBreakingThreshold
		{
			btScalar get();
			void set(btScalar contactBreakingThreshold);
		}

		property btScalar ContactProcessingThreshold
		{
			btScalar get();
			void set(btScalar contactProcessingThreshold);
		}

		property int Index1A
		{
			int get();
			void set(int value);
		}

		property int NumContacts
		{
			int get();
			void set(int cachedPoints);
		}

		static PersistentManifold Zero;
	};
};

{'repo_name': 'AndresTraks/BulletSharp', 'stars': '191', 'repo_language': 'C++', 'file_name': 'BasicDemo.sln', 'mime_type': 'text/plain', 'hash': -5580750259992827686, 'source_dataset': 'data'}


// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package get

import "testing"

var selectTagTestTags = []string{
	"go.r58",
	"go.r58.1",
	"go.r59",
	"go.r59.1",
	"go.r61",
	"go.r61.1",
	"go.weekly.2010-01-02",
	"go.weekly.2011-10-12",
	"go.weekly.2011-10-12.1",
	"go.weekly.2011-10-14",
	"go.weekly.2011-11-01",
	"go1",
	"go1.0.1",
	"go1.999",
	"go1.9.2",
	"go5",

	// these should be ignored:
	"release.r59",
	"release.r59.1",
	"release",
	"weekly.2011-10-12",
	"weekly.2011-10-12.1",
	"weekly",
	"foo",
	"bar",
	"go.f00",
	"go!r60",
	"go.1999-01-01",
	"go.2x",
	"go.20000000000000",
	"go.2.",
	"go.2.0",
	"go2x",
	"go20000000000000",
	"go2.",
	"go2.0",
}

var selectTagTests = []struct {
	version  string
	selected string
}{
	/*
		{"release.r57", ""},
		{"release.r58.2", "go.r58.1"},
		{"release.r59", "go.r59"},
		{"release.r59.1", "go.r59.1"},
		{"release.r60", "go.r59.1"},
		{"release.r60.1", "go.r59.1"},
		{"release.r61", "go.r61"},
		{"release.r66", "go.r61.1"},
		{"weekly.2010-01-01", ""},
		{"weekly.2010-01-02", "go.weekly.2010-01-02"},
		{"weekly.2010-01-02.1", "go.weekly.2010-01-02"},
		{"weekly.2010-01-03", "go.weekly.2010-01-02"},
		{"weekly.2011-10-12", "go.weekly.2011-10-12"},
		{"weekly.2011-10-12.1", "go.weekly.2011-10-12.1"},
		{"weekly.2011-10-13", "go.weekly.2011-10-12.1"},
		{"weekly.2011-10-14", "go.weekly.2011-10-14"},
		{"weekly.2011-10-14.1", "go.weekly.2011-10-14"},
		{"weekly.2011-11-01", "go.weekly.2011-11-01"},
		{"weekly.2014-01-01", "go.weekly.2011-11-01"},
		{"weekly.3000-01-01", "go.weekly.2011-11-01"},
		{"go1", "go1"},
		{"go1.1", "go1.0.1"},
		{"go1.998", "go1.9.2"},
		{"go1.1000", "go1.999"},
		{"go6", "go5"},

		// faulty versions:
		{"release.f00", ""},
		{"weekly.1999-01-01", ""},
		{"junk", ""},
		{"", ""},
		{"go2x", ""},
		{"go200000000000", ""},
		{"go2.", ""},
		{"go2.0", ""},
	*/
	{"anything", "go1"},
}

func TestSelectTag(t *testing.T) {
	for _, c := range selectTagTests {
		selected := selectTag(c.version, selectTagTestTags)
		if selected != c.selected {
			t.Errorf("selectTag(%q) = %q, want %q", c.version, selected, c.selected)
		}
	}
}

{'repo_name': 'riscv/riscv-gcc', 'stars': '155', 'repo_language': 'C', 'file_name': 'visium-protos.h', 'mime_type': 'text/x-c', 'hash': 3362128507626573944, 'source_dataset': 'data'}


/*
 * Renesas R-Car GPIO Support
 *
 *  Copyright (C) 2014 Renesas Electronics Corporation
 *  Copyright (C) 2013 Magnus Damm
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

#include <linux/clk.h>
#include <linux/err.h>
#include <linux/gpio.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/ioport.h>
#include <linux/irq.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/pinctrl/consumer.h>
#include <linux/platform_data/gpio-rcar.h>
#include <linux/platform_device.h>
#include <linux/pm_runtime.h>
#include <linux/spinlock.h>
#include <linux/slab.h>

struct gpio_rcar_priv {
	void __iomem *base;
	spinlock_t lock;
	struct gpio_rcar_config config;
	struct platform_device *pdev;
	struct gpio_chip gpio_chip;
	struct irq_chip irq_chip;
	unsigned int irq_parent;
	struct clk *clk;
};

#define IOINTSEL 0x00	/* General IO/Interrupt Switching Register */
#define INOUTSEL 0x04	/* General Input/Output Switching Register */
#define OUTDT 0x08	/* General Output Register */
#define INDT 0x0c	/* General Input Register */
#define INTDT 0x10	/* Interrupt Display Register */
#define INTCLR 0x14	/* Interrupt Clear Register */
#define INTMSK 0x18	/* Interrupt Mask Register */
#define MSKCLR 0x1c	/* Interrupt Mask Clear Register */
#define POSNEG 0x20	/* Positive/Negative Logic Select Register */
#define EDGLEVEL 0x24	/* Edge/level Select Register */
#define FILONOFF 0x28	/* Chattering Prevention On/Off Register */
#define BOTHEDGE 0x4c	/* One Edge/Both Edge Select Register */

#define RCAR_MAX_GPIO_PER_BANK		32

static inline u32 gpio_rcar_read(struct gpio_rcar_priv *p, int offs)
{
	return ioread32(p->base + offs);
}

static inline void gpio_rcar_write(struct gpio_rcar_priv *p, int offs,
				   u32 value)
{
	iowrite32(value, p->base + offs);
}

static void gpio_rcar_modify_bit(struct gpio_rcar_priv *p, int offs,
				 int bit, bool value)
{
	u32 tmp = gpio_rcar_read(p, offs);

	if (value)
		tmp |= BIT(bit);
	else
		tmp &= ~BIT(bit);

	gpio_rcar_write(p, offs, tmp);
}

static void gpio_rcar_irq_disable(struct irq_data *d)
{
	struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
	struct gpio_rcar_priv *p = container_of(gc, struct gpio_rcar_priv,
						gpio_chip);

	gpio_rcar_write(p, INTMSK, ~BIT(irqd_to_hwirq(d)));
}

static void gpio_rcar_irq_enable(struct irq_data *d)
{
	struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
	struct gpio_rcar_priv *p = container_of(gc, struct gpio_rcar_priv,
						gpio_chip);

	gpio_rcar_write(p, MSKCLR, BIT(irqd_to_hwirq(d)));
}

static void gpio_rcar_config_interrupt_input_mode(struct gpio_rcar_priv *p,
						  unsigned int hwirq,
						  bool active_high_rising_edge,
						  bool level_trigger,
						  bool both)
{
	unsigned long flags;

	/* follow steps in the GPIO documentation for
	 * "Setting Edge-Sensitive Interrupt Input Mode" and
	 * "Setting Level-Sensitive Interrupt Input Mode"
	 */

	spin_lock_irqsave(&p->lock, flags);

	/* Configure postive or negative logic in POSNEG */
	gpio_rcar_modify_bit(p, POSNEG, hwirq, !active_high_rising_edge);

	/* Configure edge or level trigger in EDGLEVEL */
	gpio_rcar_modify_bit(p, EDGLEVEL, hwirq, !level_trigger);

	/* Select one edge or both edges in BOTHEDGE */
	if (p->config.has_both_edge_trigger)
		gpio_rcar_modify_bit(p, BOTHEDGE, hwirq, both);

	/* Select "Interrupt Input Mode" in IOINTSEL */
	gpio_rcar_modify_bit(p, IOINTSEL, hwirq, true);

	/* Write INTCLR in case of edge trigger */
	if (!level_trigger)
		gpio_rcar_write(p, INTCLR, BIT(hwirq));

	spin_unlock_irqrestore(&p->lock, flags);
}

static int gpio_rcar_irq_set_type(struct irq_data *d, unsigned int type)
{
	struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
	struct gpio_rcar_priv *p = container_of(gc, struct gpio_rcar_priv,
						gpio_chip);
	unsigned int hwirq = irqd_to_hwirq(d);

	dev_dbg(&p->pdev->dev, "sense irq = %d, type = %d\n", hwirq, type);

	switch (type & IRQ_TYPE_SENSE_MASK) {
	case IRQ_TYPE_LEVEL_HIGH:
		gpio_rcar_config_interrupt_input_mode(p, hwirq, true, true,
						      false);
		break;
	case IRQ_TYPE_LEVEL_LOW:
		gpio_rcar_config_interrupt_input_mode(p, hwirq, false, true,
						      false);
		break;
	case IRQ_TYPE_EDGE_RISING:
		gpio_rcar_config_interrupt_input_mode(p, hwirq, true, false,
						      false);
		break;
	case IRQ_TYPE_EDGE_FALLING:
		gpio_rcar_config_interrupt_input_mode(p, hwirq, false, false,
						      false);
		break;
	case IRQ_TYPE_EDGE_BOTH:
		if (!p->config.has_both_edge_trigger)
			return -EINVAL;
		gpio_rcar_config_interrupt_input_mode(p, hwirq, true, false,
						      true);
		break;
	default:
		return -EINVAL;
	}
	return 0;
}

static int gpio_rcar_irq_set_wake(struct irq_data *d, unsigned int on)
{
	struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
	struct gpio_rcar_priv *p = container_of(gc, struct gpio_rcar_priv,
						gpio_chip);
	int error;

	if (p->irq_parent) {
		error = irq_set_irq_wake(p->irq_parent, on);
		if (error) {
			dev_dbg(&p->pdev->dev,
				"irq %u doesn't support irq_set_wake\n",
				p->irq_parent);
			p->irq_parent = 0;
		}
	}

	if (!p->clk)
		return 0;

	if (on)
		clk_enable(p->clk);
	else
		clk_disable(p->clk);

	return 0;
}

static irqreturn_t gpio_rcar_irq_handler(int irq, void *dev_id)
{
	struct gpio_rcar_priv *p = dev_id;
	u32 pending;
	unsigned int offset, irqs_handled = 0;

	while ((pending = gpio_rcar_read(p, INTDT) &
			  gpio_rcar_read(p, INTMSK))) {
		offset = __ffs(pending);
		gpio_rcar_write(p, INTCLR, BIT(offset));
		generic_handle_irq(irq_find_mapping(p->gpio_chip.irqdomain,
						    offset));
		irqs_handled++;
	}

	return irqs_handled ? IRQ_HANDLED : IRQ_NONE;
}

static inline struct gpio_rcar_priv *gpio_to_priv(struct gpio_chip *chip)
{
	return container_of(chip, struct gpio_rcar_priv, gpio_chip);
}

static void gpio_rcar_config_general_input_output_mode(struct gpio_chip *chip,
						       unsigned int gpio,
						       bool output)
{
	struct gpio_rcar_priv *p = gpio_to_priv(chip);
	unsigned long flags;

	/* follow steps in the GPIO documentation for
	 * "Setting General Output Mode" and
	 * "Setting General Input Mode"
	 */

	spin_lock_irqsave(&p->lock, flags);

	/* Configure postive logic in POSNEG */
	gpio_rcar_modify_bit(p, POSNEG, gpio, false);

	/* Select "General Input/Output Mode" in IOINTSEL */
	gpio_rcar_modify_bit(p, IOINTSEL, gpio, false);

	/* Select Input Mode or Output Mode in INOUTSEL */
	gpio_rcar_modify_bit(p, INOUTSEL, gpio, output);

	spin_unlock_irqrestore(&p->lock, flags);
}

static int gpio_rcar_request(struct gpio_chip *chip, unsigned offset)
{
	struct gpio_rcar_priv *p = gpio_to_priv(chip);
	int error;

	error = pm_runtime_get_sync(&p->pdev->dev);
	if (error < 0)
		return error;

	error = pinctrl_request_gpio(chip->base + offset);
	if (error)
		pm_runtime_put(&p->pdev->dev);

	return error;
}

static void gpio_rcar_free(struct gpio_chip *chip, unsigned offset)
{
	struct gpio_rcar_priv *p = gpio_to_priv(chip);

	pinctrl_free_gpio(chip->base + offset);

	/* Set the GPIO as an input to ensure that the next GPIO request won't
	 * drive the GPIO pin as an output.
	 */
	gpio_rcar_config_general_input_output_mode(chip, offset, false);

	pm_runtime_put(&p->pdev->dev);
}

static int gpio_rcar_direction_input(struct gpio_chip *chip, unsigned offset)
{
	gpio_rcar_config_general_input_output_mode(chip, offset, false);
	return 0;
}

static int gpio_rcar_get(struct gpio_chip *chip, unsigned offset)
{
	u32 bit = BIT(offset);

	/* testing on r8a7790 shows that INDT does not show correct pin state
	 * when configured as output, so use OUTDT in case of output pins */
	if (gpio_rcar_read(gpio_to_priv(chip), INOUTSEL) & bit)
		return !!(gpio_rcar_read(gpio_to_priv(chip), OUTDT) & bit);
	else
		return !!(gpio_rcar_read(gpio_to_priv(chip), INDT) & bit);
}

static void gpio_rcar_set(struct gpio_chip *chip, unsigned offset, int value)
{
	struct gpio_rcar_priv *p = gpio_to_priv(chip);
	unsigned long flags;

	spin_lock_irqsave(&p->lock, flags);
	gpio_rcar_modify_bit(p, OUTDT, offset, value);
	spin_unlock_irqrestore(&p->lock, flags);
}

static int gpio_rcar_direction_output(struct gpio_chip *chip, unsigned offset,
				      int value)
{
	/* write GPIO value to output before selecting output mode of pin */
	gpio_rcar_set(chip, offset, value);
	gpio_rcar_config_general_input_output_mode(chip, offset, true);
	return 0;
}

struct gpio_rcar_info {
	bool has_both_edge_trigger;
};

static const struct gpio_rcar_info gpio_rcar_info_gen1 = {
	.has_both_edge_trigger = false,
};

static const struct gpio_rcar_info gpio_rcar_info_gen2 = {
	.has_both_edge_trigger = true,
};

static const struct of_device_id gpio_rcar_of_table[] = {
	{
		.compatible = "renesas,gpio-r8a7790",
		.data = &gpio_rcar_info_gen2,
	}, {
		.compatible = "renesas,gpio-r8a7791",
		.data = &gpio_rcar_info_gen2,
	}, {
		.compatible = "renesas,gpio-r8a7793",
		.data = &gpio_rcar_info_gen2,
	}, {
		.compatible = "renesas,gpio-r8a7794",
		.data = &gpio_rcar_info_gen2,
	}, {
		.compatible = "renesas,gpio-r8a7795",
		/* Gen3 GPIO is identical to Gen2. */
		.data = &gpio_rcar_info_gen2,
	}, {
		.compatible = "renesas,gpio-rcar",
		.data = &gpio_rcar_info_gen1,
	}, {
		/* Terminator */
	},
};

MODULE_DEVICE_TABLE(of, gpio_rcar_of_table);

static int gpio_rcar_parse_pdata(struct gpio_rcar_priv *p)
{
	struct gpio_rcar_config *pdata = dev_get_platdata(&p->pdev->dev);
	struct device_node *np = p->pdev->dev.of_node;
	struct of_phandle_args args;
	int ret;

	if (pdata) {
		p->config = *pdata;
	} else if (IS_ENABLED(CONFIG_OF) && np) {
		const struct of_device_id *match;
		const struct gpio_rcar_info *info;

		match = of_match_node(gpio_rcar_of_table, np);
		if (!match)
			return -EINVAL;

		info = match->data;

		ret = of_parse_phandle_with_fixed_args(np, "gpio-ranges", 3, 0,
						       &args);
		p->config.number_of_pins = ret == 0 ? args.args[2]
					 : RCAR_MAX_GPIO_PER_BANK;
		p->config.gpio_base = -1;
		p->config.has_both_edge_trigger = info->has_both_edge_trigger;
	}

	if (p->config.number_of_pins == 0 ||
	    p->config.number_of_pins > RCAR_MAX_GPIO_PER_BANK) {
		dev_warn(&p->pdev->dev,
			 "Invalid number of gpio lines %u, using %u\n",
			 p->config.number_of_pins, RCAR_MAX_GPIO_PER_BANK);
		p->config.number_of_pins = RCAR_MAX_GPIO_PER_BANK;
	}

	return 0;
}

static int gpio_rcar_probe(struct platform_device *pdev)
{
	struct gpio_rcar_priv *p;
	struct resource *io, *irq;
	struct gpio_chip *gpio_chip;
	struct irq_chip *irq_chip;
	struct device *dev = &pdev->dev;
	const char *name = dev_name(dev);
	int ret;

	p = devm_kzalloc(dev, sizeof(*p), GFP_KERNEL);
	if (!p)
		return -ENOMEM;

	p->pdev = pdev;
	spin_lock_init(&p->lock);

	/* Get device configuration from DT node or platform data. */
	ret = gpio_rcar_parse_pdata(p);
	if (ret < 0)
		return ret;

	platform_set_drvdata(pdev, p);

	p->clk = devm_clk_get(dev, NULL);
	if (IS_ERR(p->clk)) {
		dev_warn(dev, "unable to get clock\n");
		p->clk = NULL;
	}

	pm_runtime_enable(dev);

	io = platform_get_resource(pdev, IORESOURCE_MEM, 0);
	irq = platform_get_resource(pdev, IORESOURCE_IRQ, 0);

	if (!io || !irq) {
		dev_err(dev, "missing IRQ or IOMEM\n");
		ret = -EINVAL;
		goto err0;
	}

	p->base = devm_ioremap_nocache(dev, io->start, resource_size(io));
	if (!p->base) {
		dev_err(dev, "failed to remap I/O memory\n");
		ret = -ENXIO;
		goto err0;
	}

	gpio_chip = &p->gpio_chip;
	gpio_chip->request = gpio_rcar_request;
	gpio_chip->free = gpio_rcar_free;
	gpio_chip->direction_input = gpio_rcar_direction_input;
	gpio_chip->get = gpio_rcar_get;
	gpio_chip->direction_output = gpio_rcar_direction_output;
	gpio_chip->set = gpio_rcar_set;
	gpio_chip->label = name;
	gpio_chip->dev = dev;
	gpio_chip->owner = THIS_MODULE;
	gpio_chip->base = p->config.gpio_base;
	gpio_chip->ngpio = p->config.number_of_pins;

	irq_chip = &p->irq_chip;
	irq_chip->name = name;
	irq_chip->irq_mask = gpio_rcar_irq_disable;
	irq_chip->irq_unmask = gpio_rcar_irq_enable;
	irq_chip->irq_set_type = gpio_rcar_irq_set_type;
	irq_chip->irq_set_wake = gpio_rcar_irq_set_wake;
	irq_chip->flags	= IRQCHIP_SET_TYPE_MASKED | IRQCHIP_MASK_ON_SUSPEND;

	ret = gpiochip_add(gpio_chip);
	if (ret) {
		dev_err(dev, "failed to add GPIO controller\n");
		goto err0;
	}

	ret = gpiochip_irqchip_add(gpio_chip, irq_chip, p->config.irq_base,
				   handle_level_irq, IRQ_TYPE_NONE);
	if (ret) {
		dev_err(dev, "cannot add irqchip\n");
		goto err1;
	}

	p->irq_parent = irq->start;
	if (devm_request_irq(dev, irq->start, gpio_rcar_irq_handler,
			     IRQF_SHARED, name, p)) {
		dev_err(dev, "failed to request IRQ\n");
		ret = -ENOENT;
		goto err1;
	}

	dev_info(dev, "driving %d GPIOs\n", p->config.number_of_pins);

	/* warn in case of mismatch if irq base is specified */
	if (p->config.irq_base) {
		ret = irq_find_mapping(gpio_chip->irqdomain, 0);
		if (p->config.irq_base != ret)
			dev_warn(dev, "irq base mismatch (%u/%u)\n",
				 p->config.irq_base, ret);
	}

	if (p->config.pctl_name) {
		ret = gpiochip_add_pin_range(gpio_chip, p->config.pctl_name, 0,
					     gpio_chip->base, gpio_chip->ngpio);
		if (ret < 0)
			dev_warn(dev, "failed to add pin range\n");
	}

	return 0;

err1:
	gpiochip_remove(gpio_chip);
err0:
	pm_runtime_disable(dev);
	return ret;
}

static int gpio_rcar_remove(struct platform_device *pdev)
{
	struct gpio_rcar_priv *p = platform_get_drvdata(pdev);

	gpiochip_remove(&p->gpio_chip);

	pm_runtime_disable(&pdev->dev);
	return 0;
}

static struct platform_driver gpio_rcar_device_driver = {
	.probe		= gpio_rcar_probe,
	.remove		= gpio_rcar_remove,
	.driver		= {
		.name	= "gpio_rcar",
		.of_match_table = of_match_ptr(gpio_rcar_of_table),
	}
};

module_platform_driver(gpio_rcar_device_driver);

MODULE_AUTHOR("Magnus Damm");
MODULE_DESCRIPTION("Renesas R-Car GPIO Driver");
MODULE_LICENSE("GPL v2");

{'repo_name': 'JideTechnology/remixos-kernel', 'stars': '142', 'repo_language': 'C', 'file_name': 'i2c-mux-gpio.c', 'mime_type': 'text/x-c', 'hash': -1129886861706956927, 'source_dataset': 'data'}


/*
 * Copyright (c) 2019 Muhammad Utsman
 *
 * 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.
 */

@file:Suppress("UNCHECKED_CAST")

package com.utsman.kemana.driver

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import com.karumi.dexter.Dexter
import com.karumi.dexter.PermissionToken
import com.karumi.dexter.listener.PermissionDeniedResponse
import com.karumi.dexter.listener.PermissionGrantedResponse
import com.karumi.dexter.listener.PermissionRequest
import com.karumi.dexter.listener.single.PermissionListener
import com.mapbox.mapboxsdk.Mapbox
import com.utsman.featurerabbitmq.Rabbit
import com.utsman.kemana.base.*
import com.utsman.kemana.driver.fragment.MainFragment
import com.utsman.kemana.driver.services.LocationServices
import com.utsman.kemana.remote.driver.*
import isfaaghyth.app.notify.Notify

class MainActivity : RxAppCompatActivity() {

    private var driver: Driver? = null
    private lateinit var locationServices: Intent
    private lateinit var mainFragment: MainFragment

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Mapbox.getInstance(this, MAPKEY)
        setContentView(R.layout.activity_main)
        driver = getBundleFrom("driver")

        locationServices = Intent(this, LocationServices::class.java)
        mainFragment = MainFragment(driver)

        setupPermission {
            startService(locationServices)

            composite.delay(900) {
                driver?.let {
                    Notify.send(it)
                }
            }
        }

        replaceFragment(mainFragment, R.id.main_frame)
    }

    private fun setupPermission(ready: () -> Unit) {
        Dexter.withActivity(this)
            .withPermission(Manifest.permission.ACCESS_FINE_LOCATION)
            .withListener(object : PermissionListener {
                override fun onPermissionGranted(response: PermissionGrantedResponse?) {
                    ready.invoke()
                }

                override fun onPermissionRationaleShouldBeShown(
                    permission: PermissionRequest?,
                    token: PermissionToken?
                ) {
                    token?.continuePermissionRequest()
                }

                override fun onPermissionDenied(response: PermissionDeniedResponse?) {
                    loge("permission denied")
                }
            })
            .check()
    }

    override fun onDestroy() {
        super.onDestroy()

        Handler().postDelayed({
            stopService(locationServices)
        }, 800)
    }
}

{'repo_name': 'utsmannn/Kemana', 'stars': '149', 'repo_language': 'Kotlin', 'file_name': 'ExampleUnitTest.kt', 'mime_type': 'text/x-c++', 'hash': 6113194024792825142, 'source_dataset': 'data'}


# -*- test-case-name: twisted.conch.test -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

#

"""
Twisted.Conch: The Twisted Shell. Terminal emulation, SSHv2 and telnet.

Currently this contains the SSHv2 implementation, but it may work over other
protocols in the future. (i.e. Telnet)

Maintainer: Paul Swartz
"""

from twisted.conch._version import version
__version__ = version.short()

{'repo_name': 'nlloyd/SubliminalCollaborator', 'stars': '213', 'repo_language': 'Python', 'file_name': 'init.pp', 'mime_type': 'text/plain', 'hash': -2828674383164648561, 'source_dataset': 'data'}


test_number=05
description="preserve header line"

infile="$test_dir/test.in"
expected="$test_dir/test_$test_number.expected"

subtest=1
outfile="$test_dir/test_$test_number.$subtest.actual"
$bin -k -f 1 -x "s/[0-9]//g" "$test_dir/test.in" > "$outfile"
if [ $? -ne 0 ] ||
   [ "`diff -q $outfile $expected`" ]; then
  test_status $test_number $subtest "$description (index)" FAIL
else
  test_status $test_number $subtest "$description (index)" PASS
  rm "$outfile"
fi

subtest=2
outfile="$test_dir/test_$test_number.$subtest.actual"
$bin -k -F Field-0 -x "s/[0-9]//g" "$test_dir/test.in" > "$outfile"
if [ $? -ne 0 ] ||
   [ "`diff -q $outfile $expected`" ]; then
  test_status $test_number $subtest "$description (label)" FAIL
else
  test_status $test_number $subtest "$description (label)" PASS
  rm "$outfile"
fi

{'repo_name': 'google/crush-tools', 'stars': '135', 'repo_language': 'Shell', 'file_name': 'missing', 'mime_type': 'text/x-shellscript', 'hash': 5396054605703043959, 'source_dataset': 'data'}


## Get

Get a presigned URL of a stored file. You can specify some options: mainly [file access `level`](https://docs.amplify.aws/lib/storage/configureaccess/q/platform/js) and whether to `download` the file:

```typescript
await Storage.get(key: string, config: {
  level?: private | protected | public, // defaults to `public`
  identityId?: string, // id of another user, if `level: protected`
  download?: boolean, // defaults to false
  expires?: number, // validity, in seconds. defaults to no expiry
  contentType?: string // set return content type, eg "text/html"
})
```

`Storage.get` returns a signed URL `string` to your file if `download` is false, which is the default.

`Storage.get` returns a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) of object data if `download` is true.

### File download

Send object data for immediate file download:

```javascript
const data = await Storage.get(`filename.txt`, { download: true })

// data is a Blob
data.Body.text().then(string => {
  // handle the String data return String
})
```

Note that the `Blob` methods like `.text()` are not supported on [IE/Opera/Safari](https://developer.mozilla.org/en-US/docs/Web/API/Blob/text); in those cases you can [parse manually](https://developer.mozilla.org/en-US/docs/Web/API/Blob#JavaScript).

### File Access Levels

You can choose to configure access level ahead of time, or at the point of calling `Storage.get`:

```javascript
// Option 1: configure access ahead of time
Storage.configure({ level: 'private' });
await Storage.get('welcome.png'); // Gets the welcome.png belonging to current user

// Option 2: configure access inside the call
await Storage.get('welcome.png', { level: 'private' }); // same effect
```

Here is a quick guide to the access levels - [see the docs](https://docs.amplify.aws/lib/storage/configureaccess/q/platform/js) for more detail:

- `public`: Accessible by all users of your app. Files are stored under the `public/` path in your S3 bucket.
- `protected`: Readable by all users, but writable only by the creating user. Files are stored under `protected/{user_identity_id}/` where the `user_identity_id` corresponds to the unique Amazon Cognito Identity ID for that user.
    **:**

    ```javascript
    // To get current user's objects
    await Storage.get('filename.txt', { level: 'protected' })
    // To get other users' objects
    await Storage.get('filename.txt', {
        level: 'protected',
        identityId: 'xxxxxxx' // the identityId of that user
    })
    ```
- `private`: **Only accessible for the signed in user**. Files are stored under `private/{user_identity_id}/` where the `user_identity_id` corresponds to the unique Amazon Cognito Identity ID for that user.

### Download expiry

You can use `expires` option to limit the availability of your URLs. This configuration returns the pre-signed URL that expires in 60 seconds:

```javascript
await Storage.get('filename.txt', { expires: 60 })
```

### Frequently Asked Questions

Users can run into unexpected issues, so we are giving you advance notice in documentation with links to open issues - please vote for what you need, to help the team prioritize.

- Very common issue: Calling `Storage.get` for a nonexistent file, or incorrect credentials, **does not throw an error** because that would involve an extra API call. [Active issue here](https://github.com/aws-amplify/amplify-js/issues/1145). If you are having trouble accessing a file, make sure to check that you have the right filename, bucket, region, and auth configs. You can get a current list of files from `Storage.list`.
- `Storage.get` is cached; if you have recently modified a file you may not get the most recent version right away. [There is an active issue for a new option to enable cache busting.](https://github.com/aws-amplify/amplify-js/issues/6413)
- `Storage.get` only returns the latest cached version of the file; there is [not yet an API to view prior versions](https://github.com/aws-amplify/amplify-js/issues/2131).
- Download progress tracking is not yet possible. [Active issue here](https://github.com/aws-amplify/amplify-js/issues/4734).
- You cannot [only get file metadata](https://github.com/aws-amplify/amplify-js/issues/6157) yet.
- [Image compression](https://github.com/aws-amplify/amplify-js/issues/6081) or CloudFront CDN caching for your S3 buckets is not yet possible.
- There is no API for [Cognito Group-based access to files](https://github.com/aws-amplify/amplify-js/issues/3388).
- There is currently [no API for getting the identityId of other users](https://github.com/aws-amplify/amplify-js/issues/5177); you have to retrieve this from elsewhere before calling `Storage.get`.

{'repo_name': 'aws-amplify/docs', 'stars': '171', 'repo_language': 'TypeScript', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': 1433006630966689022, 'source_dataset': 'data'}


{
  "itemName" : "pureerchius",
  "price" : 120,
  "rarity" : "Common",
  "category" : "fuel",
  "inventoryIcon" : "pureerchius.png",
  "description" : "You've never seen a more pristine erchius crystal.\n^blue;+^white;25 ^blue;Fuel^reset;",
  "shortdescription" : "Pure Erchius Crystal",
  "itemTags" : [ "reagent" ],
  //"learnBlueprintsOnPickup" : [ "perpetualaccelerator" ],
  "fuelAmount" : 25
}

{'repo_name': 'sayterdarkwynd/FrackinUniverse', 'stars': '315', 'repo_language': 'Lua', 'file_name': 'villager_photontop.tenant', 'mime_type': 'text/plain', 'hash': -9019887330150092797, 'source_dataset': 'data'}


<?php

namespace Faker\Provider\ko_KR;

class PhoneNumber extends \Faker\Provider\PhoneNumber
{
    //reference : https://ko.wikipedia.org/wiki/%EB%8C%80%ED%95%9C%EB%AF%BC%EA%B5%AD%EC%9D%98_%EC%A0%84%ED%99%94%EB%B2%88%ED%98%B8_%EC%B2%B4%EA%B3%84

    protected static $formats = array(
        //local area phone format
        '070-####-####',
        '02-####-####',
        '03#-####-####',
        '04#-####-####',
        '05#-####-####',
        '06#-####-####',

        //cell phone format
        '010-####-####',

        //others: Intelligent Network(기간통신사업자)
        '15##-####',
        '16##-####',
        '18##-####',
    );

    public function localAreaPhoneNumber()
    {
        $format = self::randomElement(array_slice(static::$formats, 0, 6));

        return self::numerify($this->generator->parse($format));
    }

    public function cellPhoneNumber()
    {
        $format = self::randomElement(array_slice(static::$formats, 6, 1));

        return self::numerify($this->generator->parse($format));
    }
}

{'repo_name': 'linuxserver/Heimdall', 'stars': '1983', 'repo_language': 'PHP', 'file_name': 'fontawesome.js', 'mime_type': 'text/plain', 'hash': -7880369027792040950, 'source_dataset': 'data'}


#
# JBoss, Home of Professional Open Source
# Copyright 2015, Red Hat, Inc. and/or its affiliates, and individual
# contributors by the @authors tag. See the copyright.txt in the
# distribution for a full listing of individual contributors.
#
# 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.
#

registeredMessage=Enregistr\u00E9!
registerSuccessfulMessage= enregistr\u00E9 avec succ\u00E8s!
registerFailMessage=Echec de l'enregistrement:
defaultErrorMessage=Echec de l'enregistrement. Voir journal du serveur pour plus d'informations.

{'repo_name': 'wildfly/quickstart', 'stars': '778', 'repo_language': 'Java', 'file_name': 'HelloWorldMDBServletClient.java', 'mime_type': 'text/x-java', 'hash': -6256232458097576034, 'source_dataset': 'data'}


package otgrpc

import (
	"github.com/opentracing/opentracing-go"
	"github.com/opentracing/opentracing-go/ext"
	"github.com/opentracing/opentracing-go/log"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/metadata"
)

// OpenTracingServerInterceptor returns a grpc.UnaryServerInterceptor suitable
// for use in a grpc.NewServer call.
//
// For example:
//
//     s := grpc.NewServer(
//         ...,  // (existing ServerOptions)
//         grpc.UnaryInterceptor(otgrpc.OpenTracingServerInterceptor(tracer)))
//
// All gRPC server spans will look for an OpenTracing SpanContext in the gRPC
// metadata; if found, the server span will act as the ChildOf that RPC
// SpanContext.
//
// Root or not, the server Span will be embedded in the context.Context for the
// application-specific gRPC handler(s) to access.
func OpenTracingServerInterceptor(tracer opentracing.Tracer, optFuncs ...Option) grpc.UnaryServerInterceptor {
	otgrpcOpts := newOptions()
	otgrpcOpts.apply(optFuncs...)
	return func(
		ctx context.Context,
		req interface{},
		info *grpc.UnaryServerInfo,
		handler grpc.UnaryHandler,
	) (resp interface{}, err error) {
		spanContext, err := extractSpanContext(ctx, tracer)
		if err != nil && err != opentracing.ErrSpanContextNotFound {
			// TODO: establish some sort of error reporting mechanism here. We
			// don't know where to put such an error and must rely on Tracer
			// implementations to do something appropriate for the time being.
		}
		if otgrpcOpts.inclusionFunc != nil &&
			!otgrpcOpts.inclusionFunc(spanContext, info.FullMethod, req, nil) {
			return handler(ctx, req)
		}
		serverSpan := tracer.StartSpan(
			info.FullMethod,
			ext.RPCServerOption(spanContext),
			gRPCComponentTag,
		)
		defer serverSpan.Finish()

		ctx = opentracing.ContextWithSpan(ctx, serverSpan)
		if otgrpcOpts.logPayloads {
			serverSpan.LogFields(log.Object("gRPC request", req))
		}
		resp, err = handler(ctx, req)
		if err == nil {
			if otgrpcOpts.logPayloads {
				serverSpan.LogFields(log.Object("gRPC response", resp))
			}
		} else {
			SetSpanTags(serverSpan, err, false)
			serverSpan.LogFields(log.String("event", "error"), log.String("message", err.Error()))
		}
		if otgrpcOpts.decorator != nil {
			otgrpcOpts.decorator(serverSpan, info.FullMethod, req, resp, err)
		}
		return resp, err
	}
}

// OpenTracingStreamServerInterceptor returns a grpc.StreamServerInterceptor suitable
// for use in a grpc.NewServer call. The interceptor instruments streaming RPCs by
// creating a single span to correspond to the lifetime of the RPC's stream.
//
// For example:
//
//     s := grpc.NewServer(
//         ...,  // (existing ServerOptions)
//         grpc.StreamInterceptor(otgrpc.OpenTracingStreamServerInterceptor(tracer)))
//
// All gRPC server spans will look for an OpenTracing SpanContext in the gRPC
// metadata; if found, the server span will act as the ChildOf that RPC
// SpanContext.
//
// Root or not, the server Span will be embedded in the context.Context for the
// application-specific gRPC handler(s) to access.
func OpenTracingStreamServerInterceptor(tracer opentracing.Tracer, optFuncs ...Option) grpc.StreamServerInterceptor {
	otgrpcOpts := newOptions()
	otgrpcOpts.apply(optFuncs...)
	return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
		spanContext, err := extractSpanContext(ss.Context(), tracer)
		if err != nil && err != opentracing.ErrSpanContextNotFound {
			// TODO: establish some sort of error reporting mechanism here. We
			// don't know where to put such an error and must rely on Tracer
			// implementations to do something appropriate for the time being.
		}
		if otgrpcOpts.inclusionFunc != nil &&
			!otgrpcOpts.inclusionFunc(spanContext, info.FullMethod, nil, nil) {
			return handler(srv, ss)
		}

		serverSpan := tracer.StartSpan(
			info.FullMethod,
			ext.RPCServerOption(spanContext),
			gRPCComponentTag,
		)
		defer serverSpan.Finish()
		ss = &openTracingServerStream{
			ServerStream: ss,
			ctx:          opentracing.ContextWithSpan(ss.Context(), serverSpan),
		}
		err = handler(srv, ss)
		if err != nil {
			SetSpanTags(serverSpan, err, false)
			serverSpan.LogFields(log.String("event", "error"), log.String("message", err.Error()))
		}
		if otgrpcOpts.decorator != nil {
			otgrpcOpts.decorator(serverSpan, info.FullMethod, nil, nil, err)
		}
		return err
	}
}

type openTracingServerStream struct {
	grpc.ServerStream
	ctx context.Context
}

func (ss *openTracingServerStream) Context() context.Context {
	return ss.ctx
}

func extractSpanContext(ctx context.Context, tracer opentracing.Tracer) (opentracing.SpanContext, error) {
	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		md = metadata.New(nil)
	}
	return tracer.Extract(opentracing.HTTPHeaders, metadataReaderWriter{md})
}

{'repo_name': 'moby/moby', 'stars': '57610', 'repo_language': 'Go', 'file_name': 'docker_windows.go', 'mime_type': 'text/plain', 'hash': 1745810846451148269, 'source_dataset': 'data'}


package cmd

import (
	"errors"
	"fmt"
	"net/url"
	"os"
	"reflect"
	"strings"
	"syscall"

	"github.com/deis/deis/client/controller/client"
	"github.com/deis/deis/client/controller/models/auth"
	"golang.org/x/crypto/ssh/terminal"
)

// Register creates a account on a Deis controller.
func Register(controller string, username string, password string, email string,
	sslVerify bool) error {

	u, err := url.Parse(controller)
	httpClient := client.CreateHTTPClient(sslVerify)

	if err != nil {
		return err
	}

	controllerURL, err := chooseScheme(*u)

	if err != nil {
		return err
	}

	if err = client.CheckConnection(httpClient, controllerURL); err != nil {
		return err
	}

	if username == "" {
		fmt.Print("username: ")
		fmt.Scanln(&username)
	}

	if password == "" {
		fmt.Print("password: ")
		password, err = readPassword()
		fmt.Printf("\npassword (confirm): ")
		passwordConfirm, err := readPassword()
		fmt.Println()

		if err != nil {
			return err
		}

		if password != passwordConfirm {
			return errors.New("Password mismatch, aborting registration.")
		}
	}

	if email == "" {
		fmt.Print("email: ")
		fmt.Scanln(&email)
	}

	c := &client.Client{ControllerURL: controllerURL, SSLVerify: sslVerify, HTTPClient: httpClient}

	tempClient, err := client.New()

	if err == nil {
		c.Token = tempClient.Token
	}

	err = auth.Register(c, username, password, email)

	c.Token = ""

	if err != nil {
		fmt.Fprint(os.Stderr, "Registration failed: ")
		return err
	}

	fmt.Printf("Registered %s\n", username)
	return doLogin(c, username, password)
}

func doLogin(c *client.Client, username, password string) error {
	token, err := auth.Login(c, username, password)

	if err != nil {
		return err
	}

	c.Token = token
	c.Username = username

	err = c.Save()

	if err != nil {
		return nil
	}

	fmt.Printf("Logged in as %s\n", username)
	return nil
}

// Login to a Deis controller.
func Login(controller string, username string, password string, sslVerify bool) error {
	u, err := url.Parse(controller)

	if err != nil {
		return err
	}

	controllerURL, err := chooseScheme(*u)
	httpClient := client.CreateHTTPClient(sslVerify)

	if err != nil {
		return err
	}

	if err = client.CheckConnection(httpClient, controllerURL); err != nil {
		return err
	}

	if username == "" {
		fmt.Print("username: ")
		fmt.Scanln(&username)
	}

	if password == "" {
		fmt.Print("password: ")
		password, err = readPassword()
		fmt.Println()

		if err != nil {
			return err
		}
	}

	c := &client.Client{ControllerURL: controllerURL, SSLVerify: sslVerify, HTTPClient: httpClient}

	return doLogin(c, username, password)
}

// Logout from a Deis controller.
func Logout() error {
	if err := client.Delete(); err != nil {
		return err
	}

	fmt.Println("Logged out")
	return nil
}

// Passwd changes a user's password.
func Passwd(username string, password string, newPassword string) error {
	c, err := client.New()

	if err != nil {
		return err
	}

	if password == "" && username == "" {
		fmt.Print("current password: ")
		password, err = readPassword()
		fmt.Println()

		if err != nil {
			return err
		}
	}

	if newPassword == "" {
		fmt.Print("new password: ")
		newPassword, err = readPassword()
		fmt.Printf("\nnew password (confirm): ")
		passwordConfirm, err := readPassword()

		fmt.Println()

		if err != nil {
			return err
		}

		if newPassword != passwordConfirm {
			return errors.New("Password mismatch, not changing.")
		}
	}

	err = auth.Passwd(c, username, password, newPassword)

	if err != nil {
		fmt.Fprint(os.Stderr, "Password change failed: ")
		return err
	}

	fmt.Println("Password change succeeded.")
	return nil
}

// Cancel deletes a user's account.
func Cancel(username string, password string, yes bool) error {
	c, err := client.New()

	if err != nil {
		return err
	}

	if username == "" || password != "" {
		fmt.Println("Please log in again in order to cancel this account")

		if err = Login(c.ControllerURL.String(), username, password, c.SSLVerify); err != nil {
			return err
		}
	}

	if yes == false {
		confirm := ""

		c, err = client.New()

		if err != nil {
			return err
		}

		deletedUser := username

		if deletedUser == "" {
			deletedUser = c.Username
		}

		fmt.Printf("cancel account %s at %s? (y/N): ", deletedUser, c.ControllerURL.String())
		fmt.Scanln(&confirm)

		if strings.ToLower(confirm) == "y" {
			yes = true
		}
	}

	if yes == false {
		fmt.Fprintln(os.Stderr, "Account not changed")
		return nil
	}

	err = auth.Delete(c, username)

	cleanup := fmt.Errorf("\n%s %s\n\n", "409", "Conflict")
	if reflect.DeepEqual(err, cleanup) {
		fmt.Printf("%s still has application associated with it. Transfer ownership or delete them first\n", username)
		return nil
	} else if err != nil {
		return err
	}

	// If user targets themselves, logout.
	if username == "" || c.Username == username {
		if err := client.Delete(); err != nil {
			return err
		}
	}

	fmt.Println("Account cancelled")
	return nil
}

// Whoami prints the logged in user.
func Whoami() error {
	c, err := client.New()

	if err != nil {
		return err
	}

	fmt.Printf("You are %s at %s\n", c.Username, c.ControllerURL.String())
	return nil
}

// Regenerate regenenerates a user's token.
func Regenerate(username string, all bool) error {
	c, err := client.New()

	if err != nil {
		return err
	}

	token, err := auth.Regenerate(c, username, all)

	if err != nil {
		return err
	}

	if username == "" && all == false {
		c.Token = token

		err = c.Save()

		if err != nil {
			return err
		}
	}

	fmt.Println("Token Regenerated")
	return nil
}

func readPassword() (string, error) {
	password, err := terminal.ReadPassword(int(syscall.Stdin))

	return string(password), err
}

func chooseScheme(u url.URL) (url.URL, error) {
	if u.Scheme == "" {
		u.Scheme = "http"
		u, err := url.Parse(u.String())

		if err != nil {
			return url.URL{}, err
		}

		return *u, nil
	}

	return u, nil
}

{'repo_name': 'deis/deis', 'stars': '6124', 'repo_language': 'Python', 'file_name': '0001.sh', 'mime_type': 'text/x-shellscript', 'hash': 1417330759300127385, 'source_dataset': 'data'}


<map id="PxLinkData" name="PxLinkData">
<area shape="rect" id="node2" href="$classPxVec3.html" title="3 Element vector class. " alt="" coords="11,5,79,32"/>
<area shape="rect" id="node3" href="$classPxTransform.html" title="class representing a rigid euclidean transform as a quaternion and a vector " alt="" coords="113,96,208,123"/>
<area shape="rect" id="node4" href="$classPxQuat.html" title="This is a quaternion class. For more information on quaternion mathematics consult a mathematics sour..." alt="" coords="127,5,194,32"/>
</map>

{'repo_name': 'NVIDIAGameWorks/PhysX', 'stars': '1496', 'repo_language': 'C++', 'file_name': 'targa.h', 'mime_type': 'text/x-c', 'hash': 4338152692242086764, 'source_dataset': 'data'}


/*
Copyright 2017 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package cm

import (
	"fmt"
	"strings"
	"sync"
	"time"

	"k8s.io/klog/v2"

	"k8s.io/apimachinery/pkg/util/wait"

	units "github.com/docker/go-units"
	cgroupfs "github.com/opencontainers/runc/libcontainer/cgroups/fs"
	"k8s.io/api/core/v1"
	utilfeature "k8s.io/apiserver/pkg/util/feature"
	"k8s.io/kubernetes/pkg/api/v1/resource"
	v1qos "k8s.io/kubernetes/pkg/apis/core/v1/helper/qos"
	kubefeatures "k8s.io/kubernetes/pkg/features"
)

const (
	// how often the qos cgroup manager will perform periodic update
	// of the qos level cgroup resource constraints
	periodicQOSCgroupUpdateInterval = 1 * time.Minute
)

type QOSContainerManager interface {
	Start(func() v1.ResourceList, ActivePodsFunc) error
	GetQOSContainersInfo() QOSContainersInfo
	UpdateCgroups() error
}

type qosContainerManagerImpl struct {
	sync.Mutex
	qosContainersInfo  QOSContainersInfo
	subsystems         *CgroupSubsystems
	cgroupManager      CgroupManager
	activePods         ActivePodsFunc
	getNodeAllocatable func() v1.ResourceList
	cgroupRoot         CgroupName
	qosReserved        map[v1.ResourceName]int64
}

func NewQOSContainerManager(subsystems *CgroupSubsystems, cgroupRoot CgroupName, nodeConfig NodeConfig, cgroupManager CgroupManager) (QOSContainerManager, error) {
	if !nodeConfig.CgroupsPerQOS {
		return &qosContainerManagerNoop{
			cgroupRoot: cgroupRoot,
		}, nil
	}

	return &qosContainerManagerImpl{
		subsystems:    subsystems,
		cgroupManager: cgroupManager,
		cgroupRoot:    cgroupRoot,
		qosReserved:   nodeConfig.QOSReserved,
	}, nil
}

func (m *qosContainerManagerImpl) GetQOSContainersInfo() QOSContainersInfo {
	return m.qosContainersInfo
}

func (m *qosContainerManagerImpl) Start(getNodeAllocatable func() v1.ResourceList, activePods ActivePodsFunc) error {
	cm := m.cgroupManager
	rootContainer := m.cgroupRoot
	if !cm.Exists(rootContainer) {
		return fmt.Errorf("root container %v doesn't exist", rootContainer)
	}

	// Top level for Qos containers are created only for Burstable
	// and Best Effort classes
	qosClasses := map[v1.PodQOSClass]CgroupName{
		v1.PodQOSBurstable:  NewCgroupName(rootContainer, strings.ToLower(string(v1.PodQOSBurstable))),
		v1.PodQOSBestEffort: NewCgroupName(rootContainer, strings.ToLower(string(v1.PodQOSBestEffort))),
	}

	// Create containers for both qos classes
	for qosClass, containerName := range qosClasses {
		resourceParameters := &ResourceConfig{}
		// the BestEffort QoS class has a statically configured minShares value
		if qosClass == v1.PodQOSBestEffort {
			minShares := uint64(MinShares)
			resourceParameters.CpuShares = &minShares
		}

		// containerConfig object stores the cgroup specifications
		containerConfig := &CgroupConfig{
			Name:               containerName,
			ResourceParameters: resourceParameters,
		}

		// for each enumerated huge page size, the qos tiers are unbounded
		m.setHugePagesUnbounded(containerConfig)

		// check if it exists
		if !cm.Exists(containerName) {
			if err := cm.Create(containerConfig); err != nil {
				return fmt.Errorf("failed to create top level %v QOS cgroup : %v", qosClass, err)
			}
		} else {
			// to ensure we actually have the right state, we update the config on startup
			if err := cm.Update(containerConfig); err != nil {
				return fmt.Errorf("failed to update top level %v QOS cgroup : %v", qosClass, err)
			}
		}
	}
	// Store the top level qos container names
	m.qosContainersInfo = QOSContainersInfo{
		Guaranteed: rootContainer,
		Burstable:  qosClasses[v1.PodQOSBurstable],
		BestEffort: qosClasses[v1.PodQOSBestEffort],
	}
	m.getNodeAllocatable = getNodeAllocatable
	m.activePods = activePods

	// update qos cgroup tiers on startup and in periodic intervals
	// to ensure desired state is in sync with actual state.
	go wait.Until(func() {
		err := m.UpdateCgroups()
		if err != nil {
			klog.Warningf("[ContainerManager] Failed to reserve QoS requests: %v", err)
		}
	}, periodicQOSCgroupUpdateInterval, wait.NeverStop)

	return nil
}

// setHugePagesUnbounded ensures hugetlb is effectively unbounded
func (m *qosContainerManagerImpl) setHugePagesUnbounded(cgroupConfig *CgroupConfig) error {
	hugePageLimit := map[int64]int64{}
	for _, pageSize := range cgroupfs.HugePageSizes {
		pageSizeBytes, err := units.RAMInBytes(pageSize)
		if err != nil {
			return err
		}
		hugePageLimit[pageSizeBytes] = int64(1 << 62)
	}
	cgroupConfig.ResourceParameters.HugePageLimit = hugePageLimit
	return nil
}

func (m *qosContainerManagerImpl) setHugePagesConfig(configs map[v1.PodQOSClass]*CgroupConfig) error {
	for _, v := range configs {
		if err := m.setHugePagesUnbounded(v); err != nil {
			return err
		}
	}
	return nil
}

func (m *qosContainerManagerImpl) setCPUCgroupConfig(configs map[v1.PodQOSClass]*CgroupConfig) error {
	pods := m.activePods()
	burstablePodCPURequest := int64(0)
	for i := range pods {
		pod := pods[i]
		qosClass := v1qos.GetPodQOS(pod)
		if qosClass != v1.PodQOSBurstable {
			// we only care about the burstable qos tier
			continue
		}
		req, _ := resource.PodRequestsAndLimits(pod)
		if request, found := req[v1.ResourceCPU]; found {
			burstablePodCPURequest += request.MilliValue()
		}
	}

	// make sure best effort is always 2 shares
	bestEffortCPUShares := uint64(MinShares)
	configs[v1.PodQOSBestEffort].ResourceParameters.CpuShares = &bestEffortCPUShares

	// set burstable shares based on current observe state
	burstableCPUShares := MilliCPUToShares(burstablePodCPURequest)
	configs[v1.PodQOSBurstable].ResourceParameters.CpuShares = &burstableCPUShares
	return nil
}

// setMemoryReserve sums the memory limits of all pods in a QOS class,
// calculates QOS class memory limits, and set those limits in the
// CgroupConfig for each QOS class.
func (m *qosContainerManagerImpl) setMemoryReserve(configs map[v1.PodQOSClass]*CgroupConfig, percentReserve int64) {
	qosMemoryRequests := map[v1.PodQOSClass]int64{
		v1.PodQOSGuaranteed: 0,
		v1.PodQOSBurstable:  0,
	}

	// Sum the pod limits for pods in each QOS class
	pods := m.activePods()
	for _, pod := range pods {
		podMemoryRequest := int64(0)
		qosClass := v1qos.GetPodQOS(pod)
		if qosClass == v1.PodQOSBestEffort {
			// limits are not set for Best Effort pods
			continue
		}
		req, _ := resource.PodRequestsAndLimits(pod)
		if request, found := req[v1.ResourceMemory]; found {
			podMemoryRequest += request.Value()
		}
		qosMemoryRequests[qosClass] += podMemoryRequest
	}

	resources := m.getNodeAllocatable()
	allocatableResource, ok := resources[v1.ResourceMemory]
	if !ok {
		klog.V(2).Infof("[Container Manager] Allocatable memory value could not be determined.  Not setting QOS memory limts.")
		return
	}
	allocatable := allocatableResource.Value()
	if allocatable == 0 {
		klog.V(2).Infof("[Container Manager] Memory allocatable reported as 0, might be in standalone mode.  Not setting QOS memory limts.")
		return
	}

	for qos, limits := range qosMemoryRequests {
		klog.V(2).Infof("[Container Manager] %s pod requests total %d bytes (reserve %d%%)", qos, limits, percentReserve)
	}

	// Calculate QOS memory limits
	burstableLimit := allocatable - (qosMemoryRequests[v1.PodQOSGuaranteed] * percentReserve / 100)
	bestEffortLimit := burstableLimit - (qosMemoryRequests[v1.PodQOSBurstable] * percentReserve / 100)
	configs[v1.PodQOSBurstable].ResourceParameters.Memory = &burstableLimit
	configs[v1.PodQOSBestEffort].ResourceParameters.Memory = &bestEffortLimit
}

// retrySetMemoryReserve checks for any QoS cgroups over the limit
// that was attempted to be set in the first Update() and adjusts
// their memory limit to the usage to prevent further growth.
func (m *qosContainerManagerImpl) retrySetMemoryReserve(configs map[v1.PodQOSClass]*CgroupConfig, percentReserve int64) {
	// Unreclaimable memory usage may already exceeded the desired limit
	// Attempt to set the limit near the current usage to put pressure
	// on the cgroup and prevent further growth.
	for qos, config := range configs {
		stats, err := m.cgroupManager.GetResourceStats(config.Name)
		if err != nil {
			klog.V(2).Infof("[Container Manager] %v", err)
			return
		}
		usage := stats.MemoryStats.Usage

		// Because there is no good way to determine of the original Update()
		// on the memory resource was successful, we determine failure of the
		// first attempt by checking if the usage is above the limit we attempt
		// to set.  If it is, we assume the first attempt to set the limit failed
		// and try again setting the limit to the usage.  Otherwise we leave
		// the CgroupConfig as is.
		if configs[qos].ResourceParameters.Memory != nil && usage > *configs[qos].ResourceParameters.Memory {
			configs[qos].ResourceParameters.Memory = &usage
		}
	}
}

func (m *qosContainerManagerImpl) UpdateCgroups() error {
	m.Lock()
	defer m.Unlock()

	qosConfigs := map[v1.PodQOSClass]*CgroupConfig{
		v1.PodQOSBurstable: {
			Name:               m.qosContainersInfo.Burstable,
			ResourceParameters: &ResourceConfig{},
		},
		v1.PodQOSBestEffort: {
			Name:               m.qosContainersInfo.BestEffort,
			ResourceParameters: &ResourceConfig{},
		},
	}

	// update the qos level cgroup settings for cpu shares
	if err := m.setCPUCgroupConfig(qosConfigs); err != nil {
		return err
	}

	// update the qos level cgroup settings for huge pages (ensure they remain unbounded)
	if err := m.setHugePagesConfig(qosConfigs); err != nil {
		return err
	}

	if utilfeature.DefaultFeatureGate.Enabled(kubefeatures.QOSReserved) {
		for resource, percentReserve := range m.qosReserved {
			switch resource {
			case v1.ResourceMemory:
				m.setMemoryReserve(qosConfigs, percentReserve)
			}
		}

		updateSuccess := true
		for _, config := range qosConfigs {
			err := m.cgroupManager.Update(config)
			if err != nil {
				updateSuccess = false
			}
		}
		if updateSuccess {
			klog.V(4).Infof("[ContainerManager]: Updated QoS cgroup configuration")
			return nil
		}

		// If the resource can adjust the ResourceConfig to increase likelihood of
		// success, call the adjustment function here.  Otherwise, the Update() will
		// be called again with the same values.
		for resource, percentReserve := range m.qosReserved {
			switch resource {
			case v1.ResourceMemory:
				m.retrySetMemoryReserve(qosConfigs, percentReserve)
			}
		}
	}

	for _, config := range qosConfigs {
		err := m.cgroupManager.Update(config)
		if err != nil {
			klog.Errorf("[ContainerManager]: Failed to update QoS cgroup configuration")
			return err
		}
	}

	klog.V(4).Infof("[ContainerManager]: Updated QoS cgroup configuration")
	return nil
}

type qosContainerManagerNoop struct {
	cgroupRoot CgroupName
}

var _ QOSContainerManager = &qosContainerManagerNoop{}

func (m *qosContainerManagerNoop) GetQOSContainersInfo() QOSContainersInfo {
	return QOSContainersInfo{}
}

func (m *qosContainerManagerNoop) Start(_ func() v1.ResourceList, _ ActivePodsFunc) error {
	return nil
}

func (m *qosContainerManagerNoop) UpdateCgroups() error {
	return nil
}

{'repo_name': 'kubernetes/kubernetes', 'stars': '68189', 'repo_language': 'Go', 'file_name': 'BUILD', 'mime_type': 'text/plain', 'hash': 5397929477515196297, 'source_dataset': 'data'}


.neal-countdown {
  margin: 10px auto;
  padding-bottom: 20px;

  .countdown-col{
    display: inline-block;

    // .countdown-col-element
    &-element{
      display: flex;
      flex-direction: column;
      margin: 0 20px;

      // .countdown-col-element-number
      &-number{
        font-size: 50px;
      }
    }
  }
}

{'repo_name': 'dennybritz/neal-react', 'stars': '1316', 'repo_language': 'JavaScript', 'file_name': 'segment.jsx', 'mime_type': 'text/x-java', 'hash': -7527655795409497295, 'source_dataset': 'data'}


--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -26,7 +26,6 @@ SET(libftgl_la_SOURCES
     FTGlyphContainer.h
     FTInternals.h
     FTLibrary.cpp
-    FTLibrary.h
     FTList.h
     FTPoint.cpp
     FTSize.cpp

{'repo_name': 'spack/spack', 'stars': '1652', 'repo_language': 'Python', 'file_name': 'modules.yaml', 'mime_type': 'text/plain', 'hash': 1536754560201351337, 'source_dataset': 'data'}


import { createElement } from 'lwc';
import DemoLwcComponent from 'c/demoLwcComponent';

describe('Demo Lwc Component', () => {
  afterEach(() => {
    // The jsdom instance is shared across test cases in a single file so reset the DOM
    while (document.body.firstChild) {
      document.body.removeChild(document.body.firstChild);
    }
  });

  it('Displays greeting', () => {
    const element = createElement('demo-lwc-component', {
      is: DemoLwcComponent
    });
    document.body.appendChild(element);
    const div = element.shadowRoot.querySelector('div');
    expect(div.textContent).toBe('Hello, World!');
  });

  it('Failed test', () => {
    expect(1).toEqual(2);
  });
});

{'repo_name': 'forcedotcom/salesforcedx-vscode', 'stars': '582', 'repo_language': 'TypeScript', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': -4518001201577275510, 'source_dataset': 'data'}