text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

namespace core_calendar\external;

defined('MOODLE_INTERNAL') || die();

use context;
use \core_calendar\local\event\entities\event_interface;
use stdClass;

/**
 * Class to providing the related objects when exporting a list of calendar events.
 *
 * This class is only meant for use with exporters. It attempts to bulk load
 * the related objects for a list of events and cache them to avoid having
 * to query the database when exporting each individual event.
 *
 * @package   core_calendar
 * @copyright 2017 Ryan Wyllie <ryan@moodle.com>
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class events_related_objects_cache {

    /**
     * @var array $events The events for which we need related objects.
     */
    protected $events;

    /**
     * @var array $courses The related courses.
     */
    protected $courses = null;

    /**
     * @var array $events The related groups.
     */
    protected $groups = null;

    /**
     * @var array $events The related course modules.
     */
    protected $coursemodules = [];

    /**
     * Constructor.
     *
     * @param array $events Array of event_interface events
     * @param array $courses Array of courses to populate the cache with
     */
    public function __construct(array $events, array $courses = null) {
        $this->events = $events;

        if (!is_null($courses)) {
            $this->courses = [];

            foreach ($courses as $course) {
                $this->courses[$course->id] = $course;
            }
        }
    }

    /**
     * Get the related course object for a given event.
     *
     * @param event_interface $event The event object.
     * @return stdClass|null
     */
    public function get_course(event_interface $event) {
        if (is_null($this->courses)) {
            $this->load_courses();
        }

        if ($course = $event->get_course()) {
            $courseid = $course->get('id');
            return isset($this->courses[$courseid]) ? $this->courses[$courseid] : null;
        } else {
            return null;
        }
    }

    /**
     * Get the related context for a given event.
     *
     * @param event_interface $event The event object.
     * @return context|null
     */
    public function get_context(event_interface $event) {
        global $USER;

        $courseid = $event->get_course() ? $event->get_course()->get('id') : null;
        $groupid = $event->get_group() ? $event->get_group()->get('id') : null;
        $userid = $event->get_user() ? $event->get_user()->get('id') : null;
        $moduleid = $event->get_course_module() ? $event->get_course_module()->get('id') : null;

        if (!empty($courseid)) {
            return \context_course::instance($event->get_course()->get('id'));
        } else if (!empty($groupid)) {
            $group = $this->get_group($event);
            return \context_course::instance($group->courseid);
        } else if (!empty($userid) && $userid == $USER->id) {
            return \context_user::instance($userid);
        } else if (!empty($userid) && $userid != $USER->id && $moduleid && $moduleid > 0) {
            $cm = $this->get_course_module($event);
            return \context_course::instance($cm->course);
        } else {
            return \context_user::instance($userid);
        }
    }

    /**
     * Get the related group object for a given event.
     *
     * @param event_interface $event The event object.
     * @return stdClass|null
     */
    public function get_group(event_interface $event) {
        if (is_null($this->groups)) {
            $this->load_groups();
        }

        if ($group = $event->get_group()) {
            $groupid = $group->get('id');
            return isset($this->groups[$groupid]) ? $this->groups[$groupid] : null;
        } else {
            return null;
        }
    }

    /**
     * Get the related course module for a given event.
     *
     * @param event_interface $event The event object.
     * @return stdClass|null
     */
    public function get_course_module(event_interface $event) {
        if (!$event->get_course_module()) {
            return null;
        }

        $id = $event->get_course_module()->get('id');
        $name = $event->get_course_module()->get('modname');
        $key = $name . '_' . $id;

        if (!isset($this->coursemodules[$key])) {
            $this->coursemodules[$key] = get_coursemodule_from_instance($name, $id, 0, false, MUST_EXIST);
        }

        return $this->coursemodules[$key];
    }

    /**
     * Load the list of all of the distinct courses required for the
     * list of provided events and save the result in memory.
     */
    protected function load_courses() {
        global $DB;

        $courseids = [];
        foreach ($this->events as $event) {
            if ($course = $event->get_course()) {
                $id = $course->get('id');
                $courseids[$id] = true;
            }
        }

        if (empty($courseids)) {
            $this->courses = [];
            return;
        }

        list($idsql, $params) = $DB->get_in_or_equal(array_keys($courseids));
        $sql = "SELECT * FROM {course} WHERE id {$idsql}";

        $this->courses = $DB->get_records_sql($sql, $params);
    }

    /**
     * Load the list of all of the distinct groups required for the
     * list of provided events and save the result in memory.
     */
    protected function load_groups() {
        global $DB;

        $groupids = [];
        foreach ($this->events as $event) {
            if ($group = $event->get_group()) {
                $id = $group->get('id');
                $groupids[$id] = true;
            }
        }

        if (empty($groupids)) {
            $this->groups = [];
            return;
        }

        list($idsql, $params) = $DB->get_in_or_equal(array_keys($groupids));
        $sql = "SELECT * FROM {groups} WHERE id {$idsql}";

        $this->groups = $DB->get_records_sql($sql, $params);
    }
}


text:
// ==========================================================================
// Project:   SproutCore - JavaScript Application Framework
// Copyright: ©2006-2011 Strobe Inc. and contributors.
//            portions copyright @2011 Apple Inc.
// License:   Licensed under MIT license (see license.js)
// ==========================================================================

/*global module test htmlbody ok equals same stop start target */

window.target = null;

module("SC.PickerPane Methods", {
  setup: function(){
    window.target = SC.Object.create({
      fooInvoked: NO,
      sender: null,
      foo: function(sender) {
        this.set('sender', sender);
        this.set('fooInvoked', YES);
        sender.remove();
      }
    });
  },

  teardown: function(){
    window.target = null;
  }
});

var anchor = SC.ControlTestPane.design()
  .add("anchor", SC.ButtonView, {
     title: "Anchor Button"
  });

anchor.show(); // add a test to show the test pane

var pane;

test("check default action on pane#mouseDown", function() {
  pane = SC.PickerPane.create({
    layout: { width: 300, height: 200 },
    contentView: SC.View.extend({
      layout: { top: 0, left: 0, bottom: 0, right: 0 }
    })
  });
  pane.popup(anchor.view('anchor'), SC.PICKER);

  ok(pane.get('isVisibleInWindow'), 'pane.isVisibleInWindow should be YES');

  pane.mouseDown({ pageX: 0, pageY: 0 });

  ok(!pane.get('isVisibleInWindow'), 'pane.isVisibleInWindow should be NO after mouseDown');
}) ;

test("check action on pane#mouseDown with removeAction set", function() {
  pane = SC.PickerPane.create({

    layout: { width: 300, height: 200 },
    contentView: SC.View.extend({
      layout: { top: 0, left: 0, bottom: 0, right: 0 }
    }),
    removeAction: 'foo',
    fooInvoked: NO,
    foo: function() {
      this.set('fooInvoked', YES);
      this.remove();
    }
  });
  pane.popup(anchor.view('anchor'), SC.PICKER);

  ok(pane.get('isVisibleInWindow'), 'pane.isVisibleInWindow should be YES');

  pane.mouseDown({ pageX: 0, pageY: 0 });

  ok(!pane.get('isVisibleInWindow'), 'pane.isVisibleInWindow should be NO after mouseDown');
  ok(pane.get('fooInvoked'), 'pane.fooInvoked should be YES after mouseDown');
}) ;

test("check action on pane#mouseDown with removeAction and removeTarget set", function() {
  pane = SC.PickerPane.create({

    layout: { width: 300, height: 200 },
    contentView: SC.View.extend({
      layout: { top: 0, left: 0, bottom: 0, right: 0 }
    }),
    removeAction: 'foo',
    removeTarget: target
  });
  pane.popup(anchor.view('anchor'), SC.PICKER);

  ok(pane.get('isVisibleInWindow'), 'pane.isVisibleInWindow should be YES');

  pane.mouseDown({ pageX: 0, pageY: 0 });

  ok(!pane.get('isVisibleInWindow'), 'pane.isVisibleInWindow should be NO after mouseDown');
  ok(target.get('fooInvoked'), 'target.fooInvoked should be YES');
  ok(target.get('sender'), pane, 'target.sender should be pane');
}) ;

redpajama_set_name: RedPajamaGithub


text:
class WikiCrawler
  IMAGE_PAGE = 6
  CATEGORY_PAGE = 14
  IMAGE_EXTENSIONS = ["jpg","gif","png","jpeg"]

  def initialize(conn,builder,verbose = false)
    @page_ids = {}
    @cat_stack = []
    @page_search = conn.prepare("SELECT page_namespace,page_title from page where page_id = ?")
    @category_search = conn.prepare('SELECT cl_from,cl_to,cl_sortkey,cl_timestamp from categorylinks where cl_to = ?')
    @builder = builder
    @verbose = verbose
  end

  def drill_page(page_id)
    res = @page_search.execute(page_id)
    row = res.fetch
    if row
      page_namespace = row[0].to_i
      page_title = row[1]
      res.free_result();
      case page_namespace
      when IMAGE_PAGE
        if @page_ids[page_id].nil? and page_title =~ /\.(jpg)|(png)|(gif)|(jpeg)$/
          puts "Found image page #{page_id} : #{page_title}" if @verbose
          begin
            image = Image.new(page_id,page_title)
            image.to_xml_snippet
          rescue
            puts $!
          end
        @page_ids[page_id] = true
        end
      when CATEGORY_PAGE
        puts "Found category page #{page_id} : #{page_title}" if @verbose
        drill_category(page_title) do |id|
          if @cat_stack.include?(id)
            puts "Aborting out of page loop"
            return
          end
          @cat_stack.push(id)
          drill_page(id)
          @cat_stack.pop
        end
      else
        #puts "Unknown Namespace for #{page_title}"
      end
    else
      #puts "Unknown Page ID: #{page_id}"
    end
  end

  def drill_category(category_name,&block)
    res = @category_search.execute(category_name)
    puts "Drilling into #{category_name} : Found #{res.num_rows}" if @verbose
    ids_to_check = []
    res.each do |row|
      page_id = row[0].to_i
      ids_to_check << page_id
    end
    res.free_result();
    if block
      ids_to_check.each do |page_id|
        yield page_id
      end
    else
      return ids_to_check
    end
  end
