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

import com.facebook.presto.orc.metadata.DwrfStripeCacheMode;
import com.facebook.presto.orc.writer.StreamLayoutFactory;
import com.facebook.presto.orc.writer.StreamLayoutFactory.ColumnSizeLayoutFactory;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import io.airlift.units.DataSize;
import org.testng.annotations.Test;

import java.util.Optional;
import java.util.OptionalInt;

import static com.facebook.presto.orc.metadata.DwrfStripeCacheMode.INDEX_AND_FOOTER;
import static io.airlift.units.DataSize.Unit.BYTE;
import static io.airlift.units.DataSize.Unit.KILOBYTE;
import static io.airlift.units.DataSize.Unit.MEGABYTE;
import static java.lang.Math.toIntExact;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;

public class TestOrcWriterOptions
{
    private static final DwrfStripeCacheMode DWRF_STRIPE_CACHE_MODE = INDEX_AND_FOOTER;
    private static final DataSize DWRF_STRIPE_CACHE_MAX_SIZE = new DataSize(27, MEGABYTE);

    @Test
    public void testDwrfWriterOptionsProperties()
    {
        for (boolean value : ImmutableList.of(true, false)) {
            OrcWriterOptions options = OrcWriterOptions.builder()
                    .withDwrfStripeCacheEnabled(value)
                    .withDwrfStripeCacheMode(DWRF_STRIPE_CACHE_MODE)
                    .withDwrfStripeCacheMaxSize(DWRF_STRIPE_CACHE_MAX_SIZE)
                    .build();

            assertEquals(options.getDwrfStripeCacheOptions().isPresent(), value);
            if (value) {
                DwrfStripeCacheOptions dwrfStripeCacheOptions = options.getDwrfStripeCacheOptions().get();
                assertEquals(dwrfStripeCacheOptions.getStripeCacheMode(), DWRF_STRIPE_CACHE_MODE);
                assertEquals(dwrfStripeCacheOptions.getStripeCacheMaxSize(), DWRF_STRIPE_CACHE_MAX_SIZE);
            }
            else {
                assertEquals(Optional.empty(), options.getDwrfStripeCacheOptions());
            }
        }
    }

    @Test
    public void tesDefaultValues()
    {
        OrcWriterOptions options = OrcWriterOptions.builder().build();

        assertEquals(options.getFlattenedColumns(), ImmutableSet.of());
        assertFalse(options.isMapStatisticsEnabled());
        assertEquals(options.getMaxFlattenedMapKeyCount(), 20000);
    }

    @Test
    public void testProperties()
    {
        DataSize stripeMinSize = new DataSize(13, MEGABYTE);
        DataSize stripeMaxSize = new DataSize(27, MEGABYTE);
        int stripeMaxRowCount = 1_100_000;
        int rowGroupMaxRowCount = 15_000;
        DataSize dictionaryMaxMemory = new DataSize(13_000, KILOBYTE);
        DataSize dictionaryMemoryRange = new DataSize(1_000, KILOBYTE);
        int dictionaryUsefulCheckPerChunkFrequency = 9_999;
        DataSize dictionaryUsefulCheckColumnSize = new DataSize(1, MEGABYTE);
        DataSize stringMaxStatisticsLimit = new DataSize(128, BYTE);
        DataSize maxCompressionBufferSize = new DataSize(512, KILOBYTE);
        OptionalInt compressionLevel = OptionalInt.of(5);
        StreamLayoutFactory streamLayoutFactory = new StreamLayoutFactory.StreamSizeLayoutFactory();
        boolean integerDictionaryEncodingEnabled = true;
        boolean stringDictionarySortingEnabled = false;
        boolean stringDictionaryEncodingEnabled = false;
        int preserveDirectEncodingStripeCount = 10;
        boolean mapStatisticsEnabled = true;
        int maxFlattenedMapKeyCount = 27;

        OrcWriterOptions.Builder builder = OrcWriterOptions.builder()
                .withFlushPolicy(DefaultOrcWriterFlushPolicy.builder()
                        .withStripeMinSize(stripeMinSize)
                        .withStripeMaxSize(stripeMaxSize)
                        .withStripeMaxRowCount(stripeMaxRowCount)
                        .build())
                .withRowGroupMaxRowCount(rowGroupMaxRowCount)
                .withDictionaryMaxMemory(dictionaryMaxMemory)
                .withDictionaryMemoryAlmostFullRange(dictionaryMemoryRange)
                .withDictionaryUsefulCheckPerChunkFrequency(dictionaryUsefulCheckPerChunkFrequency)
                .withDictionaryUsefulCheckColumnSize(dictionaryUsefulCheckColumnSize)
                .withMaxStringStatisticsLimit(stringMaxStatisticsLimit)
                .withMaxCompressionBufferSize(maxCompressionBufferSize)
                .withCompressionLevel(compressionLevel)
                .withStreamLayoutFactory(streamLayoutFactory)
                .withIntegerDictionaryEncodingEnabled(integerDictionaryEncodingEnabled)
                .withStringDictionarySortingEnabled(stringDictionarySortingEnabled)
                .withStringDictionaryEncodingEnabled(stringDictionaryEncodingEnabled)
                .withPreserveDirectEncodingStripeCount(preserveDirectEncodingStripeCount)
                .withFlattenedColumns(ImmutableSet.of(4, 3))
                .withMapStatisticsEnabled(mapStatisticsEnabled)
                .withMaxFlattenedMapKeyCount(maxFlattenedMapKeyCount);

        OrcWriterOptions options = builder.build();

        assertEquals(toIntExact(stripeMinSize.toBytes()), options.getFlushPolicy().getStripeMinBytes());
        assertEquals(toIntExact(stripeMaxSize.toBytes()), options.getFlushPolicy().getStripeMaxBytes());
        assertEquals(stripeMaxRowCount, options.getFlushPolicy().getStripeMaxRowCount());
        assertEquals(rowGroupMaxRowCount, options.getRowGroupMaxRowCount());
        assertEquals(dictionaryMaxMemory, options.getDictionaryMaxMemory());
        assertEquals(dictionaryMemoryRange, options.getDictionaryMemoryAlmostFullRange());
        assertEquals(dictionaryUsefulCheckPerChunkFrequency, options.getDictionaryUsefulCheckPerChunkFrequency());
        assertEquals(dictionaryUsefulCheckColumnSize, options.getDictionaryUsefulCheckColumnSize());
        assertEquals(stringMaxStatisticsLimit, options.getMaxStringStatisticsLimit());
        assertEquals(maxCompressionBufferSize, options.getMaxCompressionBufferSize());
        assertEquals(compressionLevel, options.getCompressionLevel());
        assertEquals(streamLayoutFactory, options.getStreamLayoutFactory());
        assertEquals(integerDictionaryEncodingEnabled, options.isIntegerDictionaryEncodingEnabled());
        assertEquals(stringDictionarySortingEnabled, options.isStringDictionarySortingEnabled());
        assertEquals(stringDictionaryEncodingEnabled, options.isStringDictionaryEncodingEnabled());
        assertEquals(Optional.empty(), options.getDwrfStripeCacheOptions());
        assertEquals(preserveDirectEncodingStripeCount, options.getPreserveDirectEncodingStripeCount());
        assertEquals(options.getFlattenedColumns(), ImmutableSet.of(4, 3));
        assertEquals(options.isMapStatisticsEnabled(), mapStatisticsEnabled);
        assertEquals(options.getMaxFlattenedMapKeyCount(), maxFlattenedMapKeyCount);
    }

    @Test
    public void testToString()
    {
        DataSize stripeMinSize = new DataSize(13, MEGABYTE);
        DataSize stripeMaxSize = new DataSize(27, MEGABYTE);
        int stripeMaxRowCount = 1_100_000;
        int rowGroupMaxRowCount = 15_000;
        DataSize dictionaryMaxMemory = new DataSize(13_000, KILOBYTE);
        DataSize dictionaryMemoryRange = new DataSize(1_000, KILOBYTE);
        int dictionaryUsefulCheckPerChunkFrequency = 9_999;
        DataSize dictionaryUsefulCheckColumnSize = new DataSize(1, MEGABYTE);
        DataSize stringMaxStatisticsLimit = new DataSize(128, BYTE);
        DataSize maxCompressionBufferSize = new DataSize(512, KILOBYTE);
        DataSize dwrfStripeCacheMaxSize = new DataSize(4, MEGABYTE);
        DwrfStripeCacheMode dwrfStripeCacheMode = DwrfStripeCacheMode.INDEX_AND_FOOTER;
        OptionalInt compressionLevel = OptionalInt.of(5);
        StreamLayoutFactory streamLayoutFactory = new ColumnSizeLayoutFactory();
        boolean integerDictionaryEncodingEnabled = false;
        boolean stringDictionarySortingEnabled = true;
        int preserveDirectEncodingStripeCount = 0;
        boolean mapStatisticsEnabled = true;
        int maxFlattenedMapKeyCount = 27;

        OrcWriterOptions writerOptions = OrcWriterOptions.builder()
                .withFlushPolicy(DefaultOrcWriterFlushPolicy.builder()
                        .withStripeMinSize(stripeMinSize)
                        .withStripeMaxSize(stripeMaxSize)
                        .withStripeMaxRowCount(stripeMaxRowCount)
                        .build())
                .withRowGroupMaxRowCount(rowGroupMaxRowCount)
                .withDictionaryMaxMemory(dictionaryMaxMemory)
                .withDictionaryMemoryAlmostFullRange(dictionaryMemoryRange)
                .withDictionaryUsefulCheckPerChunkFrequency(dictionaryUsefulCheckPerChunkFrequency)
                .withDictionaryUsefulCheckColumnSize(dictionaryUsefulCheckColumnSize)
                .withMaxStringStatisticsLimit(stringMaxStatisticsLimit)
                .withMaxCompressionBufferSize(maxCompressionBufferSize)
                .withCompressionLevel(compressionLevel)
                .withStreamLayoutFactory(streamLayoutFactory)
                .withIntegerDictionaryEncodingEnabled(integerDictionaryEncodingEnabled)
                .withStringDictionarySortingEnabled(stringDictionarySortingEnabled)
                .withDwrfStripeCacheEnabled(true)
                .withDwrfStripeCacheMaxSize(dwrfStripeCacheMaxSize)
                .withDwrfStripeCacheMode(dwrfStripeCacheMode)
                .withPreserveDirectEncodingStripeCount(preserveDirectEncodingStripeCount)
                .withFlattenedColumns(ImmutableSet.of(4))
                .withMapStatisticsEnabled(mapStatisticsEnabled)
                .withMaxFlattenedMapKeyCount(maxFlattenedMapKeyCount)
                .build();

        String expectedString = "OrcWriterOptions{flushPolicy=DefaultOrcWriterFlushPolicy{stripeMaxRowCount=1100000, " +
                "stripeMinBytes=13631488, stripeMaxBytes=28311552}, rowGroupMaxRowCount=15000, " +
                "dictionaryMaxMemory=13000kB, dictionaryMemoryAlmostFullRange=1000kB, dictionaryUsefulCheckPerChunkFrequency=9999, " +
                "dictionaryUsefulCheckColumnSize=1MB, maxStringStatisticsLimit=128B, maxCompressionBufferSize=512kB, " +
                "compressionLevel=OptionalInt[5], streamLayoutFactory=ColumnSizeLayoutFactory{}, integerDictionaryEncodingEnabled=false, " +
                "stringDictionarySortingEnabled=true, stringDictionaryEncodingEnabled=true, " +
                "dwrfWriterOptions=Optional[DwrfStripeCacheOptions{stripeCacheMode=INDEX_AND_FOOTER, stripeCacheMaxSize=4MB}], " +
                "ignoreDictionaryRowGroupSizes=false, preserveDirectEncodingStripeCount=0, flattenedColumns=[4], mapStatisticsEnabled=true, " +
                "maxFlattenedMapKeyCount=27}";
        assertEquals(expectedString, writerOptions.toString());
    }
}


