text:
/*
 * ModeShape (http://www.modeshape.org)
 *
 * 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.
 */
package org.modeshape.jcr.journal;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.modeshape.common.util.FileUtil;
import org.modeshape.jcr.api.value.DateTime;
import org.modeshape.jcr.cache.NodeKey;
import org.modeshape.jcr.cache.change.Change;
import org.modeshape.jcr.cache.change.ChangeSet;
import org.modeshape.jcr.value.basic.JodaDateTime;

/**
 * Unit test for {@link LocalJournal}
 *
 * @author Horia Chiorean (hchiorea@redhat.com)
 */
public class LocalJournalTest {

    protected LocalJournal journal;

    private org.joda.time.DateTime timestamp1;
    private org.joda.time.DateTime timestamp2;
    private org.joda.time.DateTime timestamp3;

    @Before
    public void before() throws Exception {
        FileUtil.delete("target/journal");
        this.journal = new LocalJournal("target/journal");
        journal.start();
        insertTestRecords();
    }

    @After
    public void after() {
        journal().shutdown();
    }

    protected void insertTestRecords() throws InterruptedException {
        // p1 has 4 changesets (sleep for 1 ms between them to make sure the timestamps are different
        ChangeSet process1Changes1 = TestChangeSet.create("j1", 5);
        journal().notify(process1Changes1);

        ChangeSet process1Changes2 = TestChangeSet.create("j1", 1);
        journal().notify(process1Changes2);

        ChangeSet process1Changes3 = TestChangeSet.create("j1", 1);
        journal().notify(process1Changes3);

        ChangeSet process1Changes4 = TestChangeSet.create("j1", 1);
        journal().notify(process1Changes4);
        timestamp1 = new org.joda.time.DateTime(process1Changes4.getTimestamp().getMilliseconds());

        // p2 has 2 changesets
        ChangeSet process2Changes1 = TestChangeSet.create("j2", 1);
        journal().notify(process2Changes1);

        ChangeSet process2Changes2 = TestChangeSet.create("j2", 1);
        journal().notify(process2Changes2);
        timestamp2 = new org.joda.time.DateTime(process2Changes2.getTimestamp().getMilliseconds());

        // p3 has 2 changesets
        ChangeSet process3Changes1 = TestChangeSet.create("j3", 2);
        journal().notify(process3Changes1);

        ChangeSet process3Changes2 = TestChangeSet.create("j3", 2);
        journal().notify(process3Changes2);
        timestamp3 = new org.joda.time.DateTime(process3Changes2.getTimestamp().getMilliseconds());

        ChangeSet process3Changes3 = TestChangeSet.create("j3", 0);
        journal().notify(process3Changes3);
    }

    @Test
    public void shouldReturnAllRecords() throws Exception {
        assertEquals(8, journal().allRecords(false).size());
    }

    @Test
    public void shouldAddRecords() throws InterruptedException {
        int initialRecordCount = journal().allRecords(false).size();
        journal().addRecords(new JournalRecord(TestChangeSet.create("j4", 2)),
                             new JournalRecord(TestChangeSet.create("j4", 1)),
                             new JournalRecord(TestChangeSet.create("j4", 3)));
        assertEquals(initialRecordCount + 3, journal().allRecords(false).size());
    }

    @Test
    public void shouldReturnLastRecord() throws Exception {
        JournalRecord lastRecord = journal().lastRecord();
        assertNotNull(lastRecord);
        assertEquals("j3", lastRecord.getJournalId());
        assertEquals(timestamp3.getMillis(), lastRecord.getChangeTimeMillis());
    }

    @Test
    public void shouldSearchRecordsBasedOnTimestamp() throws Exception {
        // find records older than -1
        assertEquals(8, journal().recordsNewerThan(new org.joda.time.DateTime(-1), true, false).size());
        // find records older than ts1, inclusive
        assertEquals(5, journal().recordsNewerThan(timestamp1, true, false).size());
        // find records older than ts1, exclusive
        assertEquals(4, journal().recordsNewerThan(timestamp1, false, false).size());
        // find records older than ts2, exclusive
        assertEquals(2, journal().recordsNewerThan(timestamp2, false, false).size());
        // find records older than ts3, exclusive
        assertEquals(0, journal().recordsNewerThan(timestamp3, false, false).size());
        // find records older than ts3, inclusive
        assertEquals(1, journal().recordsNewerThan(timestamp3, true, false).size());
        // find records older than max, exclusive
        assertEquals(0, journal().recordsNewerThan(new org.joda.time.DateTime(Long.MAX_VALUE), true, false).size());
    }

    @Test
    public void shouldRemoveOlderJournalEntries() throws Exception {
        File journalFolder = new File(localJournal().getJournalLocation());
        assertTrue(journalFolder.isDirectory() && journalFolder.canRead());
        int initialEntriesCount = journal().allRecords(false).size();

        // insert some of entries - this should create multiple files
        int entriesCount = 10;
        for (int i = 0; i < entriesCount; i++) {
            journal().notify(TestChangeSet.create("j1", entriesCount));
        }
        // make sure we have at least 3 segments
        assertEquals(entriesCount + initialEntriesCount, journal().allRecords(false).size());

        Thread.sleep(1);
        long currentMillis = System.currentTimeMillis();
        Thread.sleep(1);

        // insert another batch of record which should produce additional segments
        for (int i = 0; i < entriesCount; i++) {
            journal().notify(TestChangeSet.create("j1", entriesCount));
        }

        int sizeAfterSecondBatch = journal().allRecords(false).size();
        assertEquals(entriesCount * 2 + initialEntriesCount, sizeAfterSecondBatch);

        // this should remove all the entries from the first batch + initial entries
        localJournal().removeRecordsOlderThan(currentMillis);
        assertEquals(entriesCount, journal().allRecords(false).size());

        // now make sure we can still add data to the journal
        journal().notify(TestChangeSet.create("j4", 2));
        assertEquals(entriesCount + 1, journal().allRecords(false).size());
    }

    @Test
    public void shouldHaveSameJournalIdAfterRestart() throws Exception {
        ChangeJournal journal = journal();
        String journalId = journal.journalId();
        journal.shutdown();
        journal.start();
        assertEquals(journalId, journal.journalId());
    }

    protected ChangeJournal journal() {
        return journal;
    }

    protected LocalJournal localJournal() {
        return journal;
    }

    static class TestChangeSet implements ChangeSet {
        private static final long serialVersionUID = 1L;
        private final String uuid = UUID.randomUUID().toString();
        private List<Change> changes;
        private DateTime timestamp;
        private String journalId;

        private TestChangeSet( List<Change> changes,
                               String journalId ) {
            this.changes = changes;
            this.timestamp = new JodaDateTime();
            this.journalId = journalId;
        }

        @Override
        public int size() {
            return changes.size();
        }

        @Override
        public boolean isEmpty() {
            return changes.isEmpty();
        }

        @Override
        public String getUserId() {
            return "someUser";
        }

        @Override
        public Map<String, String> getUserData() {
            return null;
        }

        @Override
        public DateTime getTimestamp() {
            return timestamp;
        }

        @Override
        public String getProcessKey() {
            return null;
        }

        @Override
        public String getRepositoryKey() {
            return "someRepository";
        }

        @Override
        public String getWorkspaceName() {
            return "someWorkspace";
        }

        @Override
        public Set<NodeKey> changedNodes() {
            return null;
        }

        @Override
        public String getSessionId() {
            return null;
        }