end


text:
import vorlonServer = require("./Scripts/vorlon.server");
import vorlonDashboard = require("./Scripts/vorlon.dashboard");
import vorlonWebserver = require("./Scripts/vorlon.webServer");

//WEBSERVER
var webServer = new vorlonWebserver.VORLON.WebServer();

//DASHBOARD
var dashboard = new vorlonDashboard.VORLON.Dashboard();

//VORLON SERVER
var server = new vorlonServer.VORLON.Server();

webServer.components.push(dashboard);
webServer.components.push(server);
webServer.start();


text:
package com.intellij.codeInspection.visibility;

import com.intellij.codeInsight.daemon.GroupNames;
import com.intellij.codeInsight.daemon.impl.UnusedSymbolUtil;
import com.intellij.codeInspection.BaseJavaBatchLocalInspectionTool;
import com.intellij.codeInspection.InspectionProfile;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.codeInspection.deadCode.UnusedDeclarationInspectionBase;
import com.intellij.openapi.progress.EmptyProgressIndicator;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.profile.codeInspection.InspectionProjectProfileManager;
import com.intellij.psi.*;
import com.intellij.psi.search.searches.FunctionalExpressionSearch;
import com.intellij.psi.util.ClassUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.VisibilityUtil;
import com.intellij.util.containers.ContainerUtil;
import com.siyeh.ig.fixes.ChangeModifierFix;
import com.siyeh.ig.psiutils.MethodUtils;
import gnu.trove.TObjectIntHashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

class AccessCanBeTightenedInspection extends BaseJavaBatchLocalInspectionTool {
  private final VisibilityInspection myVisibilityInspection;

  AccessCanBeTightenedInspection(@NotNull VisibilityInspection visibilityInspection) {
    myVisibilityInspection = visibilityInspection;
  }

  @Override
  public boolean isEnabledByDefault() {
    return true;
  }

  @Override
  @NotNull
  public String getGroupDisplayName() {
    return GroupNames.VISIBILITY_GROUP_NAME;
  }

  @Override
  @NotNull
  public String getDisplayName() {
    return "Member access can be tightened";
  }

  @Override
  @NotNull
  public String getShortName() {
    return VisibilityInspection.SHORT_NAME;
  }

  @NotNull
  @Override
  public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, final boolean isOnTheFly) {
    return new MyVisitor(holder);
  }

  private class MyVisitor extends JavaElementVisitor {
    private final ProblemsHolder myHolder;
    private final UnusedDeclarationInspectionBase myDeadCodeInspection;

    public MyVisitor(@NotNull ProblemsHolder holder) {
      myHolder = holder;
      InspectionProfile profile = InspectionProjectProfileManager.getInstance(holder.getProject()).getCurrentProfile();
      UnusedDeclarationInspectionBase tool = (UnusedDeclarationInspectionBase)profile.getUnwrappedTool(UnusedDeclarationInspectionBase.SHORT_NAME, holder.getFile());
      myDeadCodeInspection = tool == null ? new UnusedDeclarationInspectionBase() : tool;
    }
    private final TObjectIntHashMap<PsiClass> maxSuggestedLevelForChildMembers = new TObjectIntHashMap<>();

    @Override
    public void visitClass(PsiClass aClass) {
      checkMember(aClass);
    }

    @Override
    public void visitMethod(PsiMethod method) {
      checkMember(method);
    }

    @Override
    public void visitField(PsiField field) {
      checkMember(field);
    }

    private void checkMember(@NotNull final PsiMember member) {
      final PsiClass memberClass = member.getContainingClass();
      PsiModifierList memberModifierList = member.getModifierList();
      if (memberModifierList == null) return;
      int currentLevel = PsiUtil.getAccessLevel(memberModifierList);
      int suggestedLevel = suggestLevel(member, memberClass, currentLevel);
      if (memberClass != null) {
        synchronized (maxSuggestedLevelForChildMembers) {
          int prevMax = maxSuggestedLevelForChildMembers.get(memberClass);
          maxSuggestedLevelForChildMembers.put(memberClass, Math.max(prevMax, suggestedLevel));
        }
      }

      log(member.getName() + ": effective level is '" + PsiUtil.getAccessModifier(suggestedLevel) + "'");

      if (suggestedLevel < currentLevel) {
        if (member instanceof PsiClass) {
          int memberMaxLevel;
          synchronized (maxSuggestedLevelForChildMembers) {
            memberMaxLevel = maxSuggestedLevelForChildMembers.get((PsiClass)member);
          }
          if (memberMaxLevel > suggestedLevel) {
            // a class can't have visibility less than its members
            return;
          }
        }
        PsiElement toHighlight = currentLevel == PsiUtil.ACCESS_LEVEL_PACKAGE_LOCAL ? ((PsiNameIdentifierOwner)member).getNameIdentifier() : ContainerUtil.find(
          memberModifierList.getChildren(),
          element -> element instanceof PsiKeyword && element.getText().equals(PsiUtil.getAccessModifier(currentLevel)));
        assert toHighlight != null : member +" ; " + ((PsiNameIdentifierOwner)member).getNameIdentifier() + "; "+ memberModifierList.getText();
        String suggestedModifier = PsiUtil.getAccessModifier(suggestedLevel);
        myHolder.registerProblem(toHighlight, "Access can be " + VisibilityUtil.toPresentableText(suggestedModifier), new ChangeModifierFix(suggestedModifier));
      }
    }

    @PsiUtil.AccessLevel
    private int suggestLevel(@NotNull PsiMember member, PsiClass memberClass, @PsiUtil.AccessLevel int currentLevel) {
      if (member.hasModifierProperty(PsiModifier.PRIVATE) || member.hasModifierProperty(PsiModifier.NATIVE)) return currentLevel;
      if (member instanceof PsiMethod && member instanceof SyntheticElement || !member.isPhysical()) return currentLevel;

      if (member instanceof PsiMethod) {
        PsiMethod method = (PsiMethod)member;
        if (!method.getHierarchicalMethodSignature().getSuperSignatures().isEmpty()) {
          log(member.getName() + " overrides");
          return currentLevel; // overrides
        }
        if (MethodUtils.isOverridden(method)) {
          log(member.getName() + " overridden");
          return currentLevel;
        }
      }
      if (member instanceof PsiEnumConstant) return currentLevel;
      if (member instanceof PsiClass && (member instanceof PsiAnonymousClass ||
                                         member instanceof PsiTypeParameter ||
                                         member instanceof PsiSyntheticClass ||
                                         PsiUtil.isLocalClass((PsiClass)member))) {
        return currentLevel;
      }
      if (memberClass != null && (memberClass.isInterface() || memberClass.isEnum() || memberClass.isAnnotationType() || PsiUtil.isLocalClass(memberClass) && member instanceof PsiClass)) {
        return currentLevel;
      }
      final PsiFile memberFile = member.getContainingFile();
      Project project = memberFile.getProject();

      if (myDeadCodeInspection.isEntryPoint(member)) {
        log(member.getName() +" is entry point");
        return currentLevel;
      }

      PsiDirectory memberDirectory = memberFile.getContainingDirectory();
      final PsiPackage memberPackage = memberDirectory == null ? null : JavaDirectoryService.getInstance().getPackage(memberDirectory);
      log(member.getName()+ ": checking effective level for "+member);

      AtomicInteger maxLevel = new AtomicInteger(PsiUtil.ACCESS_LEVEL_PRIVATE);
      AtomicBoolean foundUsage = new AtomicBoolean();
      boolean proceed = UnusedSymbolUtil.processUsages(project, memberFile, member, new EmptyProgressIndicator(), null, info -> {
        PsiElement element = info.getElement();
        if (element == null) return true;
        PsiFile psiFile = info.getFile();
        if (psiFile == null) return true;

        return handleUsage(member, memberClass, memberFile, maxLevel, memberPackage, element, psiFile, foundUsage);
      });

      if (proceed && member instanceof PsiClass && LambdaUtil.isFunctionalClass((PsiClass)member)) {
        // there can be lambda implementing this interface implicitly
        FunctionalExpressionSearch.search((PsiClass)member).forEach(functionalExpression -> {
          PsiFile psiFile = functionalExpression.getContainingFile();
          return handleUsage(member, memberClass, memberFile, maxLevel, memberPackage, functionalExpression, psiFile, foundUsage);
        });
      }
      if (!foundUsage.get()) {
        log(member.getName() + " unused; ignore");
        return currentLevel; // do not propose private for unused method
      }

      @PsiUtil.AccessLevel
      int suggestedLevel = maxLevel.get();
      if (suggestedLevel == PsiUtil.ACCESS_LEVEL_PRIVATE && memberClass == null) {
        suggestedLevel = suggestPackageLocal(member);
      }

      String suggestedModifier = PsiUtil.getAccessModifier(suggestedLevel);
      log(member.getName() + ": effective level is '" + suggestedModifier + "'");

      return suggestedLevel;
    }

    private boolean handleUsage(@NotNull PsiMember member,
                                @Nullable PsiClass memberClass,
                                @NotNull PsiFile memberFile,
                                @NotNull AtomicInteger maxLevel,
                                @Nullable PsiPackage memberPackage,
                                @NotNull PsiElement element,
                                @NotNull PsiFile psiFile,
                                @NotNull AtomicBoolean foundUsage) {
      foundUsage.set(true);
      if (!(psiFile instanceof PsiJavaFile)) {
        log("     refd from " + psiFile.getName() + "; set to public");
        maxLevel.set(PsiUtil.ACCESS_LEVEL_PUBLIC);
        return false; // referenced from XML, has to be public
      }
      @PsiUtil.AccessLevel
      int level = getEffectiveLevel(element, psiFile, member, memberFile, memberClass, memberPackage);
      log("    ref in file " + psiFile.getName() + "; level = " + PsiUtil.getAccessModifier(level) + "; (" + element + ")");
      maxLevel.getAndAccumulate(level, Math::max);

      return level != PsiUtil.ACCESS_LEVEL_PUBLIC;
    }

    @PsiUtil.AccessLevel
    private int getEffectiveLevel(@NotNull PsiElement element,
                                  @NotNull PsiFile file,
                                  @NotNull PsiMember member,
                                  @NotNull PsiFile memberFile,
                                  PsiClass memberClass,
                                  PsiPackage memberPackage) {
      PsiClass innerClass = PsiTreeUtil.getParentOfType(element, PsiClass.class);
      boolean isAbstractMember = member.hasModifierProperty(PsiModifier.ABSTRACT);
      if (memberClass != null && PsiTreeUtil.isAncestor(innerClass, memberClass, false) ||
          innerClass != null && PsiTreeUtil.isAncestor(memberClass, innerClass, false) && !innerClass.hasModifierProperty(PsiModifier.STATIC)) {
        // access from the same file can be via private
        // except when used in annotation:
        // @Ann(value = C.VAL) class C { public static final String VAL = "xx"; }
        // or in implements/extends clauses
        if (isInReferenceList(innerClass.getModifierList(), member) ||
            isInReferenceList(innerClass.getImplementsList(), member) ||
            isInReferenceList(innerClass.getExtendsList(), member)) {
          return suggestPackageLocal(member);
        }

        return !isAbstractMember && (myVisibilityInspection.SUGGEST_PRIVATE_FOR_INNERS ||
               !isInnerClass(memberClass)) ? PsiUtil.ACCESS_LEVEL_PRIVATE : suggestPackageLocal(member);
      }
      //if (file == memberFile) {
      //  return PsiUtil.ACCESS_LEVEL_PACKAGE_LOCAL;
      //}
      PsiDirectory directory = file.getContainingDirectory();
      PsiPackage aPackage = directory == null ? null : JavaDirectoryService.getInstance().getPackage(directory);
      if (aPackage == memberPackage || aPackage != null && memberPackage != null && Comparing.strEqual(aPackage.getQualifiedName(), memberPackage.getQualifiedName())) {
        return suggestPackageLocal(member);
      }
      if (innerClass != null && memberClass != null && innerClass.isInheritor(memberClass, true)) {
        //access from subclass can be via protected, except for constructors
        PsiElement resolved = element instanceof PsiReference ? ((PsiReference)element).resolve() : null;
        boolean isConstructor = resolved instanceof PsiClass && element.getParent() instanceof PsiNewExpression
                                || resolved instanceof PsiMethod && ((PsiMethod)resolved).isConstructor();
        if (!isConstructor) {
          return PsiUtil.ACCESS_LEVEL_PROTECTED;
        }
      }
      return PsiUtil.ACCESS_LEVEL_PUBLIC;
    }
  }

  private static boolean isInnerClass(@NotNull PsiClass memberClass) {
    return memberClass.getContainingClass() != null || memberClass instanceof PsiAnonymousClass;
  }

  private static boolean isInReferenceList(@Nullable PsiElement list, @NotNull final PsiMember member) {
    if (list == null) return false;
    final PsiManager psiManager = member.getManager();
    final boolean[] result = new boolean[1];
    list.accept(new JavaRecursiveElementWalkingVisitor() {
      @Override
      public void visitReferenceElement(PsiJavaCodeReferenceElement reference) {
        super.visitReferenceElement(reference);
        if (psiManager.areElementsEquivalent(reference.resolve(), member)) {
          result[0] = true;
          stopWalking();
        }
      }
    });
    return result[0];
  }

  @PsiUtil.AccessLevel
  private int suggestPackageLocal(@NotNull PsiMember member) {
    boolean suggestPackageLocal = member instanceof PsiClass && ClassUtil.isTopLevelClass((PsiClass)member)
                ? myVisibilityInspection.SUGGEST_PACKAGE_LOCAL_FOR_TOP_CLASSES
                : myVisibilityInspection.SUGGEST_PACKAGE_LOCAL_FOR_MEMBERS;
    return suggestPackageLocal ? PsiUtil.ACCESS_LEVEL_PACKAGE_LOCAL : PsiUtil.ACCESS_LEVEL_PUBLIC;
  }

  private static void log(String s) {
    //System.out.println(s);
  }
}


