text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class org.hibernate.cfg.AccessType (Hibernate JavaDocs)</title>
<meta name="date" content="2014-03-03">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.hibernate.cfg.AccessType

Packages that use AccessType

Package
Description

org.hibernate.cfg

org.hibernate.cfg.annotations

Uses of AccessType in org.hibernate.cfg

Methods in org.hibernate.cfg that return AccessType

Modifier and Type
Method and Description

static AccessType
AccessType.getAccessStrategy(AccessType type)

static AccessType
AccessType.getAccessStrategy(String externalName)

AccessType
PropertyData.getDefaultAccess()

AccessType
PropertyInferredData.getDefaultAccess()

AccessType
WrappedInferredData.getDefaultAccess()

AccessType
PropertyPreloadedData.getDefaultAccess()

static AccessType
AccessType.valueOf(String name)

Returns the enum constant of this type with the specified name.

static AccessType[]
AccessType.values()

Returns an array containing the constants of this enum type, in
the order they are declared.

Methods in org.hibernate.cfg with parameters of type AccessType

Modifier and Type
Method and Description

static Component
AnnotationBinder.fillComponent(PropertyHolder propertyHolder,
             PropertyData inferredData,
             AccessType propertyAccessor,
             boolean isNullable,
             EntityBinder entityBinder,
             boolean isComponentEmbedded,
             boolean isIdentifierMapper,
             boolean inSecondPass,
             Mappings mappings,
             Map<org.hibernate.annotations.common.reflection.XClass,InheritanceState> inheritanceStatePerClass)

static Component
AnnotationBinder.fillComponent(PropertyHolder propertyHolder,
             PropertyData inferredData,
             PropertyData baseInferredData,
             AccessType propertyAccessor,
             boolean isNullable,
             EntityBinder entityBinder,
             boolean isComponentEmbedded,
             boolean isIdentifierMapper,
             boolean inSecondPass,
             Mappings mappings,
             Map<org.hibernate.annotations.common.reflection.XClass,InheritanceState> inheritanceStatePerClass)

Constructors in org.hibernate.cfg with parameters of type AccessType

Constructor and Description

PropertyPreloadedData(AccessType defaultAccess,
                     String propertyName,
                     org.hibernate.annotations.common.reflection.XClass returnedClass)

Uses of AccessType in org.hibernate.cfg.annotations

Methods in org.hibernate.cfg.annotations that return AccessType

Modifier and Type
Method and Description

AccessType
SimpleValueBinder.getAccessType()

AccessType
EntityBinder.getExplicitAccessType(org.hibernate.annotations.common.reflection.XAnnotatedElement element)

AccessType
EntityBinder.getPropertyAccessor(org.hibernate.annotations.common.reflection.XAnnotatedElement element)

AccessType
EntityBinder.getPropertyAccessType()

Methods in org.hibernate.cfg.annotations with parameters of type AccessType

Modifier and Type
Method and Description

void
PropertyBinder.setAccessType(AccessType accessType)

void
CollectionBinder.setAccessType(AccessType accessType)

void
SimpleValueBinder.setAccessType(AccessType accessType)

void
EntityBinder.setPropertyAccessType(AccessType propertyAccessor)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2001-2014 Red Hat, Inc.  All Rights Reserved.


