text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.dataprotection.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.dataprotection.fluent.models.BackupVaultResourceInner;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;

/** BackupVaultResourceList List of BackupVault resources. */
@Fluent
public final class BackupVaultResourceList extends DppResourceList {
    @JsonIgnore private final ClientLogger logger = new ClientLogger(BackupVaultResourceList.class);

    /*
     * List of resources.
     */
    @JsonProperty(value = "value")
    private List<BackupVaultResourceInner> value;

    /**
     * Get the value property: List of resources.
     *
     * @return the value value.
     */
    public List<BackupVaultResourceInner> value() {
        return this.value;
    }

    /**
     * Set the value property: List of resources.
     *
     * @param value the value value to set.
     * @return the BackupVaultResourceList object itself.
     */
    public BackupVaultResourceList withValue(List<BackupVaultResourceInner> value) {
        this.value = value;
        return this;
    }

    /** {@inheritDoc} */
    @Override
    public BackupVaultResourceList withNextLink(String nextLink) {
        super.withNextLink(nextLink);
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    @Override
    public void validate() {
        super.validate();
        if (value() != null) {
            value().forEach(e -> e.validate());
        }
    }
}


text:
import socket
import sys

def is_hostname_reverse_resolving_correctly():
    '''Check if the primary IP addr for our host reverse-resolves correctly. Also returns true
       if no reverse resolve defined. This is useful for server processes like Java that sometimes
       use the '''
    my_hostname = socket.gethostname()
    my_ipaddr = socket.gethostbyname(my_hostname)
    try:
       (reverse_hostname, reverse_aliaslist, reverse_ipaddrlist) = socket.gethostbyaddr(my_ipaddr)
    except socket.herror:
       # Then there's no reverse-DNS, normal on a DHCP network.
       return True
    try:
        reverse_hostname_to_ipaddr = socket.gethostbyname(reverse_hostname)
    except:
        print >>sys.stderr, "Warning: local hostname %s running on %s, but %s reverse-resolves to invalid host %s." % \
            (my_hostname, my_ipaddr, my_ipaddr, reverse_hostname)
        return False
    return True

redpajama_set_name: RedPajamaGithub


text: from cavelink import *


text:
using System;
using System.ComponentModel;
using IdSharp.Tagging.ID3v2.Frames.Items;

namespace IdSharp.Tagging.ID3v2.Frames
{
    ///
    /// <para>Commercial frame</para>
    ///
    /// <para>From the ID3v2 specification:</para>
    ///
    ///    <para>This frame enables several competing offers in the same tag by
    ///    bundling all needed information. That makes this frame rather complex
    ///    but it's an easier solution than if one tries to achieve the same
    ///    result with several frames. The frame begins, after the frame ID,
    ///    size and encoding fields, with a price string field. A price is
    ///    constructed by one three character currency code, encoded according
    ///    to ISO-4217 alphabetic currency code, followed by a
    ///    numerical value where "." is used as decimal separator. In the price
    ///    string several prices may be concatenated, separated by a "/"
    ///    character, but there may only be one currency of each type.</para>
    ///
    ///    <para>The price string is followed by an 8 character date string in the
    ///    format YYYYMMDD, describing for how long the price is valid. After
    ///    that is a contact URL, with which the user can contact the seller,
    ///    followed by a one byte 'received as' field. It describes how the
    ///    audio is delivered when bought according to the following list:</para>
    ///
    ///         <para>$00  Other

    ///         $01  Standard CD album with other songs

    ///         $02  Compressed audio on CD

    ///         $03  File over the Internet

    ///         $04  Stream over the Internet

    ///         $05  As note sheets

    ///         $06  As note sheets in a book with other sheets

    ///         $07  Music on other media

    ///         $08  Non-musical merchandise</para>
    ///
    ///    <para>Next follows a terminated string with the name of the seller followed
    ///    by a terminated string with a short description of the product. The
    ///    last thing is the ability to include a company logotype. The first of
    ///    them is the 'Picture MIME type' field containing information about
    ///    which picture format is used. In the event that the MIME media type
    ///    name is omitted, "image/" will be implied. Currently only "image/png"
    ///    and "image/jpeg" are allowed. This format string is followed by the
    ///    binary picture data. This two last fields may be omitted if no
    ///    picture is attached. There may be more than one 'commercial frame' in
    ///    a tag, but no two may be identical.</para>
    ///
    ///      <para>[Header for 'Commercial frame', ID: "COMR"]

    ///      Text encoding      $xx

    ///      Price string       [text string] $00

    ///      Valid until        [text string]

    ///      Contact URL        [text string] $00

    ///      Received as        $xx

    ///      Name of seller     [text string according to encoding] $00 (00)

    ///      Description        [text string according to encoding] $00 (00)

    ///      Picture MIME type  [string] $00

    ///      Seller logo        [binary data]</para>
    ///
    public interface ICommercial : IFrame, ITextEncoding
    {
        ///
        /// Gets the BindingList of price information.
        ///
        /// <value>The BindingList of price information.</value>
        BindingList<IPriceInformation> PriceList { get; }

        ///
        /// Gets or sets the date which the price is valid until.
        ///
        /// <value>The date which the price is valid until.</value>
        DateTime ValidUntil { get; set; }

        ///
        /// Gets or sets the contact URL for the seller.
        ///
        /// <value>The contact URL for the seller.</value>
        string ContactUrl { get; set; }

        ///
        /// Gets or sets how the audio is delivered when bought.
        ///
        /// <value>How the audio is delivered when bought.</value>
        ReceivedAs ReceivedAs { get; set; }

        ///
        /// Gets or sets the name of the seller.
        ///
        /// <value>The name of the seller.</value>
        string NameOfSeller { get; set; }

        ///
        /// Gets or sets a short description of the product.
        ///
        /// <value>The short description of the product.</value>
        string Description { get; set; }

        ///
        /// Gets or sets the MIME type of the seller logo.
        ///
        /// <value>The MIME type of the seller logo.</value>
        string SellerLogoMimeType { get; set; }

        ///
        /// Gets or sets the seller logo.  Returns a copy of the raw data, therefore the byte array cannot
        /// be modified directly.  Use the set property to update the raw data.
        ///
        /// <value>The seller logo.</value>
        byte[] SellerLogo { get; set; }
    }
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Cores_model extends CI_Model {

	public function __construct() {
		parent::__construct();

		$this->load->database();
	}

	public function getAll(): array {
		return $this->db->get('cores')->result_array();
	}
}


text:
(function() {
  angular.module('adminApp')
    .component('content', {
      controller: ContentController,
      controllerAs: '$content',
      templateUrl: './angular_app/components/content/content.component.html'
    });

  function ContentController() {
    var vm = this;

    vm.$onInit = onInit;

    function onInit() {
    }
  }
})();


text:
package com.fasterxml.jackson.databind.introspect;

import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.DeserializationConfig;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.cfg.MapperConfig;

/**
 * Helper class used to introspect features of POJO value classes
 * used with Jackson. The main use is for finding out
 * POJO construction (creator) and value access (getters, setters)
 * methods and annotations that define configuration of using
 * those methods.
 */
public abstract class ClassIntrospector
{
    /*
    /**********************************************************
    /* Helper interfaces
    /**********************************************************
     */

    /**
     * Interface used for decoupling details of how mix-in annotation
     * definitions are accessed (via this interface), and how
     * they are stored (defined by classes that implement the interface)
     */
    public interface MixInResolver
    {
        /**
         * Method that will check if there are "mix-in" classes (with mix-in
         * annotations) for given class
         */
        public Class<?> findMixInClassFor(Class<?> cls);

        /**
         * Method called to create a new, non-shared copy, to be used by different
         * ObjectMapper instance, and one that should not be connected
         * to this instance, if resolver has mutable state.
         * If resolver is immutable may simply return `this`.
         *
         * @since 2.6
         */
        public MixInResolver copy();
    }

    protected ClassIntrospector() { }

    /**
     * Method that may be needed when `copy()`ing `ObjectMapper` instances.
     *
     * @since 2.9.6
     */
    public abstract ClassIntrospector copy();

    /*
    /**********************************************************
    /* Public API: factory methods
    /**********************************************************
     */

    /**
     * Factory method that constructs an introspector that has all
     * information needed for serialization purposes.
     */
    public abstract BeanDescription forSerialization(SerializationConfig cfg,
    		JavaType type, MixInResolver r);

    /**
     * Factory method that constructs an introspector that has all
     * information needed for deserialization purposes.
     */
    public abstract BeanDescription forDeserialization(DeserializationConfig cfg,
    		JavaType type, MixInResolver r);

    /**
     * Factory method that constructs an introspector that has all
     * information needed for constructing deserializers that use
     * intermediate Builder objects.
     *
     * @since 2.12
     */
    public abstract BeanDescription forDeserializationWithBuilder(DeserializationConfig cfg,
            JavaType builderType, MixInResolver r, BeanDescription valueTypeDesc);

    /**
     * @deprecated Since 2.12 use overload that take value type description
     */
    @Deprecated
    public abstract BeanDescription forDeserializationWithBuilder(DeserializationConfig cfg,
            JavaType builderType, MixInResolver r);

    /**
     * Factory method that constructs an introspector that has
     * information necessary for creating instances of given
     * class ("creator"), as well as class annotations, but
     * no information on member methods
     */
    public abstract BeanDescription forCreation(DeserializationConfig cfg, JavaType type,
            MixInResolver r);

    /**
     * Factory method that constructs an introspector that only has
     * information regarding annotations class itself (or its supertypes) has,
     * but nothing on methods or constructors.
     */
    public abstract BeanDescription forClassAnnotations(MapperConfig<?> cfg, JavaType type,
            MixInResolver r);

