text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.resourcemanager.servicebus.implementation;

import com.azure.core.management.Region;
import com.azure.resourcemanager.resources.fluentcore.arm.models.implementation.IndependentChildResourceImpl;
import com.azure.resourcemanager.resources.fluentcore.model.Creatable;
import com.azure.resourcemanager.resources.fluentcore.utils.ResourceManagerUtils;
import com.azure.resourcemanager.servicebus.ServiceBusManager;
import com.azure.resourcemanager.servicebus.fluent.models.QueueResourceInner;
import com.azure.resourcemanager.servicebus.models.EntityStatus;
import com.azure.resourcemanager.servicebus.models.Queue;
import com.azure.resourcemanager.servicebus.models.QueueAuthorizationRule;
import com.azure.resourcemanager.servicebus.models.QueueCreateOrUpdateParameters;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * Implementation for Queue.
 */
class QueueImpl
    extends IndependentChildResourceImpl<
        Queue,
        ServiceBusNamespaceImpl,
        QueueResourceInner,
        QueueImpl,
        ServiceBusManager>
    implements
        Queue,
        Queue.Definition,
        Queue.Update  {
    private List<Creatable<QueueAuthorizationRule>> rulesToCreate;
    private List<String> rulesToDelete;

    QueueImpl(String resourceGroupName,
              String namespaceName,
              String name,
              Region region,
              QueueResourceInner inner,
              ServiceBusManager manager) {
        super(name, inner, manager);
        this.withExistingParentResource(resourceGroupName, namespaceName);
        initChildrenOperationsCache();
        if (inner.location() == null) {
            inner.withLocation(region.toString());
        }
    }

    @Override
    public OffsetDateTime createdAt() {
        return this.innerModel().createdAt();
    }

    @Override
    public OffsetDateTime accessedAt() {
        return this.innerModel().accessedAt();
    }

    @Override
    public OffsetDateTime updatedAt() {
        return this.innerModel().updatedAt();
    }

    @Override
    public long maxSizeInMB() {
        return ResourceManagerUtils.toPrimitiveLong(this.innerModel().maxSizeInMegabytes());
    }

    @Override
    public long currentSizeInBytes() {
        return ResourceManagerUtils.toPrimitiveLong(this.innerModel().sizeInBytes());
    }

    @Override
    public boolean isBatchedOperationsEnabled() {
        return ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().enableBatchedOperations());
    }

    @Override
    public boolean isDeadLetteringEnabledForExpiredMessages() {
        return ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().deadLetteringOnMessageExpiration());
    }

    @Override
    public boolean isExpressEnabled() {
        return ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().enableExpress());
    }

    @Override
    public boolean isPartitioningEnabled() {
        return ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().enablePartitioning());
    }

    @Override
    public boolean isSessionEnabled() {
        return ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().requiresSession());
    }

    @Override
    public boolean isDuplicateDetectionEnabled() {
        return ResourceManagerUtils.toPrimitiveBoolean(this.innerModel().requiresDuplicateDetection());
    }

    @Override
    public long lockDurationInSeconds() {
        if (this.innerModel().lockDuration() == null) {
            return 0;
        }
        TimeSpan timeSpan = TimeSpan.parse(this.innerModel().lockDuration());
        return (long) timeSpan.totalSeconds();
    }

    @Override
    public long deleteOnIdleDurationInMinutes() {
        if (this.innerModel().autoDeleteOnIdle() == null) {
            return 0;
        }
        TimeSpan timeSpan = TimeSpan.parse(this.innerModel().autoDeleteOnIdle());
        return (long) timeSpan.totalMinutes();
    }

    @Override
    public Duration defaultMessageTtlDuration() {
        if (this.innerModel().defaultMessageTimeToLive() == null) {
            return null;
        }
        return TimeSpan.parse(this.innerModel().defaultMessageTimeToLive()).toDuration();
    }

    @Override
    public Duration duplicateMessageDetectionHistoryDuration() {
        if (this.innerModel().duplicateDetectionHistoryTimeWindow() == null) {
            return null;
        }
        return TimeSpan.parse(this.innerModel().duplicateDetectionHistoryTimeWindow()).toDuration();
    }

    @Override
    public int maxDeliveryCountBeforeDeadLetteringMessage() {
        return ResourceManagerUtils.toPrimitiveInt(this.innerModel().maxDeliveryCount());
    }

    @Override
    public long messageCount() {
        return ResourceManagerUtils.toPrimitiveLong(this.innerModel().messageCount());
    }

    @Override
    public long activeMessageCount() {
        if (this.innerModel().countDetails() == null
                || this.innerModel().countDetails().activeMessageCount() == null) {
            return 0;
        }
        return ResourceManagerUtils.toPrimitiveLong(this.innerModel().countDetails().activeMessageCount());
    }

    @Override
    public long deadLetterMessageCount() {
        if (this.innerModel().countDetails() == null
                || this.innerModel().countDetails().deadLetterMessageCount() == null) {
            return 0;
        }
        return ResourceManagerUtils.toPrimitiveLong(this.innerModel().countDetails().deadLetterMessageCount());
    }

    @Override
    public long scheduledMessageCount() {
        if (this.innerModel().countDetails() == null
                || this.innerModel().countDetails().scheduledMessageCount() == null) {
            return 0;
        }
        return ResourceManagerUtils.toPrimitiveLong(this.innerModel().countDetails().scheduledMessageCount());
    }

    @Override
    public long transferDeadLetterMessageCount() {
        if (this.innerModel().countDetails() == null
                || this.innerModel().countDetails().transferDeadLetterMessageCount() == null) {
            return 0;
        }
        return ResourceManagerUtils.toPrimitiveLong(this.innerModel().countDetails().transferDeadLetterMessageCount());
    }

    @Override
    public long transferMessageCount() {
        if (this.innerModel().countDetails() == null
                || this.innerModel().countDetails().transferMessageCount() == null) {
            return 0;
        }
        return ResourceManagerUtils.toPrimitiveLong(this.innerModel().countDetails().transferMessageCount());
    }

    @Override
    public EntityStatus status() {
        return this.innerModel().status();
    }

    @Override
    public QueueAuthorizationRulesImpl authorizationRules() {
        return new QueueAuthorizationRulesImpl(this.resourceGroupName(),
                this.parentName,
                this.name(),
                this.region(),
                manager());
    }

    @Override
    public QueueImpl withSizeInMB(long sizeInMB) {
        this.innerModel().withMaxSizeInMegabytes(sizeInMB);
        return this;
    }

    @Override
    public QueueImpl withPartitioning() {
        this.innerModel().withEnablePartitioning(true);
        return this;
    }

    @Override
    public QueueImpl withoutPartitioning() {
        this.innerModel().withEnablePartitioning(false);
        return this;
    }

    @Override
    public QueueImpl withDeleteOnIdleDurationInMinutes(int durationInMinutes) {
        TimeSpan timeSpan = new TimeSpan().withMinutes(durationInMinutes);
        this.innerModel().withAutoDeleteOnIdle(timeSpan.toString());
        return this;
    }

    @Override
    public QueueImpl withMessageLockDurationInSeconds(int durationInSeconds) {
        TimeSpan timeSpan = new TimeSpan().withSeconds(durationInSeconds);
        this.innerModel().withLockDuration(timeSpan.toString());
        return this;
    }

    @Override
    public QueueImpl withDefaultMessageTTL(Duration ttl) {
        this.innerModel().withDefaultMessageTimeToLive(TimeSpan.fromDuration(ttl).toString());
        return this;
    }

    @Override
    public QueueImpl withSession() {
        this.innerModel().withRequiresSession(true);
        return this;
    }

    @Override
    public QueueImpl withoutSession() {
        this.innerModel().withRequiresSession(false);
        return this;
    }

    @Override
    public QueueImpl withExpressMessage() {
        this.innerModel().withEnableExpress(true);
        return this;
    }

    @Override
    public QueueImpl withoutExpressMessage() {
        this.innerModel().withEnableExpress(false);
        return this;
    }

    @Override
    public QueueImpl withMessageBatching() {
        this.innerModel().withEnableBatchedOperations(true);
        return this;
    }

    @Override
    public QueueImpl withoutMessageBatching() {
        this.innerModel().withEnableBatchedOperations(false);
        return this;
    }

    @Override
    public QueueImpl withExpiredMessageMovedToDeadLetterQueue() {
        this.innerModel().withDeadLetteringOnMessageExpiration(true);
        return this;
    }

    @Override
    public QueueImpl withoutExpiredMessageMovedToDeadLetterQueue() {
        this.innerModel().withDeadLetteringOnMessageExpiration(false);
        return this;
    }

    @Override
    public QueueImpl withMessageMovedToDeadLetterQueueOnMaxDeliveryCount(int deliveryCount) {
        this.innerModel().withMaxDeliveryCount(deliveryCount);
        return this;
    }

    @Override
    public QueueImpl withDuplicateMessageDetection(Duration duplicateDetectionHistoryDuration) {
        this.innerModel().withRequiresDuplicateDetection(true);
        this.innerModel().withDuplicateDetectionHistoryTimeWindow(TimeSpan
                .fromDuration(duplicateDetectionHistoryDuration)
                .toString());
        return this;
    }

    @Override
    public QueueImpl withDuplicateMessageDetectionHistoryDuration(Duration duration) {
        return withDuplicateMessageDetection(duration);
    }

    @Override
    public QueueImpl withoutDuplicateMessageDetection() {
        this.innerModel().withRequiresDuplicateDetection(false);
        return this;
    }

    @Override
    public QueueImpl withNewSendRule(String name) {
        this.rulesToCreate.add(this.authorizationRules().define(name).withSendingEnabled());
        return this;
    }

    @Override
    public QueueImpl withNewListenRule(String name) {
        this.rulesToCreate.add(this.authorizationRules().define(name).withListeningEnabled());
        return this;
    }

    @Override
    public QueueImpl withNewManageRule(String name) {
        this.rulesToCreate.add(this.authorizationRules().define(name).withManagementEnabled());
        return this;
    }

    @Override
    public QueueImpl withoutAuthorizationRule(String name) {
        this.rulesToDelete.add(name);
        return this;
    }

    @Override
    protected Mono<QueueResourceInner> getInnerAsync() {
        return this.manager().serviceClient().getQueues()
                .getAsync(this.resourceGroupName(),
                        this.parentName,
                        this.name());
    }

    @Override
    protected Mono<Queue> createChildResourceAsync() {

        Mono<QueueResourceInner> createTask = this.manager().serviceClient().getQueues()
            .createOrUpdateAsync(this.resourceGroupName(),
                this.parentName,
                this.name(),
                prepareForCreate(this.innerModel()))
            .map(inner -> {
                setInner(inner);
                return inner;
            });
        Flux<Void> childOperationTasks = submitChildrenOperationsAsync();
        final Queue self = this;
        return Flux.concat(createTask, childOperationTasks)
            .doOnTerminate(() -> initChildrenOperationsCache())
            .then(Mono.just(self));
    }

    private void initChildrenOperationsCache() {
        this.rulesToCreate = new ArrayList<>();
        this.rulesToDelete = new ArrayList<>();
    }

    private Flux<Void> submitChildrenOperationsAsync() {
        Flux<Void> rulesCreateStream = Flux.empty();
        if (this.rulesToCreate.size() > 0) {
            rulesCreateStream = this.authorizationRules().createAsync(this.rulesToCreate).then().flux();
        }
        Flux<Void> rulesDeleteStream = Flux.empty();
        if (this.rulesToDelete.size() > 0) {
            rulesDeleteStream = this.authorizationRules().deleteByNameAsync(this.rulesToDelete);
        }
        return Flux.mergeDelayError(32, rulesCreateStream,
                rulesDeleteStream);
    }

    private QueueCreateOrUpdateParameters prepareForCreate(QueueResourceInner inner) {
        return new QueueCreateOrUpdateParameters()
            .withLockDuration(inner.lockDuration())
            .withAutoDeleteOnIdle(inner.autoDeleteOnIdle())
            .withEntityAvailabilityStatus(inner.entityAvailabilityStatus())
            .withDefaultMessageTimeToLive(inner.defaultMessageTimeToLive())
            .withDuplicateDetectionHistoryTimeWindow(inner.duplicateDetectionHistoryTimeWindow())
            .withEnableBatchedOperations(inner.enableBatchedOperations())
            .withDeadLetteringOnMessageExpiration(inner.deadLetteringOnMessageExpiration())
            .withEnableExpress(inner.enableExpress())
            .withEnablePartitioning(inner.enablePartitioning())
            .withIsAnonymousAccessible(inner.isAnonymousAccessible())
            .withMaxDeliveryCount(inner.maxDeliveryCount())
            .withMaxSizeInMegabytes(inner.maxSizeInMegabytes())
            .withRequiresDuplicateDetection(inner.requiresDuplicateDetection())
            .withRequiresSession(inner.requiresSession())
            .withStatus(inner.status())
            .withSupportOrdering(inner.supportOrdering())
            .withLocation(inner.location());
    }
}