        @Override
        public String getJournalId() {
            return journalId;
        }

        @Override
        public Iterator<Change> iterator() {
            return changes.iterator();
        }

        @Override
        public String getUUID() {
            return uuid;
        }

        @SuppressWarnings( "serial" )
        static ChangeSet create( String journalId,
                                 int changesCount ) throws InterruptedException {
            List<Change> changes = new ArrayList<Change>(changesCount);
            for (int i = 0; i < changesCount; i++) {
                changes.add(new Change() {});
            }
            // sleep 1 second to make sure that successive calls won't have the same TS
            Thread.sleep(1);
            return new TestChangeSet(changes, journalId);
        }
    }
}


text:
run and time the ls command

    /usr/bin/time ls

run foo.py and print time and usage statistics

    /usr/bin/time -l foo.py

# Basic Usage

Run and time a command:

    /usr/bin/time <command>

`time` is a Unix command, but is also the name of a built-in function in many
shells. These examples use the full path `/usr/bin/time` to avoid collisions
with shell functionality, which can differ in confusing ways.

redpajama_set_name: RedPajamaGithub


text:
#ifndef OMG_DDS_CORE_INSTANCE_HANDLE_HPP_
#define OMG_DDS_CORE_INSTANCE_HANDLE_HPP_

#include <vector>
#include <iostream>

#include <dds/core/types.hpp>
#include <dds/core/Value.hpp>

#include <dds/core/detail/InstanceHandle.hpp>

namespace dds {
namespace core {

/**
 * @brief
 * Class to hold the handle associated with in sample instance.
 */
class InstanceHandle : public Value<detail::InstanceHandle>
{
public:

    /**
     * Create an nil instance handle.
     */
    OMG_DDS_API InstanceHandle();

    /**
     * Create an nil instance handle.
     *
     * @param nullHandle placeholder
     */
    OMG_DDS_API InstanceHandle(
            const null_type& nullHandle);

    /**
     * Copy an existing InstancHandle
     *
     * @param other InstanceHandle to copy
     */
    OMG_DDS_API InstanceHandle(
            const InstanceHandle& other);

    /** @cond */
    OMG_DDS_API ~InstanceHandle();
    /** @endcond */

    /**
     * @cond
     * Parametric constructor for creating an instance-handle
     * from some other type. This function is intended for internal
     * usage.
     */
    OMG_DDS_API InstanceHandle(
            const detail::InstanceHandle& arg0);
    /** @endcond */

public:

    /**
     * Assign an existing InstancHandle to this InstancHandle
     *
     * @param that The InstanceHandle to assign to this
     */
    OMG_DDS_API InstanceHandle& operator =(
            const InstanceHandle& that);

    /**
     * Compare this InstanceHandle to another InstanceHandle
     *
     * @param that The InstanceHandle to compare
     * @return true if they match
     */
    OMG_DDS_API bool operator ==(
            const InstanceHandle& that) const;

    /**
     * Compare this InstanceHandle to another InstanceHandle
     *
     * @param that The InstanceHandle to compare
     * @return true if this is less than that
     */
    OMG_DDS_API bool operator <(
            const InstanceHandle& that) const;

    /**
     * Compare this InstanceHandle to another InstanceHandle
     *
     * @param that The InstanceHandle to compare
     * @return true if this is greater than that
     */
    OMG_DDS_API bool operator >(
            const InstanceHandle& that) const;

public:

    /**
     * Create an nil instance handle.
     *
     * @return a nil InstanceHandle
     */
    OMG_DDS_API static const InstanceHandle nil();

    /**
     * Check if the InstanceHandle is nil.
     *
     * @return true if the InstanceHandle is nil
     */
    OMG_DDS_API bool is_nil() const;
};

typedef std::vector<InstanceHandle> InstanceHandleSeq;

} //namespace core
} //namespace dds

inline std::ostream& operator <<(
        std::ostream& os,
        const dds::core::InstanceHandle& h);

#endif //OMG_DDS_CORE_INSTANCE_HANDLE_HPP_


text:
module Users
  class RegistrationsController < Devise::RegistrationsController
    before_filter :update_sanitized_params, if: :devise_controller?

    def update_sanitized_params
      devise_parameter_sanitizer.for(:sign_up) do |u|
        u.permit(
          :name,
          :dni,
          :email,
          :password,
          :password_confirmation
        )
      end
    end
  end
end


text:
go get -u -v golang.org/x/tools/cmd/...
go get -u -v github.com/axw/gocov/gocov
go get -u -v github.com/matm/gocov-html
go get -u -v github.com/AlekSi/gocov-xml
go get -u -v github.com/aktau/github-release
go get -u -v github.com/mitchellh/gox
go get -u -v github.com/golang/dep/cmd/dep


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

namespace StackRedis.L1.MemoryCache.Types.SortedSet
{
    internal class MemorySortedSet
    {
        private ObjMemCache _objMemCache;
        private object _setMoveLockObj = new object();

        internal MemorySortedSet(ObjMemCache objMemCache)
        {
            _objMemCache = objMemCache;
        }

        /// <summary>
        /// Adds values for which it is not known whether or not they are continuous.
        /// </summary>
        internal void AddDiscontinuous(string key, SortedSetEntry[] entries)
        {
            var set = GetSortedSet(key);
            if (set == null)
                set = SetSortedSet(key);

            foreach (var entry in entries)
                set.Add(new[] { entry }, entry.Score, entry.Score);
        }

        /// <summary>
        /// Adds entries which are known to be continuous.
        /// </summary>
        internal void AddContinuous(string key, SortedSetEntry[] entries, double? knownMin, double? knownMax)
        {
            var set = GetSortedSet(key);
            if (set == null)
                set = SetSortedSet(key);

            set.Add(entries, knownMin, knownMax);
        }

        /// <summary>
        /// If the supplied values are already all present in disjointed sections of the set, then they will be joined.
        /// </summary>
        internal void MarkValuesAsContinuous(string key, RedisValue[] entries)
        {
            var set = GetSortedSet(key);
            if(set != null)
            {
                set.JoinRanges(entries);
            }
        }

        /// <summary>
        /// Removes the specified entries
        /// </summary>
        internal void Delete(string key, RedisValue[] entries)
        {
            var set = GetSortedSet(key);
            if (set != null)
            {
                set.Remove(entries);
            }
        }

        internal void RemoveByHashCode(string key, int hashCode)
        {
            var set = GetSortedSet(key);
            if (set != null)
            {
                var entry = set.RetrieveEntryByHashCode(hashCode);
                if(entry.HasValue)
                {
                    set.Remove(new[] { entry.Value.Element });
                }
            }
        }

        /// <summary>
        /// Gets the entries matching the specified hash code
        /// </summary>
        internal SortedSetEntry? GetByHashCode(string key, int hashCode)
        {
            var set = GetSortedSet(key);
            if(set != null)
            {
                return set.RetrieveEntryByHashCode(hashCode);
            }
            return null;
        }

        internal void DeleteByScore(string key, double start, double end, Exclude exclude)
        {
            var set = GetSortedSet(key);
            if(set != null)
            {
                set.RemoveByScore(start, end, exclude);
            }
        }

        internal SortedSetEntry? GetEntry(string key, RedisValue member)
        {
            var set = GetSortedSet(key);
            if (set != null)
            {
                var entry = set.RetrieveEntry(member);
                if(entry.HasValue)
                {
                    return entry.Value;
                }
            }

            return null;
        }