text:
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInspection;

import com.intellij.codeInsight.daemon.QuickFixBundle;
import com.intellij.codeInsight.intention.FileModifier;
import com.intellij.codeInspection.dataFlow.CommonDataflow;
import com.intellij.codeInspection.dataFlow.TypeConstraint;
import com.intellij.codeInspection.dataFlow.TypeConstraints;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.psi.*;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.InheritanceUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.ObjectUtils;
import com.siyeh.ig.performance.CollectionsListSettings;
import com.siyeh.ig.psiutils.*;
import com.siyeh.ig.psiutils.ControlFlowUtils.InitializerUsageStatus;
import org.jdom.Element;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.util.Collection;
import java.util.Collections;
import java.util.Objects;

/**
 * @author Dmitry Batkovich
 */
public class CollectionAddAllCanBeReplacedWithConstructorInspection extends AbstractBaseJavaLocalInspectionTool {

  private final CollectionsListSettings mySettings = new CollectionsListSettings() {
    @Override
    protected Collection<String> getDefaultSettings() {
      return Collections.emptyList();
    }
  };

  @Override
  public void writeSettings(@NotNull Element node) throws WriteExternalException {
    mySettings.writeSettings(node);
  }

  @Nullable
  @Override
  public JComponent createOptionsPanel() {
    return mySettings.createOptionsPanel();
  }

  @Override
  public void readSettings(@NotNull Element node) throws InvalidDataException {
    mySettings.readSettings(node);
  }