text:
package com.linkedin.pinot.core.data.manager.realtime;

import java.util.Timer;

public class TimerService {
  public static final Timer timer = new Timer("RealtimeIndexingSegmentDataManager", true);
}


text:
from django.contrib.auth.models import User
from mongoreversion.models import Revision, ReversionedDocument, ContentType
from mongotesting import MongoTestCase
from mongoengine.document import Document
from mongoengine.fields import DictField, StringField, ReferenceField, IntField, DateTimeField, ListField
from django.template.defaultfilters import slugify

class MongoUser(Document):
    username = StringField(max_length=255)
    email = StringField(max_length=255)

def create_and_save_sample_user(suffix=''):
    username = 'user%s' % (suffix, )
    email = '%s@example.com' % (username, )
    return User.objects.create(username=username, email=email)

def create_and_save_sample_mongo_user(suffix=''):
    username = 'user%s' % (suffix, )
    email = '%s@example.com' % (username, )
    return MongoUser.objects.create(username=username, email=email)

class SampleTag(Document):
    slug = StringField(max_length=100)
    title = StringField(max_length=100)

    meta = {
        'versioned': True,
        'versioned_fields': ['title', 'slug', ],
        'versioned_related': [],
    }

class SampleDocument(Document):
    slug = StringField(max_length=100)
    title = StringField(max_length=100)
    tag_strings = ListField(StringField())
    tag_models = ListField(ReferenceField(SampleTag, dbref=False))

    meta = {
        'versioned': True,
        'versioned_fields': ['title', 'slug', ],
        'versioned_related': ['tag_models', ],
    }

class SampleReversionedDocument(ReversionedDocument):
    slug = StringField(max_length=100)
    title = StringField(max_length=100)
    tag_strings = ListField(StringField())
    tag_models = ListField(ReferenceField(SampleTag, dbref=False))

    meta = {
        'versioned': True,
        'versioned_fields': ['title', 'slug', ],
        'versioned_related': ['tag_models', ],
    }

def create_sample_revisioned_document():
    tag_models = []
    for i in range(3):
        title = 'Sample Tag %s' % (i, )
        tag = SampleTag(slug=slugify(title), title=title)
        tag_models.append(tag)
    doc = SampleDocument(slug='sample-doc-slug', title='Sample Document Title', tag_strings=['one', 'two', 'three', ], tag_models=tag_models)
    return doc

def create_sample_reversioned_document():
    tag_models = []
    for i in range(3):
        title = 'Sample Tag %s' % (i, )
        tag = SampleTag(slug=slugify(title), title=title)
        tag_models.append(tag)
    doc = SampleReversionedDocument(slug='sample-doc-slug', title='Sample Document Title', tag_strings=['one', 'two', 'three', ], tag_models=tag_models)
    return doc

def create_sample_reversioned_document(create_revision_after_save=False):
    tag_models = []
    for i in range(3):
        title = 'Sample Tag %s' % (i, )
        tag = SampleTag(slug=slugify(title), title=title)
        tag_models.append(tag)
    doc = SampleReversionedDocument(slug='sample-doc-slug', title='Sample Document Title', tag_strings=['one', 'two', 'three', ], tag_models=tag_models)
    doc._meta['create_revision_after_save'] = create_revision_after_save
    return doc

def save_revision_and_check(test, user, doc, comment=None, is_diff=True, instance_save_revision=False):
    revision, is_new = doc.save_revision(user, comment) if instance_save_revision else Revision.save_revision(user, doc, comment)
    test.assertEqual(is_new, is_diff)
    test.assertTrue(revision)
    test.assertTrue(revision.pk)
    test.assertTrue(revision.timestamp)
    test.assertTrue(revision.instance_type)
    test.assertEqual(revision.instance_type.class_name, doc._class_name)
    test.assertTrue(revision.instance_data)
    for key, value in revision.instance_data.items():
        if key in revision.related_field_types:
            field_model = revision.related_field_types.get(key)
            value = [field_model.objects.get(pk=v) for v in value]
        test.assertEqual(value, getattr(doc, key, None))
    return revision