        internal IEnumerable<SortedSetEntry> GetByScore(string key, double start, double end, Exclude exclude, Order order, int skip, int take)
        {
            var set = GetSortedSet(key);
            if (set != null)
            {
                return set.RetrieveByScore(start, end, exclude, order, skip, take);
            }

            return null;
        }

        private DisjointedSortedSet SetSortedSet(string key)
        {
            var set = new DisjointedSortedSet();
            _objMemCache.Add(key, set, null, When.Always);
            return set;
        }

        private DisjointedSortedSet GetSortedSet(string key)
        {
            var result = _objMemCache.Get<DisjointedSortedSet>(key);
            if (result.HasValue)
            {
                return result.Value;
            }
            else
            {
                return null;
            }
        }

        internal void IncrementOrAdd(RedisKey key, RedisValue member, double value)
        {
            var set = GetSortedSet(key);
            if (set != null)
            {
                var existingScore = set.RetrieveScoreByValue(member);
                var newScore = existingScore.GetValueOrDefault(0) + value;

                if (existingScore.HasValue)
                {
                    set.Remove(new[] { member });
                }

                set.Add(new[] { new SortedSetEntry(member, newScore) }, newScore, newScore);
            }
        }

        internal void DecrementOrAdd(RedisKey key, RedisValue member, double value)
        {
            var set = GetSortedSet(key);
            if(set != null)
            {
                var existingScore = set.RetrieveScoreByValue(member);
                var newScore = existingScore.GetValueOrDefault(0) - value;

                if (existingScore.HasValue)
                {
                    set.Remove(new[] { member });
                }

                set.Add(new[] { new SortedSetEntry(member, newScore) }, newScore, newScore);
            }
        }
    }
}


text:
import * as React from "react";
import { storiesOf } from "@storybook/react";
import fullTestData from "testing/data";
import DocRefInfoForm from "./DocRefInfoForm";

const testFolder1 = fullTestData.documentTree.children![0];

const TestHarness: React.FunctionComponent = () => {
  return <DocRefInfoForm docRef={testFolder1} />;
};

storiesOf("Doc Ref/Info", module).add("Form", () => <TestHarness />);


text:
<?php

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\NotEqualTo;
use Symfony\Component\Validator\Constraints\Range;
use Symfony\Component\Validator\Constraints\Regex;
use Symfony\Component\Validator\Constraints\Sequentially;
use Symfony\Component\Validator\Constraints\SequentiallyValidator;
use Symfony\Component\Validator\Constraints\Type;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;

class SequentiallyValidatorTest extends ConstraintValidatorTestCase
{
    protected function createValidator()
    {
        return new SequentiallyValidator();
    }

    public function testWalkThroughConstraints()
    {
        $constraints = [
            new Type('number'),
            new Range(['min' => 4]),
        ];

        $value = 6;

        $contextualValidator = $this->context->getValidator()->inContext($this->context);
        $contextualValidator->expects($this->any())->method('getViolations')->willReturn($this->context->getViolations());
        $contextualValidator->expects($this->exactly(2))
            ->method('validate')
            ->withConsecutive(
                [$value, $constraints[0]],
                [$value, $constraints[1]]
            )
            ->willReturn($contextualValidator);

        $this->validator->validate($value, new Sequentially($constraints));

        $this->assertNoViolation();
    }

    public function testStopsAtFirstConstraintWithViolations()
    {
        $constraints = [
            new Type('string'),
            new Regex(['pattern' => '[a-z]']),
            new NotEqualTo('Foo'),
        ];

        $value = 'Foo';

        $contextualValidator = $this->context->getValidator()->inContext($this->context);
        $contextualValidator->expects($this->any())->method('getViolations')->willReturn($this->context->getViolations());
        $contextualValidator->expects($this->exactly(2))
            ->method('validate')
            ->withConsecutive(
                [$value, $constraints[0]],
                [$value, $constraints[1]]
            )
            ->will($this->onConsecutiveCalls(
                // Noop, just return the validator:
                $this->returnValue($contextualValidator),
                // Add violation on second call:
                $this->returnCallback(function () use ($contextualValidator) {
                    $this->context->getViolations()->add($violation = new ConstraintViolation('regex error', null, [], null, '', null, null, 'regex'));

                    return $contextualValidator;
                }
            )));

        $this->validator->validate($value, new Sequentially($constraints));

        $this->assertCount(1, $this->context->getViolations());
    }
}


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

package com.google.devtools.build.lib.remote;

import build.bazel.remote.execution.v2.CacheCapabilities;
import build.bazel.remote.execution.v2.CapabilitiesGrpc;
import build.bazel.remote.execution.v2.CapabilitiesGrpc.CapabilitiesBlockingStub;
import build.bazel.remote.execution.v2.DigestFunction;
import build.bazel.remote.execution.v2.ExecutionCapabilities;
import build.bazel.remote.execution.v2.GetCapabilitiesRequest;
import build.bazel.remote.execution.v2.PriorityCapabilities;
import build.bazel.remote.execution.v2.PriorityCapabilities.PriorityRange;
import build.bazel.remote.execution.v2.ServerCapabilities;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.remote.options.RemoteOptions;
import com.google.devtools.build.lib.remote.util.TracingMetadataUtils;
import io.grpc.CallCredentials;
import io.grpc.Context;
import io.grpc.StatusRuntimeException;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;

/** Fetches the ServerCapabilities of the remote execution/cache server. */
class RemoteServerCapabilities {

  @Nullable private final String instanceName;
  private final ReferenceCountedChannel channel;
  @Nullable private final CallCredentials callCredentials;
  private final long callTimeoutSecs;
  private final RemoteRetrier retrier;

  public RemoteServerCapabilities(
      @Nullable String instanceName,
      ReferenceCountedChannel channel,
      @Nullable CallCredentials callCredentials,
      long callTimeoutSecs,
      RemoteRetrier retrier) {
    this.instanceName = instanceName;
    this.channel = channel;
    this.callCredentials = callCredentials;
    this.callTimeoutSecs = callTimeoutSecs;
    this.retrier = retrier;
  }

  private CapabilitiesBlockingStub capabilitiesBlockingStub() {
    return CapabilitiesGrpc.newBlockingStub(channel)
        .withInterceptors(TracingMetadataUtils.attachMetadataFromContextInterceptor())
        .withCallCredentials(callCredentials)
        .withDeadlineAfter(callTimeoutSecs, TimeUnit.SECONDS);
  }

  public ServerCapabilities get(String buildRequestId, String commandId)
      throws IOException, InterruptedException {
    Context withMetadata =
        TracingMetadataUtils.contextWithMetadata(buildRequestId, commandId, "capabilities");
    Context previous = withMetadata.attach();
    try {
      GetCapabilitiesRequest request =
          instanceName == null
              ? GetCapabilitiesRequest.getDefaultInstance()
              : GetCapabilitiesRequest.newBuilder().setInstanceName(instanceName).build();
      return retrier.execute(() -> capabilitiesBlockingStub().getCapabilities(request));
    } catch (StatusRuntimeException e) {
      if (e.getCause() instanceof IOException) {
        throw (IOException) e.getCause();
      }
      throw new IOException(e);
    } finally {
      withMetadata.detach(previous);
    }
  }

  static class ClientServerCompatibilityStatus {

    private final List<String> warnings;
    private final List<String> errors;

    private ClientServerCompatibilityStatus(List<String> warnings, List<String> errors) {
      this.warnings = warnings;
      this.errors = errors;
    }

