text:
'use babel';

import PathToModuleView from './path-to-module-view';
import { CompositeDisposable } from 'atom';

export default {

  pathToModuleView: null,
  modalPanel: null,
  subscriptions: null,

  activate(state) {
    this.pathToModuleView = new PathToModuleView(state.pathToModuleViewState);
    this.modalPanel = atom.workspace.addModalPanel({
      item: this.pathToModuleView.getElement(),
      visible: false
    });

    // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
    this.subscriptions = new CompositeDisposable();

    // Register command that toggles this view
    this.subscriptions.add(atom.commands.add('atom-workspace', {
      'path-to-module:file2module': () => this.file2module(),
      'path-to-module:module2file': () => this.module2file()
    }));
  },

  deactivate() {
    this.modalPanel.destroy();
    this.subscriptions.dispose();
    this.pathToModuleView.destroy();
  },

  serialize() {
    return {
      pathToModuleViewState: this.pathToModuleView.serialize()
    };
  },

  getRelativePath() {
      uri = atom.workspace.getActivePaneItem().getURI();
      rootDirectory = atom.project.rootDirectories[0];
      directoryPath = rootDirectory.getPath();
      return uri.substr(directoryPath.length + 1);
  },

  getAbsolutePath(file, prefix, extention) {
      path = atom.project.rootDirectories[0].getPath();
      return path + "/" + prefix + file + extention;
  },

  file2module() {
      relativePath = this.getRelativePath();
      moduleName = relativePath.replace(/^(t\/)?lib\//, '').replace(/\.(pm|t)$/, '').replace(/\//g, '::');
      atom.workspace.getActivePaneItem().insertText(moduleName);
  },

  module2file() {
      prefix = "lib/";
      ext    = ".pm";
      moduleName = atom.workspace.getActivePaneItem().getSelectedText();
      file = moduleName.replace(/::/g, '/');

      atom.clipboard.write(file);
      absPath = this.getAbsolutePath(file, prefix, ext);

      atom.workspace.open(absPath);
  }

};

redpajama_set_name: RedPajamaGithub


text:
E_BADARGS=65

EXPECTED_ARGS=3

if [ $# -ne $EXPECTED_ARGS ]
then
  echo " This script expect $EXPECTED_ARGS arguments instead of $#"
  exit $E_BADARGS
fi

MV=$(which mv)
RM=$(which rm)
DATE=$(which date)
SED=$(which sed)
CAT=$(which cat)

### CONFIG
DEP_NAME=$1
DEP_BRANCH=$2
DEP_USER=$3

. $($(which dirname) $($(which readlink) -f "$0"))/autodeploy-common.sh

# Clonar RAMA REPO con submoduless en dir tmp
# clone-with-subs.sh $REPO $BRANCH $TARGET
. $LIB/clone-with-subs.sh $REPO_BARE $DEP_BRANCH $TMP_DIR $TAG

# Copiar files y settings
# copy-files-settings.sh $SOURCE $TARGET
. $LIB/wordpress-copy-files-settings.sh $DST_DIR $TMP_DIR

# Arreglar permisos
# fix-drupal-perms.sh $TARGET
if [ "${FIX_PERMS}" = 'true' ]; then
  . $LIB/wordpress-fix-perms.sh $TMP_DIR
fi

# Firmar Robots
REPO_HASH=$($CAT $TMP_DIR/.git_hash)
REPO_DATE=$($CAT $TMP_DIR/.git_date)
SIGN="# Environment generated by $DEP_USER from $DEP_BRANCH (hash: $REPO_HASH, date: $REPO_DATE) for site $SITE_NAME on $($DATE '+%Y-%m-%d %H:%M %Z')"
$SED  -i  '1{s|^|'"${SIGN}\n"'|}' $TMP_DIR/robots.txt

# Eliminar archivos no para produccion
$RM $TMP_DIR/.git*

# Loggear despliegue
echo -e "$($DATE '+%Y-%m-%d %H:%M %Z')\t$DEP_BRANCH\t$REPO_DATE\t$REPO_HASH\t$DEP_USER" >> $LOG_FILE

$RM -r $DST_DIR
$MV $TMP_DIR $DST_DIR

# Reload apache
restartServerIfNecesary

# Borrar caches
#TODO: Add support for wp cli

# Clean Varnish
cleanVarnishIfNecesary

exit 0


text:
There are two easy ways to get SARL up and running. A pre-configured Eclipse distribution is available which has already all
the necessary plug-ins installed. Alternatively, you can install SARL SDK into your existing Eclipse using the Eclipse update
mechanism.

## Installation Instructions

You must follow the instructions given on the [download]([:sarlUrl!]/download/index.html) page for installing the SARL tools.

## What's next?

In the next section, we will learn how to create a SARL project.

[Next>](./CreateFirstProject.md)

[:Include:](../legal.inc)


text:
@interface ReceivingFileServer : NSObject <NSStreamDelegate> {
    __weak NSWindow *mWindow;
    NSMutableData *data;
    NSString *fileName;
    BOOL isHeader;
}

@property (nonatomic, weak) NSWindow *mWindow;

- (int)setup;
- (void)setview : (NSWindow *)window;

@end


text:
package com.testng;

import org.testng.annotations.*;

public class TestNGAnnotations {

    @Test
    public void testMethod() {
        System.out.println("5. testMethod");
    }

    @BeforeMethod
    public void beforeMethod() {
        System.out.println("4. beforeMethod");
    }

    @AfterMethod
    public void afterMethod() {
        System.out.println("6. afterMethod");
    }

    @BeforeClass
    public void beforeClass() {
        System.out.println("3. beforeClass");
    }

    @AfterClass
    public void afterClass() {
        System.out.println("7. afterClass");
    }

    @BeforeTest
    public void beforeTest() {
        System.out.println("2. beforeTest");
    }

    @AfterTest
    public void afterTest() {
        System.out.println("8. afterTest");
    }

    @BeforeSuite
    public void beforeSuite() {
        System.out.println("1. beforeSuite");
    }

    @AfterSuite
    public void afterSuite() {
        System.out.println("9. afterSuite");
    }

}


text:
import argparse
import json
import os
import re
import zipfile

import torch

####################################################################################################

def recursive_print(name, val, spaces=0):
    # Format the message.
    if name is None:
        msg = None
    else:
        fmt = "." * max(0, spaces - 2) + "# {:" + str(50 - spaces) + "s}"
        msg = fmt.format(name)

    # Print and recurse (if needed).
    if isinstance(val, dict):
        if msg is not None:
            print(msg)
        for k in val.keys():
            recursive_print(k, val[k], spaces + 2)
    elif isinstance(val, torch.Tensor):
        print(msg, ":", val.size())
    else:
        print(msg, ":", val)

####################################################################################################

def convert_megatron_checkpoint(args, input_state_dict):
    # The converted output model.
    output_state_dict = {}

    # The model.
    model = input_state_dict["model"]
    # The language model.
    lm = model["language_model"]
    # The embeddings.
    embeddings = lm["embedding"]

    # The word embeddings.
    word_embeddings = embeddings["word_embeddings"]["weight"]
    # Store the word embeddings.
    output_state_dict["bert.embeddings.word_embeddings.weight"] = word_embeddings

    # The position embeddings.
    pos_embeddings = embeddings["position_embeddings"]["weight"]
    # Trained for 512 x 1024.
    assert pos_embeddings.size(0) == 512 and pos_embeddings.size(1) == 1024
    # Store the position embeddings.
    output_state_dict["bert.embeddings.position_embeddings.weight"] = pos_embeddings

    # The token-type embeddings.
    tokentype_embeddings = embeddings["tokentype_embeddings"]["weight"]
    # Store the position embeddings.
    output_state_dict["bert.embeddings.token_type_embeddings.weight"] = tokentype_embeddings

    # The transformer.
    transformer = lm["transformer"]

    # The regex to extract layer names.
    layer_re = re.compile("layers\.(\d+)\.([a-z0-9_.]+)\.([a-z]+)")

    # The simple map of names for "automated" rules.
    megatron_to_transformers = {
        "attention.dense": ".attention.output.dense.",
        "mlp.dense_h_to_4h": ".intermediate.dense.",
        "mlp.dense_4h_to_h": ".output.dense.",
    }

    # Keep track of the attention/query/value tensor.
    attention_qkv_weight = None

    # Extract the layers.
    for key, val in transformer.items():
        # Match the name.
        m = layer_re.match(key)

        # Stop if that's not a layer
        if m is None:
            break

        # The index of the layer.
        layer_idx = int(m.group(1))
        # The name of the operation.
        op_name = m.group(2)
        # Is it a weight or a bias?
        weight_or_bias = m.group(3)

        # The name of the layer.
        layer_name = f"bert.encoder.layer.{layer_idx}"

        # For layernorm(s), simply store the layer norm.
        if op_name.endswith("layernorm"):

            ln_name = "attention.ln" if op_name.startswith("input") else "ln"
            output_state_dict[layer_name + "." + ln_name + "." + weight_or_bias] = val

        # Transpose the QKV matrix.
        elif op_name == "attention.query_key_value" and weight_or_bias == "weight":

            # Make sure the QKV pointer is nil.
            assert attention_qkv_weight is None, ""

            # Store the tensor as we need the bias as well to interleave QKV and biases.
            attention_qkv_weight = val

        # Transpose the bias.
        elif op_name == "attention.query_key_value" and weight_or_bias == "bias":

            # Make sure we read the weight tensor.
            assert attention_qkv_weight is not None, ""

            # Split the QKV matrix into Q, K and V. Megatron stores Q,K,V interleaved.
            q = attention_qkv_weight[0 * 1024 : 1 * 1024, :]
            k = attention_qkv_weight[1 * 1024 : 2 * 1024, :]
            v = attention_qkv_weight[2 * 1024 : 3 * 1024, :]

            # Split the bias.
            q_bias = val[0 * 1024 : 1 * 1024]
            k_bias = val[1 * 1024 : 2 * 1024]
            v_bias = val[2 * 1024 : 3 * 1024]

            # Store.
            output_state_dict[f"{layer_name}.attention.self.query.weight"] = q
            output_state_dict[f"{layer_name}.attention.self.query.bias"] = q_bias
            output_state_dict[f"{layer_name}.attention.self.key.weight"] = k
            output_state_dict[f"{layer_name}.attention.self.key.bias"] = k_bias
            output_state_dict[f"{layer_name}.attention.self.value.weight"] = v
            output_state_dict[f"{layer_name}.attention.self.value.bias"] = v_bias

            # Clear the stored tensor.
            attention_qkv_weight = None

        # Copy weights and biases as is.
        elif weight_or_bias in ["weight", "bias"]:

            out_name = megatron_to_transformers[op_name]
            output_state_dict[layer_name + out_name + weight_or_bias] = val

    # The final layernorm.
    output_state_dict["bert.encoder.ln.weight"] = transformer["final_layernorm.weight"]
    output_state_dict["bert.encoder.ln.bias"] = transformer["final_layernorm.bias"]

    # The config.
    output_config = {
        "vocab_size": word_embeddings.size(0),
        "hidden_size": 1024,
        "num_hidden_layers": 24,
        "num_attention_heads": 16,
        "hidden_act": "gelu_new",
        "intermediate_size": 4096,
        "hidden_dropout_prob": 0.1,
        "attention_probs_dropout_prob": 0.1,
        "max_position_embeddings": 512,
        "type_vocab_size": 2,
        "initializer_range": 0.2,
        "layer_norm_eps": 1e-12,
        "gradient_checkpointing": False,
        "position_embedding_type": "absolute",
        "use_cache": False,
    }

    # The pooler.
    pooler = lm["pooler"]

    # Store the matrix and the bias.
    output_state_dict["bert.pooler.dense.weight"] = pooler["dense.weight"]
    output_state_dict["bert.pooler.dense.bias"] = pooler["dense.bias"]

    # The LM head from Megatron (for RACE).
    lm_head = model["lm_head"]

    # The transform matrix.
    output_state_dict["cls.predictions.transform.dense.weight"] = lm_head["dense.weight"]
    output_state_dict["cls.predictions.transform.dense.bias"] = lm_head["dense.bias"]

    # The transform LN.
    output_state_dict["cls.predictions.transform.LayerNorm.weight"] = lm_head["layernorm.weight"]
    output_state_dict["cls.predictions.transform.LayerNorm.bias"] = lm_head["layernorm.bias"]

    # For the decoder, we replicate the weights.
    output_state_dict["cls.predictions.decoder.weight"] = word_embeddings
    output_state_dict["cls.predictions.bias"] = lm_head["bias"]

    # The classifier from Megatron (for MLNI).
    binary_head = model["binary_head"]

    # Store the classifier.
    output_state_dict["cls.seq_relationship.weight"] = binary_head["weight"]
    output_state_dict["cls.seq_relationship.bias"] = binary_head["bias"]

    # It should be done!
    return output_state_dict, output_config

####################################################################################################

def main():
    # Create the argument parser.
    parser = argparse.ArgumentParser()
    parser.add_argument("--print-checkpoint-structure", action="store_true")
    parser.add_argument("path_to_checkpoint", type=str, help="Path to the ZIP file containing the checkpoint")
    args = parser.parse_args()

    # Extract the basename.
    basename = os.path.dirname(args.path_to_checkpoint)

    # Load the model.
    print(f'Extracting PyTorch state dictionary from "{args.path_to_checkpoint}"')
    with zipfile.ZipFile(args.path_to_checkpoint, "r") as checkpoint:
        with checkpoint.open("release/mp_rank_00/model_optim_rng.pt") as pytorch_dict:
            input_state_dict = torch.load(pytorch_dict, map_location="cpu")

    # Convert.
    print("Converting")
    output_state_dict, output_config = convert_megatron_checkpoint(args, input_state_dict)

    # Print the structure of converted state dict.
    if args.print_checkpoint_structure:
        recursive_print(None, output_state_dict)

    # Store the config to file.
    output_config_file = os.path.join(basename, "config.json")
    print(f'Saving config to "{output_config_file}"')
    with open(output_config_file, "w") as f:
        json.dump(output_config, f)

    # Store the state_dict to file.
    output_checkpoint_file = os.path.join(basename, "pytorch_model.bin")
    print(f'Saving checkpoint to "{output_checkpoint_file}"')
    torch.save(output_state_dict, output_checkpoint_file)

####################################################################################################

if __name__ == "__main__":
    main()

####################################################################################################


text:
import { IExpression, Expression, ExpressionType } from './expression';
import { IIdentifierExpression, IdentifierExpression } from './identifierexpression';
import { IMemberExpression, MemberExpression } from './memberexpression';
import { ILogicalExpression, LogicalExpression, LogicalOperatorType } from './logicalexpression';
import { IMethodExpression } from './methodexpression';
import { ILiteralExpression, LiteralExpression } from './literalexpression';

import { ExpressionVisitor } from './expressionvisitor';

export class RemapVisitor extends ExpressionVisitor {
    constructor(private remapKey: (name: string) => string, private remapValue: (name: string, value: any) => any) {
        super();

        if (typeof this.remapKey != 'function')
            this.remapKey = null;

        if (typeof this.remapValue != 'function')
            this.remapValue = null;
    }

    public visit(expression: IExpression): IExpression {
        return expression.accept(this);
    }

    public visitLiteral(expression: ILiteralExpression): IExpression {
        let parent = this.stack.peek(),
            property: IExpression,
            value: any;

        if (this.remapValue && (property = this.findIdentifier(parent)) && (value = this.remapValue(this.flattenMember(property), expression.value)) !== undefined)
            return new LiteralExpression(value);

        return new LiteralExpression(expression.value)
    }

    public visitIdentifier(expression: IIdentifierExpression): IExpression {
        let parent = this.stack.peek(),
            name: string;

        if (this.remapKey && parent.type != ExpressionType.Member) {
            if ((name = this.remapKey(expression.name)) != null)
                return new IdentifierExpression(name);
        }

        return new IdentifierExpression(expression.name);
    }

    public visitMember(expression: IMemberExpression): IExpression {
        let path: string;

        if (this.remapKey && (path = this.remapKey(this.flattenMember(expression))) != null)
            return this.unflattenMember(path);

        return new MemberExpression(expression.object.accept(this), expression.property.accept(this));
    }

    private findIdentifier(expression: IExpression): IExpression {
        let member: any;

        switch (expression.type) {
            case ExpressionType.Logical:
                if ((member = this.findIdentifier((<ILogicalExpression>expression).left)) != null)
                    return member;

                if ((member = this.findIdentifier((<ILogicalExpression>expression).right)) != null)
                    return member;

                break;

            case ExpressionType.Identifier:
                return expression;

            case ExpressionType.Member:
                return expression;

            case ExpressionType.Method:
                if ((<IMethodExpression>expression).caller != null && (member = this.findIdentifier((<IMethodExpression>expression).caller)) != null)
                    return member;

                if ((<IMethodExpression>expression).parameters.length >= 1 && (member = this.findIdentifier((<IMethodExpression>expression).parameters[0])) != null)
                    return member;

                break;
        }

        return null;
    }

    private flattenMember(expression: IExpression): string {
        switch (expression.type) {
            case ExpressionType.Member:
                let prop = this.flattenMember((<IMemberExpression>expression).property);

                return this.flattenMember((<IMemberExpression>expression).object) + (prop.length > 0 ? '.' + prop : '');

            case ExpressionType.Identifier:
                return (<IIdentifierExpression>expression).name;

            default:
                return "";
        }
    }

    private unflattenMember(path: string, idx: number = 0): IExpression {
        let parts = path.split('.');

        if (idx + 1 >= parts.length)
            return new IdentifierExpression(parts[idx]);

        return new MemberExpression(new IdentifierExpression(parts[idx]), this.unflattenMember(path, idx + 1));
    }

}


text:
<?php

namespace PHPixie\Auth\Context;

interface Container
{
    /**
     * @return \PHPixie\Auth\Context
     */
    public function authContext();
}


text:
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

import { style } from './index.js';

// todo
// - animations
// - fonts

export var StyleSheet = {
  create: function create(spec) {
    return Object.keys(spec).reduce(function (o, name) {
      return o[name] = style(spec[name]), o;
    }, {});
  }
};

export function css() {
  for (var _len = arguments.length, rules = Array(_len), _key = 0; _key < _len; _key++) {
    rules[_key] = arguments[_key];
  }

  return style.apply(undefined, _toConsumableArray(rules.filter(function (x) {
    return !!x;
  }))); // aphrodite compat https://github.com/threepointone/glamor/issues/170
}


text:
package org.apache.metron.pcap.config;

public class PcapGlobalDefaults {
  public static final String BASE_PCAP_PATH_DEFAULT = "/apps/metron/pcap";
  public static final String BASE_INPUT_PATH_DEFAULT = BASE_PCAP_PATH_DEFAULT + "/input";
  public static final String BASE_INTERIM_RESULT_PATH_DEFAULT = BASE_PCAP_PATH_DEFAULT + "/interim";
  public static final String FINAL_OUTPUT_PATH_DEFAULT = BASE_PCAP_PATH_DEFAULT + "/output";
  public static final int NUM_REDUCERS_DEFAULT = 10;
  public static final int NUM_RECORDS_PER_FILE_DEFAULT = 10000;
  public static final String NUM_FINALIZER_THREADS_DEFAULT = "1";
}


text:
package com.intellij.packaging.impl.elements;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.NlsSafe;
import com.intellij.packaging.elements.PackagingElement;
import com.intellij.packaging.impl.ui.ArchiveElementPresentation;
import com.intellij.packaging.ui.ArtifactEditorContext;
import com.intellij.packaging.ui.PackagingElementPresentation;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.xmlb.XmlSerializerUtil;
import com.intellij.util.xmlb.annotations.Attribute;
import com.intellij.workspaceModel.storage.EntitySource;
import com.intellij.workspaceModel.storage.WorkspaceEntity;
import com.intellij.workspaceModel.storage.WorkspaceEntityStorageBuilder;
import com.intellij.workspaceModel.storage.bridgeEntities.*;
import kotlin.Unit;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

import java.util.List;
import java.util.Objects;

public class ArchivePackagingElement extends CompositeElementWithManifest<ArchivePackagingElement> {
  @NonNls public static final String NAME_ATTRIBUTE = "name";
  private String myArchiveFileName;

  public ArchivePackagingElement() {
    super(PackagingElementFactoryImpl.ARCHIVE_ELEMENT_TYPE);
  }

  public ArchivePackagingElement(@NotNull String archiveFileName) {
    super(PackagingElementFactoryImpl.ARCHIVE_ELEMENT_TYPE);
    myArchiveFileName = archiveFileName;
  }

  @Override
  @NotNull
  public PackagingElementPresentation createPresentation(@NotNull ArtifactEditorContext context) {
    return new ArchiveElementPresentation(this);
  }

  @Attribute(NAME_ATTRIBUTE)
  public @NlsSafe String getArchiveFileName() {
    return getMyArchiveName();
  }

  @NonNls @Override
  public String toString() {
    return "archive:" + getMyArchiveName();
  }

  @Override
  public ArchivePackagingElement getState() {
    return this;
  }

  public void setArchiveFileName(String archiveFileName) {
    renameArchive(archiveFileName);
  }

  @Override
  public String getName() {
    return getMyArchiveName();
  }

  @Override
  public void rename(@NotNull String newName) {
    renameArchive(newName);
  }

  private void renameArchive(String archiveFileName) {
    this.update(
      () -> myArchiveFileName = archiveFileName,
      (builder, entity) -> {
        builder.modifyEntity(ModifiableArchivePackagingElementEntity.class, entity, ent -> {
          ent.setFileName(archiveFileName);
          return Unit.INSTANCE;
        });
      }
    );
  }

  @Override
  public boolean isEqualTo(@NotNull PackagingElement<?> element) {
    return element instanceof ArchivePackagingElement && ((ArchivePackagingElement)element).getArchiveFileName().equals(getMyArchiveName());
  }

  @Override
  public void loadState(@NotNull ArchivePackagingElement state) {
    XmlSerializerUtil.copyBean(state, this);
  }

  @Override
  public WorkspaceEntity getOrAddEntity(@NotNull WorkspaceEntityStorageBuilder diff,
                                        @NotNull EntitySource source,
                                        @NotNull Project project) {
    WorkspaceEntity existingEntity = this.getExistingEntity(diff);
    if (existingEntity != null) return existingEntity;

    List<PackagingElementEntity> children = ContainerUtil.map(this.getChildren(), o -> {
      return (PackagingElementEntity)o.getOrAddEntity(diff, source, project);
    });

    var entity = BridgeModelModifiableEntitiesKt.addArchivePackagingElementEntity(diff, myArchiveFileName, children, source);
    diff.getMutableExternalMapping("intellij.artifacts.packaging.elements").addMapping(entity, this);
    return entity;
  }

  private String getMyArchiveName() {
    if (myStorage == null) {
      return myArchiveFileName;
    } else {
      ArchivePackagingElementEntity entity = (ArchivePackagingElementEntity)getThisEntity();
      String fileName = entity.getFileName();
      if (!Objects.equals(fileName, myArchiveFileName)) {
        myArchiveFileName = fileName;
      }
      return fileName;
    }
  }
}


text:
class Item {
  constructor(content, priority) {
    this.content = content;
    this.priority = priority;
  }
}

/**
 * The `ItemList` class collects items and then arranges them into an array
 * by priority.
 */
export default class ItemList {
  /**
   * Add an item to the list.
   *
   * @param {String} key A unique key for the item.
   * @param {*} content The item's content.
   * @param {Integer} [priority] The priority of the item. Items with a higher
   *     priority will be positioned before items with a lower priority.
   * @public
   */
  add(key, content, priority = 0) {
    this[key] = new Item(content, priority);
  }

  /**
   * Merge another list's items into this one.
   *
   * @param {ItemList} items
   * @public
   */
  merge(items) {
    for (const i in items) {
      if (items.hasOwnProperty(i) && items[i] instanceof Item) {
        this[i] = items[i];
      }
    }
  }

  /**
   * Convert the list into an array of item content arranged by priority. Each
   * item's content will be assigned an `itemName` property equal to the item's
   * unique key.
   *
   * @return {Array}
   * @public
   */
  toArray() {
    const items = [];

    for (const i in this) {
      if (this.hasOwnProperty(i) && this[i] instanceof Item) {
        if (typeof this[i].content === 'string') {
          this[i].content = new String(this[i].content);
        }

        this[i].content.itemName = i;
        items.push(this[i]);
        this[i].key = items.length;
      }
    }

    return items.sort((a, b) => {
      if (a.priority === b.priority) {
        return a.key - b.key;
      } else if (a.priority > b.priority) {
        return -1;
      }
      return 1;
    }).map(item => item.content);
  }
}


text:
import sys, traceback

DATA = b'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'

def gen_file(size, filename):
    output = []
    outfile = open(filename, mode='w')
    while True:
        append_data(output, outfile, size)
        if len(output) >= size:
            outfile.write(str(bytes(output)))
            return

def append_data(output, outfile, size):
    for x in DATA:
        output.append(x)
        if len(output) >= size:
            return

if __name__ == "__main__":
    try:
        # Setting up profiling
        import cProfile
        profile = cProfile.Profile()
        profile.enable()

        gen_file(int(sys.argv[1]), sys.argv[2])

        # Ending profiling, writing out profiling information
        profile.disable()
        profile.dump_stats("./cpu_profile")
        profile.print_stats()

        sys.exit(0)
    except Exception as e:
        traceback.print_exc()
        sys.exit(1)


text:
'use strict';

export const MY_POSITION_CHANGE = 'MY_POSITION_CHANGE';
export const FRIEND_POSITION_RECEIVED = 'FRIEND_POSITION_RECEIVED';


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Icon. pl. formos. 10:22, fig. 13. 1921

#### Original name
null

### Remarks
null


text:
name              "exim"
maintainer        "OpenStreetMap Administrators"
maintainer_email  "admins@openstreetmap.org"
license           "Apache-2.0"
description       "Installs and configures exim"

version           "1.0.0"
supports          "ubuntu"
depends           "accounts"
depends           "apache"
depends           "munin"
depends           "networking"
depends           "ssl"


text:
using Newtonsoft.Json;

namespace Tuwitchuu.Model
{
    internal class RootTokenz
    {
        [JsonProperty("authorization")]
        public Authorization Authorization { get; set; }

        [JsonProperty("user_name")]
        public string UserName { get; set; }

        [JsonProperty("valid")]
        public bool Valid { get; set; }
    }
}


text:
import { ChangeEvent, ReactElement, useCallback } from 'react';
import FormControl from 'react-bootstrap/FormControl';
import InputGroup from 'react-bootstrap/InputGroup';
import { FaCalendar, FaClock } from 'react-icons/fa';

function checkDatetimeLocalInput(): boolean {
  const input = document.createElement('input');

  input.setAttribute('type', 'datetime-local');

  const notADateValue = 'not-a-date';

  input.setAttribute('value', notADateValue);

  return input.value !== notADateValue;
}

const supportsDatetimeLocal: boolean = checkDatetimeLocalInput();

interface Props {
  value: string;
  onChange: (value: string) => void;
  placeholders?: {
    date: string;
    time: string;
    datetime: string;
  };
}

export function DateTime({
  value,
  onChange,
  placeholders,
}: Props): ReactElement {
  const [, datePart, timePart] = /(.*)T(.*)/.exec(value ?? '') || ['', '', ''];

  const propagateChange = useCallback(
    (date: string, time: string) => {
      onChange(date ? `${date}T${time || '00:00:00'}` : '');
    },
    [onChange],
  );

  const handleDateChange = useCallback(
    (e: ChangeEvent<HTMLInputElement>) => {
      propagateChange(e.target.value, timePart);
    },
    [timePart, propagateChange],
  );

  const handleTimeChange = useCallback(
    (e: ChangeEvent<HTMLInputElement>) => {
      propagateChange(datePart, e.target.value);
    },
    [datePart, propagateChange],
  );

  const handleDatetimeChange = useCallback(
    (e: ChangeEvent<HTMLInputElement>) => {
      onChange(e.target.value);
    },
    [onChange],
  );

  return supportsDatetimeLocal ? (
    <FormControl
      type="datetime-local"
      placeholder={placeholders?.datetime}
      value={value}
      onChange={handleDatetimeChange}
    />
  ) : (
    <InputGroup>
      <InputGroup.Append>
        <InputGroup.Text>
          <FaCalendar />
        </InputGroup.Text>
      </InputGroup.Append>

      <FormControl
        type="date"
        placeholder={placeholders?.date ?? 'YYY-MM-DD'}
        value={datePart}
        onChange={handleDateChange}
        pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}"
        required={!!timePart}
      />

      <InputGroup.Append>
        <InputGroup.Text>
          <FaClock />
        </InputGroup.Text>
      </InputGroup.Append>

      <FormControl
        type="time"
        placeholder={placeholders?.time ?? 'HH:MM[:SS]'}
        value={timePart}
        onChange={handleTimeChange}
        pattern="[0-9]{2}:[0-9]{2}(:[0-9]{2})?"
        required={!!datePart}
        step="1"
      />
    </InputGroup>
  );
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Runtime.Versioning;
using Cake.Core;
using Cake.Core.Polyfill;

namespace Cake.Testing
{
    /// <summary>
    /// An implementation of a fake <see cref="ICakeRuntime"/>.
    /// </summary>
    public sealed class FakeRuntime : ICakeRuntime
    {
        /// <inheritdoc/>
        public FrameworkName BuiltFramework { get; set; }

        /// <inheritdoc/>
        public Runtime Runtime { get; set; }

        /// <inheritdoc/>
        public Version CakeVersion { get; set; }

        /// <inheritdoc/>
        public bool IsCoreClr { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="FakeRuntime"/> class.
        /// </summary>
        public FakeRuntime()
        {
            BuiltFramework = new FrameworkName(".NETFramework,Version=v4.6.2");
            Runtime = Runtime.Clr;
            CakeVersion = new Version(0, 1, 2);
            IsCoreClr = false;
        }
    }
}


text:
require 'oss_spec'
require 'shared_spec'
require 'json'
vars = JSON.parse(File.read('/tmp/vars.json'))

describe 'OSS Tests' do
  include_examples 'oss::init', vars
  include_examples 'shared::init', vars
end


text:
@parent aleph-frontend
@module {can.Component} aleph-frontend/compras/registros_proveedor <aleph-compras-registros-proveedor>

A short description of the aleph-compras-registros-proveedor component

@signature `<aleph-compras-registros-proveedor>`

@body

## Use


text:
<?php namespace App\Http\Livewire;

use Livewire\Component;

class HashGenerator extends Component
{
    public string $input = 'Hello world!';

    public function md5(): string
    {
        return md5($this->input);
    }

    public function sha1(): string
    {
        return sha1($this->input);
    }

    public function sha256(): string
    {
        return hash('sha256', $this->input);
    }

    public function sha512(): string
    {
        return hash('sha512', $this->input);
    }
}


text:
#include "third_party/blink/renderer/core/layout/layout_theme.h"

#include "build/build_config.h"
#include "third_party/blink/public/strings/grit/blink_strings.h"
#include "third_party/blink/public/web/blink.h"
#include "third_party/blink/renderer/core/css_value_keywords.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/shadow_root.h"
#include "third_party/blink/renderer/core/editing/frame_selection.h"
#include "third_party/blink/renderer/core/fileapi/file.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/html/forms/html_data_list_element.h"
#include "third_party/blink/renderer/core/html/forms/html_data_list_options_collection.h"
#include "third_party/blink/renderer/core/html/forms/html_form_control_element.h"
#include "third_party/blink/renderer/core/html/forms/html_input_element.h"
#include "third_party/blink/renderer/core/html/forms/html_option_element.h"
#include "third_party/blink/renderer/core/html/forms/html_select_element.h"
#include "third_party/blink/renderer/core/html/forms/spin_button_element.h"
#include "third_party/blink/renderer/core/html/forms/text_control_inner_elements.h"
#include "third_party/blink/renderer/core/html/html_collection.h"
#include "third_party/blink/renderer/core/html/parser/html_parser_idioms.h"
#include "third_party/blink/renderer/core/html/shadow/shadow_element_names.h"
#include "third_party/blink/renderer/core/html/shadow/shadow_element_utils.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/input_type_names.h"
#include "third_party/blink/renderer/core/layout/layout_box.h"
#include "third_party/blink/renderer/core/layout/layout_theme_font_provider.h"
#include "third_party/blink/renderer/core/layout/layout_theme_mobile.h"
#include "third_party/blink/renderer/core/page/focus_controller.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/core/style/computed_style_initial_values.h"
#include "third_party/blink/renderer/platform/file_metadata.h"
#include "third_party/blink/renderer/platform/fonts/font_selector.h"
#include "third_party/blink/renderer/platform/graphics/touch_action.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/theme/web_theme_engine_helper.h"
#include "third_party/blink/renderer/platform/web_test_support.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
#include "ui/base/ui_base_features.h"
#include "ui/native_theme/native_theme.h"

// The methods in this file are shared by all themes on every platform.

namespace blink {

namespace {

// This function should match to the user-agent stylesheet.
ControlPart AutoAppearanceFor(const Element& element) {
  if (IsA<HTMLButtonElement>(element))
    return kButtonPart;
  if (IsA<HTMLMeterElement>(element))
    return kMeterPart;
  if (IsA<HTMLProgressElement>(element))
    return kProgressBarPart;
  if (IsA<HTMLTextAreaElement>(element))
    return kTextAreaPart;
  if (IsA<SpinButtonElement>(element))
    return kInnerSpinButtonPart;
  if (const auto* select = DynamicTo<HTMLSelectElement>(element))
    return select->UsesMenuList() ? kMenulistPart : kListboxPart;

  if (const auto* input = DynamicTo<HTMLInputElement>(element))
    return input->AutoAppearance();

  if (element.IsInUserAgentShadowRoot()) {
    const AtomicString& id_value =
        element.FastGetAttribute(html_names::kIdAttr);
    if (id_value == shadow_element_names::kIdSliderThumb)
      return kSliderThumbHorizontalPart;
    if (id_value == shadow_element_names::kIdSearchClearButton ||
        id_value == shadow_element_names::kIdClearButton)
      return kSearchFieldCancelButtonPart;

    // Slider container elements and -webkit-meter-inner-element don't have IDs.
    if (IsSliderContainer(element))
      return kSliderHorizontalPart;
    if (element.ShadowPseudoId() ==
        shadow_element_names::kPseudoMeterInnerElement)
      return kMeterPart;
  }
  return kNoControlPart;
}

}  // namespace

LayoutTheme& LayoutTheme::GetTheme() {
  if (RuntimeEnabledFeatures::MobileLayoutThemeEnabled()) {
    DEFINE_STATIC_REF(LayoutTheme, layout_theme_mobile,
                      (LayoutThemeMobile::Create()));
    return *layout_theme_mobile;
  }
  return NativeTheme();
}

LayoutTheme::LayoutTheme() : has_custom_focus_ring_color_(false) {
  UpdateForcedColorsState();
}

ControlPart LayoutTheme::AdjustAppearanceWithAuthorStyle(
    ControlPart part,
    const ComputedStyle& style) {
  if (IsControlStyled(part, style))
    return part == kMenulistPart ? kMenulistButtonPart : kNoControlPart;
  return part;
}

ControlPart LayoutTheme::AdjustAppearanceWithElementType(
    const ComputedStyle& style,
    const Element* element) {
  ControlPart part = style.EffectiveAppearance();
  if (!element)
    return kNoControlPart;

  ControlPart auto_appearance = AutoAppearanceFor(*element);
  if (part == auto_appearance)
    return part;

  switch (part) {
    // No restrictions.
    case kNoControlPart:
    case kMediaSliderPart:
    case kMediaSliderThumbPart:
    case kMediaVolumeSliderPart:
    case kMediaVolumeSliderThumbPart:
    case kMediaControlPart:
      return part;

    // Aliases of 'auto'.
    // https://drafts.csswg.org/css-ui-4/#typedef-appearance-compat-auto
    case kAutoPart:
    case kCheckboxPart:
    case kRadioPart:
    case kPushButtonPart:
    case kSquareButtonPart:
    case kInnerSpinButtonPart:
    case kListboxPart:
    case kMenulistPart:
    case kMeterPart:
    case kProgressBarPart:
    case kSliderHorizontalPart:
    case kSliderThumbHorizontalPart:
    case kSearchFieldPart:
    case kSearchFieldCancelButtonPart:
    case kTextAreaPart:
      return auto_appearance;

      // The following keywords should work well for some element types
      // even if their default appearances are different from the keywords.

    case kButtonPart:
      return (auto_appearance == kPushButtonPart ||
              auto_appearance == kSquareButtonPart)
                 ? part
                 : auto_appearance;

    case kMenulistButtonPart:
      return auto_appearance == kMenulistPart ? part : auto_appearance;

    case kSliderVerticalPart:
      return auto_appearance == kSliderHorizontalPart ? part : auto_appearance;

    case kSliderThumbVerticalPart:
      return auto_appearance == kSliderThumbHorizontalPart ? part
                                                           : auto_appearance;

    case kTextFieldPart:
      if (IsA<HTMLInputElement>(*element) &&
          To<HTMLInputElement>(*element).type() == input_type_names::kSearch)
        return part;
      return auto_appearance;
  }

  return part;
}

void LayoutTheme::AdjustStyle(const Element* element, ComputedStyle& style) {
  ControlPart original_part = style.Appearance();
  style.SetEffectiveAppearance(original_part);
  if (original_part == ControlPart::kNoControlPart)
    return;

  // Force inline and table display styles to be inline-block (except for table-
  // which is block)
  if (style.Display() == EDisplay::kInline ||
      style.Display() == EDisplay::kInlineTable ||
      style.Display() == EDisplay::kTableRowGroup ||
      style.Display() == EDisplay::kTableHeaderGroup ||
      style.Display() == EDisplay::kTableFooterGroup ||
      style.Display() == EDisplay::kTableRow ||
      style.Display() == EDisplay::kTableColumnGroup ||
      style.Display() == EDisplay::kTableColumn ||
      style.Display() == EDisplay::kTableCell ||
      style.Display() == EDisplay::kTableCaption)
    style.SetDisplay(EDisplay::kInlineBlock);
  else if (style.Display() == EDisplay::kListItem ||
           style.Display() == EDisplay::kTable)
    style.SetDisplay(EDisplay::kBlock);

  ControlPart part = AdjustAppearanceWithAuthorStyle(
      AdjustAppearanceWithElementType(style, element), style);
  style.SetEffectiveAppearance(part);
  DCHECK_NE(part, kAutoPart);
  if (part == kNoControlPart)
    return;
  DCHECK(element);
  // After this point, a Node must be non-null Element if
  // EffectiveAppearance() != kNoControlPart.

  AdjustControlPartStyle(style);

  // Call the appropriate style adjustment method based off the appearance
  // value.
  switch (part) {
    case kMenulistPart:
      return AdjustMenuListStyle(style);
    case kMenulistButtonPart:
      return AdjustMenuListButtonStyle(style);
    case kSliderThumbHorizontalPart:
    case kSliderThumbVerticalPart:
      return AdjustSliderThumbStyle(style);
    case kSearchFieldCancelButtonPart:
      return AdjustSearchFieldCancelButtonStyle(style);
    default:
      break;
  }

  if (IsSliderContainer(*element))
    AdjustSliderContainerStyle(*element, style);
}

String LayoutTheme::ExtraDefaultStyleSheet() {
  return g_empty_string;
}

String LayoutTheme::ExtraFullscreenStyleSheet() {
  return String();
}

Color LayoutTheme::ActiveSelectionBackgroundColor(
    mojom::blink::ColorScheme color_scheme) const {
  Color color = PlatformActiveSelectionBackgroundColor(color_scheme);
#if BUILDFLAG(IS_MAC)
  // BlendWithWhite() darkens Mac system colors too much.
  // Apply .8 (204/255) alpha instead, same as Safari.
  if (color_scheme == mojom::blink::ColorScheme::kDark)
    return Color(color.Red(), color.Green(), color.Blue(), 204);
#endif
  return color.BlendWithWhite();
}

Color LayoutTheme::InactiveSelectionBackgroundColor(
    mojom::blink::ColorScheme color_scheme) const {
  return PlatformInactiveSelectionBackgroundColor(color_scheme)
      .BlendWithWhite();
}

Color LayoutTheme::ActiveSelectionForegroundColor(
    mojom::blink::ColorScheme color_scheme) const {
  return PlatformActiveSelectionForegroundColor(color_scheme);
}

Color LayoutTheme::InactiveSelectionForegroundColor(
    mojom::blink::ColorScheme color_scheme) const {
  return PlatformInactiveSelectionForegroundColor(color_scheme);
}

Color LayoutTheme::ActiveListBoxSelectionBackgroundColor(
    mojom::blink::ColorScheme color_scheme) const {
  return PlatformActiveListBoxSelectionBackgroundColor(color_scheme);
}

Color LayoutTheme::InactiveListBoxSelectionBackgroundColor(
    mojom::blink::ColorScheme color_scheme) const {
  return PlatformInactiveListBoxSelectionBackgroundColor(color_scheme);
}

Color LayoutTheme::ActiveListBoxSelectionForegroundColor(
    mojom::blink::ColorScheme color_scheme) const {
  return PlatformActiveListBoxSelectionForegroundColor(color_scheme);
}

Color LayoutTheme::InactiveListBoxSelectionForegroundColor(
    mojom::blink::ColorScheme color_scheme) const {
  return PlatformInactiveListBoxSelectionForegroundColor(color_scheme);
}

Color LayoutTheme::PlatformSpellingMarkerUnderlineColor() const {
  return Color(255, 0, 0);
}

Color LayoutTheme::PlatformGrammarMarkerUnderlineColor() const {
  return Color(192, 192, 192);
}

Color LayoutTheme::PlatformActiveSpellingMarkerHighlightColor() const {
  return Color(255, 0, 0, 102);
}

Color LayoutTheme::PlatformActiveSelectionBackgroundColor(
    mojom::blink::ColorScheme color_scheme) const {
  // Use a blue color by default if the platform theme doesn't define anything.
  return Color(0, 0, 255);
}

Color LayoutTheme::PlatformActiveSelectionForegroundColor(
    mojom::blink::ColorScheme color_scheme) const {
  // Use a white color by default if the platform theme doesn't define anything.
  return Color::kWhite;
}

Color LayoutTheme::PlatformInactiveSelectionBackgroundColor(
    mojom::blink::ColorScheme color_scheme) const {
  // Use a grey color by default if the platform theme doesn't define anything.
  // This color matches Firefox's inactive color.
  return Color(176, 176, 176);
}

Color LayoutTheme::PlatformInactiveSelectionForegroundColor(
    mojom::blink::ColorScheme color_scheme) const {
  // Use a black color by default.
  return Color::kBlack;
}

Color LayoutTheme::PlatformActiveListBoxSelectionBackgroundColor(
    mojom::blink::ColorScheme color_scheme) const {
  return PlatformActiveSelectionBackgroundColor(color_scheme);
}

Color LayoutTheme::PlatformActiveListBoxSelectionForegroundColor(
    mojom::blink::ColorScheme color_scheme) const {
  return PlatformActiveSelectionForegroundColor(color_scheme);
}

Color LayoutTheme::PlatformInactiveListBoxSelectionBackgroundColor(
    mojom::blink::ColorScheme color_scheme) const {
  return PlatformInactiveSelectionBackgroundColor(color_scheme);
}

Color LayoutTheme::PlatformInactiveListBoxSelectionForegroundColor(
    mojom::blink::ColorScheme color_scheme) const {
  return PlatformInactiveSelectionForegroundColor(color_scheme);
}

bool LayoutTheme::IsControlStyled(ControlPart part,
                                  const ComputedStyle& style) const {
  switch (part) {
    case kPushButtonPart:
    case kSquareButtonPart:
    case kButtonPart:
    case kProgressBarPart:
      return style.HasAuthorBackground() || style.HasAuthorBorder();

    case kMenulistPart:
    case kSearchFieldPart:
    case kTextAreaPart:
    case kTextFieldPart:
      return style.HasAuthorBackground() || style.HasAuthorBorder() ||
             style.BoxShadow();

    default:
      return false;
  }
}

bool LayoutTheme::ShouldDrawDefaultFocusRing(const Node* node,
                                             const ComputedStyle& style) const {
  if (!node)
    return true;
  if (!style.HasEffectiveAppearance() && !node->IsLink())
    return true;
  // We can't use LayoutTheme::isFocused because outline:auto might be
  // specified to non-:focus rulesets.
  if (node->IsFocused() && !node->ShouldHaveFocusAppearance())
    return false;
  return true;
}

void LayoutTheme::AdjustCheckboxStyle(ComputedStyle& style) const {
  // padding - not honored by WinIE, needs to be removed.
  style.ResetPadding();

  // border - honored by WinIE, but looks terrible (just paints in the control
  // box and turns off the Windows XP theme) for now, we will not honor it.
  style.ResetBorder();
}

void LayoutTheme::AdjustRadioStyle(ComputedStyle& style) const {
  // padding - not honored by WinIE, needs to be removed.
  style.ResetPadding();

  // border - honored by WinIE, but looks terrible (just paints in the control
  // box and turns off the Windows XP theme) for now, we will not honor it.
  style.ResetBorder();
}

void LayoutTheme::AdjustButtonStyle(ComputedStyle& style) const {}

void LayoutTheme::AdjustInnerSpinButtonStyle(ComputedStyle&) const {}

void LayoutTheme::AdjustMenuListStyle(ComputedStyle& style) const {
  // Menulists should have visible overflow
  // https://bugs.webkit.org/show_bug.cgi?id=21287
  style.SetOverflowX(EOverflow::kVisible);
  style.SetOverflowY(EOverflow::kVisible);
}

void LayoutTheme::AdjustMenuListButtonStyle(ComputedStyle&) const {}

void LayoutTheme::AdjustSliderContainerStyle(const Element& element,
                                             ComputedStyle& style) const {
  DCHECK(IsSliderContainer(element));

  if (style.EffectiveAppearance() == kSliderVerticalPart) {
    style.SetTouchAction(TouchAction::kPanX);
    style.SetWritingMode(WritingMode::kVerticalRl);
    // It's always in RTL because the slider value increases up even in LTR.
    style.SetDirection(TextDirection::kRtl);
  } else {
    style.SetTouchAction(TouchAction::kPanY);
    style.SetWritingMode(WritingMode::kHorizontalTb);
    if (To<HTMLInputElement>(element.OwnerShadowHost())->list()) {
      style.SetAlignSelf(StyleSelfAlignmentData(ItemPosition::kCenter,
                                                OverflowAlignment::kUnsafe));
    }
  }
  style.SetEffectiveAppearance(kNoControlPart);
}

void LayoutTheme::AdjustSliderThumbStyle(ComputedStyle& style) const {
  AdjustSliderThumbSize(style);
}

void LayoutTheme::AdjustSliderThumbSize(ComputedStyle&) const {}

void LayoutTheme::AdjustSearchFieldCancelButtonStyle(ComputedStyle&) const {}

void LayoutTheme::PlatformColorsDidChange() {
  UpdateForcedColorsState();
  Page::PlatformColorsChanged();
}

void LayoutTheme::ColorSchemeDidChange() {
  Page::ColorSchemeChanged();
}

void LayoutTheme::ColorProvidersDidChange() {
  Page::ColorProvidersChanged();
}

void LayoutTheme::SetCaretBlinkInterval(base::TimeDelta interval) {
  caret_blink_interval_ = interval;
}

base::TimeDelta LayoutTheme::CaretBlinkInterval() const {
  // Disable the blinking caret in web test mode, as it introduces
  // a race condition for the pixel tests. http://b/1198440
  return WebTestSupport::IsRunningWebTest() ? base::TimeDelta()
                                            : caret_blink_interval_;
}

static FontDescription& GetCachedFontDescription(CSSValueID system_font_id) {
  DEFINE_STATIC_LOCAL(FontDescription, caption, ());
  DEFINE_STATIC_LOCAL(FontDescription, icon, ());
  DEFINE_STATIC_LOCAL(FontDescription, menu, ());
  DEFINE_STATIC_LOCAL(FontDescription, message_box, ());
  DEFINE_STATIC_LOCAL(FontDescription, small_caption, ());
  DEFINE_STATIC_LOCAL(FontDescription, status_bar, ());
  DEFINE_STATIC_LOCAL(FontDescription, webkit_mini_control, ());
  DEFINE_STATIC_LOCAL(FontDescription, webkit_small_control, ());
  DEFINE_STATIC_LOCAL(FontDescription, webkit_control, ());
  DEFINE_STATIC_LOCAL(FontDescription, default_description, ());
  switch (system_font_id) {
    case CSSValueID::kCaption:
      return caption;
    case CSSValueID::kIcon:
      return icon;
    case CSSValueID::kMenu:
      return menu;
    case CSSValueID::kMessageBox:
      return message_box;
    case CSSValueID::kSmallCaption:
      return small_caption;
    case CSSValueID::kStatusBar:
      return status_bar;
    case CSSValueID::kWebkitMiniControl:
      return webkit_mini_control;
    case CSSValueID::kWebkitSmallControl:
      return webkit_small_control;
    case CSSValueID::kWebkitControl:
      return webkit_control;
    case CSSValueID::kNone:
      return default_description;
    default:
      NOTREACHED();
      return default_description;
  }
}

void LayoutTheme::SystemFont(CSSValueID system_font_id,
                             FontDescription& font_description,
                             const Document* document) {
  font_description = GetCachedFontDescription(system_font_id);
  if (font_description.IsAbsoluteSize())
    return;

  font_description.SetStyle(
      LayoutThemeFontProvider::SystemFontStyle(system_font_id));
  font_description.SetWeight(
      LayoutThemeFontProvider::SystemFontWeight(system_font_id));
  font_description.SetSpecifiedSize(
      LayoutThemeFontProvider::SystemFontSize(system_font_id, document));
  font_description.SetIsAbsoluteSize(true);
  const AtomicString& system_font =
      LayoutThemeFontProvider::SystemFontFamily(system_font_id);
  font_description.FirstFamily().SetFamily(
      system_font, FontFamily::InferredTypeFor(system_font));
  font_description.SetGenericFamily(FontDescription::kNoFamily);
}

Color LayoutTheme::SystemColor(CSSValueID css_value_id,
                               mojom::blink::ColorScheme color_scheme) const {
  if (!WebTestSupport::IsRunningWebTest() && InForcedColorsMode())
    return SystemColorFromNativeTheme(css_value_id, color_scheme);
  return DefaultSystemColor(css_value_id, color_scheme);
}

Color LayoutTheme::DefaultSystemColor(
    CSSValueID css_value_id,
    mojom::blink::ColorScheme color_scheme) const {
  // The source for the deprecations commented on below is
  // https://www.w3.org/TR/css-color-4/#deprecated-system-colors.

  switch (css_value_id) {
    case CSSValueID::kActivetext:
      return Color::FromRGBA32(0xFFFF0000);
    case CSSValueID::kButtonborder:
    // The following system colors were deprecated to default to ButtonBorder.
    case CSSValueID::kActiveborder:
    case CSSValueID::kInactiveborder:
    case CSSValueID::kThreeddarkshadow:
    case CSSValueID::kThreedhighlight:
    case CSSValueID::kThreedlightshadow:
    case CSSValueID::kThreedshadow:
    case CSSValueID::kWindowframe:
      return color_scheme == mojom::blink::ColorScheme::kDark
                 ? Color::FromRGBA32(0xFF6B6B6B)
                 : Color::FromRGBA32(0xFF767676);
    case CSSValueID::kButtonface:
    // The following system colors were deprecated to default to ButtonFace.
    case CSSValueID::kButtonhighlight:
    case CSSValueID::kButtonshadow:
    case CSSValueID::kThreedface:
      return color_scheme == mojom::blink::ColorScheme::kDark
                 ? Color::FromRGBA32(0xFF6B6B6B)
                 : Color::FromRGBA32(0xFFEFEFEF);
    case CSSValueID::kButtontext:
      return color_scheme == mojom::blink::ColorScheme::kDark
                 ? Color::FromRGBA32(0xFFFFFFFF)
                 : Color::FromRGBA32(0xFF000000);
    case CSSValueID::kCanvas:
    // The following system colors were deprecated to default to Canvas.
    case CSSValueID::kAppworkspace:
    case CSSValueID::kBackground:
    case CSSValueID::kInactivecaption:
    case CSSValueID::kInfobackground:
    case CSSValueID::kMenu:
    case CSSValueID::kScrollbar:
    case CSSValueID::kWindow:
      return color_scheme == mojom::blink::ColorScheme::kDark
                 ? Color::FromRGBA32(0xFF121212)
                 : Color::FromRGBA32(0xFFFFFFFF);
    case CSSValueID::kCanvastext:
    // The following system colors were deprecated to default to CanvasText.
    case CSSValueID::kActivecaption:
    case CSSValueID::kCaptiontext:
    case CSSValueID::kInfotext:
    case CSSValueID::kMenutext:
    case CSSValueID::kWindowtext:
      return color_scheme == mojom::blink::ColorScheme::kDark
                 ? Color::FromRGBA32(0xFFFFFFFF)
                 : Color::FromRGBA32(0xFF000000);

    case CSSValueID::kField:
      return color_scheme == mojom::blink::ColorScheme::kDark
                 ? Color::FromRGBA32(0xFF3B3B3B)
                 : Color::FromRGBA32(0xFFFFFFFF);
    case CSSValueID::kFieldtext:
      return color_scheme == mojom::blink::ColorScheme::kDark
                 ? Color::FromRGBA32(0xFFFFFFFF)
                 : Color::FromRGBA32(0xFF000000);
    case CSSValueID::kGraytext:
    // The following system color was deprecated to default to GrayText.
    case CSSValueID::kInactivecaptiontext:
      return Color::FromRGBA32(0xFF808080);
    case CSSValueID::kHighlight:
      return Color::FromRGBA32(0xFFB5D5FF);
    case CSSValueID::kHighlighttext:
      return color_scheme == mojom::blink::ColorScheme::kDark
                 ? Color::FromRGBA32(0xFFFFFFFF)
                 : Color::FromRGBA32(0xFF000000);
    case CSSValueID::kLinktext:
      return Color::FromRGBA32(0xFF0000EE);
    case CSSValueID::kMark:
      return Color::FromRGBA32(0xFFFFFF00);
    case CSSValueID::kMarktext:
      return Color::FromRGBA32(0xFF000000);
    case CSSValueID::kText:
      return color_scheme == mojom::blink::ColorScheme::kDark
                 ? Color::FromRGBA32(0xFFFFFFFF)
                 : Color::FromRGBA32(0xFF000000);
    case CSSValueID::kVisitedtext:
      return Color::FromRGBA32(0xFF551A8B);
    case CSSValueID::kSelecteditem:
    case CSSValueID::kInternalActiveListBoxSelection:
      return ActiveListBoxSelectionBackgroundColor(color_scheme);
    case CSSValueID::kSelecteditemtext:
    case CSSValueID::kInternalActiveListBoxSelectionText:
      return ActiveListBoxSelectionForegroundColor(color_scheme);
    case CSSValueID::kInternalInactiveListBoxSelection:
      return InactiveListBoxSelectionBackgroundColor(color_scheme);
    case CSSValueID::kInternalInactiveListBoxSelectionText:
      return InactiveListBoxSelectionForegroundColor(color_scheme);
    case CSSValueID::kInternalSpellingErrorColor:
      return PlatformSpellingMarkerUnderlineColor();
    case CSSValueID::kInternalGrammarErrorColor:
      return PlatformGrammarMarkerUnderlineColor();
    default:
      break;
  }
  NOTREACHED();
  return Color();
}

Color LayoutTheme::SystemColorFromNativeTheme(
    CSSValueID css_value_id,
    mojom::blink::ColorScheme color_scheme) const {
  blink::WebThemeEngine::SystemThemeColor theme_color;
  switch (css_value_id) {
    case CSSValueID::kActivetext:
    case CSSValueID::kLinktext:
    case CSSValueID::kVisitedtext:
      theme_color = blink::WebThemeEngine::SystemThemeColor::kHotlight;
      break;
    case CSSValueID::kButtonface:
    case CSSValueID::kButtonhighlight:
    case CSSValueID::kButtonshadow:
    case CSSValueID::kThreedface:
      theme_color = blink::WebThemeEngine::SystemThemeColor::kButtonFace;
      break;
    case CSSValueID::kButtonborder:
    case CSSValueID::kButtontext:
    // Deprecated colors, see DefaultSystemColor().
    case CSSValueID::kActiveborder:
    case CSSValueID::kInactiveborder:
    case CSSValueID::kThreeddarkshadow:
    case CSSValueID::kThreedhighlight:
    case CSSValueID::kThreedlightshadow:
    case CSSValueID::kThreedshadow:
    case CSSValueID::kWindowframe:
      theme_color = blink::WebThemeEngine::SystemThemeColor::kButtonText;
      break;
    case CSSValueID::kGraytext:
      theme_color = blink::WebThemeEngine::SystemThemeColor::kGrayText;
      break;
    case CSSValueID::kHighlight:
      theme_color = blink::WebThemeEngine::SystemThemeColor::kHighlight;
      break;
    case CSSValueID::kHighlighttext:
      theme_color = blink::WebThemeEngine::SystemThemeColor::kHighlightText;
      break;
    case CSSValueID::kCanvas:
    case CSSValueID::kField:
    // Deprecated colors, see DefaultSystemColor().
    case CSSValueID::kAppworkspace:
    case CSSValueID::kBackground:
    case CSSValueID::kInactivecaption:
    case CSSValueID::kInfobackground:
    case CSSValueID::kMenu:
    case CSSValueID::kScrollbar:
    case CSSValueID::kWindow:
      theme_color = blink::WebThemeEngine::SystemThemeColor::kWindow;
      break;
    case CSSValueID::kCanvastext:
    case CSSValueID::kFieldtext:
    // Deprecated colors, see DefaultSystemColor().
    case CSSValueID::kActivecaption:
    case CSSValueID::kCaptiontext:
    case CSSValueID::kInfotext:
    case CSSValueID::kMenutext:
    case CSSValueID::kWindowtext:
      theme_color = blink::WebThemeEngine::SystemThemeColor::kWindowText;
      break;
    default:
      return DefaultSystemColor(css_value_id, color_scheme);
  }
  const absl::optional<SkColor> system_color =
      WebThemeEngineHelper::GetNativeThemeEngine()->GetSystemColor(theme_color);
  if (system_color)
    return Color::FromSkColor((system_color.value()));
  return DefaultSystemColor(css_value_id, color_scheme);
}

Color LayoutTheme::PlatformTextSearchHighlightColor(
    bool active_match,
    mojom::blink::ColorScheme color_scheme) const {
  if (active_match) {
    if (InForcedColorsMode())
      return GetTheme().SystemColor(CSSValueID::kHighlight, color_scheme);
    return Color(255, 150, 50);  // Orange.
  }
  return Color(255, 255, 0);     // Yellow.
}

Color LayoutTheme::PlatformTextSearchColor(
    bool active_match,
    mojom::blink::ColorScheme color_scheme) const {
  if (InForcedColorsMode() && active_match)
    return GetTheme().SystemColor(CSSValueID::kHighlighttext, color_scheme);
  return Color::kBlack;
}

Color LayoutTheme::TapHighlightColor() {
  return GetTheme().PlatformTapHighlightColor();
}

void LayoutTheme::SetCustomFocusRingColor(const Color& c) {
  custom_focus_ring_color_ = c;
  has_custom_focus_ring_color_ = true;
}

Color LayoutTheme::FocusRingColor(
    mojom::blink::ColorScheme color_scheme) const {
  return has_custom_focus_ring_color_ ? custom_focus_ring_color_
                                      : GetTheme().PlatformFocusRingColor();
}

bool LayoutTheme::DelegatesMenuListRendering() const {
  return delegates_menu_list_rendering_;
}

void LayoutTheme::SetDelegatesMenuListRenderingForTesting(bool flag) {
  delegates_menu_list_rendering_ = flag;
}

String LayoutTheme::DisplayNameForFile(const File& file) const {
  return file.name();
}

bool LayoutTheme::SupportsCalendarPicker(const AtomicString& type) const {
  DCHECK(RuntimeEnabledFeatures::InputMultipleFieldsUIEnabled());
  if (type == input_type_names::kTime)
    return true;

  return type == input_type_names::kDate ||
         type == input_type_names::kDatetime ||
         type == input_type_names::kDatetimeLocal ||
         type == input_type_names::kMonth || type == input_type_names::kWeek;
}

void LayoutTheme::AdjustControlPartStyle(ComputedStyle& style) {
  // Call the appropriate style adjustment method based off the appearance
  // value.
  switch (style.EffectiveAppearance()) {
    case kCheckboxPart:
      return AdjustCheckboxStyle(style);
    case kRadioPart:
      return AdjustRadioStyle(style);
    case kPushButtonPart:
    case kSquareButtonPart:
    case kButtonPart:
      return AdjustButtonStyle(style);
    case kInnerSpinButtonPart:
      return AdjustInnerSpinButtonStyle(style);
    default:
      break;
  }
}

bool LayoutTheme::HasCustomFocusRingColor() const {
  return has_custom_focus_ring_color_;
}

Color LayoutTheme::GetCustomFocusRingColor() const {
  return custom_focus_ring_color_;
}

void LayoutTheme::UpdateForcedColorsState() {
  in_forced_colors_mode_ =
      WebThemeEngineHelper::GetNativeThemeEngine()->GetForcedColors() !=
      ForcedColors::kNone;
}

}  // namespace blink


text:
package rkeworkerupgrader

import (
	"context"
	"fmt"
	"strings"
	"time"

	"github.com/moby/locker"
	v32 "github.com/rancher/rancher/pkg/apis/management.cattle.io/v3"
	"github.com/rancher/rancher/pkg/controllers/management/clusterprovisioner"
	v1 "github.com/rancher/rancher/pkg/generated/norman/core/v1"
	v3 "github.com/rancher/rancher/pkg/generated/norman/management.cattle.io/v3"
	nodehelper "github.com/rancher/rancher/pkg/node"
	nodeserver "github.com/rancher/rancher/pkg/rkenodeconfigserver"
	"github.com/rancher/rancher/pkg/systemaccount"
	"github.com/rancher/rancher/pkg/types/config"
	rkedefaults "github.com/rancher/rke/cluster"
	rketypes "github.com/rancher/rke/types"
	"github.com/rancher/rke/util"
	"github.com/sirupsen/logrus"
	"golang.org/x/sync/errgroup"
	"k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/util/intstr"
	"k8s.io/apimachinery/pkg/util/wait"
)

type upgradeHandler struct {
	clusters             v3.ClusterInterface
	nodes                v3.NodeInterface
	nodeLister           v3.NodeLister
	clusterLister        v3.ClusterLister
	secretLister         v1.SecretLister
	lookup               *nodeserver.BundleLookup
	systemAccountManager *systemaccount.Manager
	serviceOptionsLister v3.RkeK8sServiceOptionLister
	serviceOptions       v3.RkeK8sServiceOptionInterface
	sysImagesLister      v3.RkeK8sSystemImageLister
	sysImages            v3.RkeK8sSystemImageInterface
	clusterLock          *locker.Locker
	ctx                  context.Context
}

func Register(ctx context.Context, mgmt *config.ManagementContext, scaledContext *config.ScaledContext) {

	uh := &upgradeHandler{
		clusters:             mgmt.Management.Clusters(""),
		clusterLister:        mgmt.Management.Clusters("").Controller().Lister(),
		nodes:                mgmt.Management.Nodes(""),
		nodeLister:           mgmt.Management.Nodes("").Controller().Lister(),
		secretLister:         mgmt.Core.Secrets("").Controller().Lister(),
		lookup:               nodeserver.NewLookup(scaledContext.Core.Namespaces(""), scaledContext.Core),
		systemAccountManager: systemaccount.NewManagerFromScale(scaledContext),
		serviceOptionsLister: mgmt.Management.RkeK8sServiceOptions("").Controller().Lister(),
		serviceOptions:       mgmt.Management.RkeK8sServiceOptions(""),
		sysImagesLister:      mgmt.Management.RkeK8sSystemImages("").Controller().Lister(),
		sysImages:            mgmt.Management.RkeK8sSystemImages(""),
		clusterLock:          locker.New(),
		ctx:                  ctx,
	}

	mgmt.Management.Nodes("").Controller().AddHandler(ctx, "rke-worker-upgrader", uh.Sync)
}

func (uh *upgradeHandler) Sync(key string, node *v3.Node) (runtime.Object, error) {
	if strings.HasSuffix(key, "upgrade_") {

		cName := strings.Split(key, "/")[0]
		// provisioner.go updates cluster's AppliedSpec and then enqueues "upgrade_" key to call this sync.
		// Node plan gets calculated using cluster's AppliedSpec, so fetch the object from db instead of Lister to avoid race.
		cluster, err := uh.clusters.Get(cName, metav1.GetOptions{})
		if err != nil {
			return nil, err
		}
		if cluster.DeletionTimestamp != nil || cluster.Status.AppliedSpec.RancherKubernetesEngineConfig == nil {
			return nil, nil
		}

		if cluster.Annotations[clusterprovisioner.RkeRestoreAnnotation] == "true" {
			// rke completed etcd snapshot restore, need to update plan for nodes so worker nodes reset to old rkeConfig
			return node, uh.restore(cluster)
		}

		logrus.Infof("checking cluster [%s] for worker nodes upgrade", cluster.Name)

		if toUpgrade, planChanged, err := uh.toUpgradeCluster(cluster); err != nil {
			return nil, err
		} else if toUpgrade {
			if err := uh.upgradeCluster(cluster, key, planChanged); err != nil {
				return nil, err
			}
		}

		return nil, nil
	}

	if node == nil || node.DeletionTimestamp != nil || !v32.NodeConditionProvisioned.IsTrue(node) {
		return node, nil
	}

	cluster, err := uh.clusterLister.Get("", node.Namespace)
	if err != nil {
		return nil, err
	}

	if cluster.DeletionTimestamp != nil || cluster.Status.AppliedSpec.RancherKubernetesEngineConfig == nil {
		return node, nil
	}

	if node.Status.NodePlan == nil {
		return uh.updateNodePlan(node, cluster, true)
	}

	if v32.ClusterConditionUpdated.IsUnknown(cluster) || cluster.Annotations[clusterprovisioner.RkeRestoreAnnotation] == "true" {
		return node, nil
	}

	if v32.ClusterConditionUpgraded.IsUnknown(cluster) {
		// if sync is for a node that was just updated, do nothing

		// node is already updated to cordon/drain/uncordon, do nothing
		if node.Spec.DesiredNodeUnschedulable != "" {
			logrus.Debugf("cluster [%s] worker-upgrade: return node [%s], unschedulable field [%v]", cluster.Name,
				node.Name, node.Spec.DesiredNodeUnschedulable)
			return node, nil
		}
		// node is upgrading and already updated with new node plan, do nothing
		if v32.NodeConditionUpgraded.IsUnknown(node) && node.Status.AppliedNodeVersion != cluster.Status.NodeVersion {
			if node.Status.NodePlan.Version == cluster.Status.NodeVersion {
				logrus.Debugf("cluster [%s] worker-upgrade: return node [%s], plan's updated [%v]", cluster.Name,
					node.Name, cluster.Status.NodeVersion)
				return node, nil
			}
		}

		logrus.Infof("cluster [%s] worker-upgrade: call upgrade to reconcile for node [%s]", cluster.Name, node.Name)
		if err := uh.upgradeCluster(cluster, node.Name, false); err != nil {
			return nil, err
		}
		return node, nil
	}

	// proceed only if node and cluster's versions mismatch
	if cluster.Status.NodeVersion == node.Status.NodePlan.Version {
		return node, nil
	}

	nodePlan, err := uh.getNodePlan(node, cluster)
	if err != nil {
		return nil, err
	}

	if node.Status.AppliedNodeVersion == 0 {
		// node never received appliedNodeVersion
		if planChangedForUpgrade(nodePlan, node.Status.NodePlan.Plan) || planChangedForUpdate(nodePlan, node.Status.NodePlan.Plan) {
			return uh.updateNodePlan(node, cluster, false)
		}
	} else {
		if planChangedForUpdate(nodePlan, node.Status.NodePlan.Plan) {
			logrus.Infof("cluster [%s] worker-upgrade: plan changed for update [%s]", cluster.Name, node.Name)
			return uh.updateNodePlan(node, cluster, false)
		}
	}

	return node, nil
}

func (uh *upgradeHandler) updateNodePlan(node *v3.Node, cluster *v3.Cluster, create bool) (*v3.Node, error) {
	if node.Status.NodeConfig == nil || node.Status.DockerInfo == nil {
		logrus.Debugf("cluster [%s] worker-upgrade: node [%s] waiting for node status sync: "+
			"nodeConfigNil [%v] dockerInfoNil [%v]", cluster.Name, node.Name, node.Status.NodeConfig == nil, node.Status.DockerInfo == nil)
		// can't create correct node plan if node config or docker info hasn't been set
		return node, nil
	}
	nodePlan, err := uh.getNodePlan(node, cluster)
	if err != nil {
		return nil, fmt.Errorf("getNodePlan error for node [%s]: %v", node.Name, err)
	}

	nodeCopy := node.DeepCopy()
	np := &v32.NodePlan{
		Plan:    nodePlan,
		Version: cluster.Status.NodeVersion,
	}
	if node.Status.NodePlan == nil || node.Status.NodePlan.AgentCheckInterval == 0 {
		// default
		np.AgentCheckInterval = nodeserver.DefaultAgentCheckInterval
	} else {
		np.AgentCheckInterval = node.Status.NodePlan.AgentCheckInterval
	}
	nodeCopy.Status.NodePlan = np

	updated, err := uh.nodes.Update(nodeCopy)
	if err != nil {
		return nil, fmt.Errorf("error updating node [%s] with plan %v", node.Name, err)
	}

	if create {
		logrus.Debugf("cluster [%s]: created node plan for node [%s]", cluster.Name, node.Name)
	} else {
		logrus.Debugf("cluster [%s] worker-upgrade: updated node [%s] with plan [%v]", cluster.Name, node.Name, np.Version)
	}

	return updated, err
}

func (uh *upgradeHandler) updateNodePlanVersion(node *v3.Node, cluster *v3.Cluster) (*v3.Node, error) {
	nodeCopy := node.DeepCopy()
	nodeCopy.Status.NodePlan.Version = cluster.Status.NodeVersion
	logrus.Infof("cluster [%s] worker-upgrade: updating node [%s] with plan version [%v]", cluster.Name,
		node.Name, nodeCopy.Status.NodePlan.Version)

	updated, err := uh.nodes.Update(nodeCopy)
	if err != nil {
		return nil, err
	}
	return updated, err

}

func (uh *upgradeHandler) getNodePlan(node *v3.Node, cluster *v3.Cluster) (*rketypes.RKEConfigNodePlan, error) {
	var (
		nodePlan *rketypes.RKEConfigNodePlan
		err      error
	)
	if nodehelper.IsNonWorker(node.Status.NodeConfig) {
		nodePlan, err = uh.nonWorkerPlan(node, cluster)
	} else {
		nodePlan, err = uh.workerPlan(node, cluster)
	}
	return nodePlan, err
}

func (uh *upgradeHandler) upgradeCluster(cluster *v3.Cluster, nodeName string, planChanged bool) error {
	clusterName := cluster.Name

	uh.clusterLock.Lock(clusterName)
	defer uh.clusterLock.Unlock(clusterName)

	logrus.Debugf("cluster [%s] upgrading condition: [%v] plan changed: [%v]", clusterName, v32.ClusterConditionUpgraded.IsUnknown(cluster), planChanged)

	var (
		clusterCopy *v3.Cluster
		err         error
	)
	if !v32.ClusterConditionUpgraded.IsUnknown(cluster) || planChanged {
		clusterCopy = cluster.DeepCopy()
		v32.ClusterConditionUpgraded.Unknown(clusterCopy)
		v32.ClusterConditionUpgraded.Message(clusterCopy, "updating worker nodes")
		clusterCopy.Status.NodeVersion++
	}
	if cluster.Status.AppliedSpec.RancherKubernetesEngineConfig.UpgradeStrategy == nil {
		if clusterCopy == nil {
			clusterCopy = cluster.DeepCopy()
		}
		clusterCopy.Status.AppliedSpec.RancherKubernetesEngineConfig.UpgradeStrategy = &rketypes.NodeUpgradeStrategy{
			MaxUnavailableWorker:       rkedefaults.DefaultMaxUnavailableWorker,
			MaxUnavailableControlplane: rkedefaults.DefaultMaxUnavailableControlplane,
			Drain:                      func() *bool { b := false; return &b }(),
		}
	}
	if clusterCopy != nil {
		cluster, err = uh.clusters.Update(clusterCopy)
		if err != nil {
			return err
		}
		logrus.Infof("cluster [%s] worker-upgrade: updated cluster nodeVersion [%v] upgradeStrategy [%v] ", clusterName,
			clusterCopy.Status.NodeVersion, cluster.Status.AppliedSpec.RancherKubernetesEngineConfig.UpgradeStrategy)
	}

	logrus.Debugf("cluster [%s] worker-upgrade cluster status node version [%v]", clusterName, cluster.Status.NodeVersion)
	nodes, err := uh.nodeLister.List(clusterName, labels.Everything())
	if err != nil {
		return err
	}

	upgradeStrategy := cluster.Status.AppliedSpec.RancherKubernetesEngineConfig.UpgradeStrategy
	toDrain := upgradeStrategy.Drain != nil && *upgradeStrategy.Drain

	// get current upgrade status of nodes
	status := uh.filterNodes(nodes, cluster.Status.NodeVersion, toDrain)

	maxAllowed, err := CalculateMaxUnavailable(upgradeStrategy.MaxUnavailableWorker, status.filtered)
	if err != nil {
		return err
	}

	logrus.Debugf("cluster [%s] worker-upgrade: workerNodeInfo: nodes %v maxAllowed %v upgrading %v notReady %v "+
		"toProcess %v toPrepare %v done %v toUncordon %v", cluster.Name, status.filtered, maxAllowed, status.upgrading,
		keys(status.notReady), keys(status.toProcess), keys(status.toPrepare), keys(status.upgraded), keys(status.toUncordon))

	for _, node := range status.upgraded {
		if v32.NodeConditionUpgraded.IsTrue(node) {
			continue
		}

		if err := uh.updateNodeActive(node); err != nil {
			return err
		}

		logrus.Infof("cluster [%s] worker-upgrade: updated node [%s] to uncordon", clusterName, node.Name)
	}

	for _, node := range status.toUncordon {
		if err := uh.updateNodeActive(node); err != nil {
			return err
		}
		logrus.Infof("cluster [%s] worker-upgrade: updated node [%s] to uncordon", clusterName, node.Name)
	}

	notReady := len(status.notReady)
	if notReady > maxAllowed {
		return fmt.Errorf("cluster [%s] worker-upgrade: not enough nodes to upgrade: nodes %v notReady %v maxUnavailable %v",
			clusterName, status.filtered, keys(status.notReady), maxAllowed)
	}

	if notReady > 0 {
		// update plan for unavailable nodes
		for _, node := range status.notReady {
			if node.Status.NodePlan.Version == cluster.Status.NodeVersion {
				continue
			}

			if err := uh.setNodePlan(node, cluster, false); err != nil {
				return err
			}

			logrus.Infof("cluster [%s] worker-upgrade: updated upgrading unavailable node [%s] with version %v",
				clusterName, node.Name, cluster.Status.NodeVersion)

		}
	}

	unavailable := status.upgrading + notReady

	if unavailable > maxAllowed {
		return fmt.Errorf("cluster [%s] worker-upgrade: more than allowed nodes upgrading for cluster: unavailable %v maxUnavailable %v",
			clusterName, unavailable, maxAllowed)
	}

	for _, node := range status.toProcess {
		if node.Status.NodePlan.Version == cluster.Status.NodeVersion {
			continue
		}

		if err := uh.setNodePlan(node, cluster, true); err != nil {
			return err
		}

		logrus.Infof("cluster [%s] worker-upgrade: updated node [%s] to upgrade", clusterName, node.Name)
	}

	var nodeDrainInput *rketypes.NodeDrainInput
	state := "cordon"
	if toDrain {
		nodeDrainInput = upgradeStrategy.DrainInput
		state = "drain"
	}

	for _, node := range status.toPrepare {
		if unavailable == maxAllowed {
			break
		}
		unavailable++

		if err := uh.prepareNode(node, toDrain, nodeDrainInput); err != nil {
			return err
		}

		logrus.Infof("cluster [%s] worker-upgrade: updated node [%s] to %s", clusterName, node.Name, state)
	}

	if status.done == status.filtered {
		logrus.Debugf("cluster [%s] worker-upgrade: cluster is done upgrading, done %v len(nodes) %v", clusterName, status.done, status.filtered)
		if !v32.ClusterConditionUpgraded.IsTrue(cluster) {
			clusterCopy := cluster.DeepCopy()
			v32.ClusterConditionUpgraded.True(clusterCopy)
			v32.ClusterConditionUpgraded.Message(clusterCopy, "")

			if _, err := uh.clusters.Update(clusterCopy); err != nil {
				return err
			}

			logrus.Infof("cluster [%s] worker-upgrade: finished upgrade", clusterName)
		}
	}

	return nil
}

func (uh *upgradeHandler) toUpgradeCluster(cluster *v3.Cluster) (bool, bool, error) {
	nodes, err := uh.nodeLister.List(cluster.Name, labels.Everything())
	if err != nil {
		return false, false, err
	}

	for _, node := range nodes {
		if node.Status.NodeConfig == nil {
			continue
		}

		if !workerOnly(node.Status.NodeConfig.Role) {
			continue
		}

		if node.Status.NodePlan == nil || v32.NodeConditionRegistered.IsUnknown(node) {
			// enqueue if node plan isn't initialized yet
			if node.Status.NodePlan == nil {
				uh.nodes.Controller().Enqueue(node.Namespace, node.Name)
			}
			// node's not yet registered, change in its node plan should do nothing for cluster upgrade
			continue
		}

		// if cluster's already upgrading, skip nodes that are yet to upgrade, planChangedForUpgrade will always be true
		if v32.ClusterConditionUpgraded.IsUnknown(cluster) && node.Status.AppliedNodeVersion != cluster.Status.NodeVersion {
			continue
		}

		nodePlan, err := uh.getNodePlan(node, cluster)
		if err != nil {
			return false, false, err
		}

		if planChangedForUpgrade(nodePlan, node.Status.NodePlan.Plan) {
			return true, true, nil
		}
	}

	if v32.ClusterConditionUpgraded.IsUnknown(cluster) {
		return true, false, nil
	}

	return false, false, nil
}

func (uh *upgradeHandler) restore(cluster *v3.Cluster) error {
	nodes, err := uh.nodeLister.List(cluster.Name, labels.Everything())
	if err != nil {
		return err
	}

	var errgrp errgroup.Group
	nodesQueue := util.GetObjectQueue(nodes)
	for w := 0; w < 5; w++ {
		errgrp.Go(func() error {
			var errList []error
			for node := range nodesQueue {
				node := node.(*v3.Node)
				if node.Status.NodeConfig != nil && workerOnly(node.Status.NodeConfig.Role) {
					if node.Status.NodePlan.Version != cluster.Status.NodeVersion {
						if err := uh.setNodePlan(node, cluster, false); err != nil {
							errList = append(errList, err)
						}
						logrus.Infof("cluster [%s]: updated node [%s] for restore, plan version [%v]", cluster.Name,
							node.Name, cluster.Status.NodeVersion)
					}
				}
			}
			return util.ErrList(errList)
		})
	}
	if err := errgrp.Wait(); err != nil {
		return err
	}

	toUpdate := getRestoredCluster(cluster.DeepCopy())
	if _, err := uh.clusters.Update(toUpdate); err != nil {
		if !errors.IsConflict(err) {
			return err
		}
		return uh.retryClusterUpdate(cluster.Name)
	}
	return nil
}

func getRestoredCluster(cluster *v3.Cluster) *v3.Cluster {
	cluster.Annotations[clusterprovisioner.RkeRestoreAnnotation] = "false"

	// if restore's for a cluster stuck in upgrading, update it as upgraded
	if v32.ClusterConditionUpgraded.IsUnknown(cluster) {
		v32.ClusterConditionUpgraded.True(cluster)
		v32.ClusterConditionUpgraded.Message(cluster, "restored worker nodes")
	}

	return cluster
}

func (uh *upgradeHandler) retryClusterUpdate(name string) error {
	backoff := wait.Backoff{
		Duration: 100 * time.Millisecond,
		Factor:   1,
		Jitter:   0,
		Steps:    7,
	}

	return wait.ExponentialBackoff(backoff, func() (bool, error) {
		cluster, err := uh.clusters.Get(name, metav1.GetOptions{})
		if err != nil {
			return false, err
		}
		if cluster.Annotations[clusterprovisioner.RkeRestoreAnnotation] != "false" {
			_, err = uh.clusters.Update(getRestoredCluster(cluster))
			if err != nil {
				logrus.Debugf("cluster [%s] restore: error resetting restore annotation %v", cluster.Name, err)
				if errors.IsConflict(err) {
					return false, nil
				}
				return false, err
			}
		}
		return true, nil
	})

}

func keys(nodes []*v3.Node) []string {
	keys := make([]string, len(nodes))
	for _, node := range nodes {
		keys = append(keys, node.Name)
	}
	return keys
}

func CalculateMaxUnavailable(maxUnavailable string, nodes int) (int, error) {
	parsedMax := intstr.Parse(maxUnavailable)
	maxAllowed, err := intstr.GetValueFromIntOrPercent(&parsedMax, nodes, false)
	if err != nil {
		return 0, err
	}
	if maxAllowed > 0 {
		return maxAllowed, nil
	}
	return 1, nil
}


text:
HTML Ipsum Presents

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis.

Header Level 2

Lorem ipsum dolor sit amet, consectetuer adipiscing elit.

Aliquam tincidunt mauris eu risus.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus magna. Cras in mi at felis aliquet congue. Ut a est eget ligula molestie gravida. Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis elit sit amet quam. Vivamus pretium ornare est.

Header Level 3

Lorem ipsum dolor sit amet, consectetuer adipiscing elit.

Aliquam tincidunt mauris eu risus.

    #header h1 a {
    display: block;
    width: 300px;
    height: 80px;
    }

Definition list

Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
        aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
        commodo consequat.

Lorem ipsum dolor sit amet

Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
        aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
        commodo consequat.


text:
package org.ndexbio.rest;

import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.List;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import java.util.logging.Logger;

import javax.servlet.ServletContext;

import org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher;
import org.ndexbio.common.access.NdexDatabase;
import org.ndexbio.common.models.dao.postgresql.TaskDAO;
import org.ndexbio.common.solr.GroupIndexManager;
import org.ndexbio.common.solr.NetworkGlobalIndexManager;
import org.ndexbio.common.solr.UserIndexManager;
import org.ndexbio.model.exceptions.NdexException;
import org.ndexbio.model.object.Task;
import org.ndexbio.task.ClientTaskProcessor;
import org.ndexbio.task.NdexServerQueue;
import org.ndexbio.task.NdexSystemTask;
import org.ndexbio.task.NdexTask;
import org.ndexbio.task.SystemTaskProcessor;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;

public class NdexHttpServletDispatcher extends HttpServletDispatcher {

    private static Logger logger = Logger.getLogger(NdexHttpServletDispatcher.class.getSimpleName());

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	private static final int defaultPoolSize = 10;
	private Thread  systemTaskProcessorThread;
	private Thread  clientTaskProcessorThread;
	private SystemTaskProcessor systemTaskProcessor;
	private ClientTaskProcessor clientTaskProcessor;

	private static String ndexVersion = "";
	private static String buildNumber  = "";

//	private final static String backupDB = "BACKUP_DATABASE";

	public NdexHttpServletDispatcher() {
		super();
	}

	@Override
	public void init(javax.servlet.ServletConfig servletConfig)
	          throws javax.servlet.ServletException {
		super.init(servletConfig);

		//Configuration configuration = null;
		try {
			Configuration configuration = Configuration.createInstance();

			String poolSize = configuration.getProperty("NdexDBConnectionPoolSize");
			int size = defaultPoolSize;
			try {
				if ( poolSize != null ) {
					size = Integer.parseInt(poolSize);
				}
			} catch (NumberFormatException e) {
				logger.warning("NdexDBConnectionPoolSize doesn't have a numeric value in configuration ("+
			e.getMessage() + "). Using default setting " + defaultPoolSize + " instead.");
			}

			//and initialize the db connections

			NdexDatabase.createNdexDatabase(
					configuration.getDBURL(),
	    			configuration.getDBUser(),
	    			configuration.getDBPasswd(), size);

			logger.info("Db created for " + configuration.getDBURL());

			// create solr core for network indexes if needed.
			try (NetworkGlobalIndexManager mgr = new NetworkGlobalIndexManager()) {
				mgr.createCoreIfNotExists();
			}
			try (UserIndexManager umgr = new UserIndexManager()) {
				umgr.createCoreIfNotExists();
			}
			try (GroupIndexManager gmgr = new GroupIndexManager()) {
				gmgr.createCoreIfNotExists();
			}

		/*	try (UserDocDAO dao = new UserDocDAO(db.getAConnection())) {

				String sysUserEmail = configuration.getProperty("NdexSystemUserEmail");
				Helper.createUserIfnotExist(dao, configuration.getSystmUserName(),
					(sysUserEmail == null? "support@ndexbio.org" : sysUserEmail),
    				configuration.getSystemUserPassword());
			} */

			// find tasks that needs to be processed in system queue
			populateQueuedTasksFromDB();

			systemTaskProcessor = new SystemTaskProcessor();
			clientTaskProcessor = new ClientTaskProcessor();
			systemTaskProcessorThread = new Thread(systemTaskProcessor);
			systemTaskProcessorThread.start();
			logger.info("System task executor started.");
			clientTaskProcessorThread = new Thread(clientTaskProcessor);
			clientTaskProcessorThread.start();
			logger.info("Client task executor started.");

			// setup the automatic backup
/*			 Timer timer = new Timer();
			 String dbNeedsBackup = configuration.getProperty(backupDB);
			 if ( dbNeedsBackup ==null || dbNeedsBackup.trim().equalsIgnoreCase("true") ) {
				 timer.scheduleAtFixedRate(new DatabaseBackupTask(),
					 DatabaseBackupTask.getTomorrowBackupTime(),
					 DatabaseBackupTask.fONCE_PER_DAY);
			 }
			 timer.scheduleAtFixedRate(new EmailNotificationTask(),
					 EmailNotificationTask.getTomorrowNotificationTime(),
					 EmailNotificationTask.fONCE_PER_DAY);
*/
			 //just for testing comment out when done.
		/*	 EmailNotificationTask e = new EmailNotificationTask();
			 e.run();
			 if ( e.getError() != null)
				 throw e.getError(); */

		} catch ( Exception e) {
			e.printStackTrace();
			throw new javax.servlet.ServletException("Failed to start Ndex server. Cause: " + e.getMessage(), e);
		}

		ServletContext application = getServletConfig().getServletContext();
		try(InputStream inputStream = application.getResourceAsStream("/META-INF/MANIFEST.MF")) {
		if ( inputStream !=null) {
		try {
			Manifest manifest = new Manifest(inputStream);

			Attributes aa = manifest.getMainAttributes();

			String ver = aa.getValue("NDEx-Version");
			String bui = aa.getValue("NDEx-Build");
			System.out.println("NDEx-Version: " + ver + ",Build:" + bui);
			buildNumber= bui.substring(0, 5);
			ndexVersion = ver;
		} catch (IOException e) {
			System.out.println("failed to read MANIFEST.MF:" + e.getMessage());
			e.printStackTrace();
		}
		}
		} catch (IOException e1) {
			System.out.println("Failed to close InputStream from MANIFEST.MF: " + e1.getMessage());
			e1.printStackTrace();
		}
	}

	@Override
	public void destroy() {

		logger.info("Shutting down ndex rest server.");
        try {

        	//signal the task queues and wait for them to finish.
        	clientTaskProcessor.shutdown();
        	systemTaskProcessor.shutdown();

        	NdexServerQueue.INSTANCE.shutdown();

        	logger.info("Waiting task processors to stop.");

        	systemTaskProcessorThread.join();
        	logger.info("System task processor stopped.");
        	clientTaskProcessorThread.join();

        	logger.info("Client task processors stopped. Closing database");

        	NdexDatabase.close();
		    logger.info ("Ndex Database connections have been closed.");
        } catch (Exception ee) {
            ee.printStackTrace();
            logger.info("Error occured when closing Ndex database connections.");
        }

        // revoke the googleTokens

      /*  GoogleOpenIDAuthenticator authenticator = BasicAuthenticationFilter.getGoogleOAuthAuthenticatior();
        try {
          authenticator.revokeAllTokens();
        } catch (Exception e)  {
        	logger.severe("Error occurred when revoking Google access tokens." + e.getMessage());
        } */
		super.destroy();
	}

/*	private static void populateSystemQueue() throws NdexException {
		try ( ODatabaseDocumentTx odb = NdexDatabase.getInstance().getAConnection()) {
			OSQLSynchQuery<ODocument> query = new OSQLSynchQuery<>(
		  			"SELECT FROM network where isDeleted = true");
			List<ODocument> records = odb.command(query).execute();
			for ( ODocument doc : records ) {
				String networkId = doc.field(NdexClasses.ExternalObj_ID);
				Task t = new Task();
				t.setResource(networkId);
				t.setTaskType(TaskType.SYSTEM_DELETE_NETWORK);
				NdexServerQueue.INSTANCE.addSystemTask(t);
			}
			logger.info (records.size() + " deleted network found for system task queue.");
		}
	} */

	private static void populateQueuedTasksFromDB() throws NdexException, SQLException, JsonParseException, JsonMappingException, IOException {
		try ( TaskDAO taskDAO = new TaskDAO()) {
			List<Task> list =taskDAO.getQueuedTasks();
			for ( Task t : list) {
				if ( t.getTaskOwnerId()!=null)
					NdexServerQueue.INSTANCE.addUserTask(NdexTask.createUserTask(t));
				else {
				   NdexSystemTask sysTask = NdexSystemTask.createSystemTask(t);
				   if (sysTask !=null) {
					   sysTask.setTaskId(t.getExternalId());
					   NdexServerQueue.INSTANCE.addSystemTaskToQueue(sysTask);
				   }
				}
			}
			logger.info (list.size() + " previously queued tasks were added to the queue.");
		}
	}

	public static String getNdexVersion() {
		return ndexVersion;
	}

	public static String getBuildNumber() {
		return buildNumber;
	}

}


text:
FROM sumeetchhetri/ffead-cpp-base:6.0
LABEL maintainer="Sumeet Chhetri"
LABEL version="6.0"
LABEL description="SQL Raw Custom libpq batch patched Base ffead-cpp docker image with commit id - master"

WORKDIR /tmp
RUN mkdir postgresql

COPY postgresql/* /tmp/postgresql/

#POSTGRESQL
WORKDIR /tmp/postgresql/

# prepare PostgreSQL APT repository
RUN apt-get -yqq update && apt-get -yqq install locales gnupg lsb-release

RUN wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | apt-key add -
RUN echo "deb http://apt.postgresql.org/pub/repos/apt/ `lsb_release -cs`-pgdg main" | tee  /etc/apt/sources.list.d/pgdg.list

ENV PG_VERSION 13
RUN locale-gen en_US.UTF-8
ENV LANG en_US.UTF-8
ENV LANGUAGE en_US:en
ENV LC_ALL en_US.UTF-8
ENV DEBIAN_FRONTEND noninteractive

# install postgresql on database machine
RUN apt-get -yqq update && apt-get -yqq install postgresql-13 postgresql-contrib-13 &&  rm -rf /var/lib/apt/lists/*

# Make sure all the configuration files in main belong to postgres
RUN mv postgresql.conf /etc/postgresql/${PG_VERSION}/main/postgresql.conf
RUN mv pg_hba.conf /etc/postgresql/${PG_VERSION}/main/pg_hba.conf

RUN chown -Rf postgres:postgres /etc/postgresql/${PG_VERSION}/main

RUN mkdir /ssd
RUN cp -R -p /var/lib/postgresql/${PG_VERSION}/main /ssd/postgresql
RUN cp /etc/postgresql/${PG_VERSION}/main/postgresql.conf /ssd/postgresql
RUN mv 60-postgresql-shm.conf /etc/sysctl.d/60-postgresql-shm.conf

RUN chown -Rf postgres:postgres /var/run/postgresql
RUN chmod 2777 /var/run/postgresql
RUN chown postgres:postgres /etc/sysctl.d/60-postgresql-shm.conf
RUN chown postgres:postgres create-postgres*
RUN chown -Rf postgres:postgres /ssd

ENV PGDATA=/ssd/postgresql

USER postgres

# We have to wait for postgres to start before we can use the cli
RUN service postgresql start && \
    until psql -c "\q"; do sleep 1; done && \
    psql < create-postgres-database.sql && \
    psql -a hello_world < create-postgres.sql && \
    service postgresql stop
#POSTGRESQL

USER root

#WRK
WORKDIR /tmp/wrk
RUN apt-get -yqq update && apt-get -yqq install libluajit-5.1-dev libssl-dev luajit && rm -rf /var/lib/apt/lists/* && \
	curl -sL https://github.com/wg/wrk/archive/4.1.0.tar.gz | tar xz --strip-components=1
ENV LDFLAGS="-O3 -march=native -flto"
ENV CFLAGS="-I /usr/include/luajit-2.1 $LDFLAGS"
RUN make WITH_LUAJIT=/usr WITH_OPENSSL=/usr -j "$(nproc)"
RUN cp wrk /usr/local/bin

ENV name name
ENV server_host server_host
ENV levels levels
ENV duration duration
ENV max_concurrency max_concurrency
ENV max_threads max_threads
ENV pipeline pipeline
ENV accept accept
#WRK

WORKDIR ${IROOT}

RUN sed -i 's|"TeBkUmLpqRouter"|"TeBkUmLpqRouterPicoV"|g' $IROOT/ffead-cpp-src/web/te-benchmark-um-pq/config/application.xml

COPY sql-profiled-util.sh ${IROOT}/
RUN chmod 755 ${IROOT}/sql-profiled-util.sh
RUN ./sql-profiled-util.sh batch clang noasync

COPY sql-profiled-install-clang.sh install_ffead-cpp-sql-raw-profiled.sh ${IROOT}/
RUN chmod 755 ${IROOT}/sql-profiled-install-clang.sh ${IROOT}/install_ffead-cpp-sql-raw-profiled.sh
RUN ./sql-profiled-install-clang.sh nocleanup

RUN apt update -yqq && apt install -y git make && rm -rf /var/lib/apt/lists/*
#For Latest vlang, uncomment the below mentioned line, due to lot of new enhancements and unsafe block handling, vlang has slowed down tremendously
#RUN git clone https://github.com/vlang/v && cd v && make && ./v symlink

#For the fastest vlang performance, use 0.1.29, where the unsafe changes were only restricted to pointer arithmetic
RUN wget -q https://github.com/vlang/v/releases/download/0.1.29/v_linux.zip && unzip -q v_linux.zip && cd v && chmod +x v && ./v symlink && cd .. && rm -f v_linux.zip

RUN rm -f /usr/local/lib/libffead-* /usr/local/lib/libte_benc* /usr/local/lib/libinter.so /usr/local/lib/libdinter.so && \
	ln -s ${IROOT}/ffead-cpp-6.0-sql/lib/libffead-modules.so /usr/local/lib/libffead-modules.so && \
	ln -s ${IROOT}/ffead-cpp-6.0-sql/lib/libffead-framework.so /usr/local/lib/libffead-framework.so && \
	ldconfig

COPY sql-v-picov-profiled-install.sh install_ffead-cpp-sql-raw-v-picov-profiled.sh ${IROOT}/
RUN chmod 755 ${IROOT}/sql-v-picov-profiled-install.sh ${IROOT}/install_ffead-cpp-sql-raw-v-picov-profiled.sh
RUN ./sql-v-picov-profiled-install.sh


text:
<?php

namespace BinSoul\Db\Definition;

/**
 * Represents an index of a database table.
 */
class Index
{
    /** @var string */
    private $name;
    /** @var string[] */
    private $columns;
    /** @var string */
    private $type;

    /**
     * Constructs an instance of this class.
     *
     * @param string   $name
     * @param string[] $columns
     * @param string   $type
     */
    public function __construct($name, array $columns, $type = '')
    {
        $this->name = $name;
        $this->columns = $columns;
        $this->type = $type;
    }

    /**
     * Returns the name of the index.
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Returns the columns of the index.
     *
     * @return string[]
     */
    public function getColumns()
    {
        return $this->columns;
    }

    /**
     * Returns the type of the index.
     *
     * @return string
     */
    public function getType()
    {
        return $this->type;
    }
}


text:
using System.Collections.Generic;
using System.Data.Entity;
using Moq;

namespace iQuarc.DataAccess.UnitTests.TestDoubles
{
    static class DbUtilities
    {
        public static DbSet<T> MockDbSet<T>(this IEnumerable<T> values) where T : class
        {
            return new FakeSet<T>(values);
        }

        public static DbSet<T> MockDbSet<T>(this IEnumerable<T> values, DbContextFakeWrapper wrapper) where T : class
        {
            return new FakeSet<T>(values, wrapper);
        }

        //TODO: write an overload for DbContextFakeWrapper
        public static IDbContextFactory BuildFactoryStub(this Mock<DbContext> contextStub)
        {
            Mock<IDbContextFactory> contextFactoryStub = new Mock<IDbContextFactory>();
            contextFactoryStub.Setup(s => s.CreateContext())
                              .Returns(new DbContextFakeWrapper(contextStub));
            return contextFactoryStub.Object;
        }
    }
}


text:
import { ParameterEditor, IParameterEditorDelegate } from "./parameterEditor.base";
import { createAndCloneTemplateElement } from "../admin.pageLoader";
import { Utils } from "../admin.utils";

export class ParameterEditor_HomeMaticWindowCoveringTargetPosition extends ParameterEditor {
    private templateNode: DocumentFragment;
    private txtLevel: HTMLInputElement;
    private txtWorking: HTMLInputElement;
    constructor(valueChangeCallback: IParameterEditorDelegate) {
        super(valueChangeCallback);
        this.templateNode = createAndCloneTemplateElement(require('./parameterEditor.homematic.WindowCovering.TargetPosition.inc.html'));
        this.txtLevel = this.templateNode.querySelector("#level");
        this.txtLevel.addEventListener('input', (ev) => this.valueChanged());
        this.txtWorking = this.templateNode.querySelector("#working");
        this.txtWorking.addEventListener('input', (ev) => this.valueChanged());
    }

    refreshAndShow(containerElement: HTMLElement, parameterValue: any) {
        this.removeChildren(containerElement);
        containerElement.appendChild(this.templateNode);
        try {
            let p: Array<string>;
            if (typeof parameterValue === 'string')
                p = [parameterValue];
            else if (parameterValue instanceof Array)
                p = parameterValue;
            else
                p = [];

            Utils.setInputValue(this.txtLevel, (p.length >= 1) ? p[0] : "");
            Utils.setInputValue(this.txtWorking, (p.length >= 2) ? p[1] : "");
        }
        catch (e) {
            this.txtLevel.value = parameterValue;
            this.txtWorking.value = "";
        }
    }

    protected buildNewParameterValue(): any {
        var resultArray: Array<string> = [Utils.getInputValue(this.txtLevel).toString()];
        if (this.txtWorking.value)
            resultArray.push(Utils.getInputValue(this.txtWorking)?.toString());
        return resultArray;
    }
}


text:
package com.vaadin.tests.layouts.layouttester;

import java.io.IOException;
import java.util.List;

import org.junit.Test;

import com.vaadin.testbench.elements.ButtonElement;
import com.vaadin.tests.tb3.MultiBrowserTest;

/**
 *
 * @since
 * @author Vaadin Ltd
 */
public abstract class BaseLayoutSizingTest extends MultiBrowserTest {
    @Test
    public void LayoutSizing() throws IOException, InterruptedException {
        openTestURL();
        sleep(500);
        compareScreen("initial");
        String[] states = { "setSize350px", "setSize_-1px", "setSize75Percent",
                "setSize100Percent" };
        List<ButtonElement> buttons = $(ButtonElement.class).all();
        int index = 0;
        // go through all buttons click them and see result
        for (ButtonElement btn : buttons) {
            btn.click();
            sleep(500);
            compareScreen(states[index]);
            index++;
        }
    }

}