  @NotNull
  @Override
  public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder,
                                        boolean isOnTheFly,
                                        @NotNull LocalInspectionToolSession session) {
    return new JavaElementVisitor() {
      @Override
      public void visitMethodCallExpression(@NotNull PsiMethodCallExpression expression) {
        final PsiReferenceExpression methodExpression = expression.getMethodExpression();
        final PsiElement nameElement = methodExpression.getReferenceNameElement();
        final String methodName = methodExpression.getReferenceName();
        if (nameElement == null || !"addAll".equals(methodName) && !"putAll".equals(methodName)) return;
        PsiExpression[] args = expression.getArgumentList().getExpressions();
        if (args.length != 1) return;
        final PsiExpressionStatement parent = ObjectUtils.tryCast(expression.getParent(), PsiExpressionStatement.class);
        if (parent == null) return;
        PsiLocalVariable variable = ExpressionUtils.resolveLocalVariable(methodExpression.getQualifierExpression());
        if (variable == null) return;
        if (PsiUtil.resolveClassInClassTypeOnly(variable.getType()) == null) return;
        if (statementHasSubsequentAddAll(parent, variable, methodName)) return;
        PsiType argType = args[0].getType();
        if (!InheritanceUtil.isInheritor(argType, "putAll".equals(methodName) ?
                                                  CommonClassNames.JAVA_UTIL_MAP : CommonClassNames.JAVA_UTIL_COLLECTION)) {
          return;
        }

        InitializerUsageStatus status = ControlFlowUtils.getInitializerUsageStatus(variable, parent);

        PsiNewExpression assignmentExpression;
        if (status == InitializerUsageStatus.DECLARED_JUST_BEFORE || status == InitializerUsageStatus.AT_WANTED_PLACE_ONLY) {
          if (!isCollectionConstructor(variable.getInitializer())) return;
          assignmentExpression = (PsiNewExpression)variable.getInitializer();
        }
        else {
          assignmentExpression = getPreviousAssignment(variable, parent);
        }

        if (assignmentExpression == null || !isAddAllReplaceable(expression, assignmentExpression)) return;
        if (mayInheritComparator(args, argType, assignmentExpression)) return;
        final PsiMethod method = expression.resolveMethod();
        if (method != null) {
          holder.registerProblem(nameElement, QuickFixBundle.message("collection.addall.can.be.replaced.with.constructor.fix.description"),
                                 new ReplaceAddAllWithConstructorFix(assignmentExpression, expression, methodName));
        }
      }

      private boolean mayInheritComparator(PsiExpression[] args, PsiType argType, PsiNewExpression assignmentExpression) {
        PsiType type = assignmentExpression.getType();
        PsiClass collectionType = Objects.requireNonNull(PsiUtil.resolveClassInClassTypeOnly(type));
        String name = Objects.requireNonNull(collectionType.getQualifiedName());
        switch (name) {
          case "java.util.TreeSet":
          case "java.util.concurrent.ConcurrentSkipListSet":
            // If declared arg type inherits SortedSet, the (SortedSet) copy constructor will be invoked, which inherits the comparator
            return InheritanceUtil.isInheritor(argType, "java.util.SortedSet");
          case "java.util.TreeMap":
          case "java.util.concurrent.ConcurrentSkipListMap":
            // If declared arg type inherits SortedMap, the (SortedMap) copy constructor will be invoked, which inherits the comparator
            return InheritanceUtil.isInheritor(argType, "java.util.SortedMap");
          case "java.util.PriorityQueue":
          case "java.util.concurrent.PriorityBlockingQueue":
            // Here even (Collection) copy constructor inherits the comparator using runtime type checks, so we should be more conservative
            TypeConstraint constraint = TypeConstraint.fromDfType(CommonDataflow.getDfType(args[0]));
            PsiClassType sortedSet = JavaPsiFacade.getElementFactory(holder.getProject()).createTypeByFQClassName("java.util.SortedSet");
            return constraint.meet(TypeConstraints.instanceOf(sortedSet)) != TypeConstraints.BOTTOM ||
                   constraint.meet(TypeConstraints.instanceOf(type)) != TypeConstraints.BOTTOM;
          default:
            return false;
        }
      }
    };
  }

  private PsiNewExpression getPreviousAssignment(PsiLocalVariable variable, PsiStatement statement) {
    while (true) {
      statement = PsiTreeUtil.getPrevSiblingOfType(statement, PsiStatement.class);
      if (statement == null) return null;
      PsiExpression expression = ExpressionUtils.getAssignmentTo(statement, variable);
      if (isCollectionConstructor(expression)) {
        return (PsiNewExpression)expression;
      }
      if (VariableAccessUtils.variableIsUsed(variable, statement)) return null;
    }
  }

  private static boolean statementHasSubsequentAddAll(@NotNull PsiElement statement,
                                                      @NotNull PsiLocalVariable referent,
                                                      @NotNull String previousMethodName) {
    final PsiElement sibling = PsiTreeUtil.getNextSiblingOfType(statement, PsiStatement.class);
    if (sibling instanceof PsiExpressionStatement) {
      final PsiExpression siblingExpression = ((PsiExpressionStatement)sibling).getExpression();
      if (siblingExpression instanceof PsiMethodCallExpression) {
        final PsiMethodCallExpression siblingMethodCall = (PsiMethodCallExpression)siblingExpression;
        final PsiExpression qualifier = siblingMethodCall.getMethodExpression().getQualifierExpression();
        if (qualifier instanceof PsiReferenceExpression && referent.isEquivalentTo(((PsiReferenceExpression)qualifier).resolve())) {
          final PsiMethod method = siblingMethodCall.resolveMethod();
          if (method != null && method.getName().equals(previousMethodName)) {
            return true;
          }
        }
      }
    }
    return false;
  }

  private boolean isCollectionConstructor(PsiExpression initializer) {
    if (!(initializer instanceof PsiNewExpression)) {
      return false;
    }
    final PsiNewExpression newExpression = (PsiNewExpression)initializer;
    final PsiJavaCodeReferenceElement classReference = newExpression.getClassReference();
    if (classReference == null) {
      return false;
    }
    final PsiClass initializerClass = (PsiClass)classReference.resolve();
    if (initializerClass == null) return false;
    if (!ConstructionUtils.isCollectionWithCopyConstructor(initializerClass) &&
        (!mySettings.getCollectionClassesRequiringCapacity().contains(initializerClass.getQualifiedName()) ||
         !hasProperConstructor(initializerClass))) {
      return false;
    }
    final PsiExpressionList argumentList = newExpression.getArgumentList();
    return argumentList != null && argumentList.isEmpty();
  }

  private static boolean hasProperConstructor(PsiClass psiClass) {
    for (PsiMethod psiMethod : psiClass.getConstructors()) {
      PsiParameterList parameterList = psiMethod.getParameterList();
      if(parameterList.getParametersCount() == 1) {
        PsiParameter parameter = Objects.requireNonNull(parameterList.getParameter(0));
        PsiTypeElement typeElement = parameter.getTypeElement();
        if (typeElement != null) {
          PsiType type = typeElement.getType();
          if (InheritanceUtil.isInheritor(type, CommonClassNames.JAVA_UTIL_COLLECTION) ||
              InheritanceUtil.isInheritor(type, CommonClassNames.JAVA_UTIL_MAP)) {
            return true;
          }
        }
      }
    }
    return false;
  }

  private static boolean isAddAllReplaceable(final PsiExpression addAllExpression, PsiNewExpression newExpression) {
    final boolean[] isReplaceable = new boolean[]{true};
    final PsiFile newExpressionContainingFile = newExpression.getContainingFile();
    final TextRange newExpressionTextRange = newExpression.getTextRange();

    addAllExpression.accept(new JavaRecursiveElementVisitor() {
      @Override
      public void visitReferenceExpression(@NotNull PsiReferenceExpression expression) {
        final PsiElement resolved = expression.resolve();
        if (PsiUtil.isJvmLocalVariable(resolved)) {
          PsiVariable variable = (PsiVariable) resolved;
          final LocalSearchScope useScope = (LocalSearchScope)variable.getUseScope();
          if (!useScope.containsRange(newExpressionContainingFile, newExpressionTextRange)) {
            isReplaceable[0] = false;
          }
        }
      }
    });

    return isReplaceable[0];
  }

  private static class ReplaceAddAllWithConstructorFix implements LocalQuickFix {
    private final SmartPsiElementPointer<PsiMethodCallExpression> myMethodCallExpression;
    private final SmartPsiElementPointer<PsiNewExpression> myNewExpression;
    private final String methodName;

    ReplaceAddAllWithConstructorFix(PsiNewExpression newExpression, PsiMethodCallExpression expression, String methodName) {
      final SmartPointerManager smartPointerManager = SmartPointerManager.getInstance(newExpression.getProject());
      myMethodCallExpression = smartPointerManager.createSmartPsiElementPointer(expression);
      myNewExpression = smartPointerManager.createSmartPsiElementPointer(newExpression);
      this.methodName = methodName;
    }

    @Override
    public @Nullable FileModifier getFileModifierForPreview(@NotNull PsiFile target) {
      PsiMethodCallExpression call = myMethodCallExpression.getElement();
      PsiNewExpression newExpression = myNewExpression.getElement();
      if (call == null || newExpression == null) return null;
      return new ReplaceAddAllWithConstructorFix(PsiTreeUtil.findSameElementInCopy(newExpression, target),
                                                 PsiTreeUtil.findSameElementInCopy(call, target),
                                                 methodName);
    }

    @Nls
    @NotNull
    @Override
    public String getName() {
      return QuickFixBundle.message("collection.addall.can.be.replaced.with.constructor.fix.name", methodName);
    }

    @NotNull
    @Override
    public String getFamilyName() {
      return QuickFixBundle.message("collection.addall.can.be.replaced.with.constructor.fix.family.name");
    }

    @Override
    public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
      final PsiMethodCallExpression methodCallExpression = myMethodCallExpression.getElement();
      if (methodCallExpression == null) return;
      PsiExpressionStatement expressionStatement = ObjectUtils.tryCast(methodCallExpression.getParent(), PsiExpressionStatement.class);
      if (expressionStatement == null) return;
      final PsiNewExpression newExpression = myNewExpression.getElement();
      if (newExpression == null) return;
      PsiElement parent = PsiUtil.skipParenthesizedExprUp(newExpression.getParent());
      PsiVariable variable = null;
      if (parent instanceof PsiVariable) {
        variable = (PsiVariable)parent;
      }
      else if (parent instanceof PsiAssignmentExpression) {
        variable = ExpressionUtils.resolveLocalVariable(((PsiAssignmentExpression)parent).getLExpression());
      }
      if (variable == null) return;
      PsiJavaCodeReferenceElement reference = newExpression.getClassReference();
      if (reference == null) return;

      CommentTracker ct = new CommentTracker();
      final PsiElement parameter = methodCallExpression.getArgumentList().getExpressions()[0];
      String replacement = "new " + reference.getText() + "(" + ct.text(parameter) + ")";
      if (parent instanceof PsiAssignmentExpression) {
        ct.delete(parent);
      }
      else {
        if (variable.getParent() instanceof PsiDeclarationStatement &&
            ((PsiDeclarationStatement)variable.getParent()).getDeclaredElements().length == 1) {
          PsiElement scope = PsiTreeUtil.getParentOfType(expressionStatement, PsiMember.class, PsiStatement.class, PsiLambdaExpression.class);
          if (scope != null &&
              ReferencesSearch.search(variable).allMatch(ref -> PsiTreeUtil.isAncestor(scope, ref.getElement(), true))) {
            PsiDeclarationStatement newDeclaration =
              JavaPsiFacade.getElementFactory(project).createVariableDeclarationStatement("x", PsiType.INT, null, methodCallExpression);
            PsiVariable newVariable = (PsiVariable)newDeclaration.getDeclaredElements()[0].replace(variable);
            ct.delete(variable);
            ct.replace(Objects.requireNonNull(newVariable.getInitializer()), replacement);
            ct.replaceAndRestoreComments(expressionStatement, newDeclaration);
            return;
          }
        }
        ct.delete(newExpression);
      }
      ct.replaceAndRestoreComments(methodCallExpression, variable.getName() + "=" + replacement);
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Psalm\Internal\Codebase;

use Psalm\CodeLocation;
use Psalm\Internal\DataFlow\DataFlowNode;
use Psalm\Internal\DataFlow\Path;

use function abs;
use function array_merge;
use function count;

/**
 * @internal
 */
class VariableUseGraph extends DataFlowGraph
{
    /** @var array<string, array<string, true>> */
    protected $backward_edges = [];

    /** @var array<string, DataFlowNode> */
    private $nodes = [];

    /** @var array<string, list<CodeLocation>> */
    private $origin_locations_by_id = [];

    public function addNode(DataFlowNode $node): void
    {
        $this->nodes[$node->id] = $node;
    }

    /**
     * @param array<string> $added_taints
     * @param array<string> $removed_taints
     */
    public function addPath(
        DataFlowNode $from,
        DataFlowNode $to,
        string $path_type,
        ?array $added_taints = null,
        ?array $removed_taints = null
    ): void {
        $from_id = $from->id;
        $to_id = $to->id;

        if ($from_id === $to_id) {
            return;
        }

        $length = 0;

        if ($from->code_location
            && $to->code_location
            && $from->code_location->file_path === $to->code_location->file_path
        ) {
            $to_line = $to->code_location->raw_line_number;
            $from_line = $from->code_location->raw_line_number;
            $length = abs($to_line - $from_line);
        }

        $this->backward_edges[$to_id][$from_id] = true;
        $this->forward_edges[$from_id][$to_id] = new Path($path_type, $length);
    }

    public function isVariableUsed(DataFlowNode $assignment_node): bool
    {
        $visited_source_ids = [];

        $sources = [$assignment_node];

        for ($i = 0; count($sources) && $i < 200; $i++) {
            $new_child_nodes = [];

            foreach ($sources as $source) {
                $visited_source_ids[$source->id] = true;

                $child_nodes = $this->getChildNodes(
                    $source,
                    $visited_source_ids
                );

                if ($child_nodes === null) {
                    return true;
                }

                $new_child_nodes = array_merge(
                    $new_child_nodes,
                    $child_nodes
                );
            }

            $sources = $new_child_nodes;
        }

        return false;
    }

    /**
     * @return list<CodeLocation>
     */
    public function getOriginLocations(DataFlowNode $assignment_node): array
    {
        if (isset($this->origin_locations_by_id[$assignment_node->id])) {
            return $this->origin_locations_by_id[$assignment_node->id];
        }

        $visited_child_ids = [];

        $origin_locations = [];

        $child_nodes = [$assignment_node];

        for ($i = 0; count($child_nodes) && $i < 200; $i++) {
            $new_parent_nodes = [];

            foreach ($child_nodes as $child_node) {
                $visited_child_ids[$child_node->id] = true;

                $parent_nodes = $this->getParentNodes(
                    $child_node,
                    $visited_child_ids
                );

                if (!$parent_nodes) {
                    if ($child_node->code_location) {
                        $origin_locations[] = $child_node->code_location;
                    }

                    continue;
                }

                $new_parent_nodes = [...$new_parent_nodes, ...$parent_nodes];
            }

            $child_nodes = $new_parent_nodes;
        }

        $this->origin_locations_by_id[$assignment_node->id] = $origin_locations;

        return $origin_locations;
    }

    /**
     * @param array<string, bool> $visited_source_ids
     * @return array<string, DataFlowNode>|null
     */
    private function getChildNodes(
        DataFlowNode $generated_source,
        array $visited_source_ids
    ): ?array {
        $new_child_nodes = [];

        if (!isset($this->forward_edges[$generated_source->id])) {
            return [];
        }

        foreach ($this->forward_edges[$generated_source->id] as $to_id => $path) {
            $path_type = $path->type;

            if ($path->type === 'variable-use'
                || $path->type === 'closure-use'
                || $path->type === 'global-use'
                || $path->type === 'use-inside-instance-property'
                || $path->type === 'use-inside-static-property'
                || $path->type === 'use-inside-call'
                || $path->type === 'use-inside-conditional'
                || $path->type === 'use-inside-isset'
                || $path->type === 'arg'
                || $path->type === 'comparison'
            ) {
                return null;
            }

            if (isset($visited_source_ids[$to_id])) {
                continue;
            }

            if (self::shouldIgnoreFetch($path_type, 'arraykey', $generated_source->path_types)) {
                continue;
            }

            if (self::shouldIgnoreFetch($path_type, 'arrayvalue', $generated_source->path_types)) {
                continue;
            }

            if (self::shouldIgnoreFetch($path_type, 'property', $generated_source->path_types)) {
                continue;
            }

            $new_destination = new DataFlowNode($to_id, $to_id, null);
            $new_destination->path_types = [...$generated_source->path_types, ...[$path_type]];

            $new_child_nodes[$to_id] = $new_destination;
        }

        return $new_child_nodes;
    }

    /**
     * @param array<string, bool> $visited_source_ids
     * @return list<DataFlowNode>
     */
    private function getParentNodes(
        DataFlowNode $destination,
        array $visited_source_ids
    ): array {
        $new_parent_nodes = [];

        if (!isset($this->backward_edges[$destination->id])) {
            return [];
        }

        foreach ($this->backward_edges[$destination->id] as $from_id => $_) {
            if (isset($visited_source_ids[$from_id])) {
                continue;
            }

            if (isset($this->nodes[$from_id])) {
                $new_parent_nodes[] = $this->nodes[$from_id];
            }
        }

        return $new_parent_nodes;
    }
}


text:
<html>
<title>Package [net.fortuna.ical4j.data]</title>
<body>
Contains types providing RFC2445 input, output and parsing functionality.
</body>
</html>


text:
package com.app.prashant.monolith.articleObject;

import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;

import java.util.ArrayList;

@Root(strict = false)
public class Description {

    @ElementList(inline = true, required = false)
    private ArrayList<String> content;

    private String em;

    public ArrayList<String> getContent() {
        return content;
    }

    public void setContent(ArrayList<String> content) {
        this.content = content;
    }

    public String getEm() {
        return em;
    }

    public void setEm(String em) {
        this.em = em;
    }

    @Override
    public String toString() {
        return "ClassPojo [content = " + content + ", em = " + em + "]";
    }
}


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

#ifndef BITCOIN_SHUTDOWN_H
#define BITCOIN_SHUTDOWN_H

/** Initialize shutdown state. This must be called before using either StartShutdown(),
 * AbortShutdown() or WaitForShutdown(). Calling ShutdownRequested() is always safe.
 */
bool InitShutdownState();

/** Request shutdown of the application. */
void StartShutdown();

/** Clear shutdown flag. Only use this during init (before calling WaitForShutdown in any
 * thread), or in the unit tests. Calling it in other circumstances will cause a race condition.
 */
void AbortShutdown();

/** Returns true if a shutdown is requested, false otherwise. */
bool ShutdownRequested();

/** Wait for StartShutdown to be called in any thread. This can only be used
 * from a single thread.
 */
void WaitForShutdown();

#endif


text:
import './insert_local.js'
import './insert_both.js'
import './insert_allow.js'
import './update_local.js'
import './update_both.js'
import './update_allow.js'
import './remove_local.js'
import './remove_both.js'
import './remove_allow.js'
import './find.js'
import './findone.js'
import './find_users.js'
import './find_findone_userid.js'
import './multiple_hooks.js'
import './transform.js'
import './direct.js'
import './optional_previous.js'
import './compat.js'
import './hooks_in_loop.js'
import './upsert.js'
import './trycatch.js'
import './meteor_1_4_id_object.js'


text:
package org.apache.xml.security.stax.impl.transformer.canonicalizer;

/**
 */
public class Canonicalizer11_WithCommentsTransformer extends Canonicalizer11 {

    /**
     * Canonicalizer not complete. We are missing special handling for xml:base. But since
     * we don't support document subsets we don't need it!
     */
    public Canonicalizer11_WithCommentsTransformer() {
        super(true);
    }
}


text:
namespace TiaraCE {
    class TiaraTagSoundScenery : public TiaraTagObjectBase<HaloCE::TagObject>
    {
    public:
        TiaraTagSoundScenery(TiaraTag &tag);
    };
}


text:
package googleoauth

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"strings"
	"time"

	v32 "github.com/rancher/rancher/pkg/apis/management.cattle.io/v3"

	"github.com/mitchellh/mapstructure"
	"github.com/rancher/norman/httperror"
	"github.com/rancher/norman/types"
	"github.com/rancher/norman/types/convert"
	"github.com/rancher/rancher/pkg/auth/providers/common"
	"github.com/rancher/rancher/pkg/auth/tokens"
	client "github.com/rancher/rancher/pkg/client/generated/management/v3"
	publicclient "github.com/rancher/rancher/pkg/client/generated/management/v3public"
	corev1 "github.com/rancher/rancher/pkg/generated/norman/core/v1"
	v3 "github.com/rancher/rancher/pkg/generated/norman/management.cattle.io/v3"
	"github.com/rancher/rancher/pkg/types/config"
	"github.com/rancher/rancher/pkg/user"
	"github.com/sirupsen/logrus"
	"golang.org/x/oauth2"
	"golang.org/x/oauth2/google"
	admin "google.golang.org/api/admin/directory/v1"
	"google.golang.org/api/googleapi"
	"google.golang.org/api/option"

	apierrors "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
)