    /**
     * Factory method that constructs an introspector that only has
     * information regarding annotations class itself has (but NOT including
     * its supertypes), but nothing on methods or constructors.
     */
    public abstract BeanDescription forDirectClassAnnotations(MapperConfig<?> cfg, JavaType type,
            MixInResolver r);
}


text:
package com.lchtime.safetyexpress.ui.vip;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lchtime.safetyexpress.R;
import com.lchtime.safetyexpress.ui.BaseUI;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;

/**
 * 关于我们
 * Created by user on 2017/4/17.
 */
@ContentView(R.layout.vip_setting_about_us_ui)
public class VipSettingAboutUsUI extends BaseUI {

    @ViewInject(R.id.ll_setting_push)
    LinearLayout mCallPhoneLl; //打电话
    @ViewInject(R.id.tv_phone)
    TextView mPhoneTv;

    private AlertDialog mDialog;

    @Override
    protected void back() {
        finish();
    }

    @Override
    protected void setControlBasis() {
        setTitle("关于我们");
        final String phone = mPhoneTv.getText().toString().trim();
        if (phone != null)
            mCallPhoneLl.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                    builder.setTitle("确认拨打电话?")
                            .setMessage(phone)
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            })
                            .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone));
                                    if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                                        // TODO: Consider calling
                                        //    ActivityCompat#requestPermissions
                                        // here to request the missing permissions, and then overriding
                                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                        //                                          int[] grantResults)
                                        // to handle the case where the user grants the permission. See the documentation
                                        // for ActivityCompat#requestPermissions for more details.
                                        return;
                                    }
                                    startActivity(intent);
                            }
                        });
                mDialog = builder.create();
                mDialog.show();
            }
        });

    }

    @Override
    protected void prepareData() {

    }
}