text:
  whazzup on #{{stream.id}}

    <button class="btn btn-default" ng-click="syncStream()" ng-disabled="synchronizing">

    </button>

loading stream ...

{{ event.created_at | fromNow }}

  displaying {{ streamData.events.length }} / {{ streamData.total }} events

{{ error.status }} - {{ error.message }}

redpajama_set_name: RedPajamaGithub


text:
package sampleclean.crowd.context

/**
 * The abstract class used to represent the different contexts for different crowd tasks
 * There is only one field data of type T, which stores the necessary information for a context
 */
abstract class PointLabelingContext {
  val content : Object
}

/** An abstract class used to represent the group labeling contexts */
abstract class GroupLabelingContext {
  val taskType : String
  val data : Object
}


text:
package org.apache.causeway.core.metamodel.facets.objectvalue.temporalformat;

import java.util.Objects;
import java.util.function.BiConsumer;

import org.apache.causeway.applib.annotation.TimePrecision;
import org.apache.causeway.core.metamodel.facetapi.Facet;
import org.apache.causeway.core.metamodel.facetapi.FacetAbstract;
import org.apache.causeway.core.metamodel.facetapi.FacetHolder;

import lombok.Getter;
import lombok.NonNull;

public abstract class TimeFormatPrecisionFacetAbstract
extends FacetAbstract
implements TimeFormatPrecisionFacet {

    private static final Class<? extends Facet> type() {
        return TimeFormatPrecisionFacet.class;
    }

    @Getter(onMethod_ = {@Override})
    private final @NonNull TimePrecision timePrecision;

    protected TimeFormatPrecisionFacetAbstract(
            final TimePrecision timePrecision,
            final FacetHolder holder) {
        super(type(), holder);
        this.timePrecision = timePrecision;
    }

    protected TimeFormatPrecisionFacetAbstract(
            final TimePrecision timePrecision,
            final FacetHolder holder,
            final Facet.Precedence precedence) {
        super(type(), holder, precedence);
        this.timePrecision = timePrecision;
    }

    @Override
    public boolean semanticEquals(@NonNull final Facet other) {
        return other instanceof TimeFormatPrecisionFacet
                ? Objects.equals(
                        this.getTimePrecision(),
                        ((TimeFormatPrecisionFacet)other).getTimePrecision())
                : false;
    }

    @Override
    public void visitAttributes(final BiConsumer<String, Object> visitor) {
        super.visitAttributes(visitor);
        visitor.accept("timePrecision", timePrecision.name());
    }

}


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="cn.mutils.app.sqlcipher">

    <application android:allowBackup="true" android:label="@string/app_name"
        android:supportsRtl="true">

    </application>

</manifest>


text:
require 'matriarch'

require 'json'
require 'yaml'

require 'sinatra/base'
require 'sinatra/json'

module Matriarch
  class App < Sinatra::Base
    get '/' do
      erb :index
    end

    post '/matrix' do
      content_type 'application/json'
      begin
        config_hash = {}

        config_hash = YAML.load_documents(params['yml']).first if \
          params['yml'] && !params['yml'].empty?
        config_hash = JSON.parse(request.body.read) if \
          config_hash.nil? || config_hash.empty?

        halt 400, JSON.dump(error: 'Expecting a hash') unless \
          config_hash.is_a?(Hash)
        halt 400, JSON.dump(error: 'No language present') if \
          ((config_hash['language'] || config_hash[:language]) || '').empty?
        config = ::Matriarch::Config.new(config_hash)
      rescue => e
        halt 400, JSON.dump(error: e.to_s)
      end

      json data: config.expand
    end

    run! if app_file == $PROGRAM_NAME
  end
end


text:
require_relative '../../test_helper'

class PathCollectionWithToStateTest < StateMachinesTest
  def setup
    @klass = Class.new
    @machine = StateMachines::Machine.new(@klass)
    @machine.state :parked, :idling
    @machine.event :ignite do
      transition parked: :idling
    end
    @machine.event :shift_up do
      transition parked: :idling, idling: :first_gear
    end
    @machine.event :shift_down do
      transition first_gear: :idling
    end
    @object = @klass.new
    @object.state = 'parked'

    @paths = StateMachines::PathCollection.new(@object, @machine, to: :idling)
  end

  def test_should_stop_paths_once_target_state_reached
    assert_equal [
      [StateMachines::Transition.new(@object, @machine, :ignite, :parked, :idling)],
      [StateMachines::Transition.new(@object, @machine, :shift_up, :parked, :idling)]
    ], @paths
  end
end


text:
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE project SYSTEM "../config/MyWebTest.dtd">

<project name="testPdfLinks" default="allTests" basedir=".">

    <target name="allTests" depends="testLinks, testLinksFilter"/>

    <target name="testLinks">
        <webtest name="pdfLinks: confirm existence of PDF links">
            &sharedConfiguration;
            <steps>
                <invoke url="testDocLinks.pdf"/>
                <pdfVerifyLink text=".*external.*" regex="true"/>
                <pdfVerifyLink page="2" href="#top"/>
                <not description="expect to fail: incorrect page">
                    <pdfVerifyLink page="1" href="#top"/>
                </not>
                <not description="expect to fail: unknown page">
                    <pdfVerifyLink page="3" href="#top"/>
                </not>
                <not description="expect to fail: unknown link">
                    <pdfVerifyLink text="into the unknown"/>
                </not>
                <invoke url="testDocBookmarks.pdf"/>
                <not description="expect to fail: document has no links">
                    <pdfVerifyLink text=".*" regex="true"/>
                </not>
            </steps>
        </webtest>
    </target>

    <target name="testLinksFilter">
        <webtest name="pdfLinks: confirm verifyContent extracting links">
            &sharedConfiguration;
            <steps>
                <invoke url="testDocLinks.pdf"/>
                <verifyContent readFiltered="false" referenceFile="verifyContent/expectedPdfLinks.txt">
                    <pdfToLinksFilter description="extract PDF links"/>
                    <lineSeparatorFilter description="normalise line separators"/>
                </verifyContent>
            </steps>
        </webtest>
    </target>

</project>


text:
class Solution {
public:
    int maxArea(vector<int> &height) {
        int result = 0;
        int left=0,right=height.size()-1;
        while(left<right){
            int h = min(height[left],height[right]);
            result = max(result,h*(right-left));
            while(left<right && height[left]<=h) ++left;
            while(left<right && height[right]<=h) --right;
        }
        return result;
    }
};


text:
package scalaxy.streams.testing

trait WithTestFresh {
  private var nextId = 0L

  def fresh(s: String) = synchronized {
    val v = nextId
    nextId += 1
    s + v
  }
}


text:
"""
mbed SDK
Copyright (c) 2011-2015 ARM Limited

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.
"""
import re
import os
from project_generator_definitions.definitions import ProGenDef

from tools.export.exporters import Exporter
from tools.targets import TARGET_MAP, TARGET_NAMES