const (
	Name                 = "googleoauth"
	userType             = "user"
	groupType            = "group"
	domainPublicViewType = "domain_public"
)

var scopes = []string{"openid", "profile", "email", admin.AdminDirectoryUserReadonlyScope, admin.AdminDirectoryGroupReadonlyScope}

type googleOauthProvider struct {
	authConfigs  v3.AuthConfigInterface
	secrets      corev1.SecretInterface
	goauthClient *GClient
	userMGR      user.Manager
	tokenMGR     *tokens.Manager
	ctx          context.Context
}

func Configure(ctx context.Context, mgmtCtx *config.ScaledContext, userMGR user.Manager, tokenMGR *tokens.Manager) common.AuthProvider {
	gClient := GClient{
		httpClient: &http.Client{
			Timeout: time.Second * 30,
		},
	}
	return &googleOauthProvider{
		ctx:          ctx,
		authConfigs:  mgmtCtx.Management.AuthConfigs(""),
		secrets:      mgmtCtx.Core.Secrets(""),
		goauthClient: &gClient,
		userMGR:      userMGR,
		tokenMGR:     tokenMGR,
	}
}

func (g *googleOauthProvider) AuthenticateUser(ctx context.Context, input interface{}) (v3.Principal, []v3.Principal, string, error) {
	login, ok := input.(*v32.GoogleOauthLogin)
	if !ok {
		return v3.Principal{}, nil, "", fmt.Errorf("unexpected input type")
	}
	return g.loginUser(ctx, login, nil, false)
}

// loginUser takes as input the code; gets access_token and refresh_token in exhange; uses access_token to get user info
// and groups (if allowed); and returns the user and group principals and oauth token
func (g *googleOauthProvider) loginUser(c context.Context, googleOAuthCredential *v32.GoogleOauthLogin, config *v32.GoogleOauthConfig, testAndEnableAction bool) (v3.Principal, []v3.Principal, string, error) {
	var groupPrincipals []v3.Principal
	var userPrincipal v3.Principal
	var err error

	if config == nil {
		config, err = g.getGoogleOAuthConfigCR()
		if err != nil {
			return userPrincipal, groupPrincipals, "", err
		}
	}

	logrus.Debugf("[Google OAuth] loginuser: Using code to get oauth token")
	securityCode := googleOAuthCredential.Code
	oauth2Config, err := google.ConfigFromJSON([]byte(config.OauthCredential), scopes...)
	if err != nil {
		return userPrincipal, groupPrincipals, "", err
	}
	// Exchange the code for oauthToken
	gOAuthToken, err := oauth2Config.Exchange(c, securityCode)
	if err != nil {
		return userPrincipal, groupPrincipals, "", err
	}
	logrus.Debugf("[Google OAuth] loginuser: Exchanged code for oauth token")

	// init the admin directory service
	adminSvc, err := g.getDirectoryService(c, config.AdminEmail, []byte(config.ServiceAccountCredential), oauth2Config.TokenSource(c, gOAuthToken))
	if err != nil {
		return userPrincipal, groupPrincipals, "", err
	}
	userPrincipal, groupPrincipals, err = g.getUserInfoAndGroups(adminSvc, gOAuthToken, config, testAndEnableAction)
	if err != nil {
		return userPrincipal, groupPrincipals, "", err
	}

	logrus.Debugf("[Google OAuth] loginuser: Checking user's access to Rancher")
	allowed, err := g.userMGR.CheckAccess(config.AccessMode, config.AllowedPrincipalIDs, userPrincipal.Name, groupPrincipals)
	if err != nil {
		return userPrincipal, groupPrincipals, "", err
	}
	if !allowed {
		return userPrincipal, groupPrincipals, "", httperror.NewAPIError(httperror.Unauthorized, "unauthorized")
	}

	// save entire oauthToken because it contains refresh_token and token expiry time
	// oauth2.TokenSource used in getDirectoryService uses all these fields to auto renew the access token (Ref: https://github.com/golang/oauth2/blob/aaccbc9213b0974828f81aaac109d194880e3014/oauth2.go#L235)
	oauthToken, err := json.Marshal(gOAuthToken)
	if err != nil {
		return userPrincipal, groupPrincipals, "", err
	}

	logrus.Debugf("[Google OAuth] loginuser: Returning principals and marshaled oauth token")
	return userPrincipal, groupPrincipals, string(oauthToken), nil
}

func (g *googleOauthProvider) SearchPrincipals(searchKey, principalType string, token v3.Token) ([]v3.Principal, error) {
	var principals []v3.Principal
	var err error

	config, err := g.getGoogleOAuthConfigCR()
	if err != nil {
		return principals, err
	}

	storedOauthToken, err := g.tokenMGR.GetSecret(token.UserID, token.AuthProvider, []*v3.Token{&token})
	if err != nil && !apierrors.IsNotFound(err) {
		return nil, err
	}
	logrus.Debugf("[Google OAuth] SearchPrincipals: Retrieved stored oauth token")
	adminSvc, err := g.getdirectoryServiceFromStoredToken(storedOauthToken, config)
	if err != nil {
		return principals, err
	}

	logrus.Debugf("[Google OAuth] SearchPrincipals: Initialized dir svc with stored oauth token")
	accounts, err := g.searchPrincipals(adminSvc, searchKey, principalType, config)
	if err != nil {
		return principals, err
	}
	for _, acc := range accounts {
		principals = append(principals, g.toPrincipal(acc.Type, acc, &token))
	}
	logrus.Debugf("[Google OAuth] SearchPrincipals: Returning principals")
	return principals, nil
}

func (g *googleOauthProvider) GetPrincipal(principalID string, token v3.Token) (v3.Principal, error) {
	var principal v3.Principal
	config, err := g.getGoogleOAuthConfigCR()
	if err != nil {
		return principal, err
	}
	storedOauthToken, err := g.tokenMGR.GetSecret(token.UserID, token.AuthProvider, []*v3.Token{&token})
	if err != nil {
		if !apierrors.IsNotFound(err) {
			return principal, err
		}
	}
	logrus.Debugf("[Google OAuth] GetPrincipal: Retrieved stored oauth token")
	adminSvc, err := g.getdirectoryServiceFromStoredToken(storedOauthToken, config)
	if err != nil {
		return principal, err
	}

	logrus.Debugf("[Google OAuth] GetPrincipal: Initialized dir svc with stored oauth token")
	externalID, principalType, err := getUIDFromPrincipalID(principalID)
	if err != nil {
		return principal, err
	}
	logrus.Debugf("[Google OAuth] GetPrincipal: Parsed principalID")
	switch principalType {
	case userType:
		user, err := adminSvc.Users.Get(externalID).Do()
		if err != nil {
			if config.ServiceAccountCredential == "" {
				// used client creds, try get again with viewType=domain_public
				if gErr, ok := err.(*googleapi.Error); ok && gErr.Code == http.StatusForbidden {
					user, err = adminSvc.Users.Get(externalID).ViewType(domainPublicViewType).Do()
					if err != nil {
						return principal, err
					}
				} else {
					return principal, err
				}
			} else {
				return principal, err
			}
		}
		acc := Account{
			SubjectUniqueID: user.Id,
			Email:           user.PrimaryEmail,
			PictureURL:      user.ThumbnailPhotoUrl,
			Type:            userType,
		}
		if user.Name != nil {
			acc.Name = user.Name.FullName
			acc.GivenName = user.Name.GivenName
			acc.FamilyName = user.Name.FamilyName
		}
		return g.toPrincipal(userType, acc, &token), nil
	case groupType:
		group, err := adminSvc.Groups.Get(externalID).Do()
		if err != nil {
			if config.ServiceAccountCredential == "" {
				// used client creds, getting group for non-admin might fail with forbidden, if that's the case don't throw
				// error
				if gErr, ok := err.(*googleapi.Error); ok && gErr.Code == http.StatusForbidden {
					return principal, nil
				}
			}
			return principal, err
		}
		return g.toPrincipal(groupType, Account{SubjectUniqueID: group.Id, Email: group.Email, Name: group.Name}, &token), nil
	default:
		return principal, fmt.Errorf("cannot get the google account due to invalid externalIDType %v", principalType)
	}
}

func (g *googleOauthProvider) GetName() string {
	return Name
}

func (g *googleOauthProvider) CustomizeSchema(schema *types.Schema) {
	schema.ActionHandler = g.actionHandler
	schema.Formatter = g.formatter
}

func (g *googleOauthProvider) TransformToAuthProvider(authConfig map[string]interface{}) (map[string]interface{}, error) {
	p := common.TransformToAuthProvider(authConfig)
	val, err := g.formGoogleOAuthRedirectURLFromMap(authConfig)
	if err != nil {
		return nil, err
	}
	p[publicclient.GoogleOAuthProviderFieldRedirectURL] = val
	return p, nil
}

func (g *googleOauthProvider) RefetchGroupPrincipals(principalID string, secret string) ([]v3.Principal, error) {
	var principals []v3.Principal
	config, err := g.getGoogleOAuthConfigCR()
	if err != nil {
		return principals, err
	}
	adminSvc, err := g.getdirectoryServiceFromStoredToken(secret, config)
	if err != nil {
		return principals, err
	}
	logrus.Debugf("[Google OAuth] RefetchGroupPrincipals: Initialized dir svc with stored oauth token")
	externalID, _, err := getUIDFromPrincipalID(principalID)
	if err != nil {
		return principals, err
	}
	logrus.Debugf("[Google OAuth] GetPrincipal: Parsed principalID")
	groupPrincipals, err := g.getGroupsUserBelongsTo(adminSvc, externalID, config.Hostname, config)
	if err != nil {
		return principals, err
	}
	if !config.NestedGroupMembershipEnabled {
		return groupPrincipals, nil
	}
	return g.fetchParentGroups(config, groupPrincipals, adminSvc, config.Hostname)
}

func (g *googleOauthProvider) CanAccessWithGroupProviders(userPrincipalID string, groupPrincipals []v3.Principal) (bool, error) {
	config, err := g.getGoogleOAuthConfigCR()
	if err != nil {
		logrus.Errorf("Error fetching google OAuth config: %v", err)
		return false, err
	}
	allowed, err := g.userMGR.CheckAccess(config.AccessMode, config.AllowedPrincipalIDs, userPrincipalID, groupPrincipals)
	if err != nil {
		return false, err
	}
	return allowed, nil
}