text:
Enexure.Sql.Dynamic
===================
[![Build status](https://ci.appveyor.com/api/projects/status/1ev9rhfabj5y4jli/branch/master?svg=true)](https://ci.appveyor.com/project/Daniel45729/enexure-sql-dynamic/branch/master)

Dynamic Sql Generation Library

##How to use

All queryies start by creating a `Query` from a `TabularDataSource` this could be a table to a derived table (subquery).

	var tableA = new Table("TableA").As("a");
	var tableB = new Table("TableB").As("b");

	var query = Query
		.From(tableA)
		.Join(tableB, Expression.Eq(tableA.Field("Id"), tableB.Field("Fk")))
		.Where(Expression.Eq(tableA.Field("Id"), Expression.Const(1)))
		.Select(tableA.Field("Id"), tableB.All());

The entire query api is immutable, which means copying and reusing parts of any query is easy.

	var people = new Table("People").As("p");

	var queryBase = Query.From(people);

	var countQuery = queryBase.Select(Field.All.Count())
	var resultsQuery = queryBase.Select(people.All());

## Providers

Once you've constructed your query you need to use a provider to generate the DbCommand and SQL.

	// Get the DbCommand
	var command = TSqlProvider.GetCommand(query)

	// Get the just SQL, great for debugging
	var sql = TSqlProvider.GetSqlString(query);

The resulting SQL for the query above looks like the following.

	select [a].[Id], [b].*
	from [TableA] [a]
	join [TableB] [b] on [a].[Id] = [b].[Fk]
	where [a].[Id] = @p0


text:
@interface MLSMineMoudle : BaseMoudle

@end


text:
package org.apereo.cas.gua.impl;

import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.gua.api.UserGraphicalAuthenticationRepository;
import org.apereo.cas.util.CollectionUtils;
import org.apereo.cas.util.LdapUtils;

import com.google.common.io.ByteSource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.ldaptive.LdapException;
import org.ldaptive.ReturnAttributes;
import org.ldaptive.SearchResponse;

/**
 * This is {@link LdapUserGraphicalAuthenticationRepository}.
 *
 * @author Misagh Moayyed
 * @since 5.1.0
 */
@Slf4j
@RequiredArgsConstructor
public class LdapUserGraphicalAuthenticationRepository implements UserGraphicalAuthenticationRepository {
    private static final long serialVersionUID = 421732017215881244L;

    private final CasConfigurationProperties casProperties;

    @Override
    public ByteSource getGraphics(final String username) {
        try {
            val gua = casProperties.getAuthn().getGua();
            val response = searchForId(username);
            if (LdapUtils.containsResultEntry(response)) {
                val entry = response.getEntry();
                val attribute = entry.getAttribute(gua.getLdap().getImageAttribute());
                if (attribute != null && attribute.isBinary()) {
                    return ByteSource.wrap(attribute.getBinaryValue());
                }
            }
        } catch (final Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return ByteSource.empty();
    }

    private SearchResponse searchForId(final String id) throws LdapException {
        val gua = casProperties.getAuthn().getGua();
        val filter = LdapUtils.newLdaptiveSearchFilter(gua.getLdap().getSearchFilter(),
            LdapUtils.LDAP_SEARCH_FILTER_DEFAULT_PARAM_NAME,
            CollectionUtils.wrap(id));
        return LdapUtils.executeSearchOperation(
            LdapUtils.newLdaptiveConnectionFactory(gua.getLdap()),
            gua.getLdap().getBaseDn(),
            filter,
            0,
            new String[]{gua.getLdap().getImageAttribute()},
            ReturnAttributes.ALL_USER.value());
    }

}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.jeo</groupId>
    <artifactId>format</artifactId>
    <version>0-SNAPSHOT</version>
  </parent>

  <artifactId>jeo-geojson</artifactId>
  <name>GeoJSON Driver</name>
  <packaging>jar</packaging>

  <dependencies>
    <dependency>
      <groupId>org.jeo</groupId>
      <artifactId>jeo-core</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>com.googlecode.json-simple</groupId>
      <artifactId>json-simple</artifactId>
      <version>1.1.1</version>
    </dependency>
    <dependency>
      <groupId>org.jeo</groupId>
      <artifactId>jeo-core</artifactId>
      <version>${project.version}</version>
      <scope>test</scope>
      <classifier>tests</classifier>
    </dependency>
  </dependencies>

</project>


text:
package org.apache.geode.redis.internal.executor.hll;

import java.util.ArrayList;
import java.util.List;

import org.apache.geode.cache.Region;
import org.apache.geode.internal.hll.CardinalityMergeException;
import org.apache.geode.internal.hll.HyperLogLogPlus;
import org.apache.geode.redis.internal.ByteArrayWrapper;
import org.apache.geode.redis.internal.Coder;
import org.apache.geode.redis.internal.Command;
import org.apache.geode.redis.internal.ExecutionHandlerContext;
import org.apache.geode.redis.internal.RedisDataType;
import org.apache.geode.redis.internal.RedisConstants.ArityDef;

public class PFMergeExecutor extends HllExecutor {

  @Override
  public void executeCommand(Command command, ExecutionHandlerContext context) {
    List<byte[]> commandElems = command.getProcessedCommand();

    if (commandElems.size() < 3) {
      command.setResponse(Coder.getErrorResponse(context.getByteBufAllocator(), ArityDef.PFMERGE));
      return;
    }

    ByteArrayWrapper destKey = command.getKey();
    checkAndSetDataType(destKey, context);
    Region<ByteArrayWrapper, HyperLogLogPlus> keyRegion =
        context.getRegionProvider().gethLLRegion();
    HyperLogLogPlus mergedHLL = keyRegion.get(destKey);
    if (mergedHLL == null)
      mergedHLL = new HyperLogLogPlus(DEFAULT_HLL_DENSE);
    List<HyperLogLogPlus> hlls = new ArrayList<HyperLogLogPlus>();

    for (int i = 2; i < commandElems.size(); i++) {
      ByteArrayWrapper k = new ByteArrayWrapper(commandElems.get(i));
      checkDataType(k, RedisDataType.REDIS_HLL, context);
      HyperLogLogPlus h = keyRegion.get(k);
      if (h != null)
        hlls.add(h);
    }
    if (hlls.isEmpty()) {
      context.getRegionProvider().removeKey(destKey);
      command.setResponse(Coder.getSimpleStringResponse(context.getByteBufAllocator(), "OK"));
      return;
    }

    HyperLogLogPlus[] estimators = hlls.toArray(new HyperLogLogPlus[hlls.size()]);
    try {
      mergedHLL = (HyperLogLogPlus) mergedHLL.merge(estimators);
    } catch (CardinalityMergeException e) {
      throw new RuntimeException(e);
    }
    keyRegion.put(destKey, mergedHLL);
    command.setResponse(Coder.getSimpleStringResponse(context.getByteBufAllocator(), "OK"));
  }

}


text:
require 'yaml'

module PVersion
  class MigrationsYaml
    def self.build(root_path)
      migration_file_paths = Dir.glob(File.expand_path(File.join(root_path, 'content_migrations', '*.yml')))
      fail "I can't figure out which content_migrations YAML file to use!" unless migration_file_paths.size == 1

      migrations_yaml_path = migration_file_paths.first
      migrations_yaml = YAML.load_file(migrations_yaml_path)
      new(migrations_yaml, migrations_yaml_path)
    end

    def initialize(migrations_hash, migrations_yaml_path)
      @migrations_hash = migrations_hash
      @migrations_yaml_path = migrations_yaml_path
    end

    def old_version
      migrations_hash.fetch('to_version')
    end

    def new_version
      number = old_version.match(/([0-9]+)$/)[-1]
      next_number = number.to_i + 1
      old_version.gsub(/[0-9]+$/, next_number.to_s)
    end

    def bump_version_and_save
      save(hash_with_bumped_version.to_yaml)
    end

    private

    attr_reader :migrations_hash, :migrations_yaml_path

    def hash_with_bumped_version
      updated_migrations_hash = migrations_hash.dup
      updated_migrations_hash['to_version'] = new_version

      migrations = updated_migrations_hash.fetch('migrations')
      migrations.each do |migration|
        rules = migration.fetch('rules')
        rules.each do |rule|
          next unless rule.fetch('type') == 'update' && rule.fetch('selector') == 'product_version'
          rule['to'] = new_version
        end
      end

      updated_migrations_hash
    end

    def save(contents)
      File.open(migrations_yaml_path, 'w') do |f|
        f.write(contents)
      end
    end

    def product_name
      migrations_hash.fetch('name')
    end
  end
end


text:
import urllib
import json

def searchPortal(portal, query=None, totalResults=None, sortField='numviews', sortOrder='desc', token=None):
    '''
    Search the portal using the specified query and search parameters.
    Optionally provide a token to return results visible to that user.
    More examples on advanced search operators here:
    https://github.com/esri/ago-tools/blob/master/search-cheat-sheet.md
    '''
    # Default results are returned by highest number of views in descending order.
    allResults = []
    if not totalResults or totalResults > 100:
        numResults = 100
    else:
        numResults = totalResults
    results = __search__(portal, query, numResults, sortField, sortOrder, 0, token)

    if not 'error' in results.keys():
        if not totalResults:
            totalResults = results['total'] # Return all of the results.
        allResults.extend(results['results'])
        while results['nextStart'] > 0 and results['nextStart'] < totalResults:
            # Do some math to ensure it only returns the total results requested.
            numResults = min(totalResults - results['nextStart'] + 1, 100)
            results = __search__(portal=portal, query=query, numResults=numResults, sortField=sortField,
                                sortOrder=sortOrder, token=token, start=results['nextStart'])
            allResults.extend(results['results'])
        return allResults
    else:
        print results['error']['message']
        return results

def __search__(portal, query=None, numResults=100, sortField='numviews', sortOrder='desc', start=0, token=None):
    '''Retrieve a single page of search results.'''
    params = {
        'q': query,
        'num': numResults,
        'sortField': sortField,
        'sortOrder': sortOrder,
        'f': 'json',
        'start': start
    }
    if token:
        params['token'] = token # Adding a token provides an authenticated search.
    request = portal + '/sharing/rest/search?' + urllib.urlencode(params)
    results = json.loads(urllib.urlopen(request).read())
    return results

class Utilities:
    '''A class of tools for working with content in an AGO account'''
    def __init__(self, username, portal=None, password=None):
        from . import User
        self.user = User(username, portal, password)

    def updateWebmapService(self, webmapId, oldUrl, newUrl, folderID=None):
        try:
            params = urllib.urlencode({'token' : self.user.token,
                                       'f' : 'json'})
            print 'Getting Info for: ' + webmapId
            #Get the item data
            reqUrl = self.user.portalUrl + '/sharing/content/items/' + webmapId + '/data?' + params
            itemDataReq = urllib.urlopen(reqUrl).read()
            itemString = str(itemDataReq)

            #See if it needs to be updated
            if itemString.find(oldUrl) > -1:
                #Update the map
                newString = itemString.replace(oldUrl, newUrl)
                #Get the item's info for the addItem parameters
                itemInfoReq = urllib.urlopen(self.user.portalUrl + '/sharing/content/items/' + webmapId + '?' + params)
                itemInfo = json.loads(itemInfoReq.read(), object_hook=self.__decode_dict__)
                print 'Updating ' + itemInfo['title']

                #Set up the addItem parameters
                outParamObj = {
                    'extent' : ', '.join([str(itemInfo['extent'][0][0]), str(itemInfo['extent'][0][1]), str(itemInfo['extent'][1][0]), str(itemInfo['extent'][1][1])]),
                    'type' : itemInfo['type'],
                    'item' : itemInfo['item'],
                    'title' : itemInfo['title'],
                    'overwrite' : 'true',
                    'tags' : ','.join(itemInfo['tags']),
                    'text' : newString
                }
                # Get the item folder.
                if itemInfo['ownerFolder']:
                    folderID = itemInfo['ownerFolder']
                else:
                    folderID = ''
                #Post back the changes overwriting the old map
                modRequest = urllib.urlopen(self.user.portalUrl + '/sharing/content/users/' + self.user.username + '/' + folderID + '/addItem?' + params , urllib.urlencode(outParamObj))
                #Evaluate the results to make sure it happened
                modResponse = json.loads(modRequest.read())
                if modResponse.has_key('error'):
                    raise AGOPostError(webmapId, modResponse['error']['message'])
                else:
                    print "Successfully updated the urls"
            else:
                print 'Didn\'t find any services for ' + oldUrl
        except ValueError as e:
            print 'Error - no web maps specified'
        except AGOPostError as e:
            print 'Error updating web map ' + e.webmap + ": " + e.msg

    def updateItemUrl(self, itemId, oldUrl, newUrl, folderID=None):
        '''
        Use this to update the URL for items such as Map Services.
        The oldUrl parameter is required as a check to ensure you are not
        accidentally changing the wrong item or url.
        This can also replace part of a URL. The text of oldUrl is replaced with the text of newUrl. For example you could change just the host name of your URLs.
        '''
        try:
            params = urllib.urlencode({'token' : self.user.token,
                                       'f' : 'json'})
            print 'Getting Info for: ' + itemId
            # Get the item data
            reqUrl = self.user.portalUrl + '/sharing/rest/content/items/' + itemId + '?' + params
            itemReq = urllib.urlopen(reqUrl).read()
            itemString = str(itemReq)
            itemInfo = json.loads(itemString)

            if not itemInfo.has_key('url'):
                print itemInfo['title'] + ' doesn\'t have a url property'
                return
            print 'Updating ' + itemInfo['title']
            existingURL = itemInfo['url']

            # Double check that the existing URL matches the provided URL
            if itemString.find(oldUrl) > -1:
                # Get the item folder.
                if itemInfo['ownerFolder']:
                    folderID = itemInfo['ownerFolder']
                else:
                    folderID = ''
                # Update the item URL
                updatedURL = existingURL.replace(oldUrl, newUrl)
                updateParams = urllib.urlencode({'url' : updatedURL})
                updateUrl = self.user.portalUrl + '/sharing/rest/content/users/' + self.user.username + '/' + folderID + '/items/' + itemId + '/update?' + params
                updateReq = urllib.urlopen(updateUrl, updateParams).read()
                modResponse = json.loads(updateReq)
                if modResponse.has_key('success'):
                    print "Successfully updated the url."
                else:
                    raise AGOPostError(itemId, modResponse['error']['message'])
            else:
                print 'Didn\'t find the specified old URL: ' + oldUrl
        except ValueError as e:
            print e
        except AGOPostError as e:
            print 'Error updating item: ' + e.msg

    def updatewebmapversionAGX(self, webmapId, folderID=None):
        '''Update the web map version from 1.9x to 1.7x so that the new web maps can be opened in ArcGIS Explorer Online.'''
        try:
            params = urllib.urlencode({'token' : self.user.token,
                                       'f' : 'json'})
            print 'Getting Info for: ' + webmapId
            #Get the item data
            reqUrl = self.user.portalUrl + '/sharing/content/items/' + webmapId + '/data?' + params
            itemDataReq = urllib.urlopen(reqUrl).read()
            itemString = str(itemDataReq)

            itemString = itemString.replace('1.9', '1.7')

            itemInfoReq = urllib.urlopen(self.user.portalUrl + '/sharing/content/items/' + webmapId + '?' + params)
            itemInfo = json.loads(itemInfoReq.read(), object_hook=self.__decode_dict__)
            print 'Updating ' + itemInfo['title']

            #Set up the addItem parameters
            outParamObj = {
                'extent' : ', '.join([str(itemInfo['extent'][0][0]), str(itemInfo['extent'][0][1]), str(itemInfo['extent'][1][0]), str(itemInfo['extent'][1][1])]),
                'type' : itemInfo['type'],
                'item' : itemInfo['item'],
                'title' : itemInfo['title'],
                'overwrite' : 'true',
                'tags' : ','.join(itemInfo['tags']),
                'text' : itemString
            }
            # Get the item folder.
            if itemInfo['ownerFolder']:
                folderID = itemInfo['ownerFolder']
            else:
                folderID = ''

            #Post back the changes overwriting the old map
            modRequest = urllib.urlopen(self.user.portalUrl + '/sharing/content/users/' + self.user.username + '/' + folderID + '/addItem?' + params , urllib.urlencode(outParamObj))
            #Evaluate the results to make sure it happened
            modResponse = json.loads(modRequest.read())
            if modResponse.has_key('error'):
                raise AGOPostError(webmapId, modResponse['error']['message'])
            else:
                print "Successfully updated the version"

        except ValueError as e:
            print 'Error - no web maps specified'
        except AGOPostError as e:
            print 'Error updating web map ' + e.webmap + ": " + e.msg

    def getFolderItems(self, folderId, userName=None):
        '''
        Returns all items (list of dictionaries) for an AGOL folder using the folder ID.
        folderID -- The unique id for the folder. Use getFolderID to find the folder ID for a folder name.
        userName -- The user who owns the folder. If not specified, the user initialized with this object is used.
        '''
        if userName == None:
            userName = self.user.username
        params = urllib.urlencode({'token': self.user.token, 'f': 'json'})
        request = self.user.portalUrl + '/sharing/rest/content/users/' + userName + '/' + folderId + '?' + params
        folderContent = json.loads(urllib.urlopen(request).read())
        return folderContent['items']

    def getUserFolders(self, userName=None):
        '''
        Returns all folders (list of dictionaries) for an AGOL user.
        userName -- The user who owns the folder. If not specified, the user initialized with this object is used.
        '''
        if userName == None:
            userName = self.user.username
        parameters = urllib.urlencode({'token': self.user.token, 'f': 'json'})
        request = self.user.portalUrl + '/sharing/rest/content/users/' + userName + '?' + parameters
        userContent = json.loads(urllib.urlopen(request).read())
        return userContent['folders']

    def getFolderID(self, folderTitle, userName=None):
        '''
        Returns the folder ID given a case insensitive folder title.
        folderTitle -- The title (name) of a folder.
        userName -- The user who owns the folder. If not specified, the user initialized with this object is used.
        '''
        if userName == None:
            userName = self.user.username
        folders = self.getUserFolders(userName)
        for folder in folders:
            if folder['title'].upper() == folderTitle.upper():
                return folder['id']
                break

    def updateURLs(self, oldUrl, newUrl, items, folderID=None):
        '''
        Updates the URL or URL part for all URLs in a list of AGOL items.
        This works for all item types that store a URL. (e.g. web maps, map services, applications, etc.)
        oldUrl -- All or part of a URL to search for.
        newUrl -- The text that will be used to replace the current "oldUrl" text.
        '''
        for item in items:
            if item['type'] == 'Web Map':
                self.updateWebmapService(item['id'], oldUrl, newUrl, folderID)
            else:
                if item.has_key('url') and not item['url'] == None:
                    self.updateItemUrl(item['id'], oldUrl, newUrl, folderID)

    def __decode_dict__(self, dct):
        newdict = {}
        for k, v in dct.iteritems():
            k = self.__safeValue__(k)
            v = self.__safeValue__(v)
            newdict[k] = v
        return newdict

    def __safeValue__(self, inVal):
        outVal = inVal
        if isinstance(inVal, unicode):
            outVal = inVal.encode('utf-8')
        elif isinstance(inVal, list):
            outVal = self.__decode_list__(inVal)
        return outVal

    def __decode_list__(self, lst):
        newList = []
        for i in lst:
            i = self.__safeValue__(i)
            newList.append(i)
        return newList

    def __getItemFolder__(self, itemId):
        '''Finds the foldername for a particular item.'''
        # This method is probably not needed anymore as the item folder
        # is returned in the description response ('ownerFolder').
        # Recommend deprecating this function or rewriting it to use the simple
        # description request and return 'ownerFolder'.
        parameters = urllib.urlencode({'token' : self.user.token,
                                       'f' : 'json'})
        response = json.loads(urllib.urlopen(self.user.portalUrl + '/sharing/rest/content/users/' + self.user.username + '?' + parameters).read())
        for item in response['items']:
            if item['id'] == itemId:
                return ''
        for folder in response['folders']:
            folderContent = self.__getFolderContent__(folder['id'])
            for item in folderContent['items']:
                if item['id'] == itemId:
                    return folder['id']

    def __getFolderContent__(self, folderId):
        '''Lists all of the items in a folder.'''
        parameters = urllib.urlencode({'token' : self.user.token,
                                       'f' : 'json'})
        response = json.loads(urllib.urlopen(self.user.portalUrl + '/sharing/rest/content/users/' + self.user.username + '/' + folderId + '?' + parameters).read())
        return response

class AGOPostError(Exception):
    def __init__(self, webmap, msg):
        self.webmap = webmap
        self.msg = msg


text:
import {
  PerformanceEntries,
  PerformanceResourceTimingInfo,
  PropagateTraceHeaderCorsUrls,
} from './types';
import { PerformanceTimingNames as PTN } from './enums/PerformanceTimingNames';
import * as api from '@opentelemetry/api';
import {
  hrTimeToNanoseconds,
  timeInputToHrTime,
  urlMatches,
} from '@opentelemetry/core';
import { SemanticAttributes } from '@opentelemetry/semantic-conventions';

// Used to normalize relative URLs
let urlNormalizingAnchor: HTMLAnchorElement | undefined;
function getUrlNormalizingAnchor(): HTMLAnchorElement {
  if (!urlNormalizingAnchor) {
    urlNormalizingAnchor = document.createElement('a');
  }

  return urlNormalizingAnchor;
}

/**
 * Helper function to be able to use enum as typed key in type and in interface when using forEach
 * @param obj
 * @param key
 */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function hasKey<O>(obj: O, key: keyof any): key is keyof O {
  return key in obj;
}

/**
 * Helper function for starting an event on span based on {@link PerformanceEntries}
 * @param span
 * @param performanceName name of performance entry for time start
 * @param entries
 */
export function addSpanNetworkEvent(
  span: api.Span,
  performanceName: string,
  entries: PerformanceEntries
): api.Span | undefined {
  if (
    hasKey(entries, performanceName) &&
    typeof entries[performanceName] === 'number'
  ) {
    span.addEvent(performanceName, entries[performanceName]);
    return span;
  }
  return undefined;
}

/**
 * Helper function for adding network events
 * @param span
 * @param resource
 */
export function addSpanNetworkEvents(
  span: api.Span,
  resource: PerformanceEntries
): void {
  addSpanNetworkEvent(span, PTN.FETCH_START, resource);
  addSpanNetworkEvent(span, PTN.DOMAIN_LOOKUP_START, resource);
  addSpanNetworkEvent(span, PTN.DOMAIN_LOOKUP_END, resource);
  addSpanNetworkEvent(span, PTN.CONNECT_START, resource);
  addSpanNetworkEvent(span, PTN.SECURE_CONNECTION_START, resource);
  addSpanNetworkEvent(span, PTN.CONNECT_END, resource);
  addSpanNetworkEvent(span, PTN.REQUEST_START, resource);
  addSpanNetworkEvent(span, PTN.RESPONSE_START, resource);
  addSpanNetworkEvent(span, PTN.RESPONSE_END, resource);
  const encodedLength = resource[PTN.ENCODED_BODY_SIZE];
  if (encodedLength !== undefined) {
    span.setAttribute(
      SemanticAttributes.HTTP_RESPONSE_CONTENT_LENGTH,
      encodedLength
    );
  }
  const decodedLength = resource[PTN.DECODED_BODY_SIZE];
  // Spec: Not set if transport encoding not used (in which case encoded and decoded sizes match)
  if (decodedLength !== undefined && encodedLength !== decodedLength) {
    span.setAttribute(
      SemanticAttributes.HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED,
      decodedLength
    );
  }
}

/**
 * sort resources by startTime
 * @param filteredResources
 */
export function sortResources(filteredResources: PerformanceResourceTiming[]): PerformanceResourceTiming[] {
  return filteredResources.slice().sort((a, b) => {
    const valueA = a[PTN.FETCH_START];
    const valueB = b[PTN.FETCH_START];
    if (valueA > valueB) {
      return 1;
    } else if (valueA < valueB) {
      return -1;
    }
    return 0;
  });
}

/**
 * Get closest performance resource ignoring the resources that have been
 * already used.
 * @param spanUrl
 * @param startTimeHR
 * @param endTimeHR
 * @param resources
 * @param ignoredResources
 * @param initiatorType
 */
export function getResource(
  spanUrl: string,
  startTimeHR: api.HrTime,
  endTimeHR: api.HrTime,
  resources: PerformanceResourceTiming[],
  ignoredResources: WeakSet<PerformanceResourceTiming> = new WeakSet<PerformanceResourceTiming>(),
  initiatorType?: string
): PerformanceResourceTimingInfo {
  // de-relativize the URL before usage (does no harm to absolute URLs)
  const parsedSpanUrl = parseUrl(spanUrl);
  spanUrl = parsedSpanUrl.toString();

  const filteredResources = filterResourcesForSpan(
    spanUrl,
    startTimeHR,
    endTimeHR,
    resources,
    ignoredResources,
    initiatorType
  );

  if (filteredResources.length === 0) {
    return {
      mainRequest: undefined,
    };
  }
  if (filteredResources.length === 1) {
    return {
      mainRequest: filteredResources[0],
    };
  }
  const sorted = sortResources(filteredResources);

  if (parsedSpanUrl.origin !== location.origin && sorted.length > 1) {
    let corsPreFlightRequest: PerformanceResourceTiming | undefined = sorted[0];
    let mainRequest: PerformanceResourceTiming = findMainRequest(
      sorted,
      corsPreFlightRequest[PTN.RESPONSE_END],
      endTimeHR
    );

    const responseEnd = corsPreFlightRequest[PTN.RESPONSE_END];
    const fetchStart = mainRequest[PTN.FETCH_START];

    // no corsPreFlightRequest
    if (fetchStart < responseEnd) {
      mainRequest = corsPreFlightRequest;
      corsPreFlightRequest = undefined;
    }

    return {
      corsPreFlightRequest,
      mainRequest,
    };
  } else {
    return {
      mainRequest: filteredResources[0],
    };
  }
}

/**
 * Will find the main request skipping the cors pre flight requests
 * @param resources
 * @param corsPreFlightRequestEndTime
 * @param spanEndTimeHR
 */
function findMainRequest(
  resources: PerformanceResourceTiming[],
  corsPreFlightRequestEndTime: number,
  spanEndTimeHR: api.HrTime
): PerformanceResourceTiming {
  const spanEndTime = hrTimeToNanoseconds(spanEndTimeHR);
  const minTime = hrTimeToNanoseconds(
    timeInputToHrTime(corsPreFlightRequestEndTime)
  );

  let mainRequest: PerformanceResourceTiming = resources[1];
  let bestGap;

  const length = resources.length;
  for (let i = 1; i < length; i++) {
    const resource = resources[i];
    const resourceStartTime = hrTimeToNanoseconds(
      timeInputToHrTime(resource[PTN.FETCH_START])
    );

    const resourceEndTime = hrTimeToNanoseconds(
      timeInputToHrTime(resource[PTN.RESPONSE_END])
    );

    const currentGap = spanEndTime - resourceEndTime;

    if (resourceStartTime >= minTime && (!bestGap || currentGap < bestGap)) {
      bestGap = currentGap;
      mainRequest = resource;
    }
  }
  return mainRequest;
}

/**
 * Filter all resources that has started and finished according to span start time and end time.
 *     It will return the closest resource to a start time
 * @param spanUrl
 * @param startTimeHR
 * @param endTimeHR
 * @param resources
 * @param ignoredResources
 */
function filterResourcesForSpan(
  spanUrl: string,
  startTimeHR: api.HrTime,
  endTimeHR: api.HrTime,
  resources: PerformanceResourceTiming[],
  ignoredResources: WeakSet<PerformanceResourceTiming>,
  initiatorType?: string
) {
  const startTime = hrTimeToNanoseconds(startTimeHR);
  const endTime = hrTimeToNanoseconds(endTimeHR);
  let filteredResources = resources.filter(resource => {
    const resourceStartTime = hrTimeToNanoseconds(
      timeInputToHrTime(resource[PTN.FETCH_START])
    );
    const resourceEndTime = hrTimeToNanoseconds(
      timeInputToHrTime(resource[PTN.RESPONSE_END])
    );

    return (
      resource.initiatorType.toLowerCase() ===
        (initiatorType || 'xmlhttprequest') &&
      resource.name === spanUrl &&
      resourceStartTime >= startTime &&
      resourceEndTime <= endTime
    );
  });

  if (filteredResources.length > 0) {
    filteredResources = filteredResources.filter(resource => {
      return !ignoredResources.has(resource);
    });
  }

  return filteredResources;
}

/**
 * The URLLike interface represents an URL and HTMLAnchorElement compatible fields.
 */
export interface URLLike {
  hash: string;
  host: string;
  hostname: string;
  href: string;
  readonly origin: string;
  password: string;
  pathname: string;
  port: string;
  protocol: string;
  search: string;
  username: string;
}

/**
 * Parses url using URL constructor or fallback to anchor element.
 * @param url
 */
export function parseUrl(url: string): URLLike {
  if (typeof URL === 'function') {
    return new URL(url, location.href);
  }
  const element = getUrlNormalizingAnchor();
  element.href = url;
  return element;
}

/**
 * Parses url using URL constructor or fallback to anchor element and serialize
 * it to a string.
 *
 * Performs the steps described in https://html.spec.whatwg.org/multipage/urls-and-fetching.html#parse-a-url
 *
 * @param url
 */
export function normalizeUrl(url: string): string {
  const urlLike = parseUrl(url);
  return urlLike.href;
}

/**
 * Get element XPath
 * @param target - target element
 * @param optimised - when id attribute of element is present the xpath can be
 * simplified to contain id
 */
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
export function getElementXPath(target: any, optimised?: boolean): string {
  if (target.nodeType === Node.DOCUMENT_NODE) {
    return '/';
  }
  const targetValue = getNodeValue(target, optimised);
  if (optimised && targetValue.indexOf('@id') > 0) {
    return targetValue;
  }
  let xpath = '';
  if (target.parentNode) {
    xpath += getElementXPath(target.parentNode, false);
  }
  xpath += targetValue;

  return xpath;
}

/**
 * get node index within the siblings
 * @param target
 */
function getNodeIndex(target: HTMLElement): number {
  if (!target.parentNode) {
    return 0;
  }
  const allowedTypes = [target.nodeType];
  if (target.nodeType === Node.CDATA_SECTION_NODE) {
    allowedTypes.push(Node.TEXT_NODE);
  }
  let elements = Array.from(target.parentNode.childNodes);
  elements = elements.filter((element: Node) => {
    const localName = (element as HTMLElement).localName;
    return (
      allowedTypes.indexOf(element.nodeType) >= 0 &&
      localName === target.localName
    );
  });
  if (elements.length >= 1) {
    return elements.indexOf(target) + 1; // xpath starts from 1
  }
  // if there are no other similar child xpath doesn't need index
  return 0;
}

/**
 * get node value for xpath
 * @param target
 * @param optimised
 */
function getNodeValue(target: HTMLElement, optimised?: boolean): string {
  const nodeType = target.nodeType;
  const index = getNodeIndex(target);
  let nodeValue = '';
  if (nodeType === Node.ELEMENT_NODE) {
    const id = target.getAttribute('id');
    if (optimised && id) {
      return `//*[@id="${id}"]`;
    }
    nodeValue = target.localName;
  } else if (
    nodeType === Node.TEXT_NODE ||
    nodeType === Node.CDATA_SECTION_NODE
  ) {
    nodeValue = 'text()';
  } else if (nodeType === Node.COMMENT_NODE) {
    nodeValue = 'comment()';
  } else {
    return '';
  }
  // if index is 1 it can be omitted in xpath
  if (nodeValue && index > 1) {
    return `/${nodeValue}[${index}]`;
  }
  return `/${nodeValue}`;
}

/**
 * Checks if trace headers should be propagated
 * @param spanUrl
 * @private
 */
export function shouldPropagateTraceHeaders(
  spanUrl: string,
  propagateTraceHeaderCorsUrls?: PropagateTraceHeaderCorsUrls
): boolean {
  let propagateTraceHeaderUrls = propagateTraceHeaderCorsUrls || [];
  if (
    typeof propagateTraceHeaderUrls === 'string' ||
    propagateTraceHeaderUrls instanceof RegExp
  ) {
    propagateTraceHeaderUrls = [propagateTraceHeaderUrls];
  }
  const parsedSpanUrl = parseUrl(spanUrl);

  if (parsedSpanUrl.origin === location.origin) {
    return true;
  } else {
    return propagateTraceHeaderUrls.some(propagateTraceHeaderUrl =>
      urlMatches(spanUrl, propagateTraceHeaderUrl)
    );
  }
}


text:
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true" data-ng-click="closeRegister()">×</button>

{{messages['form.register.signup']}}

{{error.msg}}

{{usernameError}}

        <form ng-submit="register()" class="signup form-horizontal">

                    <input id="name" type="text" name="name" placeholder="{{messages['form.register.fullname']}}" class="form-control" ng-model="user.fullname"/>

                    <input id="email" type="email" name="email" placeholder="Email" class="form-control" ng-model="user.email"/>

                    <input id="username" type="text" name="username" placeholder="{{messages['form.register.username']}}" class="form-control" ng-model="user.username"/>

                    <input id="password" type="password" name="password" placeholder="{{messages['form.register.password']}}" class="form-control" ng-model="user.password"/>

                    <input id="confirmPassword" type="password" name="confirmPassword" placeholder="{{messages['form.register.password.repeat']}}" class="form-control" ng-model="user.confirmPassword"/>

                    <button type="submit" class="btn btn-primary">{{messages['form.register.signup']}}</button>
                    or {{messages['form.register.login']}}

        </form>


text:
/* @flow */
import React from 'react';
import Markdown from '../../Markdown';
import content from './import-syntax.md';

type Props = {};

export default function ImportSyntax(props: Props) {
  return <Markdown {...props}>{content}</Markdown>;
}


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

@Echo off

setlocal

echo Creating DBs...

echo Oracle...
sqlplus SYSTEM/flyway@XE < flyway-core/src/test/resources/migration/dbsupport/oracle/createDatabase.sql

echo MySQL...
mysql -uroot -pflyway < flyway-core/src/test/resources/migration/dbsupport/mysql/createDatabase.sql

echo PostgreSQL...
set PGPASSWORD=flyway
psql -Upostgres < flyway-core/src/test/resources/migration/dbsupport/postgresql/createDatabase.sql

echo SQL Server...
sqlcmd -U sa -P flyway -S localhost\SQLExpress -i flyway-core\src\test\resources\migration\dbsupport\sqlserver\createDatabase.sql

echo DB2...
db2cmd -c "db2 -tvf flyway-core/src/test/resources/migration/dbsupport/db2/createDatabase.sql"

echo Done.


text:
#import "CALayer.h"

@interface TopoProgressBar : CALayer
{
    id _owningView;
    float _progressValue;
}

+ (void)deallocImageCache;
+ (int)initImageCache;
@property(nonatomic) float progressValue; // @synthesize progressValue=_progressValue;
- (struct CGImage *)composeProgressBar;
- (void)layoutSublayers;
- (void)dealloc;
- (struct CGSize)preferredFrameSize;
@property(nonatomic) id owningView;
- (id)initWithOwningView:(id)arg1;

@end


text:
package it.org.apache.struts2.rest.example;

import net.sourceforge.jwebunit.junit.WebTestCase;

public class ListOrdersTest extends WebTestCase {

    public void setUp() throws Exception {
        getTestContext().setBaseUrl(ParameterUtils.getBaseUrl());
    }

    public void testListOrders() {
        beginAt("/orders");
        assertTextPresent("Bob");
        assertTextPresent("Sarah");
        assertTextPresent("Jim");
    }

    public void testListOrdersInHtml() {
        beginAt("/orders.xhtml");
        assertTextPresent("Bob");
        assertTextPresent("Sarah");
        assertTextPresent("Jim");
    }

    public void testListOrdersInXml() {
        beginAt("/orders.xml");
        assertTextPresent("<clientName>Bob");
        assertTextPresent("<clientName>Sarah");
        assertTextPresent("<clientName>Jim");
    }

    public void testListOrdersInJson() {
        beginAt("/orders.json");
        assertTextPresent("\"clientName\":\"Bob\"");
        assertTextPresent("\"clientName\":\"Sarah\"");
        assertTextPresent("\"clientName\":\"Jim\"");
    }
}


text:
import urllib
import urllib2
import json
import os

api_key = open(os.environ['HOME'] + "/.freebase_api_key").read()
url = 'https://www.googleapis.com/rpc'
request = {
            'method': 'freebase.topic.lookup',
            'jsonrpc' : '2.0',
            'apiVersion': 'v1',
            'params': {
              'id': ['en','bob_dylan'],
              'key': api_key
            }
          }
headers = { 'Content-Type': 'application/json' }

req = urllib2.Request(url, json.dumps(request), headers)
response = urllib2.urlopen(req)
print response.read()


text:
namespace net {
namespace test_server {

TEST(HttpResponseTest, GenerateResponse) {
  HttpResponse response;
  response.set_code(SUCCESS);
  response.set_content("Sample content - Hello world!");
  response.set_content_type("text/plain");
  response.AddCustomHeader("Simple-Header", "Simple value.");

  std::string kExpectedResponseString =
      "HTTP/1.1 200 OK\r\n"
      "Connection: closed\r\n"
      "Content-Length: 29\r\n"
      "Content-Type: text/plain\r\n"
      "Simple-Header: Simple value.\r\n\r\n"
      "Sample content - Hello world!";

  EXPECT_EQ(kExpectedResponseString, response.ToResponseString());
}

}  // namespace test_server
}  // namespace net


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function activate(cli) {
  cli.addCommand({
    name: 'x',
    commands: [{
      name: 'echo',
      run: function() {
        this.ui.info('echo')
        return 'echo invoked'
      }
    }]
  })
}
exports.activate = activate;


text:
from __future__ import absolute_import, division, print_function

import pytest

from construct.core import Construct
from pretend import stub

from tlsenum.utils import _UBInt24

@pytest.mark.parametrize("byte,number", [
    (b"\x00\x00\xFF", 255),
    (b"\x00\xFF\xFF", 65535),
    (b"\xFF\xFF\xFF", 16777215)
])
class TestUBInt24(object):
    def test_encode(self, byte, number):
        ubint24 = _UBInt24(Construct(name="test"))
        assert ubint24._encode(number, context=stub()) == byte

    def test_decode(self, byte, number):
        ubint24 = _UBInt24(Construct(name="test"))
        assert ubint24._decode(byte, context=stub()) == number


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Networking.BackgroundTransfer;
using Windows.Storage;
using AdorableData.Services;
using Adoravatars.Utils;
using Caliburn.Micro;
using AdorableData.ViewModels;

namespace Adoravatars.ViewModels
{
    public class AvatarViewModel : Screen
    {
        #region Services

        private readonly IAdorableService _adorableService;

        #endregion

        #region Bindable properties

        private ObservableCollection<AvatarKitViewModel> _avatarCollection;

        public ObservableCollection<AvatarKitViewModel> AvatarCollection
        {
            get => _avatarCollection;
            set
            {
                _avatarCollection = value;
                NotifyOfPropertyChange(nameof(AvatarCollection));
            }
        }

        #endregion

        public AvatarViewModel(IAdorableService adorableService)
        {
            _adorableService = adorableService;

            AvatarCollection = new ObservableCollection<AvatarKitViewModel>();
        }

        #region Overrided methods

        protected override async void OnActivate()
        {
            var avatarNames = _adorableService.GetAvatarNames();
            foreach (var avatarName in avatarNames)
            {
                var avatar = new AvatarKitViewModel(_adorableService, avatarName);

                avatar.Load();

                AvatarCollection.Add(avatar);
            }
        }

        #endregion
    }
}


text:
/*
 Implementation of the Telnet protocol.

 There's is not much to it, but this implementation
 supports client terminal size information (NAWS).

 Does *not* handle connections or sockets. They need to be
 provided by something else.

 These classes speak of packets. These don't really exist
 in TCP or telnet, but they are used here to refer to
 chunks sent through the connection. Reason is that we may
 want to later cancel sending the packet, for connection throttling reasons.
 This way we can distinguish from the data we may or may not want to send
 through the connection.
*/

#ifndef telnet_hpp
#define telnet_hpp

#include <map>
#include <string>
#include "types.hpp"

namespace trankesbel {

/* A packet */
class TelnetPacket
{
    private:
        std::string packet_data;
        size_t sent_data;

    public:
        TelnetPacket()
        { sent_data = 0; };
        TelnetPacket(std::string data)
        { packet_data = data; sent_data = 0; };
        TelnetPacket(const void* data, size_t datasize)
        { packet_data = std::string((const char*) data, datasize); sent_data = 0; };

        /* Returns remaining data as a new string. */
        std::string getRemainingData() const
        {
            return packet_data.substr(sent_data);
        }
        ui32 getDataLength() const { return packet_data.size() - sent_data; };

        /* Returns true if there is no more data in this packet to send. */
        bool empty() const
        {
            if (packet_data.size() == 0) return true;
            if (sent_data >= packet_data.size()) return true;
            return false;
        }
        /* Inform this packet class that some bytes were used from
           getRemainingData(). */
        void addUsedBytes(size_t used_bytes)
        {
            sent_data += used_bytes;
            if (sent_data > packet_data.size()) sent_data = packet_data.size();
        }
        /* Returns true if no data have been used from this packet yet. */
        bool isUnTouched() const
        {
            return (sent_data == 0);
        }
};

/* A session for telnet connection. An abstract class.
   You need to derive and implement readRawData and writeRawData.
   (Typically you'd call something like send/recv on them, but
    read the semantics carefully, they are a little different from them.) */
class TelnetSession
{
    private:
        /* For NAWS. If client terminal is reporting its size, these
           fields will be filled. */
        bool terminal_size_known;
        ui32 terminal_w, terminal_h;

        /* Packets we are sending. The first number is an index number
           and the order in which packets are sent. */
        std::map<ui32, TelnetPacket> packets;
        /* Running index number for packets */
        ui32 packet_index_number;

        /* Receive bufffer */
        std::string recv_buffer;

        /* Is the connection closed? */
        bool closed;

        void sendPendingData();

    protected:
        /* Reads data. Called by cycle(). Put the data you read
           to the buffer pointed by 'data'.
           Size parameter is both input and output. You should
           put the number of bytes you wrote to data buffer to it.
           Return true if connection is still alive, false if the
           connection is terminated. If you just want to signal
           there's no more data at this time, supply 0 for size and
           return true. */
        virtual bool readRawData(void* data, size_t* size) = 0;
        /* Writes data back to connection. Called when changing parameters or
           sending information. Return false, if connection has been
           terminated, true if successful. If data could not be sent at
           this time, supply 0 for size and return true. */
        virtual bool writeRawData(const void* data, size_t* size) = 0;

    public:
        TelnetSession();
        virtual ~TelnetSession();

        /* Makes the session do handshaking routines.
           In current implementation, this includes setting echo off and
           setting one-character mode. */
        void handShake();

        /* Returns true if session has been closed. */
        bool isClosed() const;

        /* Cycles packages. */
        void cycle();

        /* Sends a packet through connection.
           The packet should be 'pure', in sense that
           they must be 'untouched', see TelnetPacket::isUnTouched().
           Returns index number that can be used to refer to the
           packet later (if you want to remove it from send queue). */
        ui32 sendPacket(const TelnetPacket &tp);
        ui32 sendPacket(const void* data, size_t datasize)
        { return sendPacket(TelnetPacket(data, datasize)); };

        /* Returns true, if a packet is still cancellable in the queue.
           Returns false, if no such packet or the packet is in process
           to be sent. */
        bool isPacketCancellable(ui32 packet_index) const;
        /* Cancels a packet. Returns what isPacketCancellable would
           return. */
        bool cancelPacket(ui32 packet_index);

        /* Receive data from remote side. Returns false
           if you should not expect more data from this session anymore
           (connection was closed or something).
           Set the size of your buffer to 'datasize', this will
           be then filled with bytes read from remote side. */
        bool receive(void* data, size_t* datasize);

        /* If client terminal is using NAWS (terminal size information), then
           isTerminalSizeKnown() returns true. The terminal size can then
           be read from following functions. If terminal size is not known,
           the returned size is always 80x24. */
        bool isTerminalSizeKnown() const { return terminal_size_known; };
        ui32 getTerminalWidth() const { return terminal_w; };
        ui32 getTerminalHeight() const { return terminal_h; };
        void getTerminalSize(ui32 *w, ui32 *h) const
        {
            (*w) = terminal_w;
            (*h) = terminal_h;
        }
};

}

#endif


text:
class ArcIconCacheLacros : public crosapi::mojom::ArcObserver {
 public:
  ArcIconCacheLacros();
  ArcIconCacheLacros(const ArcIconCacheLacros&) = delete;
  ArcIconCacheLacros& operator=(const ArcIconCacheLacros&) = delete;
  ~ArcIconCacheLacros() override;

  // Start observing ARC in ash-chrome.
  void Start();

 private:
  THREAD_CHECKER(thread_checker_);

  // crosapi::mojom::ArcObserver
  void OnIconInvalidated(const std::string& package_name) override;

  // Cached activity icons.
  arc::internal::ActivityIconLoader icon_loader_;

  // Receives mojo messages from ash-chrome.
  mojo::Receiver<crosapi::mojom::ArcObserver> receiver_{this};
};

#endif  // CHROME_BROWSER_LACROS_ARC_ICON_CACHE_LACROS_H_


text:
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
    ">

  <camelContext xmlns="http://camel.apache.org/schema/spring">
    <route>
      <from uri="direct:start"/>
      <recipientList>
        listOfVendors
      </recipientList>
    </route>
    <route>
      <from uri="seda:quoteAggregator"/>
      <aggregate aggregationStrategy="aggregatorStrategy" completionTimeout="1000">
        <correlationExpression>
          quoteRequestId
        </correlationExpression>
        <to uri="mock:result"/>
      </aggregate>
    </route>
  </camelContext>

  <bean id="aggregatorStrategy" class="org.apache.camel.spring.processor.scattergather.LowestQuoteAggregationStrategy"/>

  <bean id="vendor1" class="org.apache.camel.spring.processor.scattergather.MyVendor">
    <constructor-arg>
      <value>1</value>
    </constructor-arg>
  </bean>

  <bean id="vendor2" class="org.apache.camel.spring.processor.scattergather.MyVendor">
    <constructor-arg>
      <value>2</value>
    </constructor-arg>
  </bean>

  <bean id="vendor3" class="org.apache.camel.spring.processor.scattergather.MyVendor">
    <constructor-arg>
      <value>3</value>
    </constructor-arg>
  </bean>

</beans>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>4.1. Basic Circuits — 16-223 Introduction to Physical Computing</title>

    <link rel="stylesheet" href="_static/nature.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="_static/guide.css" type="text/css" />

    <link rel="top" title="16-223 Introduction to Physical Computing" href="index.html" />
    <link rel="up" title="4. Topic Area Guides" href="guides.html" />
    <link rel="next" title="4.2. Physical Computation with the Arduino" href="Arduino.html" />
    <link rel="prev" title="4. Topic Area Guides" href="guides.html" />

Navigation

          index

          modules |

          next |

          previous |

16-223 Introduction to Physical Computing »

4. Topic Area Guides »

4.1. Basic Circuits¶

This first section is about establishing core electrical concepts and
standard vocabulary for talking about electronics. Everybody in the
class is starting from a different level of experience (perhaps none)
but needs to develop a common language for working together.

The following list is an informal summary of basic electrical concepts
which will be used throughout the course. Please read through everything
and keep this for reference. If the terminology is unfamiliar, it will
become familiar through practice with the exercises. If it is review,
then please help your classmates with understanding the exercises.

4.1.1. Takeaway Lessons¶

Electricity is the flow of electrons through a conductor.

Electricity is invisible; we use instruments such as multimeters and
oscilloscopes to measure it and render it visible.

An electrical current conveys energy.

Electric potential is measured in volts. Potential can exist between any
two points in a circuit or conductor; it is a relative measure. It is a
measure of potential energy, and exists whether or not a current is
flowing between those two points.

Electric current is measured in amperes (amps). Current is the volume of
electron flow past a point.

Electrical currents can vary with time. The simplest case is the AC
(alternating current) wall power in which the voltage is formed as a 60
Hz sine wave (in the US) for transmission efficiency. In contrast, our
lab power supplies and batteries will output DC (direct current) which
has a constant voltage.

An electrical current can encode information.

Information can be conveyed even with very small amounts of energy. In
practice there are very different kinds of electrical signals and
circuits for processing information (e.g. from sensors) versus actuating
mechanical systems (e.g. motors, speakers).

An electric potential across a resistance causes a current to flow
through it. Resistance is measured in ohms and is measured along a
pathway through a conductor.

Virtually all materials have a finite resistivity, which is a property
of the material. The resistance of a path through a material is a
function of the resistivity and the length and cross-section of the
conductive path. Longer and thinner wires have more resistance, shorter
and thicker wires have less resistance. Copper has lower resistivity
than aluminum or steel; silver is better yet.

A current flowing through a resistance converts electrical energy to
heat. This is commonly termed dissipation.

An insulator is a material with very high resistance, i.e., a typical
voltage will cause negligible current flow through it.

The relationship between current, voltage, and resistance in an
electrical path is described by Ohm’s Law: V = i * R, in which V
represents a voltage measured across a resistance R through which
current i is flowing. Ohm’s Law can be trivially rewritten as i = V / R
and R = V / i.

Electricity flow is loosely analogous to water flow: current is
analogous to the volume of flow of water through a pipe, voltage is
analogous to the pressure difference between two locations, and
resistance is analogous to friction. However, it is good practice to
think directly in terms of electrical properties rather than relying on
this comparison.

A resistor is a type of electronic component engineered for a precise
and constant resistance property. Resistors are designed with a
guaranteed minimum capability for dissipating energy. In general,
physically larger resistors have more dissipation capacity. Resistors
come in a variety of physical shapes and means of electrical connection.
No resistor is precisely the specified value; resistors are specified
with a tolerance range. Highly precise resistors generally cost more. In
practice, resistors have no dynamic behavior.

Resistors have a constant value for any voltage and current within their
rating. Ohm’s Law for a resistor means that current and voltage follow a
simple linear relationship given a constant R.

Wires can be viewed as resistors with low resistance values. Ideally the
resistance is low enough not to affect circuit operation, but in
circuits delivering energy the wire resistance needs to be considered.

A short-circuit (or “short”) is an unintended low-resistance
connection between two points, e.g. bare wires touching accidentally, a
stray drop of solder bridging two pins, or a DMM probe touching two
circuit board traces. The effects of a short can range from nothing to
smoke and destruction, depending on the location and available energy.

In practice, resistors are used to relate current and voltage within a
circuit rather than to generate heat. Heat is normally an undesirable
side-effect.

There are many other types of passive and active components: capacitors,
inductors, diodes, transistors, LEDs, lamps, integrated circuits,
motors, solenoids, and thousands more.

Unlike resistors, most components do not have a simple constant
resistance.

The DMM (digital multi-meter) measures fundamental properties of an
electrical signal: voltage and current. It also measures electrical
properties of materials (either components or conductors): resistance,
capacitance, and inductance. The DMM is most useful for measuring
relatively constant properties, as the numeric display doesn’t show
rapid variation well.

Measuring voltage with a DMM requires attaching it between two points,
since voltage is a relative measure.

Measuring current with a DMM requires routing a signal through the
meter, since current is a measurement of flow. This frequently requires
modifying the circuit by opening a connection and replacing it with
the path through the meter. The meter itself has a different physical
connection point for measuring current that offers a low-resistance
path: for this reason it is very important not to use the current input
unless actually measuring current, otherwise you will short out a
circuit and potentially damage the meter.

The oscilloscope draws a dynamic graph of the voltage of an electrical
signal. It is most useful for visualizing time-varying signals. The
oscilloscope can plot a signal over many orders of magnitude of time
scale; in the course we will generally deal with signals varying at
scales ranging from microseconds to seconds, but modern electronics
involves signals at nanosecond scales and shorter. In contrast, human
perception operates at scales closer to tenths of a second.

Sensors are transducers which convert a physical signal to an electrical
signal. Some common transducers have variable resistance, e.g., for a
given voltage across them, the current through them will vary depending
upon physical state. Two examples: a switch has a resistance near zero
or near infinity depending on position, a CdS photocell has a resistance
varying from about 1000 ohms to millions of ohms depending on light
intensity. Sensors can have a time-varying response: the switch changes
resistance near-instantly, the CdS photocell can take hundreds of
milliseconds to respond to a sudden change. There exists a vast variety
of sensors to couple nearly any physical process of interest into
electrical information. Optical sensors are especially useful building
blocks since many other physical effects can be transduced to a
variation in light, and then transduced from light to a variation in
electricity.

Circuits are arrangements of components and conductors engineered for a
particular purpose. You must learn to recognize certain fundamental
circuit structures which will be used throughout the course.

A circuit is a graph; circuit topology matters more than exact physical
layout. This becomes less true at the extremes: low-voltage,
high-current, or high-frequency circuits require more attention to
physical layout. For this course this will come into play with DC motor
circuits.

Electrical engineering has been wildly successful at providing means for
converting energy and information to and from electrical form and
providing tools for manipulating electrical energy and information.
Historically, computation and signal processing has also been performed
in other domains. The first closed-loop control system was actually a
mechanical computation performed with a flyball governor. Elaborate
mechanical computers were constructed to represent mathematical
functions before the advent of electronic computing. Analog electronic
computers were used before digital electronic computers were developed.
None of these methods have scaled to the complexity of digital
computing, but all still have application for particular problems.

Analog circuits refer to systems in which the energy or information is
represented by continuously varying electrical signals. E.g. a
photoresistor exhibits a continuously varying resistance as a function
of the incident light, and in a circuit can be wired to produce a
continuously varying voltage or current. A microphone produces a voltage
proportional to air pressure and represents sound as an oscillating
voltage.

Digital signals are discretized signals in which specific values of
voltage or current are defined to represent specific symbols. In the
most common case, only two symbols are represented, labeled zero and
one. This encodes a single binary digit, or bit, as the current or
voltage on a wire.

The specific values of voltage or current representing a digital symbol
depend on the specific components. The Arduino follows the 5V CMOS
convention, so voltages below 1.5V are considered zero or LOW and
voltages above 3.7V are considered one or HIGH. Voltages in-between are
potentially ambiguous but will be arbitrated into a distinct value when
passing through a digital input. Please note that other microcontrollers
such as the Arduino Due operate at 3.3V and circuits in laptops and cell
phones at even lower voltages, so these thresholds will be different.
Connecting between different logic families can require
level-translation circuitry if the values are not compatible.

Schematics are circuit diagrams showing the logical connection of
electronic components. A schematic does not define the physical layout
of components or conductors, so constructing a circuit from a schematic
requires applying additional knowledge. However, a good schematic
contains enough information to construct a functional circuit assuming
common engineering experience.

Schematic signals are often named to convey intended purpose of a
connection. In digital circuits, a bar over a name or a slash in front
of it indicates an active-low signal in which the low-voltage state is
the active state. The meaning of active is relative to the specific
case: for example, an input labeled /RESET is active-low, so a
zero-voltage input is "active" in the sense that the circuit is reset
(and hence not operating).

4.1.2. Reference Links¶

Wikipedia: resistor color
code

Wikipedia: voltage
divider

Wikipedia: Kirchhoff’s circuit
laws

Wikipedia: Light emitting
diode

Wikipedia: Photoresistor

Wikipedia: Force-sensing
resistor

Wikipedia: Relay

Wikipedia: Transistor

Wikipedia: MOSFET

Wikipedia: Integrated
circuit

Wikipedia: Logic level

Table Of Contents

4.1. Basic Circuits

4.1.1. Takeaway Lessons

4.1.2. Reference Links

Previous topic

4. Topic Area Guides

Next topic

4.2. Physical Computation with the Arduino

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          modules |

          next |

          previous |

16-223 Introduction to Physical Computing »

4. Topic Area Guides »

        © Copyright 2015, Garth Zeglin.
      Last updated on 2015-11-10.
      Created using Sphinx 1.3.1.


text:
<?php

namespace Oro\Bundle\TestFrameworkBundle\Tests\Unit\Behat\Cli;

use Behat\Testwork\Specification\SpecificationFinder;
use Behat\Testwork\Suite\Generator\SuiteGenerator;
use Behat\Testwork\Suite\GenericSuite;
use Behat\Testwork\Suite\SuiteRegistry;
use Oro\Bundle\TestFrameworkBundle\Behat\Cli\AvailableFeaturesController;
use Oro\Bundle\TestFrameworkBundle\Tests\Unit\Behat\Specification\Stub\SpecificationLocatorStub;
use Oro\Component\Testing\Unit\Command\Stub\InputStub;
use Oro\Component\Testing\Unit\Command\Stub\OutputStub;
use Symfony\Component\Console\Command\Command;

class AvailableFeaturesControllerTest extends \PHPUnit\Framework\TestCase
{
    public function testConfigure()
    {
        $suiteRegistry = new SuiteRegistry();
        $specificationFinder = new SpecificationFinder();
        $controller = new AvailableFeaturesController($suiteRegistry, $specificationFinder);
        $command = new Command('test');

        $controller->configure($command);

        $this->assertTrue($command->getDefinition()->hasOption('available-features'));
        $this->assertFalse($command->getDefinition()->getOption('available-features')->isValueRequired());
    }

    public function testExecute()
    {
        /** @var SuiteGenerator|\PHPUnit\Framework\MockObject\MockObject $generator */
        $generator = $this->getMockBuilder(SuiteGenerator::class)->getMock();
        $generator->method('supportsTypeAndSettings')->willReturn(true);
        $generator->method('generateSuite')->willReturn(new GenericSuite('AcmeSuite', []));

        $suiteRegistry = new SuiteRegistry();
        $suiteRegistry->registerSuiteGenerator($generator);
        $suiteRegistry->registerSuiteConfiguration('AcmeSuite', null, []);

        $specificationFinder = new SpecificationFinder();
        $specificationFinder->registerSpecificationLocator(new SpecificationLocatorStub(5));

        $output = new OutputStub();

        $controller = new AvailableFeaturesController($suiteRegistry, $specificationFinder);
        $returnCode = $controller->execute(new InputStub('', [], ['available-features' => true]), $output);

        $this->assertSame(0, $returnCode);
        $this->assertCount(5, $output->messages);
    }

    public function testNotExecute()
    {
        $suiteRegistry = new SuiteRegistry();
        $specificationFinder = new SpecificationFinder();
        $controller = new AvailableFeaturesController($suiteRegistry, $specificationFinder);
        $returnCode = $controller->execute(new InputStub(), new OutputStub());

        $this->assertNotSame(0, $returnCode);
    }
}


text:
package client.authz;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;

import client.LoggingFilter;
import client.json.JsonSerialization;

/**
 * A partial facade for the org.keycloak.authorization.client.AuthzClient
 */
public class AuthzClient {
    private Configuration deployment;

    public AuthzClient(Configuration deployment) {
        this.deployment = deployment;
    }

    public String obtainAccessToken(String username, String password) {
        Form form = new Form();
        form.param("grant_type", "password");
        form.param("username", username);
        form.param("password", password);
        form.param("client_id", deployment.getClientId());
        String secret = deployment.getClientCredentials().get("secret").toString();
        form.param("client_secret", secret);
        Client client = null;
        try {
            ClientBuilder clientBuilder = ClientBuilder.newBuilder();
            SSLContext sslcontext = deployment.getSSLContext();
            if(sslcontext != null) {
                client = clientBuilder.sslContext(sslcontext).hostnameVerifier(new AnyHostnameVerifier()).build();
            } else {
                client = clientBuilder.build();
            }

            String tokenURL = String.format("%s/auth/realms/%s/protocol/openid-connect/token",
                    deployment.getAuthServerUrl(), deployment.getRealm());
            WebTarget target = client.target(tokenURL);
            if(deployment.getDebug() > 0)
                target.register(new LoggingFilter());
            String json = target.request(MediaType.APPLICATION_JSON_TYPE)
                    .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), String.class);
            AccessToken accessToken = JsonSerialization.readValue(json, AccessToken.class);
            return accessToken.getToken();
        } catch (Exception e) {
            throw new RuntimeException("Failed to request token", e);
        } finally {
            if (client != null) {
                client.close();
            }
        }
    }

    public static AuthzClient create(Configuration configuration) {
        return new AuthzClient(configuration);
    }

    private static class AnyHostnameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String s, SSLSession sslSession) {
            return true;
        }
    }
}