    static class Builder {
      private final ImmutableList.Builder<String> warnings = ImmutableList.builder();
      private final ImmutableList.Builder<String> errors = ImmutableList.builder();

      public void addWarning(String message) {
        warnings.add(message);
      }

      public void addError(String message) {
        errors.add(message);
      }

      public ClientServerCompatibilityStatus build() {
        return new ClientServerCompatibilityStatus(warnings.build(), errors.build());
      }
    }

    public boolean isOk() {
      return warnings.isEmpty() && errors.isEmpty();
    }

    public List<String> getWarnings() {
      return warnings;
    }

    public List<String> getErrors() {
      return errors;
    }
  }

  private static void checkPriorityInRange(
      int priority,
      String optionName,
      PriorityCapabilities prCap,
      ClientServerCompatibilityStatus.Builder result) {
    if (priority != 0) {
      boolean found = false;
      StringBuilder rangeBuilder = new StringBuilder();
      for (PriorityRange pr : prCap.getPrioritiesList()) {
        rangeBuilder.append(String.format("%d-%d,", pr.getMinPriority(), pr.getMaxPriority()));
        if (pr.getMinPriority() <= priority && priority <= pr.getMaxPriority()) {
          found = true;
          break;
        }
      }
      if (!found) {
        String range = rangeBuilder.toString();
        if (!range.isEmpty()) {
          range = range.substring(0, range.length() - 1);
        }
        result.addError(
            String.format(
                "--%s %d is outside of server supported range %s.", optionName, priority, range));
      }
    }
  }

  /** Compare the remote server capabilities with those requested by current execution. */
  public static ClientServerCompatibilityStatus checkClientServerCompatibility(
      ServerCapabilities capabilities,
      RemoteOptions remoteOptions,
      DigestFunction.Value digestFunction) {
    ClientServerCompatibilityStatus.Builder result = new ClientServerCompatibilityStatus.Builder();
    boolean remoteExecution = !Strings.isNullOrEmpty(remoteOptions.remoteExecutor);
    if (!remoteExecution && Strings.isNullOrEmpty(remoteOptions.remoteCache)) {
      return result.build();
    }

    // Check API version.
    ApiVersion.ServerSupportedStatus st =
        ApiVersion.current.checkServerSupportedVersions(capabilities);
    if (st.isUnsupported()) {
      result.addError(st.getMessage());
    }
    if (st.isDeprecated()) {
      result.addWarning(st.getMessage());
    }

    // Check cache digest function.
    CacheCapabilities cacheCap = capabilities.getCacheCapabilities();
    if (!cacheCap.getDigestFunctionList().contains(digestFunction)) {
      result.addError(
          String.format(
              "Cannot use hash function %s with remote cache. "
                  + "Server supported functions are: %s",
              digestFunction, cacheCap.getDigestFunctionList()));
    }

    if (remoteExecution) {
      // Check remote execution is enabled.
      ExecutionCapabilities execCap = capabilities.getExecutionCapabilities();
      if (!execCap.getExecEnabled()) {
        result.addError(
            "Remote execution is not supported by the remote server, or the current "
                + "account is not authorized to use remote execution.");
        return result.build(); // No point checking other execution fields.
      }

      // Check execution digest function.
      if (execCap.getDigestFunction() == DigestFunction.Value.UNKNOWN) {
        // Server side error -- this is not supposed to happen.
        result.addError("Remote server error: UNKNOWN execution digest function.");
      }
      if (execCap.getDigestFunction() != digestFunction) {
        result.addError(
            String.format(
                "Cannot use hash function %s with remote execution. "
                    + "Server supported function is %s",
                digestFunction, execCap.getDigestFunction()));
      }

      // Check updating remote cache is allowed, if we ever need to do that.
      if (remoteOptions.remoteLocalFallback
          && remoteOptions.remoteUploadLocalResults
          && !cacheCap.getActionCacheUpdateCapabilities().getUpdateEnabled()) {
        result.addError(
            "--remote_local_fallback and --remote_upload_local_results are set, "
                + "but the current account is not authorized to write local results "
                + "to the remote cache.");
      }
      // Check execution priority is in the supported range.
      checkPriorityInRange(
          remoteOptions.remoteExecutionPriority,
          "remote_execution_priority",
          execCap.getExecutionPriorityCapabilities(),
          result);
    } else {
      // Local execution: check updating remote cache is allowed.
      if (remoteOptions.remoteUploadLocalResults
          && !cacheCap.getActionCacheUpdateCapabilities().getUpdateEnabled()) {
        result.addError(
            "--remote_upload_local_results is set, but the current account is not authorized "
                + "to write local results to the remote cache.");
      }
    }

    // Check result cache priority is in the supported range.
    checkPriorityInRange(
        remoteOptions.remoteResultCachePriority,
        "remote_result_cache_priority",
        cacheCap.getCachePriorityCapabilities(),
        result);
    return result.build();
  }
}


text:
package com.tngtech.archunit.core.importer.testexamples;

public enum SomeEnum {
    SOME_VALUE, OTHER_VALUE;

    void bar() {
    }
}


text:
Rails.application.routes.draw do

  match "/verify_user", :to => "eco_apps_user_services#verify"

end


text:
package org.marat.workflow.transition;

import org.marat.workflow.Node;
import org.marat.workflow.Workflow;

/**
 * A {@code Transition} describes a link between two {@link Workflow} {@link Node}s.
 *
 * This interface is meant to be overriden by custom {@code enums}, but any kind of implementations may be used. The case
 * sensitive return value of {@link #getTransition()} will actually be used to connect the workflow nodes. It's not allowed to
 * return {@code null} in custom implementations.
 *
 * @see StringTransition
 */
public interface Transition {

	/**
	 * Returns the transition (case sensitive).
	 *
	 * @return the transition, must not be {@code null}
	 */
	String getTransition();

}


text:
namespace TheCollection.Application.Services.Queries {
    using TheCollection.Domain.Core.Contracts;

    public class SearchOwnedQuery : IQuery {
        public SearchOwnedQuery(string searchTerm, int pageSize) {
            SearchTerm = searchTerm;
            PageSize = pageSize;
        }

        public string SearchTerm { get; }
        public int PageSize { get; }
    }
}


text:
package com.awn.mm;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import org.springframework.test.context.ContextConfiguration;

import com.awn.config.repository.ApplicationDataSourceConfig;
import com.awn.mm.ApplicationConfig;

/**
 * @author Rahul Vishwakarma
 *
 */
@ContextConfiguration(classes = {ApplicationConfig.class, ApplicationDataSourceConfig.class})
@RunWith(Suite.class)
@SuiteClasses({ LocationRepositoryTest.class, LocationServiceTest.class, LocationControllerTest.class })
public class MmApplicationTests {

}


text:
module ActionDispatch
  module SystemTesting
    class Browser # :nodoc:
      attr_reader :name

      def initialize(name)
        @name = name
      end

      def type
        case name
        when :headless_chrome
          :chrome
        when :headless_firefox
          :firefox
        else
          name
        end
      end

      def options
        case name
        when :headless_chrome
          headless_chrome_browser_options
        when :headless_firefox
          headless_firefox_browser_options
        end
      end

      private
        def headless_chrome_browser_options
          options = Selenium::WebDriver::Chrome::Options.new
          options.args << "--headless"
          options.args << "--disable-gpu"

          options
        end

        def headless_firefox_browser_options
          options = Selenium::WebDriver::Firefox::Options.new
          options.args << "-headless"

          options
        end
    end
  end
end


text:
package com.intellij.execution.ui.layout.actions;