func (g *googleOauthProvider) getGoogleOAuthConfigCR() (*v32.GoogleOauthConfig, error) {
	authConfigObj, err := g.authConfigs.ObjectClient().UnstructuredClient().Get(Name, metav1.GetOptions{})
	if err != nil {
		return nil, fmt.Errorf("failed to retrieve GoogleOAuthConfig, error: %v", err)
	}
	u, ok := authConfigObj.(runtime.Unstructured)
	if !ok {
		return nil, fmt.Errorf("failed to retrieve GoogleOAuthConfig, cannot read k8s Unstructured data")
	}
	storedGoogleOAuthConfigMap := u.UnstructuredContent()

	storedGoogleOAuthConfig := &v32.GoogleOauthConfig{}
	mapstructure.Decode(storedGoogleOAuthConfigMap, storedGoogleOAuthConfig)

	metadataMap, ok := storedGoogleOAuthConfigMap["metadata"].(map[string]interface{})
	if !ok {
		return nil, fmt.Errorf("failed to retrieve GoogleOAuthConfig metadata, cannot read k8s Unstructured data")
	}

	typemeta := &metav1.ObjectMeta{}
	mapstructure.Decode(metadataMap, typemeta)
	storedGoogleOAuthConfig.ObjectMeta = *typemeta
	if storedGoogleOAuthConfig.OauthCredential != "" {
		value, err := common.ReadFromSecret(g.secrets, storedGoogleOAuthConfig.OauthCredential, strings.ToLower(client.GoogleOauthConfigFieldOauthCredential))
		if err != nil {
			return nil, err
		}
		storedGoogleOAuthConfig.OauthCredential = value
	}

	if storedGoogleOAuthConfig.ServiceAccountCredential != "" {
		value, err := common.ReadFromSecret(g.secrets, storedGoogleOAuthConfig.ServiceAccountCredential, strings.ToLower(client.GoogleOauthConfigFieldServiceAccountCredential))
		if err != nil {
			return nil, err
		}
		storedGoogleOAuthConfig.ServiceAccountCredential = value
	}
	return storedGoogleOAuthConfig, nil
}

func (g *googleOauthProvider) saveGoogleOAuthConfigCR(config *v32.GoogleOauthConfig) error {
	storedGoogleOAuthConfig, err := g.getGoogleOAuthConfigCR()
	if err != nil {
		return err
	}
	config.APIVersion = "management.cattle.io/v3"
	config.Kind = v3.AuthConfigGroupVersionKind.Kind
	config.Type = client.GoogleOauthConfigType
	config.ObjectMeta = storedGoogleOAuthConfig.ObjectMeta

	secretInfo := convert.ToString(config.OauthCredential)
	field := strings.ToLower(client.GoogleOauthConfigFieldOauthCredential)
	if err := common.CreateOrUpdateSecrets(g.secrets, secretInfo, field, strings.ToLower(config.Type)); err != nil {
		return err
	}
	config.OauthCredential = common.GetName(config.Type, field)

	if config.ServiceAccountCredential != "" {
		secretInfo = convert.ToString(config.ServiceAccountCredential)
		field = strings.ToLower(client.GoogleOauthConfigFieldServiceAccountCredential)
		if err := common.CreateOrUpdateSecrets(g.secrets, secretInfo, field, strings.ToLower(config.Type)); err != nil {
			return err
		}
		config.ServiceAccountCredential = common.GetName(config.Type, field)
	}

	_, err = g.authConfigs.ObjectClient().Update(config.ObjectMeta.Name, config)
	if err != nil {
		return err
	}
	return nil
}

func (g *googleOauthProvider) toPrincipal(principalType string, acct Account, token *v3.Token) v3.Principal {
	displayName := acct.Name
	if displayName == "" {
		displayName = acct.Email
	}

	princ := v3.Principal{
		ObjectMeta:     metav1.ObjectMeta{Name: Name + "_" + principalType + "://" + acct.SubjectUniqueID},
		DisplayName:    displayName,
		LoginName:      acct.Email,
		Provider:       Name,
		Me:             false,
		ProfilePicture: acct.PictureURL,
	}

	if principalType == userType {
		princ.PrincipalType = "user"
		if token != nil {
			princ.Me = g.isThisUserMe(token.UserPrincipal, princ)
		}
	} else {
		princ.PrincipalType = "group"
		if token != nil {
			princ.MemberOf = g.tokenMGR.IsMemberOf(*token, princ)
		}
	}
	return princ
}

func (g *googleOauthProvider) isThisUserMe(me v3.Principal, other v3.Principal) bool {
	if me.ObjectMeta.Name == other.ObjectMeta.Name && me.LoginName == other.LoginName && me.PrincipalType == other.PrincipalType {
		return true
	}
	return false
}

func (g *googleOauthProvider) getDirectoryService(ctx context.Context, userEmail string, jsonCredentials []byte, accessTokenSource oauth2.TokenSource) (*admin.Service, error) {
	if userEmail != "" && len(jsonCredentials) > 0 {
		// oauth golang library performs all these steps: https://developers.google.com/identity/protocols/OAuth2ServiceAccount#jwt-auth
		// using JWTConfigFromJSON method
		config, err := google.JWTConfigFromJSON(jsonCredentials, admin.AdminDirectoryUserReadonlyScope, admin.AdminDirectoryGroupReadonlyScope)
		if err != nil {
			logrus.Errorf("[Google OAuth] error unmarshaling service account creds: %v", err)
			return nil, fmt.Errorf("invalid Service Account Credentials provided")
		}
		config.Subject = userEmail
		srv, err := admin.NewService(ctx, option.WithTokenSource(config.TokenSource(ctx)))
		if err != nil {
			logrus.Errorf("[Google OAuth] error generating tokenSource for service account creds: %v", err)
			return nil, fmt.Errorf("invalid Service Account Credentials provided")
		}
		return srv, nil
	}
	// client oauth creds are used
	srv, err := admin.NewService(ctx, option.WithTokenSource(accessTokenSource))
	if err != nil {
		return nil, err
	}
	return srv, nil
}

func (g *googleOauthProvider) GetUserExtraAttributes(userPrincipal v3.Principal) map[string][]string {
	extras := make(map[string][]string)
	if userPrincipal.Name != "" {
		extras[common.UserAttributePrincipalID] = []string{userPrincipal.Name}
	}
	if userPrincipal.LoginName != "" {
		extras[common.UserAttributeUserName] = []string{userPrincipal.LoginName}
	}
	return extras
}

// IsDisabledProvider checks if the Google auth provider is currently disabled in Rancher.
func (g *googleOauthProvider) IsDisabledProvider() (bool, error) {
	googleOauthConfig, err := g.getGoogleOAuthConfigCR()
	if err != nil {
		return false, err
	}
	return !googleOauthConfig.Enabled, nil
}

// CleanupResources deletes resources associated with the Google auth provider.
func (g *googleOauthProvider) CleanupResources(*v3.AuthConfig) error {
	return nil
}


text:
'use strict';

import createNamedLogic, * as LOGIC  from './util/createNamedLogic';
import SelCrit    from '../../shared/domain/SelCrit';
import itemTypes  from '../../shared/domain/itemTypes';
import actions    from '../actions';

/**
 * Initialize the actions.selCrit.edit action, which edits the supplied selCrit,
 * injecting additional information needed in action.
 */
export default createNamedLogic('initializeSelCritEdit', {

  type: String(actions.selCrit.edit),

  transform({ getState, action, log }, next) {

    const selCrit = action.selCrit;

    log.debug(()=> 'injecting additional information needed in action');

    // inject the DB meta definition we are working for
    const meta = action.meta = itemTypes.meta[selCrit.itemType];

    // inject the total set of fieldOptions promoted to the user
    // ... derived from meta.validFields
    const fieldOptions = action.fieldOptions = [];
    for (const fieldName in meta.validFields) {
      const fieldLabel = meta.validFields[fieldName];
      if (fieldLabel) { // missing field label is a control indication to NOT promote field to user
        fieldOptions.push( { value: fieldName, label: fieldLabel } );
      }
    }

    // inject the total set of sortOptions promoted to the user
    // ... derived from meta.validFields
    const sortOptions = action.sortOptions = [];
    for (const fieldName in meta.validFields) {
      const fieldLabel = meta.validFields[fieldName];
      if (fieldLabel) { // missing field label is a control indication to NOT promote field to user
        sortOptions.push( { value: fieldName, label: fieldLabel, ascDec: 1 } );
      }
    }

    // pass on action with newly injected properties
    next(action);
  },

});


text:
package xattr

import (
	"syscall"
)

func get(path, attr string, dest []byte) (sz int, err error) {
	return syscall.Getxattr(path, attr, dest)
}

func list(path string, dest []byte) (sz int, err error) {
	return syscall.Listxattr(path, dest)
}

func set(path, attr string, data []byte, flags int) error {
	return syscall.Setxattr(path, attr, data, flags)
}

func remove(path, attr string) error {
	return syscall.Removexattr(path, attr)
}


text:
/* Set platform defines at build time for volk to pick up. */
#if defined(_WIN32)
#   define VK_USE_PLATFORM_WIN32_KHR
#elif defined(__linux__) || defined(__unix__)
#   define VK_USE_PLATFORM_XLIB_KHR
#elif defined(__APPLE__)
#   define VK_USE_PLATFORM_MACOS_MVK
#else
#   error "Platform not supported by this example."
#endif

#define VOLK_IMPLEMENTATION
#include "volk.h"

#include "stdio.h"
#include "stdlib.h"