text:
function ConvertTo-Dsc {
    <#
.SYNOPSIS
    Converts json DSL files to PSCustomObject
.DESCRIPTION
    Converts json DSL files to PSCustomObjects that Invoke-DSCResource can consume. All property
    objects will be converted to hashtables for the property cmdlet of Invoke-DSCResource. ModuleName
    is discovered dynamically  from the resource name provided in the json.
.PARAMETER Path
    Specifies the path to a .json file.
.PARAMETER InputObject
    Specifies an InputObject containing json synatx
.EXAMPLE
    ConvertTo-Dsc -Path 'c:\json\example.json'
#>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true, ParameterSetName = 'Path', Position = 0)]
        [string]$Path,
        [Parameter(Mandatory = $true, ParameterSetName = 'InputObject', Position = 1)]
        [object[]]$InputObject
    )
    begin {

        if ($PSBoundParameters.ContainsKey('Path')) {
            $data = Get-Content -Path $path -Raw | ConvertFrom-Json
        }
        else {
            $data = $InputObject | ConvertFrom-Json
        }

        $alldscObj = @()
    }
    process {
        $dscResourceProperties = $data.DSCResourcesToExecute.PSObject.Properties |
            Where-Object { $_.MemberType -eq "NoteProperty"; };
        foreach ($dscResourceProperty in $dscResourceProperties) {
            $dscResource = $dscResourceProperty.Value
            $dscObj = New-Object psobject

            if ($dscResource.dscResourceName) {
                $resource = (Get-DscResource -Name $dscResource.dscResourceName | Sort-Object Version -Descending)[0]
            } else {
                throw "dscResourceName property is null for [$($dscResourceProperty.Name)]"
            }

            if ($dscResource.dscResourceName -eq 'file') {
                $module = 'PSDesiredStateConfiguration'
            } else {
                $module = $resource.ModuleName
            }

            if ($null -ne $data.Modules.$module -and $data.Modules -match $module)
            {
                $moduleVersion = ($data.Modules).$module

                if ($resource.Version -notmatch $moduleVersion)
                {
                    $resource = Get-DscResource -Name $dscResource.dscResourceName | Where-Object Version -Match $moduleVersion
                }
            }

            $Config = @{
                Name     = ($dscResource.dscResourceName)
                Property = @{
                }
            }
            $configkeys = ($dscResource.psobject.Properties -notmatch '(dsc)?ResourceName')
            foreach ($configKey in $configKeys) {
                $prop = $resource.Properties | Where-Object {$_.Name -eq $configKey.Name}

                if ($ConfigKey.Value -is [array] -and $prop.PropertyType -eq '[string]'){
                    $ConfigKey.Value = $configKey.Value | Out-String
                }
                if ($ConfigKey.Value -is [array]) {
                    foreach ($key in $ConfigKey.Value) {
                        if ($key.psobject.Properties['CimType']) {
                            #Create new CIM object
                            $cimhash = @{}
                            $key.Properties.psobject.Properties | ForEach-Object {
                                $cimhash[$_.Name] = $_.Value
                            }
                            if ($prop.PropertyType -match '\[\w+\[\]\]') {
                                [ciminstance[]]$value += New-CimInstance -ClassName $key.CimType -Property $cimhash -ClientOnly
                            }
                            else {
                                [ciminstance]$value = New-CimInstance -ClassName $key.CimType -Property $cimhash -ClientOnly
                            }
                        }
                        else {
                            $value = $configKey.Value
                        }
                    }
                    $config.Property.Add($configKey.Name, $value)
                    Remove-Variable -Name Value -Force
                }
                elseif ($prop.PropertyType -eq '[PSCredential]') {
                    $credSplit = $configKey.Value -split '\\'
                    $cred = New-Object System.Management.Automation.PSCredential ($credSplit[0], ($credSplit[1] | ConvertTo-SecureString -AsPlainText -Force))
                    [System.Management.Automation.PSCredential]$value = $cred
                    $config.Property.Add($configKey.Name, $value)
                    Remove-Variable -Name Value -Force
                }
                else {
                    $config.Property.Add($configKey.Name, $configKey.Value)
                }
            }
            $dscObj | Add-Member -MemberType NoteProperty -Name resourceName -Value $dscResourceProperty.Name
            $dscObj | Add-Member -MemberType NoteProperty -Name dscResourceName -Value $dscResource.dscResourceName
            $dscObj | Add-Member -MemberType NoteProperty -Name ModuleName -Value $module

            if ($null -ne $data.Modules.$module -and $data.Modules -match $module)
            {
                $dscObj | Add-Member -MemberType NoteProperty -Name ModuleVersion -Value $moduleVersion
            }
            else
            {
                $dscObj | Add-Member -MemberType NoteProperty -Name ModuleVersion -Value $null
            }

            $dscObj | Add-Member -MemberType NoteProperty -Name Property -Value $Config.Property
            $alldscObj += $dscObj
        }
    }
    end {
        return $alldscObj
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.jetbrains.idea.devkit.util;

import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.GlobalSearchScopesCore;
import com.intellij.psi.util.CachedValueProvider;
import com.intellij.psi.util.CachedValuesManager;
import com.intellij.ui.components.JBList;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;

import java.io.File;

/**
 * @author Konstantin Bulenkov
 */
public class PsiUtil {
  private static final Key<Boolean> IDEA_PROJECT = Key.create("idea.internal.inspections.enabled");
  private static final String IDE_PROJECT_MARKER_CLASS = JBList.class.getName();
  private static final String[] IDEA_PROJECT_MARKER_FILES = {
    "idea.iml", "community-main.iml", "intellij.idea.community.main.iml", "intellij.idea.ultimate.main.iml"
  };

  private PsiUtil() { }

  public static boolean isInstantiable(@NotNull PsiClass cls) {
    PsiModifierList modList = cls.getModifierList();
    if (modList == null || cls.isInterface() || modList.hasModifierProperty(PsiModifier.ABSTRACT) || !isPublicOrStaticInnerClass(cls)) {
      return false;
    }

    PsiMethod[] constructors = cls.getConstructors();
    if (constructors.length == 0) return true;

    for (PsiMethod constructor : constructors) {
      if (constructor.getParameterList().isEmpty()
          && constructor.hasModifierProperty(PsiModifier.PUBLIC)) {
        return true;
      }
    }
    return false;
  }

  public static boolean isPublicOrStaticInnerClass(@NotNull PsiClass cls) {
    PsiModifierList modifiers = cls.getModifierList();
    if (modifiers == null) return false;

    return modifiers.hasModifierProperty(PsiModifier.PUBLIC) &&
           (cls.getParent() instanceof PsiFile || modifiers.hasModifierProperty(PsiModifier.STATIC));
  }

  @Nullable
  public static String getReturnedLiteral(PsiMethod method, PsiClass cls) {
    PsiExpression value = getReturnedExpression(method);
    if (value instanceof PsiLiteralExpression) {
      Object str = ((PsiLiteralExpression)value).getValue();
      return str == null ? null : str.toString();
    }
    else if (value instanceof PsiMethodCallExpression) {
      if (isSimpleClassNameExpression((PsiMethodCallExpression)value)) {
        return cls.getName();
      }
    }
    return null;
  }

  private static boolean isSimpleClassNameExpression(PsiMethodCallExpression expr) {
    String text = expr.getText();
    if (text == null) return false;
    text = text.replaceAll(" ", "")
      .replaceAll("\n", "")
      .replaceAll("\t", "")
      .replaceAll("\r", "");
    return "getClass().getSimpleName()".equals(text) || "this.getClass().getSimpleName()".equals(text);
  }

  @Nullable
  public static PsiExpression getReturnedExpression(PsiMethod method) {
    PsiCodeBlock body = method.getBody();
    if (body != null) {
      PsiStatement[] statements = body.getStatements();
      if (statements.length == 1 && statements[0] instanceof PsiReturnStatement) {
        PsiExpression value = ((PsiReturnStatement)statements[0]).getReturnValue();
        if (value instanceof PsiReferenceExpression) {
          PsiElement element = ((PsiReferenceExpression)value).resolve();
          if (element instanceof PsiField) {
            PsiField field = (PsiField)element;
            if (field.hasModifierProperty(PsiModifier.FINAL)) {
              return field.getInitializer();
            }
          }
        }
        return value;
      }
    }

    return null;
  }

  @Nullable
  public static PsiMethod findNearestMethod(String name, @Nullable PsiClass cls) {
    if (cls == null) return null;
    for (PsiMethod method : cls.getMethods()) {
      if (method.getParameterList().isEmpty() && method.getName().equals(name)) {
        return method.getModifierList().hasModifierProperty(PsiModifier.ABSTRACT) ? null : method;
      }
    }
    return findNearestMethod(name, cls.getSuperClass());
  }

  public static boolean isIdeaProject(@Nullable Project project) {
    if (project == null) return false;

    Boolean flag = project.getUserData(IDEA_PROJECT);
    if (flag == null) {
      flag = checkIdeaProject(project);
      project.putUserData(IDEA_PROJECT, flag);
    }

    return flag;
  }

  public static boolean isPluginProject(@NotNull final Project project) {
    return CachedValuesManager.getManager(project).getCachedValue(project, () -> {
      boolean foundMarkerClass =
        JavaPsiFacade.getInstance(project).findClass(IDE_PROJECT_MARKER_CLASS,
                                                     GlobalSearchScope.allScope(project)) != null;
      return CachedValueProvider.Result.createSingleDependency(foundMarkerClass, ProjectRootManager.getInstance(project));
    });
  }

  public static boolean isPluginModule(@NotNull final Module module) {
    return CachedValuesManager.getManager(module.getProject()).getCachedValue(module, () -> {
      boolean foundMarkerClass = JavaPsiFacade.getInstance(module.getProject())
                                   .findClass(IDE_PROJECT_MARKER_CLASS,
                                              GlobalSearchScope.moduleRuntimeScope(module, false)) != null;
      return CachedValueProvider.Result.createSingleDependency(foundMarkerClass, ProjectRootManager.getInstance(module.getProject()));
    });
  }

  private static boolean isIntelliJBasedDir(VirtualFile baseDir) {
    if (baseDir == null) {
      return false;
    }

    for (VirtualFile dir : new VirtualFile[]{baseDir, baseDir.findChild("community"), baseDir.findChild("ultimate")}) {
      if (dir == null || !dir.isDirectory()) {
        continue;
      }
      for (String fileName : IDEA_PROJECT_MARKER_FILES) {
        if (dir.findChild(fileName) != null) {
          return true;
        }
      }
    }

    return false;
  }

  @TestOnly
  public static void markAsIdeaProject(@NotNull Project project, boolean value) {
    project.putUserData(IDEA_PROJECT, value);
  }

  private static boolean checkIdeaProject(@NotNull Project project) {
    if (!isIntelliJBasedDir(project.getBaseDir())) {
      return false;
    }

    GlobalSearchScope scope = GlobalSearchScopesCore.projectProductionScope(project);
    return JavaPsiFacade.getInstance(project).findClass(IDE_PROJECT_MARKER_CLASS, scope) != null;
  }

  @NotNull
  public static <E extends PsiElement> SmartPsiElementPointer<E> createPointer(@NotNull E e) {
    return SmartPointerManager.getInstance(e.getProject()).createSmartPsiElementPointer(e);
  }

  public static boolean isPluginXmlPsiElement(@NotNull PsiElement element) {
    return isPluginProject(element.getProject()) && DescriptorUtil.isPluginXml(element.getContainingFile());
  }

  public static boolean isPathToIntelliJIdeaSources(String path) {
    for (String file : IDEA_PROJECT_MARKER_FILES) {
      if (new File(path, file).isFile()) return true;
    }
    return false;
  }
}


text:
package org.apache.hadoop.hbase.regionserver;

import static junit.framework.Assert.assertEquals;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.hadoop.hbase.CompareOperator;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HBaseTestingUtil;
import org.apache.hadoop.hbase.TableExistsException;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.TableNotFoundException;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.ColumnFamilyDescriptor;
import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder;
import org.apache.hadoop.hbase.client.Durability;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.client.TableDescriptorBuilder;
import org.apache.hadoop.hbase.filter.BinaryComparator;
import org.apache.hadoop.hbase.filter.Filter;
import org.apache.hadoop.hbase.filter.SingleColumnValueFilter;
import org.apache.hadoop.hbase.io.compress.Compression.Algorithm;
import org.apache.hadoop.hbase.testclassification.MediumTests;
import org.apache.hadoop.hbase.testclassification.RegionServerTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;

@Category({ RegionServerTests.class, MediumTests.class })
/*
 * This test verifies that the scenarios illustrated by HBASE-10850 work w.r.t. essential column
 * family optimization
 */
public class TestSCVFWithMiniCluster {

  @ClassRule
  public static final HBaseClassTestRule CLASS_RULE =
    HBaseClassTestRule.forClass(TestSCVFWithMiniCluster.class);

  private static final TableName HBASE_TABLE_NAME = TableName.valueOf("TestSCVFWithMiniCluster");

  private static final byte[] FAMILY_A = Bytes.toBytes("a");
  private static final byte[] FAMILY_B = Bytes.toBytes("b");

  private static final byte[] QUALIFIER_FOO = Bytes.toBytes("foo");
  private static final byte[] QUALIFIER_BAR = Bytes.toBytes("bar");

  private static Table htable;

  private static Filter scanFilter;

  private int expected = 1;

  @BeforeClass
  public static void setUp() throws Exception {
    HBaseTestingUtil util = new HBaseTestingUtil();

    util.startMiniCluster(1);

    Admin admin = util.getAdmin();
    destroy(admin, HBASE_TABLE_NAME);
    create(admin, HBASE_TABLE_NAME, FAMILY_A, FAMILY_B);
    admin.close();
    htable = util.getConnection().getTable(HBASE_TABLE_NAME);

    /* Add some values */
    List<Put> puts = new ArrayList<>();

    /* Add a row with 'a:foo' = false */
    Put put = new Put(Bytes.toBytes("1"));
    put.setDurability(Durability.SKIP_WAL);
    put.addColumn(FAMILY_A, QUALIFIER_FOO, Bytes.toBytes("false"));
    put.addColumn(FAMILY_A, QUALIFIER_BAR, Bytes.toBytes("_flag_"));
    put.addColumn(FAMILY_B, QUALIFIER_FOO, Bytes.toBytes("_flag_"));
    put.addColumn(FAMILY_B, QUALIFIER_BAR, Bytes.toBytes("_flag_"));
    puts.add(put);

    /* Add a row with 'a:foo' = true */
    put = new Put(Bytes.toBytes("2"));
    put.setDurability(Durability.SKIP_WAL);
    put.addColumn(FAMILY_A, QUALIFIER_FOO, Bytes.toBytes("true"));
    put.addColumn(FAMILY_A, QUALIFIER_BAR, Bytes.toBytes("_flag_"));
    put.addColumn(FAMILY_B, QUALIFIER_FOO, Bytes.toBytes("_flag_"));
    put.addColumn(FAMILY_B, QUALIFIER_BAR, Bytes.toBytes("_flag_"));
    puts.add(put);

    /* Add a row with 'a:foo' qualifier not set */
    put = new Put(Bytes.toBytes("3"));
    put.setDurability(Durability.SKIP_WAL);
    put.addColumn(FAMILY_A, QUALIFIER_BAR, Bytes.toBytes("_flag_"));
    put.addColumn(FAMILY_B, QUALIFIER_FOO, Bytes.toBytes("_flag_"));
    put.addColumn(FAMILY_B, QUALIFIER_BAR, Bytes.toBytes("_flag_"));
    puts.add(put);

    htable.put(puts);
    /*
     * We want to filter out from the scan all rows that do not have the column 'a:foo' with value
     * 'false'. Only row with key '1' should be returned in the scan.
     */
    scanFilter = new SingleColumnValueFilter(FAMILY_A, QUALIFIER_FOO, CompareOperator.EQUAL,
      new BinaryComparator(Bytes.toBytes("false")));
    ((SingleColumnValueFilter) scanFilter).setFilterIfMissing(true);
  }

  @AfterClass
  public static void tearDown() throws Exception {
    htable.close();
  }

  private void verify(Scan scan) throws IOException {
    ResultScanner scanner = htable.getScanner(scan);
    Iterator<Result> it = scanner.iterator();

    /* Then */
    int count = 0;
    try {
      while (it.hasNext()) {
        it.next();
        count++;
      }
    } finally {
      scanner.close();
    }
    assertEquals(expected, count);
  }

  /**
   * Test the filter by adding all columns of family A in the scan. (OK)
   */
  @Test
  public void scanWithAllQualifiersOfFamiliyA() throws IOException {
    /* Given */
    Scan scan = new Scan();
    scan.addFamily(FAMILY_A);
    scan.setFilter(scanFilter);

    verify(scan);
  }

  /**
   * Test the filter by adding all columns of family A and B in the scan. (KO: row '3' without
   * 'a:foo' qualifier is returned)
   */
  @Test
  public void scanWithAllQualifiersOfBothFamilies() throws IOException {
    /* When */
    Scan scan = new Scan();
    scan.setFilter(scanFilter);

    verify(scan);
  }

  /**
   * Test the filter by adding 2 columns of family A and 1 column of family B in the scan. (KO: row
   * '3' without 'a:foo' qualifier is returned)
   */
  @Test
  public void scanWithSpecificQualifiers1() throws IOException {
    /* When */
    Scan scan = new Scan();
    scan.addColumn(FAMILY_A, QUALIFIER_FOO);
    scan.addColumn(FAMILY_A, QUALIFIER_BAR);
    scan.addColumn(FAMILY_B, QUALIFIER_BAR);
    scan.addColumn(FAMILY_B, QUALIFIER_FOO);
    scan.setFilter(scanFilter);

    verify(scan);
  }

  /**
   * Test the filter by adding 1 column of family A (the one used in the filter) and 1 column of
   * family B in the scan. (OK)
   */
  @Test
  public void scanWithSpecificQualifiers2() throws IOException {
    /* When */
    Scan scan = new Scan();
    scan.addColumn(FAMILY_A, QUALIFIER_FOO);
    scan.addColumn(FAMILY_B, QUALIFIER_BAR);
    scan.setFilter(scanFilter);

    verify(scan);
  }

  /**
   * Test the filter by adding 2 columns of family A in the scan. (OK)
   */
  @Test
  public void scanWithSpecificQualifiers3() throws IOException {
    /* When */
    Scan scan = new Scan();
    scan.addColumn(FAMILY_A, QUALIFIER_FOO);
    scan.addColumn(FAMILY_A, QUALIFIER_BAR);
    scan.setFilter(scanFilter);

    verify(scan);
  }

  private static void create(Admin admin, TableName tableName, byte[]... families)
    throws IOException {
    TableDescriptorBuilder builder = TableDescriptorBuilder.newBuilder(tableName);
    for (byte[] family : families) {
      ColumnFamilyDescriptor familyDescriptor = ColumnFamilyDescriptorBuilder.newBuilder(family)
        .setMaxVersions(1).setCompressionType(Algorithm.GZ).build();
      builder.setColumnFamily(familyDescriptor);
    }
    try {
      admin.createTable(builder.build());
    } catch (TableExistsException tee) {
      /* Ignore */
    }
  }

  private static void destroy(Admin admin, TableName tableName) throws IOException {
    try {
      admin.disableTable(tableName);
      admin.deleteTable(tableName);
    } catch (TableNotFoundException tnfe) {
      /* Ignore */
    }
  }
}


text:
package org.apache.harmony.tools.keytool;

/** enumeration of commands available for execution */
public enum Command {
    // show help message
    HELP,
    // generate a key pair or a secret key
    GENKEY,
    // generate a self-signed certificate using
    // an existing key pair
    SELFCERT,
    // import a trusted certificate or a CSR reply
    IMPORT,
    // export a certificate
    EXPORT,
    // change store password
    STOREPASSWD,
    // change key password
    KEYPASSWD,
    // generate a certificate signing request (CSR)
    CERTREQ,
    // check a CRL
    CHECK,
    // convert keystore to another format
    CONVERT,
    // verify a certificate chain
    VERIFY,
    // copy a key entry into a newly created one
    KEYCLONE,
    // print out the store contents
    LIST,
    // print out a certificate which is not in keystore yet
    PRINTCERT,
    // remove an entry from the store
    DELETE
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace UX.Testing.Core.Controls
{
	public interface IFormEventAttributes
	{
		string OnBlur { get; set; }

		string OnChange { get; set; }

		string OnContextMenu { get; set; }

		string OnFocus { get; set; }

		string OnFormChange { get; set; }

		string OnFormInput { get; set; }

		string OnInput { get; set; }

		string OnInvalid { get; set; }

		string OnReset { get; set; }

		string OnSelect { get; set; }

		string OnSubmit { get; set; }

	}
}


text:
package de.mccityville.libmanager.util.config;

import org.eclipse.aether.repository.RemoteRepository;
import org.eclipse.aether.repository.RepositoryPolicy;

import java.io.File;
import java.util.List;

public class BaseConfig {

    protected static final RepositoryPolicy DEFAULT_POLICY = new RepositoryPolicy();

    private File localRepositoryDirectory;
    private List<RemoteRepository> repositories;

    public File getLocalRepositoryDirectory() {
        return localRepositoryDirectory;
    }

    public void setLocalRepositoryDirectory(File localRepositoryDirectory) {
        this.localRepositoryDirectory = localRepositoryDirectory;
    }

    public List<RemoteRepository> getRepositories() {
        return repositories;
    }

    public void setRepositories(List<RemoteRepository> repositories) {
        this.repositories = repositories;
    }
}


text:
import json
import string
import uuid

from collections import defaultdict
from copy import copy
from datetime import datetime

from django.apps import apps
from django.conf import settings
from django.db import models
from django.utils import timezone
from django.utils.functional import cached_property
from django.utils.translation import gettext

import jinja2

import olympia.core.logger

from olympia import amo, constants
from olympia.access.models import Group
from olympia.addons.models import Addon
from olympia.amo.fields import PositiveAutoField
from olympia.amo.models import BaseQuerySet, ManagerBase, ModelBase
from olympia.bandwagon.models import Collection
from olympia.blocklist.models import Block
from olympia.files.models import File
from olympia.ratings.models import Rating
from olympia.reviewers.models import CannedResponse
from olympia.tags.models import Tag
from olympia.users.models import UserProfile
from olympia.users.templatetags.jinja_helpers import user_link
from olympia.versions.models import Version

log = olympia.core.logger.getLogger('z.amo.activity')

# Number of times a token can be used.
MAX_TOKEN_USE_COUNT = 100

class ActivityLogToken(ModelBase):
    id = PositiveAutoField(primary_key=True)
    version = models.ForeignKey(Version, related_name='token', on_delete=models.CASCADE)
    user = models.ForeignKey(
        'users.UserProfile',
        related_name='activity_log_tokens',
        on_delete=models.CASCADE,
    )
    uuid = models.UUIDField(default=uuid.uuid4, unique=True)
    use_count = models.IntegerField(
        default=0, help_text='Stores the number of times the token has been used'
    )

    class Meta:
        db_table = 'log_activity_tokens'
        constraints = [
            models.UniqueConstraint(fields=('version', 'user'), name='version_id'),
        ]

    def is_expired(self):
        return self.use_count >= MAX_TOKEN_USE_COUNT

    def is_valid(self):
        return (
            not self.is_expired()
            and self.version
            == self.version.addon.find_latest_version(
                channel=self.version.channel, exclude=()
            )
        )

    def expire(self):
        self.update(use_count=MAX_TOKEN_USE_COUNT)

    def increment_use(self):
        self.__class__.objects.filter(pk=self.pk).update(
            use_count=models.expressions.F('use_count') + 1
        )
        self.use_count = self.use_count + 1

class ActivityLogEmails(ModelBase):
    """A log of message ids of incoming emails so we don't duplicate process
    them."""

    messageid = models.CharField(max_length=255, unique=True)

    class Meta:
        db_table = 'log_activity_emails'

class AddonLog(ModelBase):
    """
    This table is for indexing the activity log by addon.
    """

    addon = models.ForeignKey(Addon, on_delete=models.CASCADE)
    activity_log = models.ForeignKey('ActivityLog', on_delete=models.CASCADE)

    class Meta:
        db_table = 'log_activity_addon'
        ordering = ('-created',)

    def transfer(self, new_addon):
        try:
            # arguments is a structure:
            # ``arguments = [{'addons.addon':12}, {'addons.addon':1}, ... ]``
            arguments = json.loads(self.activity_log._arguments)
        except Exception:
            log.info(
                'unserializing data from addon_log failed: %s' % self.activity_log.id
            )
            return None

        new_arguments = []
        for item in arguments:
            if item.get('addons.addon', 0) == self.addon.id:
                new_arguments.append({'addons.addon': new_addon.id})
            else:
                new_arguments.append(item)

        self.activity_log.update(_arguments=json.dumps(new_arguments))
        self.update(addon=new_addon)

class CommentLog(ModelBase):
    """
    This table is for indexing the activity log by comment.
    """

    activity_log = models.ForeignKey('ActivityLog', on_delete=models.CASCADE)
    comments = models.TextField()

    class Meta:
        db_table = 'log_activity_comment'
        ordering = ('-created',)

class VersionLog(ModelBase):
    """
    This table is for indexing the activity log by version.
    """

    activity_log = models.ForeignKey('ActivityLog', on_delete=models.CASCADE)
    version = models.ForeignKey(Version, on_delete=models.CASCADE)

    class Meta:
        db_table = 'log_activity_version'
        ordering = ('-created',)

class UserLog(ModelBase):
    """
    This table is for indexing the activity log by user.
    Note: This includes activity performed unto the user.
    """

    activity_log = models.ForeignKey('ActivityLog', on_delete=models.CASCADE)
    user = models.ForeignKey(UserProfile, on_delete=models.CASCADE)

    class Meta:
        db_table = 'log_activity_user'
        ordering = ('-created',)

class GroupLog(ModelBase):
    """
    This table is for indexing the activity log by access group.
    """

    id = PositiveAutoField(primary_key=True)
    activity_log = models.ForeignKey('ActivityLog', on_delete=models.CASCADE)
    group = models.ForeignKey(Group, on_delete=models.CASCADE)

    class Meta:
        db_table = 'log_activity_group'
        ordering = ('-created',)

class BlockLog(ModelBase):
    """
    This table is for indexing the activity log by Blocklist Block.
    """

    id = PositiveAutoField(primary_key=True)
    activity_log = models.ForeignKey('ActivityLog', on_delete=models.CASCADE)
    block = models.ForeignKey(Block, on_delete=models.SET_NULL, null=True)
    guid = models.CharField(max_length=255, null=False)

    class Meta:
        db_table = 'log_activity_block'
        ordering = ('-created',)

class IPLog(ModelBase):
    """
    This table is for indexing the activity log by IP (only for specific
    actions).
    """

    activity_log = models.ForeignKey('ActivityLog', on_delete=models.CASCADE)
    ip_address = models.CharField(max_length=45)

    class Meta:
        db_table = 'log_activity_ip'
        ordering = ('-created',)

class DraftComment(ModelBase):
    """A model that allows us to draft comments for reviews before we have
    an ActivityLog instance ready.

    This is being used by the commenting API by the code-manager.
    """

    id = PositiveAutoField(primary_key=True)
    version = models.ForeignKey(Version, on_delete=models.CASCADE)
    user = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
    filename = models.CharField(max_length=255, null=True, blank=True)
    lineno = models.PositiveIntegerField(null=True)
    canned_response = models.ForeignKey(
        CannedResponse, null=True, default=None, on_delete=models.SET_DEFAULT
    )
    comment = models.TextField(blank=True)

    class Meta:
        db_table = 'log_activity_comment_draft'

class ActivityLogQuerySet(BaseQuerySet):
    def default_transformer(self, logs):
        ActivityLog.arguments_builder(logs)

class ActivityLogManager(ManagerBase):
    _queryset_class = ActivityLogQuerySet

    def get_queryset(self):
        qs = super().get_queryset()
        qs = qs.transform(qs.default_transformer).prefetch_related('user')
        return qs

    def for_addons(self, addons):
        if isinstance(addons, Addon):
            addons = (addons,)

        return self.filter(addonlog__addon__in=addons)

    def for_versions(self, versions):
        if isinstance(versions, Version):
            versions = (versions,)

        return self.filter(versionlog__version__in=versions)

    def for_groups(self, groups):
        if isinstance(groups, Group):
            groups = (groups,)

        return self.filter(grouplog__group__in=groups)

    def for_user(self, user):
        return self.filter(userlog__user=user)

    def for_block(self, block):
        return self.filter(blocklog__block=block)

    def for_guidblock(self, guid):
        return self.filter(blocklog__guid=guid)

    def for_developer(self):
        return self.exclude(
            action__in=constants.activity.LOG_ADMINS
            + constants.activity.LOG_HIDE_DEVELOPER
        )

    def admin_events(self):
        return self.filter(action__in=constants.activity.LOG_ADMINS)

    def moderation_events(self):
        return self.filter(action__in=constants.activity.LOG_RATING_MODERATION)

    def review_queue(self):
        qs = self._by_type()
        return qs.filter(action__in=constants.activity.LOG_REVIEW_QUEUE).exclude(
            user__id=settings.TASK_USER_ID
        )

    def review_log(self):
        qs = self._by_type()
        return qs.filter(
            action__in=constants.activity.LOG_REVIEWER_REVIEW_ACTION
        ).exclude(user__id=settings.TASK_USER_ID)

    def total_ratings(self, theme=False):
        """Return the top users, and their # of reviews."""
        qs = self._by_type()
        action_ids = (
            [amo.LOG.THEME_REVIEW.id]
            if theme
            else constants.activity.LOG_REVIEWER_REVIEW_ACTION
        )
        return (
            qs.values('user', 'user__display_name', 'user__username')
            .filter(action__in=action_ids)
            .exclude(user__id=settings.TASK_USER_ID)
            .annotate(approval_count=models.Count('id'))
            .order_by('-approval_count')
        )

    def monthly_reviews(self, theme=False):
        """Return the top users for the month, and their # of reviews."""
        qs = self._by_type()
        now = datetime.now()
        created_date = datetime(now.year, now.month, 1)
        actions = (
            [constants.activity.LOG.THEME_REVIEW.id]
            if theme
            else constants.activity.LOG_REVIEWER_REVIEW_ACTION
        )
        return (
            qs.values('user', 'user__display_name', 'user__username')
            .filter(created__gte=created_date, action__in=actions)
            .exclude(user__id=settings.TASK_USER_ID)
            .annotate(approval_count=models.Count('id'))
            .order_by('-approval_count')
        )

    def user_approve_reviews(self, user):
        qs = self._by_type()
        return qs.filter(
            action__in=constants.activity.LOG_REVIEWER_REVIEW_ACTION, user__id=user.id
        )

    def current_month_user_approve_reviews(self, user):
        now = datetime.now()
        ago = datetime(now.year, now.month, 1)
        return self.user_approve_reviews(user).filter(created__gte=ago)

    def user_position(self, values_qs, user):
        try:
            return (
                next(
                    i
                    for (i, d) in enumerate(list(values_qs))
                    if d.get('user') == user.id
                )
                + 1
            )
        except StopIteration:
            return None

    def total_ratings_user_position(self, user, theme=False):
        return self.user_position(self.total_ratings(theme), user)

    def monthly_reviews_user_position(self, user, theme=False):
        return self.user_position(self.monthly_reviews(theme), user)

    def _by_type(self):
        qs = self.get_queryset()
        table = 'log_activity_addon'
        return qs.extra(
            tables=[table], where=['%s.activity_log_id=%s.id' % (table, 'log_activity')]
        )

class SafeFormatter(string.Formatter):
    """A replacement for str.format that escapes interpolated values."""

    def get_field(self, *args, **kw):
        # obj is the value getting interpolated into the string.
        obj, used_key = super(SafeFormatter, self).get_field(*args, **kw)
        return jinja2.escape(obj), used_key

class ActivityLog(ModelBase):
    TYPES = sorted(
        [(value.id, key) for key, value in constants.activity.LOG_BY_ID.items()]
    )
    user = models.ForeignKey('users.UserProfile', null=True, on_delete=models.SET_NULL)
    action = models.SmallIntegerField(choices=TYPES)
    _arguments = models.TextField(blank=True, db_column='arguments')
    _details = models.TextField(blank=True, db_column='details')
    objects = ActivityLogManager()

    formatter = SafeFormatter()

    class Meta:
        db_table = 'log_activity'
        ordering = ('-created',)
        indexes = [
            models.Index(fields=('action',), name='log_activity_1bd4707b'),
            models.Index(fields=('created',), name='created_idx'),
        ]

    def f(self, *args, **kw):
        """Calls SafeFormatter.format and returns a Markup string."""
        # SafeFormatter escapes everything so this is safe.
        return jinja2.Markup(self.formatter.format(*args, **kw))

    @classmethod
    def arguments_builder(cls, activities):
        def handle_renames(value):
            # Cope with renames of key models (use the original model name like
            # it was in the ActivityLog as the key so that we can find it
            # later)
            return 'ratings.rating' if value == 'reviews.review' else value

        # We need to do 2 passes on each log:
        # - The first time, gather the references to every instance we need
        # - The second time, we built querysets for all instances of the same
        #   type, pick data from that queryset.
        #
        # Because it relies on in_bulk(), this method needs the pks to be of a
        # consistent type, which doesn't appear to be guaranteed in our
        # existing data. For this reason, it forces a conversion to int. If we
        # ever want to store ActivityLog items pointing to models using a non
        # integer PK field, we'll need to make this a little smarter.
        instances_to_load = defaultdict(list)
        instances = {}

        for activity in activities:
            try:
                # `arguments_data` will be a list of dicts like:
                # `[{'addons.addon':12}, {'addons.addon':1}, ... ]`
                activity.arguments_data = json.loads(activity._arguments)
            except Exception as e:
                log.info('unserializing data from activity_log failed: %s', activity.id)
                log.info(e)
                activity.arguments_data = []

            for item in activity.arguments_data:
                # Each 'item' should have one key and one value only.
                name, pk = list(item.items())[0]
                if name not in ('str', 'int', 'null') and pk:
                    # Convert pk to int to have consistent data for when we
                    # call .in_bulk() later.
                    name = handle_renames(name)
                    instances_to_load[name].append(int(pk))

        # At this point, instances_to_load is a dict of "names" that
        # each have a bunch of pks we want to load.
        for name, pks in instances_to_load.items():
            (app_label, model_name) = name.split('.')
            model = apps.get_model(app_label, model_name)
            # Load the instances, avoiding transformers other than translations
            # and coping with soft-deleted models and unlisted add-ons.
            qs = model.get_unfiltered_manager().all()
            if hasattr(qs, 'only_translations'):
                qs = qs.only_translations()
            instances[name] = qs.in_bulk(pks)

        # instances is now a dict of "model names" that each have a dict of
        # {pk: instance}. We do our second pass on the logs to build the
        # "arguments" property from that data, which is a list of the instances
        # that each particular log has, in the correct order.
        for activity in activities:
            objs = []
            # We preloaded that property earlier
            for item in activity.arguments_data:
                # As above, each 'item' should have one key and one value only.
                name, pk = list(item.items())[0]
                if name in ('str', 'int', 'null'):
                    # It's not actually a model reference, just return the
                    # value directly.
                    objs.append(pk)
                elif pk:
                    # Fetch the instance from the cache we built.
                    name = handle_renames(name)
                    obj = instances[name].get(int(pk))
                    # Most of the time, we're eventually going to call
                    # to_string() on each ActivityLog that we're processing
                    # here. For some of the models, that will result in a call
                    # to <model>.get_absolute_url(), which in turn can cause an
                    # extra SQL query because some parent model is needed to
                    # build the URL.
                    # It's difficult to predict what we'll need as ActivitLog
                    # is fairly generic, but we know Addon is going to be
                    # needed in some cases for sure (Version, Rating) so if
                    # we're dealing with objects that have an `addon_id`
                    # property, and we have already fetched the corresponding
                    # Addon instance, set the `addon`  property on the object
                    # to the Addon instance we already have to avoid the extra
                    # SQL query.
                    addon_id = getattr(obj, 'addon_id', None)
                    if addon := instances.get('addons.addon', {}).get(addon_id):
                        obj.addon = addon
                    objs.append(obj)
            # Override the arguments cached_property with what we got.
            activity.arguments = objs

    @cached_property
    def arguments(self):
        # This is a fallback : in 99% of the cases we should not be using this
        # but go through the default transformer instead, which executes
        # arguments_builder on the whole list of items in the queryset,
        # allowing us to fetch the instances in arguments in an optimized
        # manner.
        self.arguments_builder([self])
        return self.arguments

    def set_arguments(self, args=None):
        """
        Takes an object or a tuple of objects and serializes them and stores it
        in the db as a json string.
        """
        if args is None:
            args = []

        if not isinstance(args, (list, tuple)):
            args = (args,)

        serialize_me = []

        for arg in args:
            if isinstance(arg, str):
                serialize_me.append({'str': arg})
            elif isinstance(arg, int):
                serialize_me.append({'int': arg})
            elif isinstance(arg, tuple):
                # Instead of passing an addon instance you can pass a tuple:
                # (Addon, 3) for Addon with pk=3
                serialize_me.append(dict(((str(arg[0]._meta), arg[1]),)))
            else:
                serialize_me.append(dict(((str(arg._meta), arg.pk),)))

        self._arguments = json.dumps(serialize_me)

    @property
    def details(self):
        if self._details:
            return json.loads(self._details)

    @details.setter
    def details(self, data):
        self._details = json.dumps(data)

    @property
    def log(self):
        return constants.activity.LOG_BY_ID[self.action]

    def to_string(self, type_=None):
        log_type = constants.activity.LOG_BY_ID[self.action]
        if type_ and hasattr(log_type, '%s_format' % type_):
            format = getattr(log_type, '%s_format' % type_)
        else:
            format = log_type.format

        # We need to copy arguments so we can remove elements from it
        # while we loop over self.arguments.
        arguments = copy(self.arguments)
        addon = None
        rating = None
        version = None
        collection = None
        tag = None
        group = None
        file_ = None
        status = None

        for arg in self.arguments:
            if isinstance(arg, Addon) and not addon:
                if arg.has_listed_versions():
                    addon = self.f(
                        '{1}', arg.get_absolute_url(), arg.name
                    )
                else:
                    addon = self.f('{0}', arg.name)
                arguments.remove(arg)
            if isinstance(arg, Rating) and not rating:
                rating = self.f(
                    '{1}', arg.get_absolute_url(), gettext('Review')
                )
                arguments.remove(arg)
            if isinstance(arg, Version) and not version:
                text = gettext('Version {0}')
                if arg.channel == amo.RELEASE_CHANNEL_LISTED:
                    version = self.f(
                        '%s' % text,
                        arg.version,
                        arg.get_absolute_url(),
                    )
                else:
                    version = self.f(text, arg.version)
                arguments.remove(arg)
            if isinstance(arg, Collection) and not collection:
                collection = self.f(
                    '{1}', arg.get_absolute_url(), arg.name
                )
                arguments.remove(arg)
            if isinstance(arg, Tag) and not tag:
                if arg.can_reverse():
                    tag = self.f(
                        '{1}', arg.get_absolute_url(), arg.tag_text
                    )
                else:
                    tag = self.f('{0}', arg.tag_text)
            if isinstance(arg, Group) and not group:
                group = arg.name
                arguments.remove(arg)
            if isinstance(arg, File) and not file_:
                validation = 'passed'
                if self.action in (
                    amo.LOG.UNLISTED_SIGNED.id,
                    amo.LOG.UNLISTED_SIGNED_VALIDATION_FAILED.id,
                ):
                    validation = 'ignored'

                file_ = self.f(
                    '{1} (validation {2})',
                    arg.get_absolute_url(),
                    arg.filename,
                    validation,
                )
                arguments.remove(arg)
            if self.action == amo.LOG.CHANGE_STATUS.id and not isinstance(arg, Addon):
                # Unfortunately, this action has been abused in the past and
                # the non-addon argument could be a string or an int. If it's
                # an int, we want to retrieve the string and translate it.
                if isinstance(arg, int) and arg in amo.STATUS_CHOICES_ADDON:
                    status = gettext(amo.STATUS_CHOICES_ADDON[arg])
                else:
                    # It's not an int or not one of the choices, so assume it's
                    # a string or an unknown int we want to display as-is.
                    status = arg
                arguments.remove(arg)

        user = user_link(self.user)

        try:
            kw = {
                'addon': addon,
                'rating': rating,
                'version': version,
                'collection': collection,
                'tag': tag,
                'user': user,
                'group': group,
                'file': file_,
                'status': status,
            }
            return self.f(str(format), *arguments, **kw)
        except (AttributeError, KeyError, IndexError):
            log.warning('%d contains garbage data' % (self.id or 0))
            return 'Something magical happened.'

    def __str__(self):
        return self.to_string()

    def __html__(self):
        return self

    @property
    def author_name(self):
        """Name of the user that triggered the activity.

        If it's a reviewer action that will be shown to developers, the
        `reviewer_name` property is used if present, otherwise `name` is
        used."""
        if self.action in constants.activity.LOG_REVIEW_QUEUE_DEVELOPER:
            return self.user.reviewer_name or self.user.name
        return self.user.name

    @classmethod
    def create(cls, action, *args, **kw):
        """
        e.g. ActivityLog.create(amo.LOG.CREATE_ADDON, addon),
             ActivityLog.create(amo.LOG.ADD_FILE_TO_VERSION, file, version)
        In case of circular import you can use `olympia.activity.log_create()`
        """
        from olympia import core

        user = kw.get('user', core.get_user())

        if not user:
            log.warning('Activity log called with no user: %s' % action.id)
            return

        # We make sure that we take the timestamp if provided, instead of
        # creating a new one, especially useful for log entries created
        # in a loop.
        al = ActivityLog(
            user=user, action=action.id, created=kw.get('created', timezone.now())
        )
        al.set_arguments(args)
        if 'details' in kw:
            al.details = kw['details']
        al.save()

        if 'details' in kw and 'comments' in al.details:
            CommentLog.objects.create(
                comments=al.details['comments'],
                activity_log=al,
                created=kw.get('created', timezone.now()),
            )

        for arg in args:
            if isinstance(arg, tuple):
                class_ = arg[0]
                id_ = arg[1]
            else:
                class_ = arg.__class__
                id_ = arg.id if isinstance(arg, ModelBase) else None

            if class_ == Addon:
                AddonLog.objects.create(
                    addon_id=id_,
                    activity_log=al,
                    created=kw.get('created', timezone.now()),
                )
            elif class_ == Version:
                VersionLog.objects.create(
                    version_id=id_,
                    activity_log=al,
                    created=kw.get('created', timezone.now()),
                )
            elif class_ == UserProfile:
                UserLog.objects.create(
                    user_id=id_,
                    activity_log=al,
                    created=kw.get('created', timezone.now()),
                )
            elif class_ == Group:
                GroupLog.objects.create(
                    group_id=id_,
                    activity_log=al,
                    created=kw.get('created', timezone.now()),
                )
            elif class_ == Block:
                BlockLog.objects.create(
                    block_id=id_,
                    activity_log=al,
                    guid=arg.guid,
                    created=kw.get('created', timezone.now()),
                )

        if getattr(action, 'store_ip', False):
            # Index specific actions by their IP address. Note that the caller
            # must take care of overriding remote addr if the action is created
            # from a task.
            IPLog.objects.create(
                ip_address=core.get_remote_addr(),
                activity_log=al,
                created=kw.get('created', timezone.now()),
            )

        # Index by every user
        UserLog.objects.create(
            activity_log=al, user=user, created=kw.get('created', timezone.now())
        )
        return al


text:
/**
 * @fileOverview _header.js traverse throught DOM and assign a11y labels.
 *
 * @author Gagandeep Singh <robi_osahan@yahoo.com>
 * @version 1.0.0
 */

(function(window, $, undefined){

    a11y._header = function(scope, options){

        var ele = scope.find("header"),
            self = this,
            labeler = {

                init: function(){

                    if( ele.length > 0){
                        this.assignLabels();
                    }

                },

                assignLabels: function(){

                    // Role for header is only assigned once (assumed the first header is main);

                    var $this = el.first(),
                        role = $this.prop('role');

                    if(typeof role === "undefined"){
                        $this.attr("role", "banner");
                    }

                }
            };

        labeler.init();

    };

})(this, jQuery);


text:
@interface SkillCCell ()

@property (strong, nonatomic) UILabel *contentLabel;
@property (strong, nonatomic) UIButton *deleteB;

@end

@implementation SkillCCell

- (void)setCurSkill:(CodingSkill *)curSkill{
    _curSkill = curSkill;
    if (!_curSkill) {
        return;
    }
    if (!_contentLabel) {
        self.contentView.backgroundColor = kColorBrandBlue;
        self.contentView.layer.cornerRadius = 2.0;
        self.layer.cornerRadius = 2.0;
        _contentLabel = [UILabel labelWithFont:[UIFont systemFontOfSize:14] textColor:kColorWhite];
        _contentLabel.minimumScaleFactor = 0.5;
        _contentLabel.adjustsFontSizeToFitWidth = YES;
        [self.contentView addSubview:_contentLabel];
        _deleteB = [UIButton new];
        [_deleteB setImage:[UIImage imageNamed:@"skill_delete"] forState:UIControlStateNormal];
        __weak typeof(self) weakSelf = self;
        [_deleteB bk_addEventHandler:^(id sender) {
            if (weakSelf.deleteBlock) {
                weakSelf.deleteBlock(weakSelf.curSkill);
            }
        } forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:_deleteB];
        [_deleteB mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.right.equalTo(self.contentView);
            make.width.mas_equalTo(30);
        }];
        [_contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.contentView);
            make.left.equalTo(self.contentView).offset(10);
            make.right.equalTo(_deleteB.mas_left).offset(-5);
        }];
    }
    _contentLabel.text = _curSkill.skill_str;
}