import com.intellij.execution.ui.actions.BaseViewAction;
import com.intellij.execution.ui.layout.ViewContext;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentManager;

public class CloseAllViewsAction extends BaseViewAction {
  @Override
  protected void update(final AnActionEvent e, final ViewContext context, final Content[] content) {
    setEnabled(e, isEnabled(context, content, e.getPlace()));
  }

  @Override
  protected void actionPerformed(final AnActionEvent e, final ViewContext context, final Content[] content) {
    final ContentManager manager = context.getContentManager();
    for (Content c : manager.getContents()) {
      if (c.isCloseable()) {
        manager.removeContent(c, context.isToDisposeRemovedContent());
      }
    }
  }

  public static boolean isEnabled(ViewContext context, Content[] content, String place) {
    int closeable = 0;
    for (Content c : context.getContentManager().getContents()) {
      if (c.isCloseable()) closeable ++;
    }
    return closeable > 1;
  }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<response>
  <status>success</status>
  <items_returned>4</items_returned>
  <items_available>4</items_available>
  <first_item_position>0</first_item_position>
  <result>
    <activity_fact>
      <month>2012-07-01T00:00:00Z</month>
      <code_added>996</code_added>
      <code_removed>483</code_removed>
      <comments_added>101</comments_added>
      <comments_removed>38</comments_removed>
      <blanks_added>149</blanks_added>
      <blanks_removed>53</blanks_removed>
      <commits>30</commits>
      <contributors>1</contributors>
    </activity_fact>
    <activity_fact>
      <month>2012-08-01T00:00:00Z</month>
      <code_added>552</code_added>
      <code_removed>69</code_removed>
      <comments_added>56</comments_added>
      <comments_removed>1</comments_removed>
      <blanks_added>75</blanks_added>
      <blanks_removed>1</blanks_removed>
      <commits>22</commits>
      <contributors>1</contributors>
    </activity_fact>
    <activity_fact>
      <month>2012-09-01T00:00:00Z</month>
      <code_added>197</code_added>
      <code_removed>69</code_removed>
      <comments_added>21</comments_added>
      <comments_removed>0</comments_removed>
      <blanks_added>38</blanks_added>
      <blanks_removed>4</blanks_removed>
      <commits>8</commits>
      <contributors>1</contributors>
    </activity_fact>
    <activity_fact>
      <month>2012-10-01T00:00:00Z</month>
      <code_added>5889</code_added>
      <code_removed>116</code_removed>
      <comments_added>4</comments_added>
      <comments_removed>4</comments_removed>
      <blanks_added>16</blanks_added>
      <blanks_removed>1</blanks_removed>
      <commits>14</commits>
      <contributors>1</contributors>
    </activity_fact>
  </result>
</response>


text:
---
layout: post
title: 'SonarSource y la calidad de código'
description: Herramientas para desarrolladores, DevOps y ejecutivos
date: '2021-01-28T08:00:00.000+01:00'
author:  Anna Torres
categories:
- sonarsource
- productos

cover: /img/posts/2021-01-28-sonarsource-herramientas-para-desarrolladores-devops-ejecutivos.png
modified_time: '2021-01-28T08:00:00.000+01:00'
---

Los productos **SonarSource** son un estándar de facto para que los equipos y las organizaciones, de todos los tamaños, ofrezcan un **software mejor y más seguro**.

**SonarLint**, **SonarCloud** y **SonarQube** son sus analizadores de código **comercial** y **open source**. Soportan el desarrollo en más de 27 lenguajes de programación cómo Python, Java, C #, JavaScript, TypeScript, C / C ++, COBOL, entre otros. Y permite a los equipos de desarrollo de resolver problemas de codificación dentro de sus **flujos de trabajo existentes**.

Los productos SonarSource son las soluciones preferidas y de mayor confianza en el mercado con
- más de 6.000 clientes
- más de 200.000 organizaciones en todo el mundo confían en la Community Edition (open source)

## Productos

SonarLint es una extensión IDE que le ayuda a detectar y solucionar problemas de calidad mientras escribes código. Como un corrector ortográfico, SonarLint garabatea fallas para que puedan corregirse antes de enviar código.

SonarQube es la herramienta líder para inspeccionar continuamente la calidad y seguridad del código de sus bases de código y guiar a los equipos de desarrollo durante las revisiones de código.

SonarCloud es un servicio de análisis de código basado en la nube diseñado para detectar problemas de calidad del código, lo que garantiza continuamente el mantenimiento, la confiabilidad y la seguridad de su código.

## ¿A quién va dirigido?

### SonarSource para Desarrolladores

#### **Herramientas que ayudan a los desarrolladores a generar la calidad del código de manera continua.**

Antes de todo, SonarQube NO es una herramienta para fiscalizar los proyectos, medir la rentabilidad de un producto software o espiar a los equipos. SonarQube es el mejor amigo de un desarrollador.

SonarQube es una herramienta que acompaña los desarrolladores durante todo el proceso y te proporciona información en todos los paso del proceso de desarrollo, desde el IDE hasta llegar al lanzamiento. Esto permite a los desarrolladores actuar de manera temprana en la calidad del código y hacer un mejor trabajo (= un mejor software).

### SonarSource para DevOps

#### **Todos los equipos colaboran y comparten los mismos criterios.**

Los equipos de DevOps que tienen varías responsabilidad, desde el proceso de desarrollo hasta la implementación continua. Y para ellos la calidad del código es la condición más importante para lograr todos esos objetivos.

Las herramientas SonarSource permiten a los equipos de DevOps aplicar, de manera automática, criterios de calidad garantizando que se produzca un mejor software.

### SonarSource para Ejecutivos

#### **SonarSource mejora la productividad del equipo y ayudan a mantener el control de los costos.**

Las herramientas de SonarSource son valiosas también para los ejecutivos porque les permiten ver los riesgos operacionales que enfrentan, así como los costos de su mitigación.

Mejorar la capacidad de mantenimiento permite aumentar la productividad a largo plazo de los equipos de desarrollo y garantizar un mejor software siempre teniendo bajo control los costos.

¿Quieres solicitar tu licencia de prueba?

Somos Partner Exclusivo en España y Partner Oficial en Latinoamérica.

Contacta con nosotros y te guiáremos hacia la mejor implementación de la inspección continua con SonarSource.

Solicita ahora

¿Necesitas ayuda en tu camino de inspección continua?

Rellena el formulario y te responderemos en 24 horas (o menos).


text:
<?php

namespace Scribe\MantleBundle\Component\HttpFoundation\Exception\Model;

/**
 * Trait HttpExceptionTrait.
 */
trait HttpExceptionTrait
{
    /**
     * @return int
     */
    abstract public function getStatusCode();

    /**
     * @param int|null $code
     *
     * @return $this
     */
    public function setStatusCode($code)
    {
        $this->statusCode = (int) $code;

        return $this;
    }

    /**
     * @return bool
     */
    public function hasStatusCode()
    {
        return (bool) ($this->getStatusCode() !== null ?: false);
    }

    /**
     * @return array
     */
    abstract public function getHeaders();

    /**
     * @param array|null $headers
     *
     * @return $this
     */
    public function setHeaders(array $headers = [])
    {
        $this->headers = $headers;

        return $this;
    }