int main()
{
    VkResult r;
    uint32_t version;
    void* ptr;

    /* This won't compile if the appropriate Vulkan platform define isn't set. */
    ptr =
#if defined(_WIN32)
    &vkCreateWin32SurfaceKHR;
#elif defined(__linux__) || defined(__unix__)
    &vkCreateXlibSurfaceKHR;
#elif defined(__APPLE__)
    &vkCreateMacOSSurfaceMVK;
#else
    /* Platform not recogized for testing. */
    NULL;
#endif

    /* Try to initialize volk. This might not work on CI builds, but the
     * above should have compiled at least. */
    r = volkInitialize();
    if (r != VK_SUCCESS) {
        printf("volkInitialize failed!\n");
        return -1;
    }

    version = volkGetInstanceVersion();
    printf("Vulkan version %d.%d.%d initialized.\n",
            VK_VERSION_MAJOR(version),
            VK_VERSION_MINOR(version),
            VK_VERSION_PATCH(version));

    return 0;
}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Packaging;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Options;
using Microsoft.CodeAnalysis.SymbolSearch;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CodeFixes.AddImport
{
    internal abstract partial class AbstractAddImportCodeFixProvider<TSimpleNameSyntax>
    {
        private class SymbolReferenceFinder
        {
            private const string AttributeSuffix = "Attribute";

            private readonly Diagnostic _diagnostic;
            private readonly Document _document;
            private readonly SemanticModel _semanticModel;

            private readonly INamedTypeSymbol _containingType;
            private readonly ISymbol _containingTypeOrAssembly;
            private readonly ISet<INamespaceSymbol> _namespacesInScope;
            private readonly ISyntaxFactsService _syntaxFacts;
            private readonly AbstractAddImportCodeFixProvider<TSimpleNameSyntax> _owner;

            private readonly SyntaxNode _node;

            public SymbolReferenceFinder(
                AbstractAddImportCodeFixProvider<TSimpleNameSyntax> owner,
                Document document, SemanticModel semanticModel,
                Diagnostic diagnostic, SyntaxNode node,
                CancellationToken cancellationToken)
            {
                _owner = owner;
                _document = document;
                _semanticModel = semanticModel;
                _diagnostic = diagnostic;
                _node = node;

                _containingType = semanticModel.GetEnclosingNamedType(node.SpanStart, cancellationToken);
                _containingTypeOrAssembly = _containingType ?? (ISymbol)semanticModel.Compilation.Assembly;
                _syntaxFacts = document.Project.LanguageServices.GetService<ISyntaxFactsService>();

                _namespacesInScope = GetNamespacesInScope(cancellationToken);
            }

            private ISet<INamespaceSymbol> GetNamespacesInScope(CancellationToken cancellationToken)
            {
                // Add all hte namespaces brought in by imports/usings.
                var set = _owner.GetImportNamespacesInScope(_semanticModel, _node, cancellationToken);

                // Also add all the namespaces we're containing in.  We don't want
                // to add imports for these namespaces either.
                for (var containingNamespace = _semanticModel.GetEnclosingNamespace(_node.SpanStart, cancellationToken);
                     containingNamespace != null;
                     containingNamespace = containingNamespace.ContainingNamespace)
                {
                    set.Add(MapToCompilationNamespaceIfPossible(containingNamespace));
                }

                return set;
            }

            private INamespaceSymbol MapToCompilationNamespaceIfPossible(INamespaceSymbol containingNamespace)
            {
                return _semanticModel.Compilation.GetCompilationNamespace(containingNamespace) ?? containingNamespace;
            }

            internal Task<List<SymbolReference>> FindInAllSymbolsInStartingProjectAsync(
                bool exact, CancellationToken cancellationToken)
            {
                var searchScope = new AllSymbolsProjectSearchScope(_owner, _document.Project, exact, cancellationToken);
                return DoAsync(searchScope);
            }

            internal Task<List<SymbolReference>> FindInSourceSymbolsInProjectAsync(
                ConcurrentDictionary<Project, AsyncLazy<IAssemblySymbol>> projectToAssembly,
                Project project, bool exact, CancellationToken cancellationToken)
            {
                var searchScope = new SourceSymbolsProjectSearchScope(
                    _owner, projectToAssembly, project, exact, cancellationToken);
                return DoAsync(searchScope);
            }

            internal Task<List<SymbolReference>> FindInMetadataSymbolsAsync(
                IAssemblySymbol assembly, PortableExecutableReference metadataReference,
                bool exact, CancellationToken cancellationToken)
            {
                var searchScope = new MetadataSymbolsSearchScope(
                    _owner, _document.Project.Solution, assembly, metadataReference, exact, cancellationToken);
                return DoAsync(searchScope);
            }

            private async Task<List<SymbolReference>> DoAsync(SearchScope searchScope)
            {
                searchScope.CancellationToken.ThrowIfCancellationRequested();

                // Spin off tasks to do all our searching.
                var tasks = new List<Task<IList<SymbolReference>>>
                {
                    this.GetNamespacesForMatchingTypesAsync(searchScope),
                    this.GetMatchingTypesAsync(searchScope),
                    this.GetNamespacesForMatchingNamespacesAsync(searchScope),
                    this.GetNamespacesForMatchingFieldsAndPropertiesAsync(searchScope),
                    this.GetNamespacesForMatchingExtensionMethodsAsync(searchScope),
                };

                // Searching for things like "Add" (for collection initializers) and "Select"
                // (for extension methods) should only be done when doing an 'exact' search.
                // We should not do fuzzy searches for these names.  In this case it's not
                // like the user was writing Add or Select, but instead we're looking for
                // viable symbols with those names to make a collection initializer or
                // query expression valid.
                if (searchScope.Exact)
                {
                    tasks.Add(this.GetNamespacesForCollectionInitializerMethodsAsync(searchScope));
                    tasks.Add(this.GetNamespacesForQueryPatternsAsync(searchScope));
                }

                await Task.WhenAll(tasks).ConfigureAwait(false);
                searchScope.CancellationToken.ThrowIfCancellationRequested();

                List<SymbolReference> allReferences = null;
                foreach (var task in tasks)
                {
                    var taskResult = await task.ConfigureAwait(false);
                    if (taskResult?.Count > 0)
                    {
                        allReferences = allReferences ?? new List<SymbolReference>();
                        allReferences.AddRange(taskResult);
                    }
                }

                return DeDupeAndSortReferences(allReferences);
            }

            private List<SymbolReference> DeDupeAndSortReferences(List<SymbolReference> allReferences)
            {
                if (allReferences == null)
                {
                    return null;
                }

                return allReferences
                    .Distinct()
                    .Where(NotNull)
                    .Where(NotGlobalNamespace)
                    .OrderBy((r1, r2) => r1.CompareTo(_document, r2))
                    .ToList();
            }

            private async Task<IList<SymbolReference>> GetNamespacesForMatchingTypesAsync(SearchScope searchScope)
            {
                searchScope.CancellationToken.ThrowIfCancellationRequested();

                TSimpleNameSyntax nameNode;
                if (!_owner.CanAddImportForType(_diagnostic, _node, out nameNode))
                {
                    return null;
                }

                string name;
                int arity;
                bool inAttributeContext, hasIncompleteParentMember;
                CalculateContext(nameNode, _syntaxFacts, out name, out arity, out inAttributeContext, out hasIncompleteParentMember);

                var symbols = await GetTypeSymbols(searchScope, name, nameNode, inAttributeContext).ConfigureAwait(false);
                if (symbols == null)
                {
                    return null;
                }

                return GetNamespacesForMatchingTypesAsync(searchScope, arity, inAttributeContext, hasIncompleteParentMember, symbols);
            }

            private async Task<IList<SymbolReference>> GetMatchingTypesAsync(SearchScope searchScope)
            {
                searchScope.CancellationToken.ThrowIfCancellationRequested();

                TSimpleNameSyntax nameNode;
                if (!_owner.CanAddImportForType(_diagnostic, _node, out nameNode))
                {
                    return null;
                }

                string name;
                int arity;
                bool inAttributeContext, hasIncompleteParentMember;
                CalculateContext(nameNode, _syntaxFacts, out name, out arity, out inAttributeContext, out hasIncompleteParentMember);

                var symbols = await GetTypeSymbols(searchScope, name, nameNode, inAttributeContext).ConfigureAwait(false);
                if (symbols == null)
                {
                    return null;
                }

                return GetMatchingTypes(searchScope, name, arity, inAttributeContext, symbols, hasIncompleteParentMember);
            }

            internal async Task FindNugetOrReferenceAssemblyReferencesAsync(
                List<Reference> allReferences, CancellationToken cancellationToken)
            {
                if (allReferences.Count > 0)
                {
                    // Only do this if none of the project or metadata searches produced
                    // any results. We always consider source and local metadata to be
                    // better than any nuget/assembly-reference results.
                    return;
                }

                TSimpleNameSyntax nameNode;
                if (!_owner.CanAddImportForType(_diagnostic, _node, out nameNode))
                {
                    return;
                }

                string name;
                int arity;
                bool inAttributeContext, hasIncompleteParentMember;
                CalculateContext(nameNode, _syntaxFacts, out name, out arity, out inAttributeContext, out hasIncompleteParentMember);

                if (ExpressionBinds(nameNode, checkForExtensionMethods: false, cancellationToken: cancellationToken))
                {
                    return;
                }

                await FindNugetOrReferenceAssemblyTypeReferencesAsync(
                    allReferences, nameNode, name, arity, inAttributeContext, cancellationToken).ConfigureAwait(false);
            }

            private async Task FindNugetOrReferenceAssemblyTypeReferencesAsync(
                List<Reference> allReferences, TSimpleNameSyntax nameNode,
                string name, int arity, bool inAttributeContext,
                CancellationToken cancellationToken)
            {
                if (arity == 0 && inAttributeContext)
                {
                    await FindNugetOrReferenceAssemblyTypeReferencesWorkerAsync(
                        allReferences, nameNode, name + AttributeSuffix, arity,
                        isAttributeSearch: true, cancellationToken: cancellationToken).ConfigureAwait(false);
                }

                await FindNugetOrReferenceAssemblyTypeReferencesWorkerAsync(
                    allReferences, nameNode, name, arity,
                    isAttributeSearch: false, cancellationToken: cancellationToken).ConfigureAwait(false);
            }

            private async Task FindNugetOrReferenceAssemblyTypeReferencesWorkerAsync(
                List<Reference> allReferences, TSimpleNameSyntax nameNode,
                string name, int arity, bool isAttributeSearch, CancellationToken cancellationToken)
            {
                var workspaceServices = _document.Project.Solution.Workspace.Services;

                var symbolSearchService = _owner._symbolSearchService ?? workspaceServices.GetService<ISymbolSearchService>();
                var installerService = _owner._packageInstallerService ?? workspaceServices.GetService<IPackageInstallerService>();

                var language = _document.Project.Language;

                var options = workspaceServices.Workspace.Options;
                var searchReferenceAssemblies = options.GetOption(
                    SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, language);
                var searchNugetPackages = options.GetOption(
                    SymbolSearchOptions.SuggestForTypesInNuGetPackages, language);

                if (symbolSearchService != null &&
                    searchReferenceAssemblies)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    await FindReferenceAssemblyTypeReferencesAsync(
                        symbolSearchService, allReferences, nameNode, name, arity, isAttributeSearch, cancellationToken).ConfigureAwait(false);
                }

                if (symbolSearchService != null &&
                    searchNugetPackages &&
                    installerService.IsEnabled)
                {
                    foreach (var packageSource in installerService.PackageSources)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        await FindNugetTypeReferencesAsync(
                            packageSource, symbolSearchService, installerService, allReferences,
                            nameNode, name, arity, isAttributeSearch, cancellationToken).ConfigureAwait(false);
                    }
                }
            }

            private async Task FindReferenceAssemblyTypeReferencesAsync(
                ISymbolSearchService searchService,
                List<Reference> allReferences,
                TSimpleNameSyntax nameNode,
                string name,
                int arity,
                bool isAttributeSearch,
                CancellationToken cancellationToken)
            {
                cancellationToken.ThrowIfCancellationRequested();
                var results = await searchService.FindReferenceAssembliesWithTypeAsync(
                    name, arity, cancellationToken).ConfigureAwait(false);
                if (results.IsDefault)
                {
                    return;
                }

                var project = _document.Project;
                var projectId = project.Id;
                var workspace = project.Solution.Workspace;

                foreach (var result in results)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    await HandleReferenceAssemblyReferenceAsync(
                        allReferences, nameNode, project,
                        isAttributeSearch, result, weight: allReferences.Count, cancellationToken: cancellationToken).ConfigureAwait(false);
                }
            }

            private async Task FindNugetTypeReferencesAsync(
                PackageSource source,
                ISymbolSearchService searchService,
                IPackageInstallerService installerService,
                List<Reference> allReferences,
                TSimpleNameSyntax nameNode,
                string name,
                int arity,
                bool isAttributeSearch,
                CancellationToken cancellationToken)
            {
                cancellationToken.ThrowIfCancellationRequested();
                var results = await searchService.FindPackagesWithTypeAsync(
                    source.Name, name, arity, cancellationToken).ConfigureAwait(false);
                if (results.IsDefault)
                {
                    return;
                }

                var project = _document.Project;
                var projectId = project.Id;
                var workspace = project.Solution.Workspace;

                foreach (var result in results)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    await HandleNugetReferenceAsync(
                        source.Source, installerService, allReferences, nameNode,
                        project, isAttributeSearch, result, weight: allReferences.Count).ConfigureAwait(false);
                }
            }

            private async Task HandleReferenceAssemblyReferenceAsync(
                List<Reference> allReferences,
                TSimpleNameSyntax nameNode,
                Project project,
                bool isAttributeSearch,
                ReferenceAssemblyWithTypeResult result,
                int weight,
                CancellationToken cancellationToken)
            {
                foreach (var reference in project.MetadataReferences)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
                    var assemblySymbol = compilation.GetAssemblyOrModuleSymbol(reference) as IAssemblySymbol;
                    if (assemblySymbol?.Name == result.AssemblyName)
                    {
                        // Project already has a reference to an assembly with this name.
                        return;
                    }
                }

                var desiredName = GetDesiredName(isAttributeSearch, result.TypeName);
                allReferences.Add(new AssemblyReference(_owner,
                    new SearchResult(desiredName, nameNode, result.ContainingNamespaceNames, weight), result));
            }

            private Task HandleNugetReferenceAsync(
                string source,
                IPackageInstallerService installerService,
                List<Reference> allReferences,
                TSimpleNameSyntax nameNode,
                Project project,
                bool isAttributeSearch,
                PackageWithTypeResult result,
                int weight)
            {
                if (!installerService.IsInstalled(project.Solution.Workspace, project.Id, result.PackageName))
                {
                    var desiredName = GetDesiredName(isAttributeSearch, result.TypeName);
                    allReferences.Add(new PackageReference(_owner, installerService,
                        new SearchResult(desiredName, nameNode, result.ContainingNamespaceNames, weight),
                        source, result.PackageName, result.Version));
                }

                return SpecializedTasks.EmptyTask;
            }

            private static string GetDesiredName(bool isAttributeSearch, string typeName)
            {
                var desiredName = typeName;
                if (isAttributeSearch)
                {
                    desiredName = desiredName.GetWithoutAttributeSuffix(isCaseSensitive: false);
                }

                return desiredName;
            }

            private async Task<ImmutableArray<SymbolResult<ITypeSymbol>>> GetTypeSymbols(
                SearchScope searchScope,
                string name,
                TSimpleNameSyntax nameNode,
                bool inAttributeContext)
            {
                if (searchScope.CancellationToken.IsCancellationRequested)
                {
                    return ImmutableArray<SymbolResult<ITypeSymbol>>.Empty;
                }

                if (ExpressionBinds(nameNode, checkForExtensionMethods: false, cancellationToken: searchScope.CancellationToken))
                {
                    return ImmutableArray<SymbolResult<ITypeSymbol>>.Empty;
                }

                var symbols = await searchScope.FindDeclarationsAsync(name, nameNode, SymbolFilter.Type).ConfigureAwait(false);

                // also lookup type symbols with the "Attribute" suffix.
                if (inAttributeContext)
                {
                    var attributeSymbols = await searchScope.FindDeclarationsAsync(name + AttributeSuffix, nameNode, SymbolFilter.Type).ConfigureAwait(false);

                    symbols = symbols.AddRange(
                        attributeSymbols.Select(r => r.WithDesiredName(r.DesiredName.GetWithoutAttributeSuffix(isCaseSensitive: false))));
                }

                return OfType<ITypeSymbol>(symbols);
            }

            protected bool ExpressionBinds(
                TSimpleNameSyntax nameNode, bool checkForExtensionMethods, CancellationToken cancellationToken)
            {
                // See if the name binds to something other then the error type. If it does, there's nothing further we need to do.
                // For extension methods, however, we will continue to search if there exists any better matched method.
                cancellationToken.ThrowIfCancellationRequested();
                var symbolInfo = _semanticModel.GetSymbolInfo(nameNode, cancellationToken);
                if (symbolInfo.CandidateReason == CandidateReason.OverloadResolutionFailure && !checkForExtensionMethods)
                {
                    return true;
                }

                return symbolInfo.Symbol != null;
            }

            private async Task<IList<SymbolReference>> GetNamespacesForMatchingNamespacesAsync(
                SearchScope searchScope)
            {
                searchScope.CancellationToken.ThrowIfCancellationRequested();

                TSimpleNameSyntax nameNode;
                if (!_owner.CanAddImportForNamespace(_diagnostic, _node, out nameNode))
                {
                    return null;
                }

                string name;
                int arity;
                _syntaxFacts.GetNameAndArityOfSimpleName(nameNode, out name, out arity);

                if (arity > 0)
                {
                    return null;
                }

                if (ExpressionBinds(nameNode, checkForExtensionMethods: false, cancellationToken: searchScope.CancellationToken))
                {
                    return null;
                }

                var symbols = await searchScope.FindDeclarationsAsync(name, nameNode, SymbolFilter.Namespace).ConfigureAwait(false);

                return GetProposedNamespaces(
                    searchScope, OfType<INamespaceSymbol>(symbols).Select(s => s.WithSymbol(s.Symbol.ContainingNamespace)));
            }

            private async Task<IList<SymbolReference>> GetNamespacesForMatchingExtensionMethodsAsync(SearchScope searchScope)
            {
                searchScope.CancellationToken.ThrowIfCancellationRequested();

                TSimpleNameSyntax nameNode;
                if (!_owner.CanAddImportForMethod(_diagnostic, _syntaxFacts, _node, out nameNode))
                {
                    return null;
                }

                if (nameNode == null)
                {
                    return null;
                }

                var symbols = await GetSymbolsAsync(searchScope, nameNode).ConfigureAwait(false);
                var extensionMethods = FilterForExtensionMethods(searchScope, nameNode.Parent, symbols);

                return extensionMethods.ToList();
            }

            private async Task<IList<SymbolReference>> GetNamespacesForCollectionInitializerMethodsAsync(SearchScope searchScope)
            {
                searchScope.CancellationToken.ThrowIfCancellationRequested();

                TSimpleNameSyntax nameNode;
                if (!_owner.CanAddImportForMethod(_diagnostic, _syntaxFacts, _node, out nameNode))
                {
                    return null;
                }

                var methodSymbols = await GetAddMethodsAsync(searchScope, _node.Parent).ConfigureAwait(false);
                return GetProposedNamespaces(searchScope, methodSymbols.Select(m => m.WithSymbol(m.Symbol.ContainingNamespace)));
            }

            private async Task<IList<SymbolReference>> GetNamespacesForMatchingFieldsAndPropertiesAsync(
                SearchScope searchScope)
            {
                searchScope.CancellationToken.ThrowIfCancellationRequested();

                TSimpleNameSyntax nameNode;
                if (!_owner.CanAddImportForMethod(_diagnostic, _syntaxFacts, _node, out nameNode))
                {
                    return null;
                }

                if (nameNode == null)
                {
                    return null;
                }

                // We have code like "Color.Black".  "Color" bound to a 'Color Color' property, and
                // 'Black' did not bind.  We want to find a type called 'Color' that will actually
                // allow 'Black' to bind.
                var syntaxFacts = this._document.GetLanguageService<ISyntaxFactsService>();
                if (!syntaxFacts.IsMemberAccessExpressionName(nameNode))
                {
                    return null;
                }

                var expression = syntaxFacts.GetExpressionOfMemberAccessExpression(nameNode.Parent);
                if (expression == null)
                {
                    return null;
                }

                if (!(expression is TSimpleNameSyntax))
                {
                    return null;
                }

                // Check if the expression before the dot binds to a property or field.
                var symbol = this._semanticModel.GetSymbolInfo(expression, searchScope.CancellationToken).GetAnySymbol();
                if (symbol?.Kind != SymbolKind.Property && symbol?.Kind != SymbolKind.Field)
                {
                    return null;
                }

                var propertyOrFieldType = symbol.GetSymbolType();
                if (!(propertyOrFieldType is INamedTypeSymbol))
                {
                    return null;
                }

                // Check if we have teh 'Color Color' case.
                var propertyType = (INamedTypeSymbol)propertyOrFieldType;
                if (!Equals(propertyType.Name, symbol.Name))
                {
                    return null;
                }

                // Try to look up 'Color' as a type.
                var symbolResults = await searchScope.FindDeclarationsAsync(
                    symbol.Name, (TSimpleNameSyntax)expression, SymbolFilter.Type).ConfigureAwait(false);

                // Return results that have accesible members.
                var name = nameNode.GetFirstToken().ValueText;
                return symbolResults.Where(sr => HasAccessibleStaticFieldOrProperty(sr.Symbol, name))
                                    .Select(sr => sr.WithSymbol(sr.Symbol.ContainingNamespace))
                                    .Select(searchScope.CreateReference)
                                    .ToList();
            }

            private bool HasAccessibleStaticFieldOrProperty(ISymbol symbol, string fieldOrPropertyName)
            {
                var namedType = (INamedTypeSymbol)symbol;
                if (namedType != null)
                {
                    var members = namedType.GetMembers(fieldOrPropertyName);
                    var query = from m in members
                                where m is IFieldSymbol || m is IPropertySymbol
                                where m.IsAccessibleWithin(_semanticModel.Compilation.Assembly)
                                where m.IsStatic
                                select m;
                    return query.Any();
                }

                return false;
            }

            private async Task<IList<SymbolReference>> GetNamespacesForQueryPatternsAsync(SearchScope searchScope)
            {
                searchScope.CancellationToken.ThrowIfCancellationRequested();

                if (!_owner.CanAddImportForQuery(_diagnostic, _node))
                {
                    return null;
                }

                ITypeSymbol type = _owner.GetQueryClauseInfo(_semanticModel, _node, searchScope.CancellationToken);
                if (type == null)
                {
                    return null;
                }

                // find extension methods named "Select"
                var symbols = await searchScope.FindDeclarationsAsync("Select", nameNode: null, filter: SymbolFilter.Member).ConfigureAwait(false);

                // Note: there is no "desiredName" when doing this.  We're not going to do any
                // renames of the user code.  We're just looking for an extension method called
                // "Select", but that name has no bearing on the code in question that we're
                // trying to fix up.
                var extensionMethodSymbols = OfType<IMethodSymbol>(symbols)
                    .Where(s => s.Symbol.IsExtensionMethod && _owner.IsViableExtensionMethod(s.Symbol, type))
                    .Select(s => s.WithDesiredName(null))
                    .ToList();

                return GetProposedNamespaces(
                    searchScope, extensionMethodSymbols.Select(s => s.WithSymbol(s.Symbol.ContainingNamespace)));
            }

            private List<SymbolReference> GetMatchingTypes(
                SearchScope searchScope, string name, int arity, bool inAttributeContext, IEnumerable<SymbolResult<ITypeSymbol>> symbols, bool hasIncompleteParentMember)
            {
                var accessibleTypeSymbols = symbols
                    .Where(s => ArityAccessibilityAndAttributeContextAreCorrect(
                                    _semanticModel, s.Symbol, arity,
                                    inAttributeContext, hasIncompleteParentMember))
                    .ToList();

                return GetProposedTypes(searchScope, name, accessibleTypeSymbols);
            }

            private ImmutableArray<SymbolReference> GetNamespacesForMatchingTypesAsync(
                SearchScope searchScope, int arity, bool inAttributeContext, bool hasIncompleteParentMember,
                IEnumerable<SymbolResult<ITypeSymbol>> symbols)
            {
                var accessibleTypeSymbols = symbols
                    .Where(s => s.Symbol.ContainingSymbol is INamespaceSymbol
                                && ArityAccessibilityAndAttributeContextAreCorrect(
                                    _semanticModel, s.Symbol, arity,
                                    inAttributeContext, hasIncompleteParentMember))
                    .ToList();

                return GetProposedNamespaces(searchScope, accessibleTypeSymbols.Select(s => s.WithSymbol(s.Symbol.ContainingNamespace)));
            }

            private ImmutableArray<SymbolReference> GetProposedNamespaces(SearchScope scope, IEnumerable<SymbolResult<INamespaceSymbol>> namespaces)
            {
                // We only want to offer to add a using if we don't already have one.
                return
                    namespaces.Where(n => !n.Symbol.IsGlobalNamespace)
                              .Select(n => n.WithSymbol(MapToCompilationNamespaceIfPossible(n.Symbol)))
                              .Where(n => n.Symbol != null && !_namespacesInScope.Contains(n.Symbol))
                              .Select(n => scope.CreateReference(n))
                              .ToImmutableArray();
            }

            private List<SymbolReference> GetProposedTypes(SearchScope searchScope, string name, List<SymbolResult<ITypeSymbol>> accessibleTypeSymbols)
            {
                List<SymbolReference> result = null;
                if (accessibleTypeSymbols != null)
                {
                    foreach (var typeSymbol in accessibleTypeSymbols)
                    {
                        if (typeSymbol.Symbol?.ContainingType != null)
                        {
                            result = result ?? new List<SymbolReference>();
                            result.Add(searchScope.CreateReference(typeSymbol.WithSymbol(typeSymbol.Symbol.ContainingType)));
                        }
                    }
                }

                return result;
            }

            private Task<ImmutableArray<SymbolResult<ISymbol>>> GetSymbolsAsync(SearchScope searchScope, TSimpleNameSyntax nameNode)
            {
                searchScope.CancellationToken.ThrowIfCancellationRequested();

                // See if the name binds.  If it does, there's nothing further we need to do.
                if (ExpressionBinds(nameNode, checkForExtensionMethods: true, cancellationToken: searchScope.CancellationToken))
                {
                    return SpecializedTasks.EmptyImmutableArray<SymbolResult<ISymbol>>();
                }

                string name;
                int arity;
                _syntaxFacts.GetNameAndArityOfSimpleName(nameNode, out name, out arity);
                if (name == null)
                {
                    return SpecializedTasks.EmptyImmutableArray<SymbolResult<ISymbol>>();
                }

                return searchScope.FindDeclarationsAsync(name, nameNode, SymbolFilter.Member);
            }

            private ImmutableArray<SymbolReference> FilterForExtensionMethods(
                SearchScope searchScope, SyntaxNode expression, ImmutableArray<SymbolResult<ISymbol>> symbols)
            {
                var extensionMethodSymbols = OfType<IMethodSymbol>(symbols)
                    .Where(s => s.Symbol.IsExtensionMethod &&
                                s.Symbol.IsAccessibleWithin(_semanticModel.Compilation.Assembly) == true &&
                                _owner.IsViableExtensionMethod(s.Symbol, expression, _semanticModel, _syntaxFacts, searchScope.CancellationToken))
                    .ToList();

                return GetProposedNamespaces(
                    searchScope, extensionMethodSymbols.Select(s => s.WithSymbol(s.Symbol.ContainingNamespace)));
            }

            private async Task<ImmutableArray<SymbolResult<IMethodSymbol>>> GetAddMethodsAsync(
                SearchScope searchScope, SyntaxNode expression)
            {
                string name;
                int arity;
                _syntaxFacts.GetNameAndArityOfSimpleName(_node, out name, out arity);
                if (name != null || !_owner.IsAddMethodContext(_node, _semanticModel))
                {
                    return ImmutableArray<SymbolResult<IMethodSymbol>>.Empty;
                }

                // Note: there is no desiredName for these search results.  We're searching for
                // extension methods called "Add", but we have no intention of renaming any
                // of the existing user code to that name.
                var symbols = await searchScope.FindDeclarationsAsync("Add", nameNode: null, filter: SymbolFilter.Member).ConfigureAwait(false);
                return OfType<IMethodSymbol>(symbols)
                    .WhereAsArray(s => s.Symbol.IsExtensionMethod &&
                                s.Symbol.IsAccessibleWithin(_semanticModel.Compilation.Assembly) == true &&
                                     _owner.IsViableExtensionMethod(s.Symbol, expression, _semanticModel, _syntaxFacts, searchScope.CancellationToken))
                    .SelectAsArray(s => s.WithDesiredName(null));
            }

            private ImmutableArray<SymbolResult<T>> OfType<T>(ImmutableArray<SymbolResult<ISymbol>> symbols) where T : ISymbol
            {
                return symbols.WhereAsArray(s => s.Symbol is T)
                              .SelectAsArray(s => s.WithSymbol((T)s.Symbol));
            }
        }
    }
}