class RevisionModelTest(MongoTestCase):

    def test_create_revision_initial(self):
        """
            Test creating a document initial revision
        """
        user = create_and_save_sample_user()
        doc = create_sample_revisioned_document()
        for tag in doc.tag_models:
            save_revision_and_check(self, user, tag)
        save_revision_and_check(self, user, doc, 'sample comment...')

    def test_create_revision_initial_with_mongouser(self):
        """
            Test creating a document initial revision with a mongo user as author
        """
        user = create_and_save_sample_mongo_user()
        doc = create_sample_revisioned_document()
        for tag in doc.tag_models:
            save_revision_and_check(self, user, tag)
        save_revision_and_check(self, user, doc, 'sample comment...')

    def test_create_reversioned_document_initial(self):
        """
            Test creating a document initial revision
        """
        user = create_and_save_sample_user()
        doc = create_sample_reversioned_document()
        for tag in doc.tag_models:
            save_revision_and_check(self, user, tag)
        save_revision_and_check(self, user, doc, 'sample comment...')

    def test_create_reversioned_document_initial_with_mongouser(self):
        """
            Test creating a document initial revision with a mongo user as author
        """
        user = create_and_save_sample_mongo_user()
        doc = create_sample_reversioned_document()
        for tag in doc.tag_models:
            save_revision_and_check(self, user, tag)
        save_revision_and_check(self, user, doc, 'sample comment...')

    def test_create_revision_with_no_diff(self):
        """
            Test creating a revision with a document that has no changes from
            the previous revision.
        """
        user = create_and_save_sample_user()
        doc = create_sample_revisioned_document()
        for tag in doc.tag_models:
            save_revision_and_check(self, user, tag)
        save_revision_and_check(self, user, doc, 'sample comment...')
        save_revision_and_check(self, user, doc, 'sample comment...', is_diff=False)

    def test_create_revision_with_diff(self):
        """
            Test creating a revision with a document that has no changes from
            the previous revision.
        """
        user = create_and_save_sample_user()
        doc = create_sample_revisioned_document()
        for tag in doc.tag_models:
            save_revision_and_check(self, user, tag)
        save_revision_and_check(self, user, doc, 'sample comment...')
        doc.title = 'New Sample Title'
        save_revision_and_check(self, user, doc, 'another sample comment...')

    def test_create_mongouser_revision_with_diff(self):
        """
            Test creating a revision with a document that has no changes from
            the previous revision.
        """
        user = create_and_save_sample_mongo_user()
        doc = create_sample_revisioned_document()
        for tag in doc.tag_models:
            save_revision_and_check(self, user, tag)
        save_revision_and_check(self, user, doc, 'sample comment...')
        doc.title = 'New Sample Title'
        save_revision_and_check(self, user, doc, 'another sample comment...')

    def test_create_mongouser_revision_with_diff(self):
        """
            Test creating a revision with a document that has no changes from
            the previous revision.
        """
        user = create_and_save_sample_mongo_user()
        doc = create_sample_revisioned_document()
        for tag in doc.tag_models:
            save_revision_and_check(self, user, tag)
        save_revision_and_check(self, user, doc, 'sample comment...')
        doc.title = 'New Sample Title'
        save_revision_and_check(self, user, doc, 'another sample comment...')

    def test_revert_revision(self):
        """
            Test reverting a document back to a specific revision.
        """
        user = create_and_save_sample_user()
        doc = create_sample_revisioned_document()
        for tag in doc.tag_models:
            save_revision_and_check(self, user, tag)
        rev1 = save_revision_and_check(self, user, doc, 'sample comment...')
        doc1_id = doc.pk
        doc.title = 'New Sample Title'
        rev2 = save_revision_and_check(self, user, doc, 'another sample comment...')
        doc1 = rev1.revert()
        doc1 = SampleDocument.objects.get(pk=doc1_id)
        self.assertNotEqual(doc1.title, rev2.instance.title)
        self.assertEqual(doc1.title, rev1.instance.title)

    def test_revert_mongouser_revision(self):
        """
            Test reverting a document back to a specific revision.
        """
        user = create_and_save_sample_mongo_user()
        doc = create_sample_revisioned_document()
        for tag in doc.tag_models:
            save_revision_and_check(self, user, tag)
        rev1 = save_revision_and_check(self, user, doc, 'sample comment...')
        doc1_id = doc.pk
        doc.title = 'New Sample Title'
        rev2 = save_revision_and_check(self, user, doc, 'another sample comment...')
        doc1 = rev1.revert()
        doc1 = SampleDocument.objects.get(pk=doc1_id)
        self.assertNotEqual(doc1.title, rev2.instance.title)
        self.assertEqual(doc1.title, rev1.instance.title)

class ReversionedDocumentTest(MongoTestCase):

    def test_is_versioned(self):
        doc = create_sample_reversioned_document()
        doc._meta['versioned'] = True
        self.assertEqual(True, doc.is_versioned)
        doc._meta['versioned'] = False
        self.assertEqual(False, doc.is_versioned)
        doc._meta['versioned'] = True

    def test_revisions(self):
        user = create_and_save_sample_user()
        doc = create_sample_reversioned_document()
        for tag in doc.tag_models:
            tag.save()
        doc.save()
        ContentType.objects.get_or_create(class_name=doc._class_name)

        self.assertEqual(0, doc.revisions.count())
        doc.slug = 'new-sample-slug'
        save_revision_and_check(self, user, doc, 'sample comment...')
        self.assertEqual(1, doc.revisions.count())

    def test_save_revision(self):
        user = create_and_save_sample_user()
        doc = create_sample_reversioned_document()
        for tag in doc.tag_models:
            tag.save()
        doc.save()
        ContentType.objects.get_or_create(class_name=doc._class_name)

        self.assertEqual(0, doc.revisions.count())
        doc.slug = 'new-sample-slug'
        save_revision_and_check(self, user, doc, 'sample comment...', instance_save_revision=True)
        self.assertEqual(1, doc.revisions.count())

    def test_create_revision_after_save(self):
        user = create_and_save_sample_user()
        doc = create_sample_reversioned_document(create_revision_after_save=True)
        for tag in doc.tag_models:
            tag.save()
        doc.save(user=user)

        self.assertEqual(1, doc.revisions.count())
        doc.slug = 'new-sample-slug'
        doc.save(user=user)
        self.assertEqual(2, doc.revisions.count())


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon"
          type="image/png"
          href="img/app-icon-3.png">

    <title>Cod3</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/sb-admin.css" rel="stylesheet">

    <link href="css/custom.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

    <link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">

                <input id="latitude" type="hidden" name="latitude" value="{{ latitude }}">
                <input id="longitude" type="hidden" name="longitude" value="{{ longitude }}">

                <input class="form-control" id="us5-street1" name="us5-street1" type="hidden">
                <input class="form-control" id="us5-city" name="us5-city" type="hidden">
                <input class="form-control" id="us5-state" name="us5-state" type="hidden">
                <input class="form-control" id="us5-zip" name="us5-zip" type="hidden">
                <input class="form-control" id="us5-country" name="us5-country" type="hidden">

                                        ??:??

                                        within
??:??

                                        within
??:??

                                    ??:??

                                    within
??:??

                                    within
??:??


text:
package org.apache.commons.math3.random;

/** This interface represents a random generator for whole vectors.
 *
 * @since 1.2
 * @version $Id: RandomVectorGenerator.java 1416643 2012-12-03 19:37:14Z tn $
 *
 */

public interface RandomVectorGenerator {

    /** Generate a random vector.
     * @return a random vector as an array of double.
     */
    double[] nextVector();

}


text:
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2018 Couchbase, Inc.
 *
 *   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.
 */

#include "engine_wrapper.h"
#include "executors.h"
#include "utilities.h"
#include <memcached/protocol_binary.h>