+ (CGSize)ccellSizeWithObj:(id)obj{
    CGSize ccellSize = CGSizeZero;
    if ([obj isKindOfClass:[CodingSkill class]]) {
        ccellSize = CGSizeMake((kScreen_Width - 30 - 10)/ 2, 30);
    }
    return ccellSize;
}

@end


text:
import introJs from 'intro.js';
import PropTypes from 'prop-types';
import { Component, isValidElement } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';

import * as introJsPropTypes from '../../helpers/proptypes';
import * as introJsDefaultProps from '../../helpers/defaultProps';
import { isServer } from '../../helpers/server';

/**
 * Intro.js Steps Component.
 */
export default class Steps extends Component {
  /**
   * React Props
   * @type {Object}
   */
  static propTypes = {
    enabled: PropTypes.bool,
    initialStep: PropTypes.number.isRequired,
    steps: PropTypes.arrayOf(
      PropTypes.shape({
        element: PropTypes.oneOfType([
          PropTypes.string,
          /* istanbul ignore next */
          typeof Element === 'undefined' ? PropTypes.any : PropTypes.instanceOf(Element),
        ]),
        intro: PropTypes.node.isRequired,
        position: introJsPropTypes.tooltipPosition,
        tooltipClass: PropTypes.string,
        highlightClass: PropTypes.string,
      })
    ).isRequired,
    onStart: PropTypes.func,
    onExit: PropTypes.func.isRequired,
    onBeforeExit: PropTypes.func,
    onBeforeChange: PropTypes.func,
    onAfterChange: PropTypes.func,
    onChange: PropTypes.func,
    onPreventChange: PropTypes.func,
    onComplete: PropTypes.func,
    options: introJsPropTypes.options,
  };