text:
package basictracer

import (
	"sync/atomic"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
)

func TestInMemoryRecorderSpans(t *testing.T) {
	recorder := NewInMemoryRecorder()
	var apiRecorder SpanRecorder = recorder
	span := RawSpan{
		Context:   SpanContext{},
		Operation: "test-span",
		Start:     time.Now(),
		Duration:  -1,
	}
	apiRecorder.RecordSpan(span)
	assert.Equal(t, []RawSpan{span}, recorder.GetSpans())
	assert.Equal(t, []RawSpan{}, recorder.GetSampledSpans())
}

type CountingRecorder int32

func (c *CountingRecorder) RecordSpan(r RawSpan) {
	atomic.AddInt32((*int32)(c), 1)
}


text:
var settings = require('./config');
var nodemailer = require('nodemailer');
var smtpPool = require('nodemailer-smtp-pool');

var transporter;

var Mailer = module.exports = {
	init: function() {

		return function(done) {

			if (settings.general.mailer.service == 'Gmail') {

				// Initializing XOAuth2
				var generator = require('xoauth2')
					.createXOAuth2Generator(settings.general.mailer.auth);

				// Create a pool of connections
				var pool = smtpPool({
					service: settings.general.mailer.service,
					auth: {
						xoauth2: generator
					}
				});

				// Create a transport
				transporter = nodemailer.createTransport(pool);

				done();
				return;
			}

			// Create a pool of connections for specific mail service
			var pool = smtpPool({
				service: settings.general.mailer.service,
				auth: settings.general.mailer.auth
			});

			// Create a transport
			transporter = nodemailer.createTransport(pool);

			done();
		};
	},
	sendMail: function(msg) {

		return function(done) {

			transporter.sendMail(msg, done);
		};
	},
	sendMailFromService: function(to, subject, html) {

		return Mailer.sendMail({
			from: settings.general.mailer.sender.name + ' <' + settings.general.mailer.sender.address + '>',
			to: to,
			subject: subject,
			html: html
		});
	}
};