text:
class CreateTemplateFields < ActiveRecord::Migration[4.2]
  def change
    create_table :template_fields do |t|
      t.string :name, default: '', null: false
      t.text :default_value, null: false
      t.string :presentation, default: 'text', null: false
      t.references :template, index: true, null: false

      t.timestamps null: false
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright 2015 Google Inc. All rights reserved.

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.google.motive.linear_processor"
          android:versionCode="1"
          android:versionName="1.0">

    <uses-sdk android:minSdkVersion="9"/>

    <application android:label="motive_linear_processor"
                 android:hasCode="false"
                 android:debuggable="true">
        <activity android:name="android.app.NativeActivity"
                  android:label="motive_linear_processor">
            <meta-data android:name="android.app.lib_name"
                       android:value="motive_linear_processor" />
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>


text:
<?php

namespace TestSupport\Factory;

use DvsaCommon\HttpRestJson\Client;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use TestSupport\Service\AeUserService;
use TestSupport\Service\AccountDataService;
use TestSupport\Service\AccountService;
use Doctrine\ORM\EntityManager;

use Interop\Container\ContainerInterface;

class AedmServiceFactory implements FactoryInterface
{
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        return $this($serviceLocator, AeUserService::class);
    }

    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        return new AeUserService(
            $container->get(AccountDataService::class),
            $container->get(AccountService::class),
            $container->get(EntityManager::class),
            $container->get(Client::class)
        );
    }
}