# If you wish to add a new target, add it to project_generator_definitions, and then
# define progen_target name in the target class (`` self.progen_target = 'my_target_name' ``)
class IAREmbeddedWorkbench(Exporter):
    """
    Exporter class for IAR Systems. This class uses project generator.
    """
    # These 2 are currently for exporters backward compatiblity
    NAME = 'IAR'
    TOOLCHAIN = 'IAR'
    # PROGEN_ACTIVE contains information for exporter scripts that this is using progen
    PROGEN_ACTIVE = True

    # backward compatibility with our scripts
    TARGETS = []
    for target in TARGET_NAMES:
        try:
            if (ProGenDef('iar').is_supported(str(TARGET_MAP[target])) or
                ProGenDef('iar').is_supported(TARGET_MAP[target].progen['target'])):
                TARGETS.append(target)
        except AttributeError:
            # target is not supported yet
            continue

    def generate(self):
        """ Generates the project files """
        project_data = self.progen_get_project_data()
        tool_specific = {}
        # Expand tool specific settings by IAR specific settings which are required
        try:
            if TARGET_MAP[self.target].progen['iar']['template']:
                tool_specific['iar'] = TARGET_MAP[self.target].progen['iar']
        except KeyError:
            # use default template
            # by the mbed projects
            tool_specific['iar'] = {
                    # We currently don't use misc, template sets those for us
                    # 'misc': {
                    #     'cxx_flags': ['--no_rtti', '--no_exceptions'],
                    #     'c_flags': ['--diag_suppress=Pa050,Pa084,Pa093,Pa082'],
                    #     'ld_flags': ['--skip_dynamic_initialization'],
                    # },
                    'template': [os.path.join(os.path.dirname(__file__),  'iar_template.ewp.tmpl')],
            }

        project_data['tool_specific'] = {}
        project_data['tool_specific'].setdefault("iar", {})
        project_data['tool_specific']['iar'].setdefault("misc", {})
        project_data['tool_specific']['iar'].update(tool_specific['iar'])
        project_data['tool_specific']['iar']['misc'].update(self.progen_flags)
        project_data['common']['build_dir'] = os.path.join(project_data['common']['build_dir'], 'iar_arm')
        self.progen_gen_file('iar_arm', project_data)

# Currently not used, we should reuse folder_name to create virtual folders
class IarFolder():
    """
    This is a recursive folder object.
    To present the folder structure in the IDE as it is presented on the disk.
    This can be used for uvision as well if you replace the __str__ method.
    Example:
    files: ./main.cpp, ./apis/I2C.h, ./mbed/common/I2C.cpp
    in the project this would look like:
    main.cpp
    common/I2C.cpp
    input:
    folder_level : folder path to current folder
    folder_name : name of current folder
    source_files : list of source_files (all must be in same directory)
    """
    def __init__(self, folder_level, folder_name, source_files):
        self.folder_level = folder_level
        self.folder_name = folder_name
        self.source_files = source_files
        self.sub_folders = {}

    def __str__(self):
        """
        converts the folder structue to IAR project format.
        """
        group_start = ""
        group_end = ""
        if self.folder_name != "":
            group_start = "<group>\n<name>%s</name>\n" %(self.folder_name)
            group_end = "</group>\n"

        str_content = group_start
        #Add files in current folder
        if self.source_files:
            for src in self.source_files:
                str_content += "<file>\n<name>$PROJ_DIR$/%s</name>\n</file>\n" % src
        #Add sub folders
        if self.sub_folders:
            for folder_name in self.sub_folders.iterkeys():
                str_content += self.sub_folders[folder_name].__str__()

        str_content += group_end
        return str_content

    def insert_file(self, source_input):
        """
        Inserts a source file into the folder tree
        """
        if self.source_files:
            #All source_files in a IarFolder must be in same directory.
            dir_sources = IarFolder.get_directory(self.source_files[0])
            #Check if sources are already at their deepest level.
            if not self.folder_level == dir_sources:
                _reg_exp = r"^" + re.escape(self.folder_level) + r"[/\\]?([^/\\]+)"
                folder_name = re.match(_reg_exp, dir_sources).group(1)
                self.sub_folders[folder_name] = IarFolder(os.path.join(self.folder_level, folder_name), folder_name, self.source_files)
                self.source_files = []

        dir_input = IarFolder.get_directory(source_input)
        if dir_input == self.folder_level:
            self.source_files.append(source_input)
        else:
            _reg_exp = r"^" + re.escape(self.folder_level) + r"[/\\]?([^/\\]+)"
            folder_name = re.match(_reg_exp, dir_input).group(1)
            if self.sub_folders.has_key(folder_name):
                self.sub_folders[folder_name].insert_file(source_input)
            else:
                if self.folder_level == "":
                    #Top level exception
                    self.sub_folders[folder_name] = IarFolder(folder_name, folder_name, [source_input])
                else:
                    self.sub_folders[folder_name] = IarFolder(os.path.join(self.folder_level, folder_name), folder_name, [source_input])

    @staticmethod
    def get_directory(file_path):
        """
        Returns the directory of the file
        """
        return os.path.dirname(file_path)


text:
<component name="libraryTable">
  <library name="org.reflections_reflections_0.9.6">
    <CLASSES>
      <root url="jar://C:/play/repository/local/org.reflections/reflections/0.9.6/jars/reflections.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>


text:
=head1 AUTHORS

Vasily Petrushin, http://petrushin.org

=head1 COPYRIGHT

**********************************************************************
                          MIT License
**********************************************************************
Copyright (c) 2016 Vasily Petrushin

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

************************************************************************

=head1 SUPPORT / WARRANTY

This is free Open Source software. IT COMES WITHOUT WARRANTY OF ANY KIND.

=cut

use strict;

use MongoDB;

use Getopt::Std;
use Zabbix::Sender;

use List::MoreUtils 'any';

my (%opts, $mongo_name, $zab_host, $mongo_port, $mongo_user, $mongo_pass);

getopts("h:u:p:s:n:D",\%opts);

$mongo_name = $opts{h};
$zab_host = $opts{n};
$mongo_port = $opts{p};
$mongo_user = $opts{u};
$mongo_pass = $opts{s};

my $mongo_conn = MongoDB::MongoClient->new("host" => "mongodb://".$mongo_user.':'.$mongo_pass.'@'.$mongo_name.':'.$mongo_port."/admin");

my $q = "mongo -u ".$mongo_user." -p ".$mongo_pass." ".$mongo_name.':'.$mongo_port.'/admin --eval "rs.status()" --quiet 2>&1';
print $q, "\n";
print "zab_host ", $zab_host, "\n";
my $status_str = `$q`;
# this data easy to read by human but can't parse with Jason module for easy automated processing

my $zab = Zabbix::Sender->new({
        'server' => '127.0.0.1',
        'port' => 10051,
        'hostname' => $zab_host,
    });

$zab->send('mongors_status_str', $status_str); # Send to zabbix full output of rs.status(), also will report if any error with connection

unless ($mongo_conn) {
	$zab->send('mongors_conn_error', 1);  # Send connection error flag
	print "MongoDB connection error!\n";
	exit();
}

$zab->send('mongors_conn_error', 0);

my $db = $mongo_conn->get_database('admin');

my $res = $db->run_command(['replSetGetStatus' => 1]); # Get rs.status() via perl mongo driver -- this data is ready for processing

print $res->{"ok"}, "\n";

$zab->send('mongors_set', $res->{set}); # Send to zabbix replicaset name

my $rs_anyerror = 0;
my $rs_member_error = 0;
my $rs_anyerror_str = "\n";
my $rs_members_visible = 0;
my $rs_member_state = "\n";

for (my $j = 0; $j <= $#{$res->{members}}; $j++) {
	print "j $j\n";
	print "health ", $res->{members}->[$j]->{health}, "\n";
	print "state ", $res->{members}->[$j]->{state}, "\n";
	print "name ", $res->{members}->[$j]->{name}, "\n";
	unless (($res->{members}->[$j]->{health} == 1) or (any {$_ == $res->{members}->[$j]->{state}} (1, 2, 3, 5, 7))) {
		$rs_anyerror = 1;  # There is something wrong with replicaset
		$rs_anyerror_str .= "RS Member ".$res->{members}->[$j]->{name}. " is in state ". $res->{members}->[$j]->{state}."\n".
			"RS Member ".$res->{members}->[$j]->{name}. " error string: ".$res->{members}->[$j]->{stateStr}."\n".
			"RS Member ".$res->{members}->[$j]->{name}. " last hearbeat: ".$res->{members}->[$j]->{lastHeartbeat}."\n".
			"RS Member ".$res->{members}->[$j]->{name}. " last hearbeat msg: ".$res->{members}->[$j]->{lastHeartbeatMessage}."\n";
		# This should explain what's wrong with replicaset
		print "rs_anyerror_str: \n",$rs_anyerror_str;
		$rs_member_error = 1 if exists ($res->{members}->[$j]->{self}); # Flag if error occurs on monitored host
		next;
	}
	$rs_members_visible++;
	$rs_member_state = $res->{members}->[$j]->{stateStr} if exists ($res->{members}->[$j]->{self}); # Flag if error occurs on monitored host
}

if ($rs_anyerror == 0) {
	$rs_anyerror_str = "OK";
}

$zab->send('mongors_member_statestr', $rs_member_state);

$zab->send('mongors_anyerror', $rs_anyerror);

$zab->send('mongors_anyerror_str', $rs_anyerror_str);

$zab->send('mongors_member_error', $rs_member_error);

$zab->send('mongors_members_visible', $rs_members_visible);