    /**
     * @return bool
     */
    public function hasHeaders()
    {
        return (bool) (empty($this->getHeaders()) !== true ?: false);
    }
}

/* EOF */


text:
import { NativeModules } from 'react-native';

const DatecsPrinter = NativeModules.DatecsPrinter;

module.exports = DatecsPrinter;


text:
package example;

import java.awt.*;
import javax.swing.*;

public final class MainPanel extends JPanel {
  private MainPanel() {
    super(new BorderLayout());

    JTextArea log = new JTextArea();

    JButton readOnlyButton = new JButton("readOnly");
    readOnlyButton.addActionListener(e -> {
      UIManager.put("FileChooser.readOnly", Boolean.TRUE);
      JFileChooser fileChooser = new JFileChooser();
      int retValue = fileChooser.showOpenDialog(getRootPane());
      if (retValue == JFileChooser.APPROVE_OPTION) {
        log.setText(fileChooser.getSelectedFile().getAbsolutePath());
      }
    });

    JButton defaultButton = new JButton("Default");
    defaultButton.addActionListener(e -> {
      UIManager.put("FileChooser.readOnly", Boolean.FALSE);
      JFileChooser fileChooser = new JFileChooser();
      int retValue = fileChooser.showOpenDialog(getRootPane());
      if (retValue == JFileChooser.APPROVE_OPTION) {
        log.setText(fileChooser.getSelectedFile().getAbsolutePath());
      }
    });

    JPanel p = new JPanel();
    p.setBorder(BorderFactory.createTitledBorder("JFileChooser"));
    p.add(readOnlyButton);
    p.add(defaultButton);
    add(p, BorderLayout.NORTH);
    add(new JScrollPane(log));
    setPreferredSize(new Dimension(320, 240));
  }

  public static void main(String[] args) {
    EventQueue.invokeLater(MainPanel::createAndShowGui);
  }

  private static void createAndShowGui() {
    try {
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
      // UIManager.put("FileChooser.readOnly", Boolean.TRUE);
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
      ex.printStackTrace();
      Toolkit.getDefaultToolkit().beep();
    }
    JFrame frame = new JFrame("@title@");
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.getContentPane().add(new MainPanel());
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}


text:
import argparse
import sys
from time import sleep

from transmissionscripts import filesystem, natural_size
from transmissionscripts import make_client, make_arg_parser
try:
    # noinspection PyUnresolvedReferences
    import curses
except ImportError:
    if sys.platform == "win32":
        print("Please install the UniCurses package")
    else:
        print("Please install the python curses module")
    exit(1)

HEADER_SIZE = 4
BODY_SIZE = 6

def draw_header(scr):
    max_height, max_width = scr.getmaxyx()
    drives = {"/"}
    scr.addstr(0, 1, "Disk free: {}".format(", ".join(
        ["{} ({})".format(natural_size(filesystem.get_free_space(d)), d) for d in drives]
    )))
    scr.addstr(1, 1, "1")
    scr.addstr(2, 1, "2")
    scr.addstr(3, 1, "3s")
    scr.refresh()

def draw_footer(scr):
    max_height, max_width = scr.getmaxyx()
    scr.addstr(max_height-1, 2, "{}".format(max_height))
    scr.refresh()

def draw_body(scr):
    max_height, max_width = scr.getmaxyx()
    for i in range(0, max_height - 1):
        scr.addstr(i, 1, '10 divided by {}'.format(i))
    scr.refresh()

def top(args):
    scr = curses.initscr()
    #scr.start_color()
    curses.noecho()
    curses.cbreak()
    hx, wm = scr.getmaxyx()
    scr.keypad(True)
    try:
        header = curses.newwin(HEADER_SIZE, wm, 0, 0)
        body = curses.newwin(BODY_SIZE, wm, HEADER_SIZE, 0)
        while True:
            draw_header(header)
            draw_body(body)
            draw_footer(scr)
            sleep(0.2)
    except KeyboardInterrupt:
        curses.nocbreak()
        scr.keypad(False)
        curses.echo()
        curses.endwin()

def parse_args():
    parser = argparse.ArgumentParser(
        description='Top like curses client for transmission',
        parents=[make_arg_parser()]
    )
    parser.add_argument("--rate", "-r", dest="rate", help="Update rate for data display", default=5.0, type=float)
    return parser.parse_args()

if __name__ == "__main__":
    try:
        cli_args = parse_args()
        cli = make_client(cli_args)
        top(cli_args)
    except KeyboardInterrupt:
        print("")


text:
<link rel="import" href="scrollbar-css.html">
<link rel="import" href="css-import-behavior.html">
<link rel="import" href="main-behavior.html">
<link rel="import" type="css" href="scrollbar.css">

<dom-module id="simpl-main">
	<template>

		<simpl-globals></simpl-globals>

		<template is="dom-if" if="[[useKeyboard]]">
			<iron-a11y-keys id="keys" target="[[target]]" keys="up down left right space space+shift" on-keys-pressed="keyHandler"></iron-a11y-keys>
		</template>

		<simpl-dispatcher id="dispatcherId" name="[[mmenuName]]" pages="{{pages}}" on-menu-selected="menuItemSelected" selected="{{route}}"></simpl-dispatcher>
		<paper-multidrawer-panel id="drawerPanel" drawer-width="230px" responsive-width="[[responsiveWidth]]" disable-swipe="false">

							<template is="dom-if" if="[[logoUrl]]">

							</template>
							<template is="dom-if" if="[[logoData]]">
								<simpl-import class="brand__logo" method="global.svgimport" data="[[logoData]]"></simpl-import>
							</template>

					<simpl-mmenu id="menuId" on-menu-ready="onMenuReady" on-menu-update="onMenuUpdate" name="[[mmenuName]]" sliding-submenus="true" searchfield="true" class="flex" />

			<paper-scroll-header-panel id="scrollHeaderPanelId" fixed$="[[header-fixed]]" header-height="64" slot="main">
				<paper-toolbar slot="header" class="main__toolbar" id="mainToolbar">

						<paper-icon-button id="menuButton" icon="menu" paper-multidrawer-toggle-left on-tap="togglePanel"></paper-icon-button>

[[selectedPage.path]]

							<paper-icon-button on-click="reload" class="langIcon" src="[[getLangIcon()]]"></paper-icon-button>

				</paper-toolbar>

				<neon-animated-pages style="position:absolute;height:100%;width:100%;" slot="content" id="pages" selected="[[route]]" attr-for-selected="hash">
					<template is="dom-repeat" items="[[pages]]">
						<simpl-animatable-page style="position: relative;display:block;height:100%;width:100%;" hash$="{{item.hash}}">

{{item.name}}

						</simpl-animatable-page>
					</template>
				</neon-animated-pages>
			</paper-scroll-header-panel>

		</paper-multidrawer-panel>

		<template is="dom-if" if="[[pages]]">
			<flatiron-director route="{{route}}" auto-hash></flatiron-director>
		</template>

	</template>

</dom-module>


text:
package com.hotfixs.thinkinginjava.enumerated;

import static com.hotfixs.thinkinginjava.common.Print.print;

import com.hotfixs.thinkinginjava.common.Generator;

import java.util.Random;

/**
 * @author Junwei Wang (i.junwei.wang@gmail.com)
 */
enum CartoonCharacter implements Generator<CartoonCharacter> {
    A, B, C, D, E, F;
    private Random rand = new Random(47);

    @Override
    public CartoonCharacter next() {
        return values()[rand.nextInt(values().length)];
    }
}

public class EnumImplementation {
    public static <T> void printNext(Generator<T> gen) {
        print(gen.next());
    }