text:
package com.alucn.casemanager.server.common.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.UnknownHostException;

import org.apache.commons.net.telnet.TelnetClient;

public class TelnetCla {
	Object lock = new Object();
	TelnetClient telnet = null;
	String hostname;
	int hostport = 23;
	String user;
	String password;
	String userAD4;
	String passwordAD4;
	private InputStream in;
	private PrintStream out;
	private static final String ORIG_CODEC = "ISO8859-1";
	private static final String TRANSLATE_CODEC = "GBK";

	public TelnetCla(String hostname, int hostport, String user, String password, String userAD4, String passwordAD4) throws Exception {
		super();
		this.hostname = hostname;
		this.hostport = hostport;
		this.user = user;
		this.password = password;
		this.userAD4 = userAD4;
		this.passwordAD4 = passwordAD4;

		telnet = new TelnetClient("VT100");                           // VT100 VT52 VT220 VTNT ANSI
		telnet.setDefaultTimeout(10000);
		telnet.connect(hostname, hostport);
		in = telnet.getInputStream();
		out = new PrintStream(telnet.getOutputStream());

		if(!ping(hostname)){
			if(readUntil("Username: ")){
				write(userAD4);
				write("\n");
			}
			if(readUntil("Password: ")){
				write(passwordAD4);
				write("\n");
			}
		}

		if(readUntil("login: ")){
			write(user);
			write("\n");
		}

		if(readUntil("Password: ")){
			write(password);
			write("\n");
		}
	}