text:
<?php

namespace osc\admin\controller;
use osc\common\controller\AdminBase;
use think\Db;
class Brand extends AdminBase{

	protected function _initialize(){
		parent::_initialize();
		$this->assign('breadcrumb1','商品');
		$this->assign('breadcrumb2','品牌');
	}

    public function index(){

		$list = Db::name('brand')->paginate(config('page_num'));
		$this->assign('empty', '
~~暂无数据
');
		$this->assign('list', $list);

		return $this->fetch();

	 }
	 public	function add(){
		if(request()->isPost()){
			return $this->single_table_insert('Brand','添加了品牌');
		}
		$this->assign('crumbs', '新增');
		$this->assign('action', url('Brand/add'));
		return $this->fetch('edit');
	}
	 public	function edit(){
		if(request()->isPost()){
			return $this->single_table_update('Brand','修改了品牌');
		}
		$this->assign('crumbs', '修改');
		$this->assign('action', url('Brand/edit'));
		$this->assign('d',Db::name('Brand')->find((int)input('id')));
		return $this->fetch('edit');
	}
	public	function del(){
		if(request()->isGet()){
			$r= $this->single_table_delete('Brand','删除了品牌');
			if($r){
				$this->redirect('Brand/index');
			}
		}
	}

	public function autocomplete(){

		$filter_name=input('filter_name');

		if (isset($filter_name)) {
			$sql='SELECT * FROM '.config('database.prefix')."brand where name LIKE'%".$filter_name."%' LIMIT 0,20";
		}else{
			$sql='SELECT * FROM '.config('database.prefix')."brand  LIMIT 0,20";
		}

		$results = Db::query($sql);
		$json=[];
		foreach ($results as $result) {
				$json[] = array(
					'name'            => strip_tags(html_entity_decode($result['name'], ENT_QUOTES, 'UTF-8')),
					'brand_id' => $result['brand_id']
				);
			}

		return 	$json;
	}
}
?>


text:
using System;
using System.ComponentModel;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Linq;
using STEP;

namespace IFC
{
	/// <summary>
	/// <see href="http://www.buildingsmart-tech.org/ifc/IFC4/final/html/link/ifcmaterialdefinition.htm"/>
	/// </summary>
	public abstract partial class IfcMaterialDefinition : BaseIfc
	{
		public List<IfcRelAssociatesMaterial> AssociatedTo{get;set;} // inverse
		public List<IfcExternalReferenceRelationship> HasExternalReferences{get;set;} // inverse
		public List<IfcMaterialProperties> HasProperties{get;set;} // inverse

		/// <summary>
		/// Construct a IfcMaterialDefinition with all required attributes.
		/// </summary>
		[JsonConstructor]
		public IfcMaterialDefinition():base()
		{
			AssociatedTo = new List<IfcRelAssociatesMaterial>();
			HasExternalReferences = new List<IfcExternalReferenceRelationship>();
			HasProperties = new List<IfcMaterialProperties>();

		}
		public static  IfcMaterialDefinition FromJSON(string json){ return JsonConvert.DeserializeObject<IfcMaterialDefinition>(json); }

	}
}


text:
namespace gcm {

namespace android {

static base::android::RegistrationMethod kGCMDriverRegisteredMethods[] = {
    {"GCMDriver", gcm::GCMDriverAndroid::RegisterBindings},
};

bool RegisterGCMDriverJni(JNIEnv* env) {
  return base::android::RegisterNativeMethods(
      env,
      kGCMDriverRegisteredMethods,
      arraysize(kGCMDriverRegisteredMethods));
}

}  // namespace android

}  // namespace gcm


text:
<?php

namespace Grav\Plugin\Shortcodes;

use Thunder\Shortcode\Shortcode\ShortcodeInterface;

/**
 * Class ButtonShortcode handles a bootstrap button component
 *
 * @author Giansimon Diblas
 */
class GravstrapButtonShortcode extends GravstrapShortcode
{
    /**
     * {@inheritdoc}
     */
    protected function shortcodeName()
    {
        return 'gravstrap-button';
    }

    /**
     * {@inheritdoc}
     */
    protected function template()
    {
        return 'basic/button.html.twig';
    }

    /**
     * {@inheritdoc}
     */
    protected function aliases()
    {
        return array(
            'g-button',
        );
    }

    /**
     * {@inheritdoc}
     */
    protected function renderOutput(ShortcodeInterface $shortcode)
    {
        return $this->twig->processTemplate($this->template(), [
            'name' => $shortcode->getParameter('name'),
            'button_label' => $shortcode->getParameter('button_label'),
            'button_type' => $shortcode->getParameter('button_type'),
            'button_attributes' => $shortcode->getParameter('button_attributes'),
            'button_url' => $shortcode->getParameter('button_url'),
        ]);
    }
}