  /**
   * React Default Props
   * @type {Object}
   */
  static defaultProps = {
    enabled: false,
    onStart: null,
    onBeforeExit: null,
    onBeforeChange: null,
    onAfterChange: null,
    onChange: null,
    onPreventChange: null,
    onComplete: null,
    options: introJsDefaultProps.options,
  };

  /**
   * Creates a new instance of the component.
   * @class
   * @param {Object} props - The props of the component.
   */
  constructor(props) {
    super(props);

    this.introJs = null;
    this.isConfigured = false;
    // We need to manually keep track of the visibility state to avoid a callback hell.
    this.isVisible = false;

    this.installIntroJs();
  }

  /**
   * Lifecycle: componentDidMount.
   * We use this event to enable Intro.js steps at mount time if enabled right from the start.
   */
  componentDidMount() {
    if (this.props.enabled) {
      this.configureIntroJs();
      this.renderSteps();
    }
  }

  /**
   * Lifecycle: componentDidUpdate.
   * @param  {Object} prevProps - The previous props.
   */
  componentDidUpdate(prevProps) {
    const { enabled, steps, options } = this.props;

    if (!this.isConfigured || prevProps.steps !== steps || prevProps.options !== options) {
      this.configureIntroJs();
      this.renderSteps();
    }

    if (prevProps.enabled !== enabled) {
      this.renderSteps();
    }
  }