$zab->send('mongors_members_total', $#{$res->{members}}+1);

print "mongors_members_total ", $#{$res->{members}}+1, "\n";

#print $status_str, "\n\n";


text:
 {{contact.firstName[0]}} {{contact.lastName[0]}}

<form name='editContact' class='form-horizontal'>
	<form-field record='contact' field='firstName' required='true'></form-field>
	<form-field record='contact' field='lastName' required='true'></form-field>
	<form-field record='contact' field='{{k}}' ng-repeat='(k,y) in contact | keyFilter: "firstName" | keyFilter: "lastName" | keyFilter: "id" | keyFilter: "userId"'></form-field>

	<new-field record='contact'></new-field>

			<button class='btn btn-danger' ng-click='delete()'> Delete Contact </button>

</form>


text:
__author__ = 'dmorina'
from rest_framework import permissions

class IsWorker(permissions.BasePermission):
    def has_permission(self, request, view):
        return hasattr(request.user.userprofile, 'worker')

class IsRequester(permissions.BasePermission):
    def has_object_permission(self, request, view, object):
        return hasattr(request.user.userprofile, 'requester')


text:
#include <curlpp/cURLpp.hpp>
#include <curlpp/Easy.hpp>
#include <curlpp/Options.hpp>
#include <curlpp/Infos.hpp>

#ifndef DD_HTTPCLIENT_H
#define DD_HTTPCLIENT_H

namespace dd
{

  class httpclient
  {
  public:
    static void get_call(const std::string &url,
			 const std::string &http_method,
			 int &outcode,
			 std::string &outstr)
    {
      curlpp::Cleanup cl;
      std::ostringstream os;
      curlpp::Easy request;
      curlpp::options::WriteStream ws(&os);
      curlpp::options::CustomRequest pr(http_method);
      request.setOpt(curlpp::options::Url(url));
      request.setOpt(ws);
      request.setOpt(pr);
      request.perform();
      outstr = os.str();
      //std::cout << "outstr=" << outstr << std::endl;
      outcode = curlpp::infos::ResponseCode::get(request);
    }

    static void post_call(const std::string &url,
			  const std::string &jcontent,
			  const std::string &http_method,
			  int &outcode,
			  std::string &outstr,
			  const std::string &content_type="Content-Type: application/json")
    {
      curlpp::Cleanup cl;
      std::ostringstream os;
      curlpp::Easy request_put;
      curlpp::options::WriteStream ws(&os);
      curlpp::options::CustomRequest pr(http_method);
      request_put.setOpt(curlpp::options::Url(url));
      request_put.setOpt(ws);
      request_put.setOpt(pr);
      std::list<std::string> header;
      header.push_back(content_type);
      request_put.setOpt(curlpp::options::HttpHeader(header));
      request_put.setOpt(curlpp::options::PostFields(jcontent));
      request_put.setOpt(curlpp::options::PostFieldSize(jcontent.length()));
      request_put.perform();
      outstr = os.str();
      //std::cout << "outstr=" << outstr << std::endl;
      outcode = curlpp::infos::ResponseCode::get(request_put);
    }

  };

}

#endif


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="../assets/img/icon.ico">
    <link rel="stylesheet" href="https://use.fontawesome.com/0fee7aa685.css" media="all">

    <link href="../css/eden.css" rel="stylesheet">
    <title>Container by Eden.</title>
    <link href="../css/style.css" rel="stylesheet">

          <button type="button" class="transparent rounded border uppercase-and-space">Standard</button>
          <button type="button" class="light">Light</button>
          <button type="button" class="dark">Dark</button>
          <button type="button" class="rounded eden shadow">Eden</button>
          <button type="button" class="border uppercase space">Eden</button>StandardDark


text:
PATH=/bin:/usr/bin:/usr/sbin
app_url=http://$OPENSHIFT_APP_DNS/

curl --insecure --location --silent --fail "$app_url" >/dev/null


text:
package com.wonderpush.sdk.push.hcm;

import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.huawei.agconnect.AGConnectOptionsBuilder;
import com.huawei.hms.aaid.HmsInstanceId;
import com.huawei.hms.api.HuaweiApiAvailability;
import com.wonderpush.sdk.WonderPush;
import com.wonderpush.sdk.WonderPushSettings;
import com.wonderpush.sdk.push.PushService;
import com.wonderpush.sdk.push.PushServiceManager;
import com.wonderpush.sdk.push.PushServiceResult;

public class HCMPushService implements PushService {

    private static final String TAG = "WonderPush.Push.HCM." + HCMPushService.class.getSimpleName();

    public static final String IDENTIFIER = "HCM"; // This key serves for ordering in case multiple push services are available
    static Context sContext;
    private static String sHCMAppId;

    @Override
    public String getIdentifier() {
        return IDENTIFIER;
    }

    @Override
    public String getName() {
        return "Huawei Push Kit";
    }

    @Override
    public String getVersion() {
        return BuildConfig.WONDERPUSH_HCM_VERSION;
    }

    @Override
    public void initialize(Context context) {
        sContext = context;

        sHCMAppId = WonderPushSettings.getString("WONDERPUSH_HCM_APP_ID", "wonderpush_hcmAppId", "com.wonderpush.sdk.hcmAppId");
        if (sHCMAppId != null) {
            if (WonderPush.getLogging()) Log.d(TAG, "Applying configuration: HCM AppId: " + sHCMAppId);
        } else {
            sHCMAppId = HCMPushService.getDefaultAppId();
            if (sHCMAppId == null) {
                Log.w(TAG, "No HCM App ID " + sHCMAppId + ". Check your HMS integration. Please refer to the documentation.");
            } else {
                if (WonderPush.getLogging()) Log.d(TAG, "Using App Id from HMS: " + sHCMAppId);
            }
        }
    }

    @Override
    public boolean isAvailable() {
        try {
            if (HuaweiApiAvailability.getInstance().isHuaweiMobileNoticeAvailable(sContext) != 0) {
                Log.w(TAG, "HMS is not available");
                return false;
            }
            return sHCMAppId != null;
        } catch (Exception ex) {
            Log.e(TAG, "Failed to check for HMS availability", ex);
            return false;
        }
    }

    @Override
    public void execute() {
        fetchInstanceId();
    }

    @Override
    public int getNotificationIcon() {
        int iconId = 0;
        try {
            Bundle metaData = sContext.getPackageManager().getApplicationInfo(sContext.getPackageName(), PackageManager.GET_META_DATA).metaData;
            if (metaData == null) {
                metaData = new Bundle();
            }
            iconId = metaData.getInt("com.huawei.messaging.default_notification_icon");
        } catch (Exception e) {
            Log.e(TAG, "Unexpected error while getting notification icon", e);
        }
        if (iconId == 0) {
            // Default to an embedded icon
            iconId = com.wonderpush.sdk.R.drawable.ic_notifications_white_24dp;
        }
        return iconId;
    }

    @Override
    public int getNotificationColor() {
        int color = 0;
        try {
            Bundle metaData = sContext.getPackageManager().getApplicationInfo(sContext.getPackageName(), PackageManager.GET_META_DATA).metaData;
            if (metaData == null) {
                metaData = new Bundle();
            }
            int resId = metaData.getInt("com.huawei.messaging.default_notification_color");
            if (resId != 0) {
                color = contextCompatGetColor(sContext, resId);
            }
        } catch (Exception e) {
            Log.e(TAG, "Unexpected error while getting notification color", e);
        }
        return color;
    }

    @SuppressWarnings("deprecation")
    public static int contextCompatGetColor(Context context, int id) {
        return Build.VERSION.SDK_INT >= 23 ? context.getColor(id) : context.getResources().getColor(id);
    }

    public static void fetchInstanceId() {
        final String appId = getHCMAppId();
        if (WonderPush.getLogging()) Log.d(TAG, "HmsInstanceId.getToken(\"" + appId + "\", \"HCM\") will be called in the background…");
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (WonderPush.getLogging()) Log.d(TAG, "HmsInstanceId.getToken(\"" + appId + "\", \"HCM\") called…");
                    String pushToken = HmsInstanceId.getInstance(sContext).getToken(appId, "HCM");
                    if (TextUtils.isEmpty(pushToken)) {
                        if (WonderPush.getLogging()) Log.d(TAG, "HmsInstanceId.getToken() = null");
                    } else {
                        if (WonderPush.getLogging()) Log.d(TAG, "HmsInstanceId.getToken() = " + pushToken);
                        storeRegistrationId(sContext, getHCMAppId(), pushToken);
                    }
                } catch (Exception ex) {
                    Log.e(TAG, "Could not get HMS InstanceId", ex);
                }
            }
        }, "WonderPush.Push.HCM.HuaweiMessagingService.fetchInstanceId").start();
    }

    static void storeRegistrationId(Context context, String senderIds, String registrationId) {
        PushServiceResult result = new PushServiceResult();
        result.setService("HCM");
        result.setData(registrationId);
        result.setSenderIds(senderIds);
        PushServiceManager.onResult(result);
    }

    static String getDefaultAppId() {
        String appId = new AGConnectOptionsBuilder().build(sContext).getString("client/app_id");
        if (TextUtils.isEmpty(appId)) {
            return null;
        }
        return appId;
    }

    static String getHCMAppId() {
        return sHCMAppId;
    }

}


text:
import time

from .imp_device import Device, DeviceError
from .imp_datatypes import DataTypes
from .imp_packages import Package
from .imp_commands import Command
from .imp_responces import Responce
from .imp_tables import Tables
from .imp_helper import _imprange

class BusError(Exception):
    pass