void dcp_seqno_acknowledged_executor(Cookie& cookie) {
    auto ret = cookie.swapAiostat(ENGINE_SUCCESS);

    if (ret == ENGINE_SUCCESS) {
        const auto& req = cookie.getRequest();
        auto extdata = req.getExtdata();
        using cb::mcbp::request::DcpSeqnoAcknowledgedPayload;
        const auto& extras =
                *reinterpret_cast<const DcpSeqnoAcknowledgedPayload*>(
                        extdata.data());
        ret = dcpSeqnoAcknowledged(cookie,
                                   req.getOpaque(),
                                   req.getVBucket(),
                                   extras.getPreparedSeqno());
    }

    if (ret != ENGINE_SUCCESS) {
        handle_executor_status(cookie, ret);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
using Pchp.Core;
using Pchp.Library.Streams;

namespace Peachpie.Library.XmlDom
{
    ///
    /// Represents an entire HTML or XML document; serves as the root of the document tree.
    ///
    [PhpType(PhpTypeAttribute.InheritName), PhpExtension("dom")]
    public class DOMDocument : DOMNode
    {
        #region Fields and Properties

        internal XmlDocument XmlDocument
        {
            get
            {
                return XmlNode as XmlDocument ?? XmlNode?.OwnerDocument;
            }
            set
            {
                XmlNode = value;
            }
        }

        private bool _formatOutput;
        private bool _validateOnParse;
        internal bool _isHtmlDocument;

        ///
        /// Returns "#document".
        ///
        public override string nodeName => "#document";

        ///
        /// Returns null.
        ///
        public override string nodeValue
        {
            get { return null; }
            set { }
        }

        ///
        /// Returns the type of the node (<see cref="NodeType.Document"/>).
        ///
        public override int nodeType => (int)NodeType.Document;

        ///
        /// Returns the node containing the DOCTYPE declaration.
        ///
        public DOMDocumentType doctype
        {
            get
            {
                var doc_type = XmlDocument.DocumentType;
                return (DOMDocumentType)DOMNode.Create(doc_type);
            }
        }

        ///
        /// Returns the DOM implementation.
        ///
        public DOMImplementation implementation => new DOMImplementation();

        ///
        /// Returns the root element of this document.
        ///
        public DOMElement documentElement
        {
            get
            {
                XmlElement root = XmlDocument.DocumentElement;
                return (DOMElement)Create(root);
            }
        }

        ///
        /// Returns the encoding of this document.
        ///
        public string actualEncoding => this.encoding;

        ///
        /// Returns the encoding of this document.
        ///
        public string xmlEncoding => this.encoding;

        ///
        /// Returns or set the encoding of this document.
        ///
        public string encoding
        {
            get
            {
                var decl = GetXmlDeclaration();
                return decl?.Encoding;
            }
            set
            {
                var decl = GetXmlDeclaration();
                if (decl != null)
                {
                    decl.Encoding = value;
                }
                else
                {
                    decl = XmlDocument.CreateXmlDeclaration("1.0", value, null);
                    XmlDocument.InsertBefore(decl, XmlDocument.FirstChild);
                }
            }
        }

        ///
        /// Returns or sets the standalone flag of this document.
        ///
        public bool xmlStandalone
        {
            get { return this.standalone; }
            set { this.standalone = value; }
        }

        ///
        /// Returns or sets the standalone flag of this document.
        ///
        public bool standalone
        {
            get
            {
                XmlDeclaration decl = GetXmlDeclaration();
                return (decl == null || (decl.Standalone != "no"));
            }
            set
            {
                string stand = (value ? "yes" : "no");

                var decl = GetXmlDeclaration();
                if (decl != null)
                {
                    decl.Standalone = stand;
                }
                else
                {
                    decl = XmlDocument.CreateXmlDeclaration("1.0", null, stand);
                    XmlDocument.InsertBefore(decl, XmlDocument.FirstChild);
                }
            }
        }

        ///
        /// Returns or sets the XML version of this document.
        ///
        public string xmlVersion
        {
            get { return this.version; }
            set { this.version = value; }
        }

        ///
        /// Returns or sets the XML version of this document.
        ///
        public string version
        {
            get
            {
                XmlDeclaration decl = GetXmlDeclaration();
                return (decl == null ? "1.0" : decl.Version);
            }
            set
            {
                XmlDeclaration decl = GetXmlDeclaration();
                if (decl != null)
                {
                    XmlDeclaration new_decl = XmlDocument.CreateXmlDeclaration(value, decl.Encoding, decl.Standalone);
                    XmlDocument.ReplaceChild(new_decl, decl);
                }
                else
                {
                    decl = XmlDocument.CreateXmlDeclaration(value, null, null);
                    XmlDocument.InsertBefore(decl, XmlDocument.FirstChild);
                }
            }
        }

        ///
        /// Returns true.
        ///
        public bool strictErrorChecking
        {
            get { return true; }
            set { }
        }

        ///
        /// Returns the base URI of this document.
        ///
        public string documentURI
        {
            get { return XmlDocument.BaseURI; }
            set { }
        }

        ///
        /// Returns null.
        ///
        public DOMConfiguration config => null;

        ///
        /// Returns or sets whether XML is formatted by <see cref="save(string,int)"/> and <see cref="saveXML(DOMNode)"/>.
        ///
        public bool formatOutput
        {
            get { return _formatOutput; }
            set { _formatOutput = value; }
        }

        ///
        /// Returns of sets whether XML is validated against schema by <see cref="load(DOMDocument,string,int)"/> and
        /// <see cref="loadXML(DOMDocument,string,int)"/>.
        ///
        public bool validateOnParse
        {
            get { return _validateOnParse; }
            set { _validateOnParse = value; }
        }

        ///
        /// Returns false.
        ///
        public bool resolveExternals
        {
            get { return false; }
            set { }
        }

        ///
        /// Returns or sets whether whitespace should be preserved by this XML document.
        ///
        public bool preserveWhiteSpace
        {
            get { return XmlDocument.PreserveWhitespace; }
            set { XmlDocument.PreserveWhitespace = value; }
        }

        ///
        /// Returns false.
        ///
        public bool recover
        {
            get { return false; }
            set { }
        }

        ///
        /// Returns false.
        ///
        public bool substituteEntities
        {
            get { return false; }
            set { }
        }

        #endregion

        #region Construction

        public DOMDocument(string version = null, string encoding = null)
        {
            this.XmlDocument = PhpXmlDocument.Create();

            __construct(version, encoding);
        }

        internal DOMDocument(XmlDocument xmlDocument)
        {
            this.XmlDocument = xmlDocument;
        }

        private protected override DOMNode CloneObjectInternal(bool deepCopyFields) => new DOMDocument(XmlDocument);

        public virtual void __construct(string version = null, string encoding = null)
        {
            // To prevent problems from subsequent calls
            if (XmlDocument.HasChildNodes)
            {
                return;
            }

            // append the corresponding XML declaration to the document
            XmlDocument.AppendChild(XmlDocument.CreateXmlDeclaration(version ?? "1.0", encoding, string.Empty));
        }

        #endregion

        #region Node factory

        ///
        /// Creates an element with the specified name and inner text.
        ///
        /// <param name="tagName">The qualified name of the element.</param>
        /// <param name="value">The inner text (value) of the element.</param>
        /// <returns>A new <see cref="DOMElement"/>.</returns>
        public virtual DOMElement createElement(string tagName, string value = null)
        {
            XmlElement element = XmlDocument.CreateElement(tagName);
            if (value != null) element.InnerText = value;
            return new DOMElement(element);
        }

        ///
        /// Creates a new document fragment.
        ///
        /// <returns>A new <see cref="DOMDocumentFragment"/>.</returns>
        public virtual DOMDocumentFragment createDocumentFragment()
        {
            XmlDocumentFragment fragment = XmlDocument.CreateDocumentFragment();
            return new DOMDocumentFragment(fragment);
        }

        ///
        /// Creates a new text node with the specified text.
        ///
        /// <param name="data">The text for the text node.</param>
        /// <returns>A new <see cref="DOMText"/>.</returns>
        public virtual DOMText createTextNode(string data)
        {
            XmlText text = XmlDocument.CreateTextNode(data);
            return new DOMText(text);
        }

        ///
        /// Creates a comment node containing the specified data.
        ///
        /// <param name="data">The comment data.</param>
        /// <returns>A new <see cref="DOMComment"/>.</returns>
        public virtual DOMComment createComment(string data)
        {
            XmlComment comment = XmlDocument.CreateComment(data);
            return new DOMComment(comment);
        }

        ///
        /// Creates a CDATA section containing the specified data.
        ///
        /// <param name="data">The content of the new CDATA section.</param>
        /// <returns>A new <see cref="DOMCdataSection"/>.</returns>
        public virtual DOMCdataSection createCDATASection(string data)
        {
            XmlCDataSection cdata = XmlDocument.CreateCDataSection(data);
            return new DOMCdataSection(cdata);
        }

        ///
        /// Creates a processing instruction with the specified name and data.
        ///
        /// <param name="target">The name of the processing instruction.</param>
        /// <param name="data">The data for the processing instruction.</param>
        /// <returns>A new <see cref="DOMProcessingInstruction"/>.</returns>
        public virtual DOMProcessingInstruction createProcessingInstruction(string target, string data = null)
        {
            XmlProcessingInstruction pi = XmlDocument.CreateProcessingInstruction(target, data);
            return new DOMProcessingInstruction(pi);
        }

        ///
        /// Creates an attribute with the specified name.
        ///
        /// <param name="name">The qualified name of the attribute.</param>
        /// <returns>A new <see cref="DOMAttr"/>.</returns>
        public virtual DOMAttr createAttribute(string name)
        {
            XmlAttribute attribute = XmlDocument.CreateAttribute(name);
            return new DOMAttr(attribute);
        }

        ///
        /// Creates an entity reference with the specified name.
        ///
        /// <param name="name">The name of the entity reference.</param>
        /// <returns>A new <see cref="DOMEntityReference"/>.</returns>
        public DOMEntityReference createEntityReference(string name)
        {
            XmlEntityReference entref = XmlDocument.CreateEntityReference(name);
            return new DOMEntityReference(entref);
        }

        ///
        /// Creates an element with the specified namespace URI and qualified name.
        ///
        /// <param name="namespaceUri">The namespace URI of the element.</param>
        /// <param name="qualifiedName">The qualified name of the element.</param>
        /// <param name="value">The inner text (value) of the element.</param>
        /// <returns>A new <see cref="DOMElement"/>.</returns>
        public virtual DOMElement createElementNS(string namespaceUri, string qualifiedName, string value = null)
        {
            XmlElement element = XmlDocument.CreateElement(qualifiedName, namespaceUri);
            if (value != null) element.InnerText = value;
            return new DOMElement(element);
        }

        ///
        /// Creates an attribute with the specified namespace URI and qualified name.
        ///
        /// <param name="namespaceUri">The namespace URI of the attribute.</param>
        /// <param name="qualifiedName">The qualified name of the attribute.</param>
        /// <returns>A new <see cref="DOMAttr"/>.</returns>
        public virtual DOMAttr createAttributeNS(string namespaceUri, string qualifiedName)
        {
            XmlAttribute attribute = XmlDocument.CreateAttribute(qualifiedName, namespaceUri);
            return new DOMAttr(attribute);
        }

        #endregion

        #region Child elements

        ///
        /// Gets all descendant elements with the matching tag name.
        ///
        /// <param name="name">The tag name. Use * to return all elements within the element tree.</param>
        /// <returns>A <see cref="DOMNodeList"/>.</returns>
        public virtual DOMNodeList getElementsByTagName(string name)
        {
            DOMNodeList list = new DOMNodeList();

            // enumerate elements in the default namespace
            foreach (XmlNode node in XmlDocument.GetElementsByTagName(name))
            {
                var dom_node = DOMNode.Create(node);
                if (dom_node != null) list.AppendNode(dom_node);
            }

            // enumerate all namespaces
            XPathNavigator navigator = XmlDocument.CreateNavigator();
            XPathNodeIterator iterator = navigator.Select("//namespace::*[not(. = ../../namespace::*)]");

            while (iterator.MoveNext())
            {
                string prefix = iterator.Current.Name;
                if (!String.IsNullOrEmpty(prefix) && prefix != "xml")
                {
                    // enumerate elements in this namespace
                    foreach (XmlNode node in XmlDocument.GetElementsByTagName(name, iterator.Current.Value))
                    {
                        var dom_node = DOMNode.Create(node);
                        if (dom_node != null) list.AppendNode(dom_node);
                    }
                }
            }

            return list;
        }

        ///
        /// Gets all descendant elements with the matching namespace URI and local name.
        ///
        /// <param name="namespaceUri">The namespace URI.</param>
        /// <param name="localName">The local name. Use * to return all elements within the element tree.</param>
        /// <returns>A <see cref="DOMNodeList"/>.</returns>
        public virtual DOMNodeList getElementsByTagNameNS(string namespaceUri, string localName)
        {
            DOMNodeList list = new DOMNodeList();

            foreach (XmlNode node in XmlDocument.GetElementsByTagName(localName, namespaceUri))
            {
                var dom_node = DOMNode.Create(node);
                if (dom_node != null) list.AppendNode(dom_node);
            }

            return list;
        }

        ///
        /// Gets the first element with the matching ID attribute.
        ///
        /// <param name="elementId">The attribute ID to match.</param>
        /// <returns>A <see cref="DOMElement"/>.</returns>
        public virtual DOMElement getElementById(string elementId)
        {
            XmlElement element = XmlDocument.GetElementById(elementId);
            return element != null ? new DOMElement(element) : null;
        }

        #endregion

        #region Hierarchy

        ///
        /// Imports a node from another document to the current document.
        ///
        /// <param name="importedNode">The node being imported.</param>
        /// <param name="deep">True to perform deep clone; otheriwse false.</param>
        /// <returns>The imported <see cref="DOMNode"/>.</returns>
        public virtual DOMNode importNode(DOMNode importedNode, bool deep = false)
        {
            if (importedNode.IsAssociated)
            {
                return DOMNode.Create(XmlDocument.ImportNode(importedNode.XmlNode, deep));
            }
            else
            {
                importedNode.Associate(XmlDocument);
                return importedNode;
            }
        }

        ///
        /// Not implemented in PHP 7.1.1.
        ///
        public virtual DOMNode adoptNode(DOMNode source)
        {
            throw new NotImplementedException();
        }

        ///
        /// Puts the entire XML document into a "normal" form.
        ///
        public virtual void normalizeDocument() => XmlDocument.Normalize();

        ///
        /// Not implemented in PHP 7.1.1.
        ///
        public virtual void renameNode(DOMNode node, string namespaceUri, string qualifiedName)
        {
            throw new NotImplementedException();
        }

        private XmlDeclaration GetXmlDeclaration() => (XmlDocument.FirstChild as XmlDeclaration);

        ///
        /// Register extended class used to create base node type.
        ///
        /// <param name="baseclass">The DOM class that you want to extend.</param>
        /// <param name="extendedclass">Your extended class name. If NULL is provided, any previously
        /// registered class extending <paramref name="baseclass"/> will be removed.</param>
        /// <returns>Returns true on success or false on failure.</returns>
        public virtual bool registerNodeClass(string baseclass, string extendedclass)
        {
            throw new NotImplementedException();
        }

        #endregion

        #region Load and Save

        ///
        /// To be used as a static method.
        /// Loads the XML document from the specified URL.
        ///
        /// <returns>returns a <see cref="DOMDocument"/> or <c>FALSE</c> on failure.</returns>
        [Obsolete]
        [return: CastToFalse]
        public static DOMDocument load(Context ctx, string fileName)
        {
            var document = new DOMDocument();

            if (document.load(ctx, fileName))
            {
                return document;
            }
            else
            {
                return null; // FALSE
            }
        }

        ///
        /// Loads the XML document from the specified URL.
        ///
        /// <param name="ctx">Current runtime context.</param>
        /// <param name="fileName">URL for the file containing the XML document to load.</param>
        /// <param name="options">Undocumented.</param>
        /// <returns>True on success or false on failure.</returns>
        public virtual bool load(Context ctx, string fileName, int options = 0)
        {
            // TODO: this method can be called both statically and via an instance

            _isHtmlDocument = false;

            using (PhpStream stream = PhpStream.Open(ctx, fileName, "rt"))
            {
                if (stream == null) return false;

                try
                {
                    XmlReaderSettings settings = new XmlReaderSettings() { DtdProcessing = DtdProcessing.Parse };

                    // validating XML reader
                    if (this._validateOnParse)
                    {
#pragma warning disable 618
                        settings.ValidationType = ValidationType.Auto;
#pragma warning restore 618
                    }
                    XmlDocument.Load(XmlReader.Create(stream.RawStream, settings, XIncludeHelper.UriResolver(fileName, ctx.WorkingDirectory)));
                }
                catch (XmlException e)
                {
                    PhpLibXml.IssueXmlError(ctx, PhpLibXml.LIBXML_ERR_ERROR, 0, 0, 0, e.Message, fileName);
                    return false;
                }
                catch (IOException e)
                {
                    PhpLibXml.IssueXmlError(ctx, PhpLibXml.LIBXML_ERR_ERROR, 0, 0, 0, e.Message, fileName);
                    return false;
                }
            }

            return true;
        }

        ///
        /// Loads the XML document from the specified string.
        ///
        /// <param name="ctx">Runtime context.</param>
        /// <param name="xmlString">The XML string.</param>
        /// <param name="options">Undocumented.</param>
        /// <returns>True on success or false on failure.</returns>
        public virtual bool loadXML(Context ctx, string xmlString, int options = 0)
        {
            // TODO: this method can be called both statically and via an instance

            return loadXMLInternal(ctx, xmlString, options, false);
        }

        ///
        /// Loads provided XML string into this <see cref="DOMDocument"/>.
        ///
        /// <param name="ctx">Runtime context.</param>
        /// <param name="xmlString">String representing XML document.</param>
        /// <param name="options">PHP options.</param>
        /// <param name="isHtml">Whether the <paramref name="xmlString"/> represents XML generated from HTML document (then it may contain some invalid XML characters).</param>
        /// <returns></returns>
        private bool loadXMLInternal(Context ctx, string xmlString, int options, bool isHtml)
        {
            this._isHtmlDocument = isHtml;

            var stream = new StringReader(xmlString);

            try
            {
                XmlReaderSettings settings = new XmlReaderSettings() { DtdProcessing = DtdProcessing.Parse };

                // validating XML reader
                if (this._validateOnParse)
                {
#pragma warning disable 618
                    settings.ValidationType = ValidationType.Auto;
#pragma warning restore 618
                }

                // do not check invalid characters in HTML (XML)
                if (isHtml)
                {
                    settings.CheckCharacters = false;
                }

                // load the document
                this.XmlDocument.Load(XmlReader.Create(stream, settings));

                // done
                return true;
            }
            catch (XmlException e)
            {
                PhpLibXml.IssueXmlError(ctx, PhpLibXml.LIBXML_ERR_ERROR, 0, e.LineNumber, e.LinePosition, e.Message, null);
                return false;
            }
            catch (IOException e)
            {
                PhpLibXml.IssueXmlError(ctx, PhpLibXml.LIBXML_ERR_ERROR, 0, 0, 0, e.Message, null);
                return false;
            }
        }

        ///
        /// Saves the XML document to the specified stream.
        ///
        /// <param name="ctx">Current runtime context.</param>
        /// <param name="fileName">The location of the file where the document should be saved.</param>
        /// <param name="options">Unsupported.</param>
        /// <returns>The number of bytes written or false on error.</returns>
        public virtual PhpValue save(Context ctx, string fileName, int options = 0)
        {
            using (PhpStream stream = PhpStream.Open(ctx, fileName, StreamOpenMode.WriteText))
            {
                if (stream == null) return PhpValue.Create(false);

                try
                {
                    // direct stream write indents
                    if (_formatOutput)
                    {
                        XmlDocument.Save(stream.RawStream);
                    }
                    else
                    {
                        var settings = new XmlWriterSettings()
                        {
                            Encoding = Utils.GetNodeEncoding(ctx, XmlNode)
                        };

                        using (var writer = System.Xml.XmlWriter.Create(stream.RawStream, settings))
                        {
                            XmlDocument.Save(writer);
                        }
                    }
                }
                catch (XmlException e)
                {
                    PhpLibXml.IssueXmlError(ctx, PhpLibXml.LIBXML_ERR_ERROR, 0, 0, 0, e.Message, fileName);
                    return PhpValue.False;
                }
                catch (IOException e)
                {
                    PhpLibXml.IssueXmlError(ctx, PhpLibXml.LIBXML_ERR_ERROR, 0, 0, 0, e.Message, fileName);
                    return PhpValue.False;
                }

                // TODO:
                return PhpValue.Create(stream.RawStream.CanSeek ? stream.RawStream.Position : 1);
            }
        }

        ///
        /// Returns the string representation of this document.
        ///
        /// <param name="ctx">Current runtime context.</param>
        /// <param name="node">The node to dump (the entire document if null).</param>
        /// <param name="options">Unsupported.</param>
        /// <returns>The string representation of the document / the specified node or false.</returns>
        [return: CastToFalse]
        public virtual PhpString saveXML(Context ctx, DOMNode node = null, int options = 0)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                if (SaveXMLInternal(ctx, stream, node))
                {
                    return new PhpString(stream.ToArray());
                }
                else
                {
                    return default(PhpString);
                }
            }
        }

        ///
        /// Saves this document to a given stream.
        ///
        /// <param name="ctx">Current runtime context.</param>
        /// <param name="outStream">The output stream.</param>
        /// <param name="node">The node to dump (the entire document if null).</param>
        /// <param name="omitXmlDeclaration">Whether to skip the opening XML declaration.</param>
        /// <returns>True for success, false for failure.</returns>
        private bool SaveXMLInternal(Context ctx, Stream outStream, DOMNode node = null, bool omitXmlDeclaration = false)
        {
            XmlNode xml_node;

            if (node == null)
            {
                xml_node = XmlDocument;
            }
            else
            {
                xml_node = node.XmlNode;

                if (xml_node.OwnerDocument != XmlDocument && xml_node != XmlNode)
                {
                    DOMException.Throw(ExceptionCode.WrongDocument);
                    return false;
                }
            }

            var settings = new XmlWriterSettings()
            {
                NewLineHandling = NewLineHandling.None,
                Encoding = Utils.GetNodeEncoding(ctx, xml_node),
                Indent = _formatOutput,
                ConformanceLevel = node == null ? ConformanceLevel.Document : ConformanceLevel.Fragment,
                OmitXmlDeclaration = omitXmlDeclaration
            };

            // use a XML writer and set its Formatting property to Formatting.Indented
            using (var writer = System.Xml.XmlWriter.Create(outStream, settings))
            {
                xml_node.WriteTo(writer);
            }

            return true;
        }

        ///
        /// Processes HTML errors, if any.
        ///
        /// <param name="ctx">Runtime context.</param>
        /// <param name="htmlDoc"><see cref="HtmlAgilityPack.HtmlDocument"/> instance to process errors from.</param>
        /// <param name="filename">HTML file name or <c>null</c> if HTML has been loaded from a string.</param>
        private void CheckHtmlErrors(Context ctx, HtmlAgilityPack.HtmlDocument htmlDoc, string filename)
        {
            Debug.Assert(htmlDoc != null);

            foreach (var error in htmlDoc.ParseErrors)
            {
                switch (error.Code)
                {
                    case HtmlAgilityPack.HtmlParseErrorCode.EndTagNotRequired:
                    case HtmlAgilityPack.HtmlParseErrorCode.TagNotOpened:
                        break;
                    default:
                        PhpLibXml.IssueXmlError(ctx, PhpLibXml.LIBXML_ERR_ERROR, 0, error.Line, error.LinePosition, "(" + error.Code.ToString() + ")" + error.Reason, filename);
                        break;
                }
            }
        }

        ///
        /// To be used as a static method.
        /// Loads HTML from a string.
        ///
        /// <param name="ctx">Runtime context.</param>
        /// <param name="source">String containing HTML document.</param>
        /// <returns>returns a <see cref="DOMDocument"/> or <c>FALSE</c> on failure.</returns>
        [Obsolete]
        [return: CastToFalse]
        public static DOMDocument loadHTML(Context ctx, string source)
        {
            var document = new DOMDocument();

            if (document.loadHTML(ctx, source))
            {
                return document;
            }
            else
            {
                return null; // FALSE
            }
        }

        ///
        /// Loads HTML from a string.
        ///
        /// <param name="ctx">Runtime context.</param>
        /// <param name="source">String containing HTML document.</param>
        /// <param name="options">Unsupported.</param>
        /// <returns>TRUE on success or FALSE on failure.</returns>
        public virtual bool loadHTML(Context ctx, string source, int options = 0)
        {
            if (string.IsNullOrEmpty(source))
            {
                PhpException.InvalidArgument(nameof(source), Pchp.Library.Resources.Resources.arg_null_or_empty);
                return false;
            }

            return loadHTML(ctx, new StringReader(source), null);
        }

        ///
        /// Loads HTML from a file.
        ///
        /// <param name="ctx">Current runtime context.</param>
        /// <param name="sourceFile">Path to a file containing HTML document.</param>
        /// <param name="options">Unsupported.</param>
        public virtual bool loadHTMLFile(Context ctx, string sourceFile, int options = 0)
        {
            using (PhpStream stream = PhpStream.Open(ctx, sourceFile, "rt"))
            {
                if (stream == null) return false;

                return loadHTML(ctx, new StreamReader(stream.RawStream), sourceFile);
            }
        }

        ///
        /// Load HTML DOM from given <paramref name="stream"/>.
        ///
        private protected bool loadHTML(Context ctx, TextReader stream, string filename, int options = 0)
        {
            HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();

            // setup HTML parser
            htmlDoc.OptionOutputAsXml = true;
            //htmlDoc.OptionOutputOriginalCase = true;  // NOTE: we need lower-cased names because of XPath queries
            //htmlDoc.OptionFixNestedTags = true;
            htmlDoc.OptionCheckSyntax = false;
            htmlDoc.OptionUseIdAttribute = false;   // only needed when XPath navigator is used on htmlDoc
            htmlDoc.OptionWriteEmptyNodes = true;

            // load HTML (from string or a stream)
            htmlDoc.Load(stream);

            CheckHtmlErrors(ctx, htmlDoc, filename);

            //// save to string as XML
            //using (var sw = new StringWriter())
            //{
            //    htmlDoc.Save(sw);

            //    // load as XML
            //    return loadXMLInternal(ctx, sw.ToString(), 0, true);
            //}

            this.XmlDocument.LoadHtml(htmlDoc);
            return true;
        }

        ///
        /// Dumps the internal document into a string using HTML formatting.
        ///
        /// <param name="ctx">Current runtime context.</param>
        /// <param name="node">Optional parameter to output a subset of the document.</param>
        /// <returns>Returns the HTML, or FALSE if an error occurred.</returns>
        [return: CastToFalse]
        public virtual PhpString saveHTML(Context ctx, DOMNode node = null)
        {
            using (var ms = new MemoryStream())
            {
                if (node == null && XmlDocument?.DocumentType == null)
                {
                    // we are saving the whole document and there is no DOCTYPE,
                    // output the default DOCTYPE:
                    OutputDefaultHtmlDoctype(ms);
                }

                SaveXMLInternal(ctx, ms, node, omitXmlDeclaration: true);

                return new PhpString(ms.ToArray());
            }
        }

        ///
        /// Dumps the internal document into a file using HTML formatting.
        ///
        /// <param name="ctx">Current runtime context.</param>
        /// <param name="file">The path to the saved HTML document.</param>
        public virtual PhpValue saveHTMLFile(Context ctx, string file)
        {
            using (PhpStream stream = PhpStream.Open(ctx, file, "wt"))
            {
                if (stream == null)
                {
                    return PhpValue.False;
                }

                if (XmlDocument?.DocumentType == null)
                {
                    OutputDefaultHtmlDoctype(stream.RawStream);
                }

                SaveXMLInternal(ctx, stream.RawStream, null, omitXmlDeclaration: true);

                // TODO:
                return PhpValue.Create(stream.RawStream.CanSeek ? stream.RawStream.Position : 1);
            }
        }

        private void OutputDefaultHtmlDoctype(Stream outStream)
        {
            using (var sw = new StreamWriter(outStream, Encoding.ASCII, bufferSize: 128, leaveOpen: true))
            {
                // HTML 4.01 Transitional
                sw.WriteLine("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\">");
                sw.Flush();
            }
        }

        #endregion

        #region XInclude

        ///
        /// Substitutes XIncludes in a DOMDocument Object
        ///
        /// <returns>Returns the number of XIncludes in the document, -1 if some processing failed, or FALSE if there were no substitutions.</returns>
        public virtual PhpValue xinclude(Context ctx, int options = 0)
        {
            // TODO: xinclude options

            return new XIncludeHelper(ctx).Include(XmlDocument);
        }
        #endregion

        #region Validation

        ///
        /// Not implemented (System.Xml does not support post-load DTD validation).
        ///
        public virtual bool validate()
        {
            //PhpException.Throw(PhpError.Warning, Resources.PostLoadDtdUnsupported);
            throw new DOMException(Resources.PostLoadDtdUnsupported);
        }

        ///
        /// Validates the document against the specified XML schema.
        ///
        /// <param name="ctx">Current runtime context.</param>
        /// <param name="schemaFile">URL for the file containing the XML schema to load.</param>
        /// <param name="flags">Unsupported.</param>
        /// <returns>True or false.</returns>
        public virtual bool schemaValidate(Context ctx, string schemaFile, int flags = 0)
        {
            if ((flags & PhpLibXml.LIBXML_SCHEMA_CREATE) == PhpLibXml.LIBXML_SCHEMA_CREATE)
            {
                PhpException.Throw(PhpError.Warning, Resources.SchemaCreateUnsupported);
            }

            XmlSchema schema;

            using (PhpStream stream = PhpStream.Open(ctx, schemaFile, "rt"))
            {
                if (stream == null) return false;

                try
                {
                    schema = XmlSchema.Read(stream.RawStream, null);
                }
                catch (XmlException e)
                {
                    PhpLibXml.IssueXmlError(ctx, PhpLibXml.LIBXML_ERR_WARNING, 0, 0, 0, e.Message, schemaFile);
                    return false;
                }
                catch (IOException e)
                {
                    PhpLibXml.IssueXmlError(ctx, PhpLibXml.LIBXML_ERR_ERROR, 0, 0, 0, e.Message, schemaFile);
                    return false;
                }
            }

            XmlDocument.Schemas.Add(schema);
            try
            {
                XmlDocument.Validate(null);
            }
            catch (XmlException)
            {
                return false;
            }
            finally
            {
                XmlDocument.Schemas.Remove(schema);
            }
            return true;
        }

        ///
        /// Validates the document against the specified XML schema.
        ///
        /// <param name="ctx">Current runtime context.</param>
        /// <param name="schemaString">The XML schema string.</param>
        /// <param name="flags">Unsupported.</param>
        /// <returns>True or false.</returns>
        public virtual bool schemaValidateSource(Context ctx, string schemaString, int flags = 0)
        {
            if ((flags & PhpLibXml.LIBXML_SCHEMA_CREATE) == PhpLibXml.LIBXML_SCHEMA_CREATE)
            {
                PhpException.Throw(PhpError.Warning, Resources.SchemaCreateUnsupported);
            }

            XmlSchema schema;

            try
            {
                schema = XmlSchema.Read(new System.IO.StringReader(schemaString), null);
            }
            catch (XmlException e)
            {
                PhpLibXml.IssueXmlError(ctx, PhpLibXml.LIBXML_ERR_WARNING, 0, 0, 0, e.Message, null);
                return false;
            }

            XmlDocument.Schemas.Add(schema);
            try
            {
                XmlDocument.Validate(null);
            }
            catch (XmlException)
            {
                return false;
            }
            finally
            {
                XmlDocument.Schemas.Remove(schema);
            }
            return true;
        }

        ///
        /// Not implemented (TODO: will need a Relax NG validator for this).
        ///
        public virtual bool relaxNGValidate(string schemaFile)
        {
            PhpException.Throw(PhpError.Warning, Resources.RelaxNGUnsupported);
            return true;
        }

        ///
        /// Not implemented (TODO: will need a Relax NG validator for this).
        ///
        public virtual bool relaxNGValidateSource(string schema)
        {
            PhpException.Throw(PhpError.Warning, Resources.RelaxNGUnsupported);
            return true;
        }

        #endregion
    }
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE761_Free_Pointer_Not_at_Start_of_Buffer__wchar_t_fixed_string_61b.c
Label Definition File: CWE761_Free_Pointer_Not_at_Start_of_Buffer.label.xml
Template File: source-sinks-61b.tmpl.c
*/
/*
 * @description
 * CWE: 761 Free Pointer not at Start of Buffer
 * BadSource: fixed_string Initialize data to be a fixed string
 * Sinks:
 *    GoodSink: free() memory correctly at the start of the buffer
 *    BadSink : free() memory not at the start of the buffer
 * Flow Variant: 61 Data flow: data returned from one function to another in different source files
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

#define BAD_SOURCE_FIXED_STRING L"Fixed String" /* MAINTENANCE NOTE: This string must contain the SEARCH_CHAR */

#define SEARCH_CHAR L'S'

#ifndef OMITBAD

wchar_t * CWE761_Free_Pointer_Not_at_Start_of_Buffer__wchar_t_fixed_string_61b_badSource(wchar_t * data)
{
    /* POTENTIAL FLAW: Initialize data to be a fixed string that contains the search character in the sinks */
    wcscpy(data, BAD_SOURCE_FIXED_STRING);
    return data;
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodB2G() uses the BadSource with the GoodSink */
wchar_t * CWE761_Free_Pointer_Not_at_Start_of_Buffer__wchar_t_fixed_string_61b_goodB2GSource(wchar_t * data)
{
    /* POTENTIAL FLAW: Initialize data to be a fixed string that contains the search character in the sinks */
    wcscpy(data, BAD_SOURCE_FIXED_STRING);
    return data;
}

#endif /* OMITGOOD */


text:
source="${BASH_SOURCE[0]}"
darcVersion=''
versionEndpoint='https://maestro-prod.westus2.cloudapp.azure.com/api/assets/darc-version?api-version=2019-01-16'
verbosity='minimal'

while [[ $# > 0 ]]; do
  opt="$(echo "$1" | awk '{print tolower($0)}')"
  case "$opt" in
    --darcversion)
      darcVersion=$2
      shift
      ;;
    --versionendpoint)
      versionEndpoint=$2
      shift
      ;;
    --verbosity)
      verbosity=$2
      shift
      ;;
    --toolpath)
      toolpath=$2
      shift
      ;;
    *)
      echo "Invalid argument: $1"
      usage
      exit 1
      ;;
  esac

  shift