  /**
   * Lifecycle: componentWillUnmount.
   * We use this even to hide the steps when the component is unmounted.
   */
  componentWillUnmount() {
    this.introJs.exit();
  }

  /**
   * Triggered when Intro.js steps are exited.
   */
  onExit = () => {
    const { onExit } = this.props;

    this.isVisible = false;

    onExit(this.introJs._currentStep);
  };

  /**
   * Triggered before exiting the intro.
   * @return {Boolean} Returning `false` will prevent exiting the intro.
   */
  onBeforeExit = () => {
    const { onBeforeExit } = this.props;

    if (onBeforeExit) {
      return onBeforeExit(this.introJs._currentStep);
    }

    return true;
  };

  /**
   * Triggered before changing step.
   * @return {Boolean} Returning `false` will prevent the step transition.
   */
  onBeforeChange = nextElement => {
    if (!this.isVisible) {
      return true;
    }

    const { onBeforeChange, onPreventChange } = this.props;

    if (onBeforeChange) {
      const continueStep = onBeforeChange(this.introJs._currentStep, nextElement);

      if (continueStep === false && onPreventChange) {
        setTimeout(() => {
          onPreventChange(this.introJs._currentStep);
        }, 0);
      }

      return continueStep;
    }

    return true;
  };

  /**
   * Triggered after changing step.
   * @param  {HTMLElement} element - The element associated to the new step.
   */
  onAfterChange = element => {
    if (!this.isVisible) {
      return;
    }

    const { onAfterChange } = this.props;

    if (onAfterChange) {
      onAfterChange(this.introJs._currentStep, element);
    }
  };