class Bus:
    """The Bus object represents the IMPBus2 master device. It is used to
    initialize the Bus, set the baudrate and find the connected probes. A
    simple example of how to initialize and search the bus would be::

        >>> from implib2 import Bus, Module
        >>> bus = Bus('/dev/ttyUSB0')
        >>> bus.sync()
        >>> bus.scan()

    :param port: The serial port to use, defaults to `/dev/ttyUSB0`
    :type  port: string

    :param rs485: Set this to `True` in order to use the way more
                  relaxed rs485 timings. Defaults to `False`.
    :type  rs485: bool

    """
    def __init__(self, port='/dev/ttyUSB0', rs485=False):
        tbl = Tables()
        pkg = Package()
        dts = DataTypes()

        self.cmd = Command(tbl, pkg, dts)
        self.res = Responce(tbl, pkg, dts)
        self.dev = Device(port)
        self.bus_synced = False

        # timing magic, adds some extra love for rs485
        self.trans_wait = 0.002 if not rs485 else 0.070
        self.cycle_wait = 0.001 if not rs485 else 0.070
        self.range_wait = 0.020 if not rs485 else 0.070

    def _wait(self, package_len, process_time=0.1):
        transit_time = package_len * self.trans_wait
        time.sleep(transit_time + process_time + transit_time)

    def _search(self, range_address, range_marker, found):
        probes = len(found)
        bcast_address = range_address + range_marker

        if not self.probe_range(bcast_address):
            return False

        if range_marker == 1:
            if self.probe_module_short(bcast_address):
                found.append(bcast_address)

            if self.probe_module_short(bcast_address - 1):
                found.append(bcast_address - 1)

            return not probes == len(found)

        # divide-and-conquer by splitting the range into two pices.
        self._search(bcast_address, range_marker >> 1, found)
        self._search(range_address, range_marker >> 1, found)
        return True

    def wakeup(self):
        """This function sends a broadcast packet which sets the 'EnterSleep'
        parameter of the 'ACTION_PARAMETER_TABLE' to '0', which actually means
        to disable the sleep mode of all connected modules. But the real aim of
        this command is to wake up sleeping modules by sending 'something'.

        :rtype: :const:`True`

        """
        address = 16777215  # 0xFFFFFF
        table = 'ACTION_PARAMETER_TABLE'
        param = 'EnterSleep'
        value = 0
        ad_param = 0

        package = self.cmd.set_parameter(address, table, param,
                                         [value], ad_param)

        self.dev.open_device()
        self.dev.write_pkg(package)
        time.sleep(0.300)

        return True

    def sync(self, baudrate=9600):
        """This command synchronises the connected modules to the given
        baudrate.

        The communication between master and slaves can only be successful
        if they use the same baudrate. In order to synchronise the modules
        on a given baudrate, the bus master has to transmit the broadcast
        command "SetSysPara" with the parameter Baudrate on all possible
        baudrates. There must be a delay of at least 500ms after each command!

        :param baudrate: Baudrate to use (1200-2400-4800-9600).
        :type  baudrate: int

        :raises BusError: If baudrate is unknown.

        :rtype: :const:`True`

        """
        address = 16777215
        table = 'SYSTEM_PARAMETER_TABLE'
        param = 'Baudrate'
        value = baudrate//100
        ad_param = 0

        if value not in (12, 24, 48, 96):
            raise BusError("Unknown baudrate!")

        package = self.cmd.set_parameter(address, table, param,
                                         [value], ad_param)

        # first close the device
        self.dev.close_device()

        # trying to set baudrate at 1200
        self.dev.open_device(baudrate=1200)
        self.dev.write_pkg(package)
        time.sleep(0.500)
        self.dev.close_device()

        # trying to set baudrate at 2400
        self.dev.open_device(baudrate=2400)
        self.dev.write_pkg(package)
        time.sleep(0.420)
        self.dev.close_device()

        # trying to set baudrate at 4800
        self.dev.open_device(baudrate=4800)
        self.dev.write_pkg(package)
        time.sleep(0.340)
        self.dev.close_device()

        # trying to set baudrate at 9600
        self.dev.open_device(baudrate=9600)
        self.dev.write_pkg(package)
        time.sleep(0.260)
        self.dev.close_device()

        # at last open the device with the setted baudrate
        self.dev.open_device(baudrate=baudrate)
        self.bus_synced = True
        time.sleep(1.000)

        return True

    def scan(self, minserial=0, maxserial=16777215):
        """ Command to scan the IMPBUS for connected probes.

        This command can be uses to search the IMPBus2 for connected probes. It
        uses the :func:`probe_range` command, to address a whole serial number
        range and in the case of some 'answers' from the range it recursively
        devides the range into equal parts and repeads this binary search
        schema until the all probes are found.

        .. note:: Searching the IMPBus2

            The 3 bytes IMPBus2 serial numbers spans a 24bit [0 - 16777215]
            address range, which is a whole lot of serial numbers to try. So in
            order to quickly identify the connected probes the command
            :func:`probe_range` can be used. In order to address more than one
            probe a a time the header package of the :func:`probe_range`
            command contains a range pattern where you would normaly find the
            target probes serial number. Example: ::

                range serno:   10010001 10000000 00000000 (0x918000)
                range address: 10010001 00000000 00000000
                range mark:    00000000 10000000 00000000

            As you can see in the example above, the "range serno" from the
            header package consists of a range address and a range marker. The
            Range marker is alwayse the most right '1' of the "range serno"::

                range min:     10010001 00000000 00000000 (0x910000)
                range max:     10010001 11111111 11111111 (0x91ffff)

            So all probes with serial numbers between min and max would answer
            to a :func:`probe_range` command with the "range serno" 0x918000.
            The probes would send the CRC of there serial number as reply to
            this command. But because the probes share the same bus it is higly
            possible the replyes are damaged when red from the serial line. So
            the onoly thing we will know from a :func:`probe_range` command is
            whether or not there is someone in the addressed range. So the next
            thing to do, if we get something back from the addressed range, is
            to devide the range into two pices by shifting the range mark
            right::

                range mark:  00000000 01000000 00000000 (new range mark)
                lower half:  10010001 00000000 00000000 (old mark gets 0)
                higher half: 10010001 10000000 00000000 (old mark gets 1)

            So the new "range sernos" ("range address" + "range mark") are::

                lower half:  10010001 01000000 00000000 (0x914000)
                higher half: 10010001 11000000 00000000 (0x91c000)

            This way we recursively divide the range until we hit the last
            ranges, spanning only two serial numbers. Than we can query them
            directly, using the :func:`probe_module_short` command.

        :param minserial: Start of the range to search (usually: 0).
        :type  minserial: int

        :param maxserial: End of the range to search (usually: 16777215).
        :type  maxserial: int

        :rtype: tuple

        """
        sernos = list()
        rng, mark = _imprange(minserial, maxserial)
        self._search(rng, mark, sernos)

        sernos = [x for x in sernos if x >= minserial and x <= maxserial]
        sernos.sort()

        return tuple(sernos)

    def find_single_module(self):
        """ Find a single module on the Bus.

        This command is used to identify a single module on the bus
        which serial number is unknown. It is a broadcast command and
        serves to get the serial number of the module.

        :rtype: :const:`False` or :const:`tuple` containing the serial number.

        """
        package = self.cmd.get_negative_ack()

        try:
            self.dev.write_pkg(package)
            self._wait(len(package))
            bytes_recv = self.dev.read_pkg()
        except DeviceError:
            return False
        finally:
            time.sleep(self.cycle_wait)

        return self.res.get_negative_ack(bytes_recv)

    def probe_module_long(self, serno):
        """ This command with will call up the slave which is addressed
        by its serial number. In return, the slave replies with a
        complete address block. It can be used to test the presence
        of a module in conjunction with the quality of the bus connection.

        :param serno: Serial number of the probe do connect.
        :type  serno: int

        :rtype: :const:`bool`

        """
        package = self.cmd.get_long_ack(serno)

        try:
            self.dev.write_pkg(package)
            self._wait(len(package))
            bytes_recv = self.dev.read_pkg()
        except DeviceError:
            return False
        finally:
            time.sleep(self.cycle_wait)

        return self.res.get_long_ack(bytes_recv, serno)

    def probe_module_short(self, serno):
        """This command will call up the slave which is addressed by its serial
        number. In return, the slave replies by just one byte: The CRC of its
        serial number. It is the shortest possible command without the transfer
        of any data block and the only one without a complete address block. It
        can be used to test the presence of a module.

        :param serno: Serial number of the probe do connect.
        :type  serno: int

        :rtype: :const:`bool`

        """
        package = self.cmd.get_short_ack(serno)

        try:
            self.dev.write_pkg(package)
            self._wait(len(package))
            bytes_recv = self.dev.read_bytes(1)
        except DeviceError:
            return False
        finally:
            time.sleep(self.cycle_wait)

        return self.res.get_short_ack(bytes_recv, serno)

    def probe_range(self, broadcast):
        """ This command is very similar to probe_module_short(). However,
        it addresses not just one single serial number, but a serial
        number range. This is done by setting the values of byte 4 to byte 6
        of the package header to a broadcast pattern. For more details refer to
        the explanation at :func:`scan`.

        :param serno: Broadcast address.
        :type  serno: int

        :rtype: :const:`bool`

        """
        package = self.cmd.get_range_ack(broadcast)
        self.dev.write_pkg(package)
        self._wait(len(package))
        bytes_recv = self.dev.read()
        time.sleep(self.cycle_wait)
        return self.res.get_range_ack(bytes_recv)

    def get(self, serno, table, param):
        """This is the base command for getting some information from the
        probes. Instead of using this command directly, it's highly recommendet
        to use the higher level `API` commands in :class:`Module`. Nevertheless
        here is a small example of how to use this command to request the
        serial number of a probe::

            >>> table = 'SYSTEM_PARAMETER_TABLE'
            >>> param = 'SerialNum'
            >>> serno = 33912
            >>> bus.get(serno, table, param)

        :param serno: Serial number of the probe to request.
        :type  serno: int

        :param table: System table containing the requested infomation.
        :type  table: string

        :param param: Parameter od row containing the requested infomation.
        :type  param: string

        :rtype: :const:`bool`

        """
        package = self.cmd.get_parameter(serno, table, param)
        self.dev.write_pkg(package)
        self._wait(len(package))
        bytes_recv = self.dev.read_pkg()
        time.sleep(self.cycle_wait)
        return self.res.get_parameter(bytes_recv, table, param)

    def set(self, serno, table, param, value, ad_param=0):
        """This is the base command for sending and storing some information in
        the tables of the probes. It's the counterpart of the :func:`get`
        command. Instead of using this command directly, it's highly
        recommendet to use the higher level `API` commands in :class:`Module`.
        Nevertheless here is a small example of how to use this command to
        set the serial number of a probe::

            >>> table = 'SYSTEM_PARAMETER_TABLE'
            >>> param = 'SerialNum'
            >>> serno = 33912
            >>> new_serno = 33913
            >>> bus.set(serno, table, param, [new_serno])

        :param serno: Serial number of the probe to address.
        :type  serno: int

        :param table: System table to store the infomation.
        :type  table: string

        :param param: Parameter od row containing the requested infomation.
        :type  param: string

        :param value: Values to store.
        :type  value: iterable

        :rtype: :const:`bool`

        """
        # pylint: disable=too-many-arguments
        package = self.cmd.set_parameter(serno, table, param,
                                         value, ad_param)
        self.dev.write_pkg(package)
        self._wait(len(package))
        bytes_recv = self.dev.read_pkg()
        time.sleep(self.cycle_wait)
        return self.res.set_parameter(bytes_recv, table, serno)

    def get_eeprom_page(self, serno, page_nr):
        """This is the base command for reading a single page of EEPRom data
        from a particular probe. It is later used within some higher `API`
        commands within the :class:`Module`-Class. For more Information please
        refer to the description in the :class:`EEPRom`-Class.

        :param serno: Serial number of the probe to address.
        :type  serno: int

        :param page_nr: EEPRom Page to get.
        :type  page_nr: int

        """
        package = self.cmd.get_epr_page(serno, page_nr)
        self.dev.write_pkg(package)
        self._wait(len(package))
        bytes_recv = self.dev.read_pkg()
        time.sleep(self.cycle_wait)
        return self.res.get_epr_page(bytes_recv)

    def set_eeprom_page(self, serno, page_nr, page):
        """This is the base command for writing a single page of EEPRom data
        into a particular probe. It is later used within some higher `API`
        commands within the :class:`Module`-Class. For more Information please
        refer to the description in the :class:`EEPRom`-Class.

        :param serno: Serial number of the probe to address.
        :type  serno: int

        :param page_nr: EEPRom Page to write.
        :type  page_nr: int

        :param page: EEPRom page data.
        :type  page: bytes

        """
        package = self.cmd.set_epr_page(serno, page_nr, page)

        self.dev.write_pkg(package)
        self._wait(len(package))
        bytes_recv = self.dev.read_pkg()
        time.sleep(self.cycle_wait)

        return self.res.set_epr_page(bytes_recv)