done

# resolve $source until the file is no longer a symlink
while [[ -h "$source" ]]; do
  scriptroot="$( cd -P "$( dirname "$source" )" && pwd )"
  source="$(readlink "$source")"
  # if $source was a relative symlink, we need to resolve it relative to the path where the
  # symlink file was located
  [[ $source != /* ]] && source="$scriptroot/$source"
done
scriptroot="$( cd -P "$( dirname "$source" )" && pwd )"

. "$scriptroot/tools.sh"

if [ -z "$darcVersion" ]; then
  darcVersion=$(curl -X GET "$versionEndpoint" -H "accept: text/plain")
fi

function InstallDarcCli {
  local darc_cli_package_name="microsoft.dotnet.darc"

  InitializeDotNetCli
  local dotnet_root=$_InitializeDotNetCli

  if [ -z "$toolpath" ]; then
    local tool_list=$($dotnet_root/dotnet tool list -g)
    if [[ $tool_list = *$darc_cli_package_name* ]]; then
      echo $($dotnet_root/dotnet tool uninstall $darc_cli_package_name -g)
    fi
  else
    local tool_list=$($dotnet_root/dotnet tool list --tool-path "$toolpath")
    if [[ $tool_list = *$darc_cli_package_name* ]]; then
      echo $($dotnet_root/dotnet tool uninstall $darc_cli_package_name --tool-path "$toolpath")
    fi
  fi

  local arcadeServicesSource="https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-eng/nuget/v3/index.json"

  echo "Installing Darc CLI version $darcVersion..."
  echo "You may need to restart your command shell if this is the first dotnet tool you have installed."
  if [ -z "$toolpath" ]; then
    echo $($dotnet_root/dotnet tool install $darc_cli_package_name --version $darcVersion --add-source "$arcadeServicesSource" -v $verbosity -g)
  else
    echo $($dotnet_root/dotnet tool install $darc_cli_package_name --version $darcVersion --add-source "$arcadeServicesSource" -v $verbosity --tool-path "$toolpath")
  fi
}

InstallDarcCli


text:
class CompareLinker
  class GithubTagFinder
    attr_reader :octokit

    def initialize(octokit)
      @octokit = octokit
    end

    def find(repo_full_name, gem_version)
      tags = octokit.tags(repo_full_name)
      if tags
        tags.find { |tag|
          tag.name == gem_version || tag.name == "v#{gem_version}"
        }
      end
    end
  end
end


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

namespace Obscur.Core.Cryptography.Ciphers.Block
{
    /// <summary>
    /// Symmetric block ciphers able to be used in an ObscurCore CryptoStream.
    /// </summary>
    public enum BlockCipher
    {
        None,
        /// <summary>
        /// Very popular and well-regarded 128-bit block cipher, 128/192/256-bit key.
        /// Restricted subset of Rijndael (which offers 128/192/256 block sizes).
        /// </summary>
        Aes,

        /// <summary>
        /// Classic block cipher. Published 1993 by Bruce Schneier.
        /// </summary>
        Blowfish,

        /// <summary>
        /// 128-bit block cipher jointly developed by Mitsubishi and NTT. Comparable to AES.
        /// </summary>
        Camellia,
#if INCLUDE_IDEA
        /// <summary>
        /// International Data SymmetricCipher Algorithm - patent unencumbered as of 2012. 64 bit block size.
        /// </summary>
        Idea,
#endif
        /// <summary>
        /// 128-bit block cipher. Year 2000 NESSIE entrant - not selected. Similar to AES.
        /// </summary>
        Noekeon,

        /// <summary>
        /// 128-bit block cipher. Finalist of AES content. Derivative of RC5.
        /// </summary>
        Rc6,

        /// <summary>
        /// 128-bit block cipher, finalist in AES content, 2nd place after Rijndael.
        /// </summary>
        Serpent,

        /// <summary>
        /// High performance large-block cipher. Successor to Twofish.
        /// </summary>
		Threefish,

        /// <summary>
        /// 128-bit block cipher. Derivative of Blowfish with better security.
        /// </summary>
        Twofish
    }
}