  /**
   * Triggered when changing step.
   * @param  {HTMLElement} element - The element associated to the next step.
   */
  onChange = element => {
    if (!this.isVisible) {
      return;
    }

    const { onChange } = this.props;

    if (onChange) {
      onChange(this.introJs._currentStep, element);
    }
  };

  /**
   * Triggered when completing all the steps.
   */
  onComplete = () => {
    const { onComplete } = this.props;

    if (onComplete) {
      onComplete();
    }
  };

  /**
   * Updates the element associated to a step based on its index.
   * This is useful when the associated element is not present in the DOM on page load.
   * @param  {number} stepIndex - The index of the step to update.
   */
  updateStepElement = stepIndex => {
    const element = document.querySelector(this.introJs._options.steps[stepIndex].element);

    if (element) {
      this.introJs._introItems[stepIndex].element = element;
      this.introJs._introItems[stepIndex].position = this.introJs._options.steps[stepIndex].position || 'auto';
    }
  };

  /**
   * Installs Intro.js.
   */
  installIntroJs() {
    if (isServer()) {
      return;
    }

    this.introJs = introJs();

    this.introJs.onexit(this.onExit);
    this.introJs.onbeforeexit(this.onBeforeExit);
    this.introJs.onbeforechange(this.onBeforeChange);
    this.introJs.onafterchange(this.onAfterChange);
    this.introJs.onchange(this.onChange);
    this.introJs.oncomplete(this.onComplete);
  }