text:
describe("Ext.data.soap.Proxy", function() {
    var proxy;

    function makeProxy(config) {
        proxy = new Ext.data.soap.Proxy(Ext.apply({
            model: 'spec.Foo',
            type: 'soap',
            url: '/soapUrl',
            api: {
                create: 'Create',
                read: 'Read',
                update: 'Update',
                destroy: 'Destroy'
            },
            soapAction: {
                create: 'CreateAction',
                read: 'ReadAction',
                update: 'UpdateAction',
                destroy: 'DestroyAction'
            },
            operationParam: 'operation',
            targetNamespace: 'tns'
        }, config || {}));
    }

    beforeEach(function() {
        Ext.ClassManager.enableNamespaceParseCache = false;
        Ext.define('spec.Foo', {
            extend: 'Ext.data.Model',
            fields: [
                { name: 'id', type: 'int' },
                { name: 'bar', type: 'string' }
            ]
        });
    });

    afterEach(function(){
        Ext.ClassManager.enableNamespaceParseCache = true;
        Ext.ModelManager.types = {};
        Ext.undefine('spec.Foo');
    });

    describe("construction", function() {
        beforeEach(function() {
            makeProxy();
        });
        it("should create a soap reader", function() {
            expect(proxy.reader instanceof Ext.data.soap.Reader).toBe(true);
        });
    });

    describe("doRequest", function() {
        var operation, callback, createdCallback, scope, request;

        function makeRequest(action, proxyConfig, requestParams) {
            makeProxy(proxyConfig);
            callback = function() {};
            createdCallback = function() {};
            scope = {};

            spyOn(Ext.Ajax, 'request');
            spyOn(proxy, 'createRequestCallback').andReturn(createdCallback);

            operation = new Ext.data.Operation({ action: action });

            if (action !== 'read') {
                operation.records = [
                    new spec.Foo({id: 1, bar: 'abc'}),
                    new spec.Foo({id: 2, bar: 'xyz'})
                ]
            }
            if (requestParams) {
                operation.params = requestParams;
            }
            request = proxy.doRequest(operation, callback, scope);
        }

        describe("read operation", function() {
            it("should construct a request object", function() {
                makeRequest('read');
                expect(request instanceof Ext.data.Request).toBe(true);
            });

            it("should pass the request object to Ext.Ajax.request", function() {
                makeRequest('read');
                expect(Ext.Ajax.request).toHaveBeenCalledWith(request);
            });

            it("should set the url in the request object and append the operationParam to the url", function() {
                makeRequest('read');
                expect(request.url).toBe('/soapUrl?operation=Read');
            });

            it("should do an HTTP POST", function() {
                makeRequest('read');
                expect(request.method).toBe('POST');
            });

            it("should set the action in the request object", function() {
                makeRequest('read');
                expect(request.action).toBe('read');
            });

            it("should not set request parameters", function() {
                makeRequest('read');
                expect(request.params).toBeUndefined();
            });

            it("should set the SOAPAction header in the request", function() {
                makeRequest('read');
                expect(request.headers.SOAPAction).toBe('ReadAction');
            });

            it("should allow the addition of extra request headers", function() {
                makeRequest('read', {
                    headers: {
                        wibble: 'wobble'
                    }
                });
                expect(request.headers.SOAPAction).toBe('ReadAction');
                expect(request.headers.wibble).toBe('wobble');
            });

            it("should create a request callback request object", function() {
                makeRequest('read');
                expect(proxy.createRequestCallback).toHaveBeenCalledWith(request, operation, callback, scope);
            });

            it("should set the request callback in the request object", function() {
                makeRequest('read');
                expect(request.callback).toBe(createdCallback);
            });

            it("should encode the parameters into a soap envelope", function() {
                makeRequest('read', null, {
                    foo: 42,
                    bar: 'abc'
                });
                expect(request.xmlData).toBe([
                    '<?xml version="1.0" encoding="utf-8" ?>',
                    '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">',
                        '<soap:Body>',
                            '<Read xmlns="tns">',
                                '<foo>42</foo>',
                                '<bar>abc</bar>',
                            '</Read>',
                        '</soap:Body>',
                    '</soap:Envelope>'
                ].join(''));
            });

            it("should have a soap envelope with empty operation element if there are no paremeters", function() {
                makeRequest('read');
                expect(request.xmlData).toBe([
                    '<?xml version="1.0" encoding="utf-8" ?>',
                    '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">',
                        '<soap:Body>',
                            '<Read xmlns="tns">',
                            '</Read>',
                        '</soap:Body>',
                    '</soap:Envelope>'
                ].join(''));
            });

            it("should merge extraParams into params before creating the soap envelope", function() {
                makeRequest('read', {
                    extraParams: {
                        baz: 9000
                    }
                }, {
                    foo: 42,
                    bar: 'abc'
                });
                expect(request.xmlData).toBe([
                    '<?xml version="1.0" encoding="utf-8" ?>',
                    '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">',
                        '<soap:Body>',
                            '<Read xmlns="tns">',
                                '<foo>42</foo>',
                                '<bar>abc</bar>',
                                '<baz>9000</baz>',
                            '</Read>',
                        '</soap:Body>',
                    '</soap:Envelope>'
                ].join(''));
            });

            it("should give params precedence over extraParams if there is a conflict", function() {
                makeRequest('read', {
                    extraParams: {
                        baz: 9000,
                        bar: 'xyz'
                    }
                }, {
                    foo: 42,
                    bar: 'abc'
                });
                expect(request.xmlData).toBe([
                    '<?xml version="1.0" encoding="utf-8" ?>',
                    '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">',
                        '<soap:Body>',
                            '<Read xmlns="tns">',
                                '<foo>42</foo>',
                                '<bar>abc</bar>',
                                '<baz>9000</baz>',
                            '</Read>',
                        '</soap:Body>',
                    '</soap:Envelope>'
                ].join(''));
            });

            it("should allow configuration of a custom envelope template", function() {
                makeRequest('read', {
                    envelopeTpl: [
                        '<?xml version="1.0" encoding="utf-8" ?>',
                        '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" ',
                            'xmlns:xsd= "http://www.w3.org/2001/XMLSchema">',
                            '{[values.bodyTpl.apply(values)]}',
                        '</soap:Envelope>'
                    ]
                }, {
                    foo: 42
                });
                expect(request.xmlData).toBe([
                    '<?xml version="1.0" encoding="utf-8" ?>',
                    '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" ',
                        'xmlns:xsd= "http://www.w3.org/2001/XMLSchema">',
                        '<soap:Body>',
                            '<Read xmlns="tns">',
                                '<foo>42</foo>',
                            '</Read>',
                        '</soap:Body>',
                    '</soap:Envelope>'
                ].join(''));
            });

            it("should allow configuration of a custom body template", function() {
                makeRequest('read', {
                    readBodyTpl: [
                        '<soap:Body>',
                            '<RequestContainer>',
                                '<{operation} xmlns="{targetNamespace}">',
                                    '<tpl foreach="params">',
                                        '<{$}>{.}</{$}>',
                                    '</tpl>',
                                '</{operation}>',
                            '</RequestContainer>',
                        '</soap:Body>'
                    ]
                }, {
                    foo: 42
                });
                expect(request.xmlData).toBe([
                    '<?xml version="1.0" encoding="utf-8" ?>',
                    '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">',
                        '<soap:Body>',
                            '<RequestContainer>',
                                '<Read xmlns="tns">',
                                    '<foo>42</foo>',
                                '</Read>',
                            '</RequestContainer>',
                        '</soap:Body>',
                    '</soap:Envelope>'
                ].join(''));
            });
        });

        describe("create operation", function() {
            it("should construct a request object", function() {
                makeRequest('create');
                expect(request instanceof Ext.data.Request).toBe(true);
            });

            it("should pass the request object to Ext.Ajax.request", function() {
                makeRequest('create');
                expect(Ext.Ajax.request).toHaveBeenCalledWith(request);
            });

            it("should set the url in the request object and append the operationParam to the url", function() {
                makeRequest('create');
                expect(request.url).toBe('/soapUrl?operation=Create');
            });

            it("should do an HTTP POST", function() {
                makeRequest('create');
                expect(request.method).toBe('POST');
            });

            it("should set the action in the request object", function() {
                makeRequest('create');
                expect(request.action).toBe('create');
            });

            it("should not set request parameters", function() {
                makeRequest('create');
                expect(request.params).toBeUndefined();
            });

            it("should set the SOAPAction header in the request", function() {
                makeRequest('create');
                expect(request.headers.SOAPAction).toBe('CreateAction');
            });

            it("should allow the addition of extra request headers", function() {
                makeRequest('create', {
                    headers: {
                        wibble: 'wobble'
                    }
                });
                expect(request.headers.SOAPAction).toBe('CreateAction');
                expect(request.headers.wibble).toBe('wobble');
            });

            it("should create a request callback request object", function() {
                makeRequest('create');
                expect(proxy.createRequestCallback).toHaveBeenCalledWith(request, operation, callback, scope);
            });

            it("should set the request callback in the request object", function() {
                makeRequest('create');
                expect(request.callback).toBe(createdCallback);
            });

            it("should encode the records into a soap envelope", function() {
                makeRequest('create');
                expect(request.xmlData).toBe([
                    '<?xml version="1.0" encoding="utf-8" ?>',
                    '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">',
                        '<soap:Body>',
                            '<Create xmlns="tns">',
                                '<Foo>',
                                    '<id>1</id>',
                                    '<bar>abc</bar>',
                                '</Foo>',
                                '<Foo>',
                                    '<id>2</id>',
                                    '<bar>xyz</bar>',
                                '</Foo>',
                            '</Create>',
                        '</soap:Body>',
                    '</soap:Envelope>'
                ].join(''));
            });

            it("should allow configuration of a custom envelope template", function() {
                makeRequest('create', {
                    envelopeTpl: [
                        '<?xml version="1.0" encoding="utf-8" ?>',
                        '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" ',
                            'xmlns:xsd= "http://www.w3.org/2001/XMLSchema">',
                            '{[values.bodyTpl.apply(values)]}',
                        '</soap:Envelope>'
                    ]
                });
                expect(request.xmlData).toBe([
                    '<?xml version="1.0" encoding="utf-8" ?>',
                    '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" ',
                        'xmlns:xsd= "http://www.w3.org/2001/XMLSchema">',
                        '<soap:Body>',
                            '<Create xmlns="tns">',
                                '<Foo>',
                                    '<id>1</id>',
                                    '<bar>abc</bar>',
                                '</Foo>',
                                '<Foo>',
                                    '<id>2</id>',
                                    '<bar>xyz</bar>',
                                '</Foo>',
                            '</Create>',
                        '</soap:Body>',
                    '</soap:Envelope>'
                ].join(''));
            });

            it("should allow configuration of a custom body template", function() {
                makeRequest('create', {
                    createBodyTpl: [
                        '<soap:Body>',
                            '<RequestContainer>',
                                '<{operation} xmlns="{targetNamespace}">',
                                    '<tpl for="records">',
                                        '{% var recordName=values.modelName.split(".").pop(); %}',
                                        '<{[recordName]}>',
                                            '<tpl for="fields">',
                                                '<{name}>{[parent.get(values.name)]}</{name}>',
                                            '</tpl>',
                                        '</{[recordName]}>',
                                    '</tpl>',
                                '</{operation}>',
                            '</RequestContainer>',
                        '</soap:Body>'
                    ]
                });
                expect(request.xmlData).toBe([
                    '<?xml version="1.0" encoding="utf-8" ?>',
                    '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">',
                        '<soap:Body>',
                            '<RequestContainer>',
                                '<Create xmlns="tns">',
                                    '<Foo>',
                                        '<id>1</id>',
                                        '<bar>abc</bar>',
                                    '</Foo>',
                                    '<Foo>',
                                        '<id>2</id>',
                                        '<bar>xyz</bar>',
                                    '</Foo>',
                                '</Create>',
                            '</RequestContainer>',
                        '</soap:Body>',
                    '</soap:Envelope>'
                ].join(''));
            });
        });

        describe("update operation", function() {
            it("should construct a request object", function() {
                makeRequest('update');
                expect(request instanceof Ext.data.Request).toBe(true);
            });

            it("should pass the request object to Ext.Ajax.request", function() {
                makeRequest('update');
                expect(Ext.Ajax.request).toHaveBeenCalledWith(request);
            });

            it("should set the url in the request object and append the operationParam to the url", function() {
                makeRequest('update');
                expect(request.url).toBe('/soapUrl?operation=Update');
            });

            it("should do an HTTP POST", function() {
                makeRequest('update');
                expect(request.method).toBe('POST');
            });

            it("should set the action in the request object", function() {
                makeRequest('update');
                expect(request.action).toBe('update');
            });

            it("should not set request parameters", function() {
                makeRequest('update');
                expect(request.params).toBeUndefined();
            });

            it("should set the SOAPAction header in the request", function() {
                makeRequest('update');
                expect(request.headers.SOAPAction).toBe('UpdateAction');
            });

            it("should allow the addition of extra request headers", function() {
                makeRequest('update', {
                    headers: {
                        wibble: 'wobble'
                    }
                });
                expect(request.headers.SOAPAction).toBe('UpdateAction');
                expect(request.headers.wibble).toBe('wobble');
            });

            it("should create a request callback request object", function() {
                makeRequest('update');
                expect(proxy.createRequestCallback).toHaveBeenCalledWith(request, operation, callback, scope);
            });

            it("should set the request callback in the request object", function() {
                makeRequest('update');
                expect(request.callback).toBe(createdCallback);
            });

            it("should encode the records into a soap envelope", function() {
                makeRequest('update');
                expect(request.xmlData).toBe([
                    '<?xml version="1.0" encoding="utf-8" ?>',
                    '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">',
                        '<soap:Body>',
                            '<Update xmlns="tns">',
                                '<Foo>',
                                    '<id>1</id>',
                                    '<bar>abc</bar>',
                                '</Foo>',
                                '<Foo>',
                                    '<id>2</id>',
                                    '<bar>xyz</bar>',
                                '</Foo>',
                            '</Update>',
                        '</soap:Body>',
                    '</soap:Envelope>'
                ].join(''));
            });

            it("should allow configuration of a custom envelope template", function() {
                makeRequest('update', {
                    envelopeTpl: [
                        '<?xml version="1.0" encoding="utf-8" ?>',
                        '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" ',
                            'xmlns:xsd= "http://www.w3.org/2001/XMLSchema">',
                            '{[values.bodyTpl.apply(values)]}',
                        '</soap:Envelope>'
                    ]
                });
                expect(request.xmlData).toBe([
                    '<?xml version="1.0" encoding="utf-8" ?>',
                    '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" ',
                        'xmlns:xsd= "http://www.w3.org/2001/XMLSchema">',
                        '<soap:Body>',
                            '<Update xmlns="tns">',
                                '<Foo>',
                                    '<id>1</id>',
                                    '<bar>abc</bar>',
                                '</Foo>',
                                '<Foo>',
                                    '<id>2</id>',
                                    '<bar>xyz</bar>',
                                '</Foo>',
                            '</Update>',
                        '</soap:Body>',
                    '</soap:Envelope>'
                ].join(''));
            });

            it("should allow configuration of a custom body template", function() {
                makeRequest('update', {
                    updateBodyTpl: [
                        '<soap:Body>',
                            '<RequestContainer>',
                                '<{operation} xmlns="{targetNamespace}">',
                                    '<tpl for="records">',
                                        '{% var recordName=values.modelName.split(".").pop(); %}',
                                        '<{[recordName]}>',
                                            '<tpl for="fields">',
                                                '<{name}>{[parent.get(values.name)]}</{name}>',
                                            '</tpl>',
                                        '</{[recordName]}>',
                                    '</tpl>',
                                '</{operation}>',
                            '</RequestContainer>',
                        '</soap:Body>'
                    ]
                });
                expect(request.xmlData).toBe([
                    '<?xml version="1.0" encoding="utf-8" ?>',
                    '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">',
                        '<soap:Body>',
                            '<RequestContainer>',
                                '<Update xmlns="tns">',
                                    '<Foo>',
                                        '<id>1</id>',
                                        '<bar>abc</bar>',
                                    '</Foo>',
                                    '<Foo>',
                                        '<id>2</id>',
                                        '<bar>xyz</bar>',
                                    '</Foo>',
                                '</Update>',
                            '</RequestContainer>',
                        '</soap:Body>',
                    '</soap:Envelope>'
                ].join(''));
            });
        });

        describe("destroy operation", function() {
            it("should construct a request object", function() {
                makeRequest('destroy');
                expect(request instanceof Ext.data.Request).toBe(true);
            });

            it("should pass the request object to Ext.Ajax.request", function() {
                makeRequest('destroy');
                expect(Ext.Ajax.request).toHaveBeenCalledWith(request);
            });

            it("should set the url in the request object and append the operationParam to the url", function() {
                makeRequest('destroy');
                expect(request.url).toBe('/soapUrl?operation=Destroy');
            });

            it("should do an HTTP POST", function() {
                makeRequest('destroy');
                expect(request.method).toBe('POST');
            });

            it("should set the action in the request object", function() {
                makeRequest('destroy');
                expect(request.action).toBe('destroy');
            });

            it("should not set request parameters", function() {
                makeRequest('destroy');
                expect(request.params).toBeUndefined();
            });

            it("should set the SOAPAction header in the request", function() {
                makeRequest('destroy');
                expect(request.headers.SOAPAction).toBe('DestroyAction');
            });

            it("should allow the addition of extra request headers", function() {
                makeRequest('destroy', {
                    headers: {
                        wibble: 'wobble'
                    }
                });
                expect(request.headers.SOAPAction).toBe('DestroyAction');
                expect(request.headers.wibble).toBe('wobble');
            });

            it("should create a request callback request object", function() {
                makeRequest('destroy');
                expect(proxy.createRequestCallback).toHaveBeenCalledWith(request, operation, callback, scope);
            });

            it("should set the request callback in the request object", function() {
                makeRequest('destroy');
                expect(request.callback).toBe(createdCallback);
            });

            it("should encode the records into a soap envelope", function() {
                makeRequest('destroy');
                expect(request.xmlData).toBe([
                    '<?xml version="1.0" encoding="utf-8" ?>',
                    '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">',
                        '<soap:Body>',
                            '<Destroy xmlns="tns">',
                                '<Foo>',
                                    '<id>1</id>',
                                    '<bar>abc</bar>',
                                '</Foo>',
                                '<Foo>',
                                    '<id>2</id>',
                                    '<bar>xyz</bar>',
                                '</Foo>',
                            '</Destroy>',
                        '</soap:Body>',
                    '</soap:Envelope>'
                ].join(''));
            });

            it("should allow configuration of a custom envelope template", function() {
                makeRequest('destroy', {
                    envelopeTpl: [
                        '<?xml version="1.0" encoding="utf-8" ?>',
                        '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" ',
                            'xmlns:xsd= "http://www.w3.org/2001/XMLSchema">',
                            '{[values.bodyTpl.apply(values)]}',
                        '</soap:Envelope>'
                    ]
                });
                expect(request.xmlData).toBe([
                    '<?xml version="1.0" encoding="utf-8" ?>',
                    '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" ',
                        'xmlns:xsd= "http://www.w3.org/2001/XMLSchema">',
                        '<soap:Body>',
                            '<Destroy xmlns="tns">',
                                '<Foo>',
                                    '<id>1</id>',
                                    '<bar>abc</bar>',
                                '</Foo>',
                                '<Foo>',
                                    '<id>2</id>',
                                    '<bar>xyz</bar>',
                                '</Foo>',
                            '</Destroy>',
                        '</soap:Body>',
                    '</soap:Envelope>'
                ].join(''));
            });

            it("should allow configuration of a custom body template", function() {
                makeRequest('destroy', {
                    destroyBodyTpl: [
                        '<soap:Body>',
                            '<RequestContainer>',
                                '<{operation} xmlns="{targetNamespace}">',
                                    '<tpl for="records">',
                                        '{% var recordName=values.modelName.split(".").pop(); %}',
                                        '<{[recordName]}>',
                                            '<tpl for="fields">',
                                                '<{name}>{[parent.get(values.name)]}</{name}>',
                                            '</tpl>',
                                        '</{[recordName]}>',
                                    '</tpl>',
                                '</{operation}>',
                            '</RequestContainer>',
                        '</soap:Body>'
                    ]
                });
                expect(request.xmlData).toBe([
                    '<?xml version="1.0" encoding="utf-8" ?>',
                    '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">',
                        '<soap:Body>',
                            '<RequestContainer>',
                                '<Destroy xmlns="tns">',
                                    '<Foo>',
                                        '<id>1</id>',
                                        '<bar>abc</bar>',
                                    '</Foo>',
                                    '<Foo>',
                                        '<id>2</id>',
                                        '<bar>xyz</bar>',
                                    '</Foo>',
                                '</Destroy>',
                            '</RequestContainer>',
                        '</soap:Body>',
                    '</soap:Envelope>'
                ].join(''));
            });
        });
    });
});