    public static void main(String[] args) {
        CartoonCharacter a = CartoonCharacter.A;
        for (int i = 0; i < 10; i++) {
            printNext(a);
        }
    }
}


text:
namespace Azure.ResourceManager.DataBoxEdge.Models
{
    /// <summary> Details about Edge Profile for the resource. </summary>
    internal partial class EdgeProfile
    {
        /// <summary> Initializes a new instance of EdgeProfile. </summary>
        internal EdgeProfile()
        {
        }

        /// <summary> Initializes a new instance of EdgeProfile. </summary>
        /// <param name="subscription"> Edge Profile Subscription. </param>
        internal EdgeProfile(EdgeProfileSubscription subscription)
        {
            Subscription = subscription;
        }

        /// <summary> Edge Profile Subscription. </summary>
        public EdgeProfileSubscription Subscription { get; }
    }
}


text:
#include <pam.h>
#include "hfy_imgutils.h"

hfy_img *hfy_pgmread(char *path) {
    // input image file
    struct pam imgstruct;
    FILE *buf = fopen(path, "r");
    tuple **imgtuple = pnm_readpam(buf, &imgstruct, PAM_STRUCT_SIZE(tuple_type));
    fclose(buf);

    // output image data
    hfy_img *img = (hfy_img *)malloc(sizeof(hfy_img));
    img->height = imgstruct.height;
    img->width = imgstruct.width;
    img->data = (double *)calloc(img->height*img->width, sizeof(double));

    // export normalized image data
    int pos = 0;
    int i, j;
    for(i = 0; i < img->height; ++i) {
        for(j = 0; j < img->width; ++j) {
            img->data[pos++] = ((double)imgtuple[i][j][0]) / imgstruct.maxval;
        }
    }
    // clean and return
    pnm_freepamarray(imgtuple, &imgstruct);
    return img;
}

void hfy_pgmfree(hfy_img *img) {
    free(img->data);
    free(img);
}

void hfy_pgmwrite(hfy_img *img, char *path){
    // loop varibales
    int i, j;

    // pam info containers
    FILE *buf = fopen(path, "w");
    struct pam imgstruct;
    imgstruct.size = PAM_STRUCT_SIZE(tuple_type);
    imgstruct.len = imstruct.size;
    imgstruct.file = buf;
    imgstruct.format = PGM_FORMAT;
    imgstruct.plainformat = 1;
    imgstruct.height = img->height;
    imgstruct.width = img->width;
    imgstruct.depth = 1;
    imgstruct.maxval = 255;
    imgstruct.tuple_type = PAM_PGM_TUPLETYPE;
    imgstruct.comment_p = NULL;

    // image data containers
    tuple **imgtuple = pnm_allocpamarray(&imgstruct);
    double *data = img->data;

    // export scaled data into imgtuple
    int pos = 0;
    for(i = 0; i < img->height; ++i) {
        for(j = 0; j < img->width; ++j) {
            imgtuple[i][j][0] = (sample)
                round( 255.0 * data[pos] );
            ++pos;
        }
    }
    // write the image file
    pnm_writepam(&imgstruct, imgtuple);

    // clean up
    pnm_freepamarray(imgtuple, &imgstruct);
    fclose(path);
}


text:
package bosphorus;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

import com.dyuproject.protostuff.GraphIOUtil;
import com.dyuproject.protostuff.Input;
import com.dyuproject.protostuff.Message;
import com.dyuproject.protostuff.Output;
import com.dyuproject.protostuff.Schema;

public final class ARCHETYPECONSTRAINTALTERNATIVES implements Externalizable, Message<ARCHETYPECONSTRAINTALTERNATIVES>, Schema<ARCHETYPECONSTRAINTALTERNATIVES>
{

    public static Schema<ARCHETYPECONSTRAINTALTERNATIVES> getSchema()
    {
        return DEFAULT_INSTANCE;
    }

    public static ARCHETYPECONSTRAINTALTERNATIVES getDefaultInstance()
    {
        return DEFAULT_INSTANCE;
    }

    static final ARCHETYPECONSTRAINTALTERNATIVES DEFAULT_INSTANCE = new ARCHETYPECONSTRAINTALTERNATIVES();

    private CSINGLEATTRIBUTE csingleattributefield;
    private CONSTRAINTREF constraintreffield;
    private ARCHETYPESLOT archetypeslotfield;
    private ARCHETYPEINTERNALREF archetypeinternalreffield;
    private CDOMAINTYPE cdomaintypefield;
    private CMULTIPLEATTRIBUTE cmultipleattributefield;
    private CPRIMITIVEOBJECT cprimitiveobjectfield;
    private CDEFINEDOBJECT cdefinedobjectfield;
    private CCOMPLEXOBJECT ccomplexobjectfield;

    public ARCHETYPECONSTRAINTALTERNATIVES()
    {

    }

    // getters and setters

    // csingleattributefield

    public CSINGLEATTRIBUTE getCsingleattributefield()
    {
        return csingleattributefield;
    }

    public void setCsingleattributefield(CSINGLEATTRIBUTE csingleattributefield)
    {
        this.csingleattributefield = csingleattributefield;
    }

    // constraintreffield

    public CONSTRAINTREF getConstraintreffield()
    {
        return constraintreffield;
    }

    public void setConstraintreffield(CONSTRAINTREF constraintreffield)
    {
        this.constraintreffield = constraintreffield;
    }

    // archetypeslotfield

    public ARCHETYPESLOT getArchetypeslotfield()
    {
        return archetypeslotfield;
    }

    public void setArchetypeslotfield(ARCHETYPESLOT archetypeslotfield)
    {
        this.archetypeslotfield = archetypeslotfield;
    }

    // archetypeinternalreffield

    public ARCHETYPEINTERNALREF getArchetypeinternalreffield()
    {
        return archetypeinternalreffield;
    }

    public void setArchetypeinternalreffield(ARCHETYPEINTERNALREF archetypeinternalreffield)
    {
        this.archetypeinternalreffield = archetypeinternalreffield;
    }

    // cdomaintypefield

    public CDOMAINTYPE getCdomaintypefield()
    {
        return cdomaintypefield;
    }

    public void setCdomaintypefield(CDOMAINTYPE cdomaintypefield)
    {
        this.cdomaintypefield = cdomaintypefield;
    }

    // cmultipleattributefield

    public CMULTIPLEATTRIBUTE getCmultipleattributefield()
    {
        return cmultipleattributefield;
    }

    public void setCmultipleattributefield(CMULTIPLEATTRIBUTE cmultipleattributefield)
    {
        this.cmultipleattributefield = cmultipleattributefield;
    }

    // cprimitiveobjectfield

    public CPRIMITIVEOBJECT getCprimitiveobjectfield()
    {
        return cprimitiveobjectfield;
    }

    public void setCprimitiveobjectfield(CPRIMITIVEOBJECT cprimitiveobjectfield)
    {
        this.cprimitiveobjectfield = cprimitiveobjectfield;
    }

    // cdefinedobjectfield

    public CDEFINEDOBJECT getCdefinedobjectfield()
    {
        return cdefinedobjectfield;
    }

    public void setCdefinedobjectfield(CDEFINEDOBJECT cdefinedobjectfield)
    {
        this.cdefinedobjectfield = cdefinedobjectfield;
    }

    // ccomplexobjectfield

    public CCOMPLEXOBJECT getCcomplexobjectfield()
    {
        return ccomplexobjectfield;
    }

    public void setCcomplexobjectfield(CCOMPLEXOBJECT ccomplexobjectfield)
    {
        this.ccomplexobjectfield = ccomplexobjectfield;
    }