  /**
   * Configures Intro.js if not already configured.
   */
  configureIntroJs() {
    const { options, steps } = this.props;

    const sanitizedSteps = steps.map(step => {
      if (isValidElement(step.intro)) {
        return {
          ...step,
          intro: renderToStaticMarkup(step.intro),
        };
      }

      return step;
    });

    this.introJs.setOptions({ ...options, steps: sanitizedSteps });

    this.isConfigured = true;
  }

  /**
   * Renders the Intro.js steps.
   */
  renderSteps() {
    const { enabled, initialStep, steps, onStart } = this.props;

    if (enabled && steps.length > 0 && !this.isVisible) {
      this.introJs.start();

      this.isVisible = true;

      this.introJs.goToStepNumber(initialStep + 1);

      if (onStart) {
        onStart(this.introJs._currentStep);
      }
    } else if (!enabled && this.isVisible) {
      this.isVisible = false;

      this.introJs.exit();
    }
  }

  /**
   * Renders the component.
   * @return {null} We do not want to render anything.
   */
  render() {
    return null;
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Tester</title>
<meta name="date" content="2017-04-03">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

Tester

Classes

against_human

extensive_game

extensive_game_file

rule_extensive_xperiments

until_success_game


text:
.typeahead {

}

.selectionList {

  background: #fff;
  position: absolute;
  display: block;
  min-width: 200px;
  margin-left: 10px;

  transition visibility 100ms;
  border-radius: 5px;

}

.selectionItem {
  display: block;
  padding: 5px 10px;
  font-size: 1.1em;
  color: #ccc;
  cursor: pointer;
  border-radius: 5px;
  transition: all 100ms;
}

  .selectionItem:hover,
  .selectionItem.hovered {
    background: rgb(0, 108, 203);
    color: #fff;
  }

#hiddenInputContent {
  position: absolute;
  z-index: -1;
  color: rgba(255,255,255,0);
  height: 0;
}


text:
.class final Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;
.super Ljava/lang/Object;
.source "AppWidgetServiceImpl.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/appwidget/AppWidgetServiceImpl;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x1a
    name = "Widget"
.end annotation

# instance fields
.field appWidgetId:I

.field host:Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;

.field options:Landroid/os/Bundle;

.field provider:Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;

.field restoredId:I

.field views:Landroid/widget/RemoteViews;

# direct methods
.method private constructor <init>()V
    .locals 0

    .prologue
    .line 3390
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

.method synthetic constructor <init>(Lcom/android/server/appwidget/AppWidgetServiceImpl$1;)V
    .locals 0
    .param p1, "x0"    # Lcom/android/server/appwidget/AppWidgetServiceImpl$1;

    .prologue
    .line 3390
    invoke-direct {p0}, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;-><init>()V

    return-void
.end method

# virtual methods
.method public toString()Ljava/lang/String;
    .locals 3

    .prologue
    const/16 v2, 0x3a

    .line 3400
    new-instance v0, Ljava/lang/StringBuilder;

    invoke-direct {v0}, Ljava/lang/StringBuilder;-><init>()V

    const-string v1, "AppWidgetId{"

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    iget v1, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;->appWidgetId:I

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-virtual {v0, v2}, Ljava/lang/StringBuilder;->append(C)Ljava/lang/StringBuilder;

    move-result-object v0

    iget-object v1, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;->host:Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-virtual {v0, v2}, Ljava/lang/StringBuilder;->append(C)Ljava/lang/StringBuilder;

    move-result-object v0

    iget-object v1, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;->provider:Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v0

    const/16 v1, 0x7d

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(C)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v0

    return-object v0
.end method


text:
This exercise answer is currently not available. If you already finished this task and you want to share your answer. Please follow these steps:

1. Fork it!
2. Edit
3. Commit.
4. Push.
5. Submit a pull request :D

Thank for participating!


text:
var App = require('app');
var validator = require('utils/validator');

App.User = DS.Model.extend({
  userName:DS.attr('string'),
  id: Em.computed.alias('userName'),
  userType: DS.attr('string'),
  admin: DS.attr('boolean'),
  operator: DS.attr('boolean'),
  clusterUser: DS.attr('boolean'),

  /**
   * List of permissions assigned to user
   *  Available permissions:
   *    AMBARI.ADMINISTRATOR
   *    CLUSTER.USER
   *    CLUSTER.ADMINISTRATOR
   *    VIEW.USER
   * @property {Array} permissions
   **/
  permissions: DS.attr('array'),

  /**
   * @type {Boolean}
   */
  isLdap: Em.computed.equal('userType', 'LDAP')
});

App.User.FIXTURES = [];


text:
"""
  Purpose:
  This script will generate a list of discovered nodes and display the system information for the nodes
"""

import os
import sys
import subprocess

# set path to common libraries
sys.path.append(subprocess.check_output("git rev-parse --show-toplevel", shell=True).rstrip("\n") + "/test/common")
import fit_common
import test_api_utils

class display_sysinfo(fit_common.unittest.TestCase):
    def test_01_get_product_info(self):
        print "============== Displaying Product Info"
        nodes = test_api_utils.monorail_get_node_list(fit_common.ARGS_LIST['ora'])
        if len(nodes) == 0:
            print "No Nodes found on Onrack server "+fit_common.ARGS_LIST['ora']
        else:
            inode=0
            while inode<len(nodes):
                nn=nodes[inode]
                print "Node: "+nn
                monurl = "/api/1.1/nodes/"+nn+"/catalogs/dmi"
                mondata = fit_common.rackhdapi(monurl)
                catalog = mondata['json']
                result = mondata['status']