text:
.class Lcom/zte/mifavor/widget/ZTEDaysOfWeek$4;
.super Ljava/lang/Object;
.source "ZTEDaysOfWeek.java"

# interfaces
.implements Landroid/widget/CompoundButton$OnCheckedChangeListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/zte/mifavor/widget/ZTEDaysOfWeek;->InitToggleButton()V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/zte/mifavor/widget/ZTEDaysOfWeek;

# direct methods
.method constructor <init>(Lcom/zte/mifavor/widget/ZTEDaysOfWeek;)V
    .locals 0

    .prologue
    .line 136
    iput-object p1, p0, Lcom/zte/mifavor/widget/ZTEDaysOfWeek$4;->this$0:Lcom/zte/mifavor/widget/ZTEDaysOfWeek;

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

    return-void
.end method

# virtual methods
.method public onCheckedChanged(Landroid/widget/CompoundButton;Z)V
    .locals 2
    .param p1, "buttonView"    # Landroid/widget/CompoundButton;
    .param p2, "isChecked"    # Z

    .prologue
    .line 138
    iget-object v0, p0, Lcom/zte/mifavor/widget/ZTEDaysOfWeek$4;->this$0:Lcom/zte/mifavor/widget/ZTEDaysOfWeek;

    const/4 v1, 0x3

    # invokes: Lcom/zte/mifavor/widget/ZTEDaysOfWeek;->set(IZ)V
    invoke-static {v0, v1, p2}, Lcom/zte/mifavor/widget/ZTEDaysOfWeek;->access$000(Lcom/zte/mifavor/widget/ZTEDaysOfWeek;IZ)V

    .line 139
    return-void