	public boolean readUntil(String str) {
		try {
			StringBuffer sb = new StringBuffer();
			char c;
			int code = -1;
			boolean ansiControl = false;
			boolean returnValue = false;
			while ((code = (in.read())) != -1) {
				c = (char) code;
				if (c == '\033') {
					ansiControl = true;
					int code2 = in.read();
					char cc = (char) code2;
					if (cc == '[' || cc == '(') {
					}
				}
				if (!ansiControl) {
					if (c == '\r') {
						if (sb.lastIndexOf(str)!=-1) {
							returnValue = true;
							break;
						}
						if (sb.lastIndexOf(">")!=-1 ) {
							returnValue = false;
							break;
						}
						sb.delete(0, sb.length());
					}else if (c == '\n'){
					}else{
						sb.append(c);
					}
					if (sb.lastIndexOf(str)!=-1) {
						returnValue = true;
						break;
					}
					if (sb.lastIndexOf(">")!=-1) {
						returnValue = false;
						break;
					}
				}

				if (ansiControl) {
					if (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '"') {
						ansiControl = false;
					}
				}
			}
			return returnValue;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public String readResult(String str) {
		try {
			StringBuffer sb = new StringBuffer();
			char c;
			int code = -1;
			boolean ansiControl = false;

			while ((code = (in.read())) != -1) {
				c = (char) code;
				if (c == '\033') {
					ansiControl = true;
					int code2 = in.read();
					char cc = (char) code2;
					if (cc == '[' || cc == '(') {
					}
				}
				if (!ansiControl) {
					if (c == '\r') {
						sb.append(",");
						if (sb.lastIndexOf(str) != -1) {
							break;
						}
					} else if (c == '\n')
						;
					else
						sb.append(c);
					if (sb.lastIndexOf(str) != -1) {
						break;
					}
				}

				if (ansiControl) {
					if (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '"') {
						ansiControl = false;
					}
				}
			}
			return new String(sb.toString().getBytes(ORIG_CODEC), TRANSLATE_CODEC);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	public void write(String s) {
		try {
			out.write(s.getBytes());
			out.flush();
		} catch (Exception e) {
		}
	}

	public void write(String s, int sleep) {
		write(s);
		try {
			Thread.sleep(sleep);
		} catch (Exception e) {
		}
	}

	public void close() {
		if (out != null)
			out.close();
		if (in != null)
			try {
				in.close();
			} catch (IOException e1) {
			}
		if (telnet != null)
			try {
				telnet.disconnect();;
			} catch (Exception e) {
			}
	}

	public String doJob(String user, String caseName) throws Exception {
		try {
				String tmsSql = "tmsquery -y select level where tidnum=\""+caseName.split("/")[1].replaceAll(".json","")+"\"\n";
				write(tmsSql);
				String result = readResult("apxtms: /home/"+user+">");
				return result;
		} finally {
			Thread.sleep(200);
			close();
		}
	}

	public boolean ping(String ip) throws UnknownHostException, IOException{
		int  timeOut =  5000;
		boolean status = InetAddress.getByName(ip).isReachable(timeOut);
		return status;
	}

	public static void main(String[] args) throws Exception {
		String hostname = "135.3.27.70";
		int hostport = 23;

		String userAD4 = "svc_surepay";
		String passwordAD4 = "asb#2345";

		String user = "yahou";//yanzhizh yahou
		String password = "tyz89bgv";//yanzhizh tyz89bgv
		TelnetCla helper = null;
		helper = new TelnetCla(hostname, hostport, user, password, userAD4, passwordAD4);
		System.out.println(helper.readUntil("apxtms: /home/yahou>"));
		helper.close();
	}
}