    // java serialization

    public void readExternal(ObjectInput in) throws IOException
    {
        GraphIOUtil.mergeDelimitedFrom(in, this, this);
    }

    public void writeExternal(ObjectOutput out) throws IOException
    {
        GraphIOUtil.writeDelimitedTo(out, this, this);
    }

    // message method

    public Schema<ARCHETYPECONSTRAINTALTERNATIVES> cachedSchema()
    {
        return this;
    }

    // schema methods

    public ARCHETYPECONSTRAINTALTERNATIVES newMessage()
    {
        return new ARCHETYPECONSTRAINTALTERNATIVES();
    }

    public Class<ARCHETYPECONSTRAINTALTERNATIVES> typeClass()
    {
        return ARCHETYPECONSTRAINTALTERNATIVES.class;
    }

    public String messageName()
    {
        return ARCHETYPECONSTRAINTALTERNATIVES.class.getSimpleName();
    }

    public String messageFullName()
    {
        return ARCHETYPECONSTRAINTALTERNATIVES.class.getName();
    }

    public boolean isInitialized(ARCHETYPECONSTRAINTALTERNATIVES message)
    {
        return true;
    }

    public void mergeFrom(Input input, ARCHETYPECONSTRAINTALTERNATIVES message) throws IOException
    {
        for(int number = input.readFieldNumber(this);; number = input.readFieldNumber(this))
        {
            switch(number)
            {
                case 0:
                    return;
                case 1:
                    message.csingleattributefield = input.mergeObject(message.csingleattributefield, CSINGLEATTRIBUTE.getSchema());
                    break;

                case 2:
                    message.constraintreffield = input.mergeObject(message.constraintreffield, CONSTRAINTREF.getSchema());
                    break;

                case 3:
                    message.archetypeslotfield = input.mergeObject(message.archetypeslotfield, ARCHETYPESLOT.getSchema());
                    break;

                case 4:
                    message.archetypeinternalreffield = input.mergeObject(message.archetypeinternalreffield, ARCHETYPEINTERNALREF.getSchema());
                    break;

                case 5:
                    message.cdomaintypefield = input.mergeObject(message.cdomaintypefield, CDOMAINTYPE.getSchema());
                    break;

                case 6:
                    message.cmultipleattributefield = input.mergeObject(message.cmultipleattributefield, CMULTIPLEATTRIBUTE.getSchema());
                    break;

                case 7:
                    message.cprimitiveobjectfield = input.mergeObject(message.cprimitiveobjectfield, CPRIMITIVEOBJECT.getSchema());
                    break;

                case 8:
                    message.cdefinedobjectfield = input.mergeObject(message.cdefinedobjectfield, CDEFINEDOBJECT.getSchema());
                    break;

                case 9:
                    message.ccomplexobjectfield = input.mergeObject(message.ccomplexobjectfield, CCOMPLEXOBJECT.getSchema());
                    break;

                default:
                    input.handleUnknownField(number, this);
            }
        }
    }

    public void writeTo(Output output, ARCHETYPECONSTRAINTALTERNATIVES message) throws IOException
    {
        if(message.csingleattributefield != null)
             output.writeObject(1, message.csingleattributefield, CSINGLEATTRIBUTE.getSchema(), false);

        if(message.constraintreffield != null)
             output.writeObject(2, message.constraintreffield, CONSTRAINTREF.getSchema(), false);

        if(message.archetypeslotfield != null)
             output.writeObject(3, message.archetypeslotfield, ARCHETYPESLOT.getSchema(), false);

        if(message.archetypeinternalreffield != null)
             output.writeObject(4, message.archetypeinternalreffield, ARCHETYPEINTERNALREF.getSchema(), false);

        if(message.cdomaintypefield != null)
             output.writeObject(5, message.cdomaintypefield, CDOMAINTYPE.getSchema(), false);

        if(message.cmultipleattributefield != null)
             output.writeObject(6, message.cmultipleattributefield, CMULTIPLEATTRIBUTE.getSchema(), false);

        if(message.cprimitiveobjectfield != null)
             output.writeObject(7, message.cprimitiveobjectfield, CPRIMITIVEOBJECT.getSchema(), false);

        if(message.cdefinedobjectfield != null)
             output.writeObject(8, message.cdefinedobjectfield, CDEFINEDOBJECT.getSchema(), false);

        if(message.ccomplexobjectfield != null)
             output.writeObject(9, message.ccomplexobjectfield, CCOMPLEXOBJECT.getSchema(), false);

    }

    public String getFieldName(int number)
    {
        return Integer.toString(number);
    }

    public int getFieldNumber(String name)
    {
        return Integer.parseInt(name);
    }

}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Language.StandardClassification;
using Microsoft.VisualStudio.Utilities;

namespace Microsoft.VisualStudio.InteractiveWindow.Commands
{
    [Export(typeof(IInteractiveWindowCommandsFactory))]
    internal class InteractiveCommandsFactory : IInteractiveWindowCommandsFactory
    {
        private readonly IContentTypeRegistryService _contentTypeRegistry;
        private readonly IStandardClassificationService _standardClassification;

        [ImportingConstructor]
        public InteractiveCommandsFactory(IContentTypeRegistryService contentTypeRegistry, IStandardClassificationService classification)
        {
            _contentTypeRegistry = contentTypeRegistry;
            _standardClassification = classification;
        }

        public IInteractiveWindowCommands CreateInteractiveCommands(IInteractiveWindow window, string prefix, IEnumerable<IInteractiveWindowCommand> commands)
        {
            return new Commands(window, prefix, commands.ToArray(), _contentTypeRegistry, _standardClassification);
        }
    }
}


text:
package kz.epam.zd.model;

import java.util.Map;

@SuppressWarnings("unused")
public class Order extends Entity {
    private OrderStatus status;
    private int userId;
    private Map<Book, Integer> books;
    private Integer totalPrice;

    public Integer getTotalPrice() {
        return totalPrice;
    }

    public void setTotalPrice(Integer totalPrice) {
        this.totalPrice = totalPrice;
    }

    public OrderStatus getStatus() {
        return status;
    }

    public void setStatus(OrderStatus status) {
        this.status = status;
    }

    public Map<Book, Integer> getBooks() {
        return books;
    }

    public void setBooks(Map<Book, Integer> books) {
        this.books = books;
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }
}


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

<com.github.gfranks.collapsible.calendar.widget.WeekView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="2dp">

    <include layout="@layout/day_layout" />

    <include layout="@layout/day_layout" />

    <include layout="@layout/day_layout" />

    <include layout="@layout/day_layout" />

    <include layout="@layout/day_layout" />

    <include layout="@layout/day_layout" />

    <include layout="@layout/day_layout" />

</com.github.gfranks.collapsible.calendar.widget.WeekView>


text:
{{'INSTANCES_INCLUDES_ACTIONS' | translate}}

{{'INSTANCES_INCLUDES_DEPLOY_INSTANCE' | translate}}

{{'INSTANCES_INCLUDES_DEPLOY_START_IT' | translate}}

{{'INSTANCES_INCLUDES_CREATE_CHILD' | translate}}

{{'INSTANCES_INCLUDES_DELETE_INSTANCE' | translate}}

<rbcf-delete-instance ng-show="deletionAsked"></rbcf-delete-instance>

{{'COMMON_DESCRIPTION' | translate}}

{{'INSTANCES_INCLUDES_DESCRIPTION_APP_NOT_DEPLOYED' | translate}}