.end method


text:
package com.monitorjbl.xlsx;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellReference;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import static org.junit.jupiter.api.Assertions.assertEquals;

final class TestUtils {

  static Workbook openWorkbook(String fileName) throws IOException {
    try(InputStream stream = TestUtils.class.getResourceAsStream("/" + fileName)) {
      return StreamingReader.builder()
          .open(stream);
    }
  }

  static void expectSameStringContent(Cell cell1, Cell cell2) {
    assertEquals(cell1.getStringCellValue(), cell2.getStringCellValue(),
        "Cell " + ref(cell1) + " has should equal cell " + ref(cell2) + " string value.");
  }

  static void expectStringContent(Cell cell, String value) {
    assertEquals(value, cell.getStringCellValue(), "Cell " + ref(cell) + " has wrong string content.");
  }

  static void expectCachedType(Cell cell, CellType cellType) {
    assertEquals(cellType, cell.getCachedFormulaResultType(), "Cell " + ref(cell) + " has wrong cached type." + cellType);
  }

  static void expectType(Cell cell, CellType cellType) {
    assertEquals(cellType, cell.getCellType(), "Cell " + ref(cell) + " has wrong type.");
  }

  static void expectFormula(Cell cell, String formula) {
    assertEquals(formula, cell.getCellFormula(), "Cell " + ref(cell) + " has wrong formula.");
  }

  private static String ref(Cell cell) {
    return new CellReference(cell).formatAsString();
  }

  static Cell getCellFromNextRow(Iterator<Row> rowIterator, int index) {
    return nextRow(rowIterator)
        .getCell(index);
  }

  static Row nextRow(Iterator<Row> rowIterator) {
    return rowIterator.next();
  }

}


text:
require 'logger'
require 'syslog'

#
module StatMonitor
  #This class represents configuration data for the various classes in StatMonitor.
  #
  #==Configuration file format
  #The configuration file is a JSON structure with the following fields:
  #* "MonitoredMounts": an array of strings representing the mount points for which the client should report disk usage
  #  - If omitted, the client will return an empty dictionary for disk usage.
  #* "Timeout": the threshold for a network timeout in seconds
  #  - The default value is 3 seconds.
  #* "Port": the port used for client/server communication
  #  - The default value is 9445.
  #* "Key": the file containing the 128-bit AES encryption key for network transmissions
  #  - The default value is "/etc/stat-monitor/aes128.key".
  #* "PIDFile": the file in which to write the PID
  #  - The default is "/var/run/stat-monitor-client.pid".
  #* "LogFile": the file in which to log errors
  #  - The default is "/var/log/stat-monitor-client.log"
  #* "Debug": a boolean value specifying whether to log debug messages
  #  - The default value is false
  #* "RootDir"
  #  - The directory that should be treated as root when loading files for parsing; mainly useful for unit testing.
  #    Setting this to a value other than <tt>"/"</tt> will also change the value of df_command
  #    to the equivalent of <tt>"cat #{root_dir}/df.snapshot"</tt>.
	class Config
    #A Set containing the names of all mount points whose disk space is monitored
  	attr_reader :monitored_mounts
    #The port used for client/server communication
    attr_reader :port
    #The network timeout to be used
  	attr_reader :timeout
    #The directory containing the info files to be read; this is set to the system root directory unless
    #a snapshot is being used for unit testing.
  	attr_reader :root_dir
    #The command to obtain disk usage statistics
  	attr_reader :df_command
    #The file containg memory info
  	attr_reader :meminfo_file
    #The file containing CPU info
  	attr_reader :cpuinfo_file
    #The file containing load averages
  	attr_reader :loadavg_file
    #The file containing UTMP structures for all user processes
  	attr_reader :utmp_file
    #The file containing the encryption key
    attr_reader :key_file
    #The encryption key
    attr_reader :key
    #The location of the PID file
    attr_reader :pid_file
    #The location of the log file
    attr_reader :log_file
    #The Logger object for the log file
    attr_reader :log
    #The syslog object
    attr_reader :syslog
    #The debug status
    attr_reader :debug

    #Initialies the object using the given configuration file
		def initialize(filename)
			#To do: error checking
      file = nil
      config = nil
      begin
        file = File.open(filename, "r")
  			config = JSON.parse(file.read)
      ensure
        file.close unless file.nil?
      end

      @debug = (config['Debug'] == true)

      #This should be done first so future errors can go to the log.
      if config.include?'LogFile'
        @log_file = config['LogFile'].to_s
      else
        @log_file = "/var/log/stat-monitor-client.log"
      end

      open_logs()

      if @debug
        log.level = Logger::DEBUG
        syslog.mask = Syslog::LOG_UPTO(Syslog::LOG_DEBUG)
      else
        log.level = Logger::INFO
        syslog.mask = Syslog::LOG_UPTO(Syslog::LOG_INFO)
      end

	    #To do: make sure all loaded data are the correct type?
	    if config.include?'MonitoredMounts'
	      @monitored_mounts = Set.new(config['MonitoredMounts'])
	    else
	      @monitored_mounts = Set.new
	    end

	    if config.include?'Timeout'
	      @timeout = config['Timeout'].to_f
	    else
	      @timeout = 3.0
	    end

	    if config.include?'Port'
	    	@port = config['Port'].to_i
	    else
	    	@port = 9445
	    end

      @key_file = config['Key'] || '/etc/stat-monitor/aes128.key'

      if File.file? @key_file
        File.open(@key_file) do |file|
	       @key = file.read[0 .. 15]
         @key = nil unless @key.length == 16
        end
      end

      if config.include?'PIDFile'
        @pid_file = config['PIDFile'].to_s
      else
        @pid_file = '/var/run/stat-monitor-client.pid'
      end

      @root_dir = config['RootDir'] || '/'
      if @root_dir == '/'
        @df_command = 'df -P | sed 1d'
      else
        #Make sure to escape single quotes for the shell's sake.
        @df_command = "cat '" << File.join(@root_dir, 'df.snapshot').gsub(/'/, "'\\''") << "'"
      end

      @meminfo_file = File.join(@root_dir, 'proc/meminfo')
      @cpuinfo_file = File.join(@root_dir, 'proc/cpuinfo')
      @loadavg_file = File.join(@root_dir, 'proc/loadavg')
      @utmp_file = File.join(@root_dir, 'var/run/utmp')
		end

		#Opens log files and syslogd connections
		def open_logs()
		  @log = Logger.new(@log_file)
      @syslog = Syslog.open($0, Syslog::LOG_PID | Syslog::LOG_CONS)
		end

		#Closes all open log files/syslogd connections
		def close_logs()
		  if @log
  		  @log.close
  		  @log = nil
  		end
  		if @syslog
  		  @syslog.close
  		  @syslog = nil
  		end
		end
	end
end


text:
// Copyright 2004-present Facebook. All Rights Reserved.

package com.facebook.jni;

import com.facebook.proguard.annotations.DoNotStrip;
import com.facebook.soloader.SoLoader;

/**
 * Utility class to determine CPU capabilities
 */
@DoNotStrip
public class CpuCapabilitiesJni {

  static {
    SoLoader.loadLibrary("fb");
  }

  @DoNotStrip
  public static native boolean nativeDeviceSupportsNeon();

  @DoNotStrip
  public static native boolean nativeDeviceSupportsVFPFP16();

  @DoNotStrip
  public static native boolean nativeDeviceSupportsX86();

}


text:
/* -*- C++ -*- */

// $Id: ID_Generator.h 80826 2008-03-04 14:51:23Z wotte $

// ============================================================================
//
// = LIBRARY
//    none
//
// = FILENAME
//    ID_Generator.h
//
// = AUTHOR
//    Nanbor Wang
//
// ============================================================================

#ifndef ACE_ID_GENERATOR_H
#define ACE_ID_GENERATOR_h

#include "ace/config-all.h"

#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */

#define ACE_OFFER_ID_LENGTH 21

class ACE_ID_Generator
  // = TITLE
  //     An unique ID generator.
  //
  // = DESCRIPTION

  //     Generate an offer ID according to current time and avoid
  //     duplicate ID.  It guarantees ID uniqueness within a process,
  //     i.e. no two threads may get the same ID string.  Using a
  //     similar method like the backery algorithm.
{
public:
  static char *get_new_id (char *id);
  // allocate a new ID string and point <id> to it.

private:
  static void get_serial_id (time_t &t, size_t &s);
  // Atomically get info required to generate an offer ID.

  static ACE_SYNCH_MUTEX *get_lock (void);
  // Get the lock instance.

  static time_t last_time_;
  // Record the time last offer ID generated.

  static size_t last_number_;
  // Record serial number of last offer ID with same
  // generation time.

  static ACE_SYNCH_MUTEX *lock_;
  // mutex to access private member.
};

#endif /* ACE_ID_GENERATOR_H */