                if result != 200:
                    print "Error on catalog/dmi command"
                else:
                    # Check BMC IP vs OBM IP setting
                    print " ID: "+catalog["id"]
                    print " Product Name : "+catalog["data"]["System Information"]["Product Name"]
                    print " Serial Number: "+catalog["data"]["System Information"]["Serial Number"]
                    print " UUID         : "+catalog["data"]["System Information"]["UUID"]
                inode +=1

    def test_02_get_catalog_source(self):
        print "============== Displaying Catalog Sources"
        nodes = test_api_utils.monorail_get_node_list(fit_common.ARGS_LIST['ora'])
        if len(nodes) == 0:
            print "No Nodes found on Onrack server "+fit_common.ARGS_LIST['ora']
        else:
            inode=0
            while inode<len(nodes):
                print("")
                nn=nodes[inode]
                print "Node: "+nn

                monurl = "/api/1.1/nodes/"+nn+"/catalogs"
                mondata = fit_common.rackhdapi(monurl)
                catalog = mondata['json']
                result = mondata['status']

                if result != 200:
                    print "Error: failed catalog request"
                else:
                    i = 0
                    while i<len(catalog):
                        print "Source: "+catalog[i]["source"]
                        i +=1
                inode +=1

if __name__ == '__main__':
    fit_common.unittest.main()


text:
package org.apache.spark.sql.catalog

import javax.annotation.Nullable

import org.apache.spark.annotation.Stable
import org.apache.spark.sql.catalyst.DefinedByConstructorParams

// Note: all classes here are expected to be wrapped in Datasets and so must extend
// DefinedByConstructorParams for the catalog to be able to create encoders for them.

/**
 * A database in Spark, as returned by the `listDatabases` method defined in [[Catalog]].
 *
 * @param name name of the database.
 * @param description description of the database.
 * @param locationUri path (in the form of a uri) to data files.
 * @since 2.0.0
 */
@Stable
class Database(
    val name: String,
    @Nullable val description: String,
    val locationUri: String)
  extends DefinedByConstructorParams {

  override def toString: String = {
    "Database[" +
      s"name='$name', " +
      Option(description).map { d => s"description='$d', " }.getOrElse("") +
      s"path='$locationUri']"
  }

}

/**
 * A table in Spark, as returned by the `listTables` method in [[Catalog]].
 *
 * @param name name of the table.
 * @param catalog name of the catalog that the table belongs to.
 * @param namespace the namespace that the table belongs to.
 * @param description description of the table.
 * @param tableType type of the table (e.g. view, table).
 * @param isTemporary whether the table is a temporary table.
 * @since 2.0.0
 */
@Stable
class Table(
    val name: String,
    @Nullable val catalog: String,
    @Nullable val namespace: Array[String],
    @Nullable val description: String,
    val tableType: String,
    val isTemporary: Boolean)
  extends DefinedByConstructorParams {

  def this(
      name: String,
      database: String,
      description: String,
      tableType: String,
      isTemporary: Boolean) = {
    this(name, null, Array(database), description, tableType, isTemporary)
  }

  def database: String = {
    if (namespace == null) {
      null
    } else if (namespace.length == 1) {
      namespace(0)
    } else {
      null
    }
  }

  override def toString: String = {
    "Table[" +
      s"name='$name', " +
      Option(catalog).map { d => s"catalog='$d', " }.getOrElse("") +
      Option(database).map { d => s"database='$d', " }.getOrElse("") +
      Option(description).map { d => s"description='$d', " }.getOrElse("") +
      s"tableType='$tableType', " +
      s"isTemporary='$isTemporary']"
  }

}

/**
 * A column in Spark, as returned by `listColumns` method in [[Catalog]].
 *
 * @param name name of the column.
 * @param description description of the column.
 * @param dataType data type of the column.
 * @param nullable whether the column is nullable.
 * @param isPartition whether the column is a partition column.
 * @param isBucket whether the column is a bucket column.
 * @since 2.0.0
 */
@Stable
class Column(
    val name: String,
    @Nullable val description: String,
    val dataType: String,
    val nullable: Boolean,
    val isPartition: Boolean,
    val isBucket: Boolean)
  extends DefinedByConstructorParams {

  override def toString: String = {
    "Column[" +
      s"name='$name', " +
      Option(description).map { d => s"description='$d', " }.getOrElse("") +
      s"dataType='$dataType', " +
      s"nullable='$nullable', " +
      s"isPartition='$isPartition', " +
      s"isBucket='$isBucket']"
  }

}

/**
 * A user-defined function in Spark, as returned by `listFunctions` method in [[Catalog]].
 *
 * @param name name of the function.
 * @param database name of the database the function belongs to.
 * @param description description of the function; description can be null.
 * @param className the fully qualified class name of the function.
 * @param isTemporary whether the function is a temporary function or not.
 * @since 2.0.0
 */
@Stable
class Function(
    val name: String,
    @Nullable val database: String,
    @Nullable val description: String,
    val className: String,
    val isTemporary: Boolean)
  extends DefinedByConstructorParams {

  override def toString: String = {
    "Function[" +
      s"name='$name', " +
      Option(database).map { d => s"database='$d', " }.getOrElse("") +
      Option(description).map { d => s"description='$d', " }.getOrElse("") +
      s"className='$className', " +
      s"isTemporary='$isTemporary']"
  }

}


text:
/**
 * Series rulesets.
 */

if (typeof circus == 'undefined') circus = {};

circus.ruleset = (function() {

	var op = [
		{op: '=', label: 'is'},
		{op: '>', label: '>'},
		{op: '<', label: '<'},
		{op: '>=', label: '>='},
		{op: '<=', label: '<='},
		{op: '!=', label: 'is not'},
		{op: '*=', label: 'contains'},
		{op: '^=', label: 'begins with'},
		{op: '$=', label: 'ends with'}
	];
	var oph = {};
	for (var i = 0; i < op.length; i++) oph[op[i].op] = op[i];

	/**
	 * Converts the given filter node into human-readable format.
	 */
	function stringifyNode(node)
	{
		var depth = arguments[1] ? arguments[1] : 0;

		function stringifyGroupNode(node)
		{
			var result = $('').addClass('group-text');
			for (var i = 0; i < node.members.length; i++)
			{
				if (i > 0)
					result.append(
						' ',
						$('').addClass('group-type-text').text(node.group),
						' '
					);
				result.append(stringifyNode(node.members[i], depth + 1));
			}
			if (depth)
			{
				result.prepend($('('));
				result.append($(')'));
			}
			return result;
		}

		function stringifyComparisonNode(node)
		{
			return $('').addClass('comparison-text').append(
				$('').addClass('key-text').text(node.key),
				' ',
				$('').addClass('condition-text').text(oph[node.condition].label),
				' ',
				$('').addClass('value-text').text(node.value)
			);
		}

		if (node.members instanceof Array)
			return stringifyGroupNode(node);
		else if (node.key !== undefined)
			return stringifyComparisonNode(node);
		else
			throw "exception";
	}

	function stringifyRule(rule)
	{
		var results = [];
		var st = parseInt(rule.start_img_num) || 0;
		var ed = parseInt(rule.end_img_num) || 0;
		if (st > 0 || ed > 0)
			results.push('Clip(' + st + ' - ' + ed + ')');
		if (typeof(rule.required_private_tags) == 'string'
			&& rule.required_private_tags.length > 0)
		{
			results.push('Require private tags(' + rule.required_private_tags + ')');
		}
		if (rule.image_delta > 0)
		{
			results.push('Direction(forward)');
		}
		if (rule.image_delta < 0)
		{
			results.push('Direction(reverse)');
		}
		if (rule.environment)
		{
			results.push('Environment(' + rule.environment + ')');
		}
		if (rule.continuous)
		{
			results.push('Continuous');
		}

		return results.join(', ');
	}

	return {
		op: op,
		stringifyNode: stringifyNode,
		stringifyRule: stringifyRule
	};
})();


text:
using System;
using Newtonsoft.Json;

namespace PodioAPI.Models
{
    public class SearchResult
    {
        [JsonProperty("id")]
        public int Id { get; set; }

        [JsonProperty("type")]
        public string Type { get; set; }

        [JsonProperty("rank")]
        public int Rank { get; set; }

        [JsonProperty("title")]
        public string Title { get; set; }

        [JsonProperty("created_on")]
        public DateTime CreatedOn { get; set; }

        [JsonProperty("link")]
        public string Link { get; set; }

        [JsonProperty("app")]
        public Application App { get; set; }

        [JsonProperty("org")]
        public OrganizationMicro Org { get; set; }

        [JsonProperty("space")]
        public SpaceMicro Space { get; set; }

        [JsonProperty("created_by")]
        public ByLine CreatedBy { get; set; }
    }
}