text:
package net.bytebuddy.test.utility;

import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;

import java.lang.reflect.*;
import java.util.*;

import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;

public class ObjectPropertyAssertion<T> {

    private static final boolean DEFAULT_BOOLEAN = false, OTHER_BOOLEAN = true;

    private static final byte DEFAULT_BYTE = 1, OTHER_BYTE = 42;

    private static final char DEFAULT_CHAR = 1, OTHER_CHAR = 42;

    private static final short DEFAULT_SHORT = 1, OTHER_SHORT = 42;

    private static final int DEFAULT_INT = 1, OTHER_INT = 42;

    private static final long DEFAULT_LONG = 1, OTHER_LONG = 42;

    private static final float DEFAULT_FLOAT = 1, OTHER_FLOAT = 42;

    private static final double DEFAULT_DOUBLE = 1, OTHER_DOUBLE = 42;

    private static final String DEFAULT_STRING = "foo", OTHER_STRING = "bar";

    private final Class<T> type;

    private final ApplicableRefinement refinement;

    private final ApplicableGenerator generator;

    private final ApplicableCreator creator;

    private final boolean skipSynthetic;

    private final String optionalToStringRegex;

    private ObjectPropertyAssertion(Class<T> type,
                                    ApplicableGenerator generator,
                                    ApplicableRefinement refinement,
                                    ApplicableCreator creator,
                                    boolean skipSynthetic,
                                    String optionalToStringRegex) {
        this.type = type;
        this.generator = generator;
        this.refinement = refinement;
        this.creator = creator;
        this.skipSynthetic = skipSynthetic;
        this.optionalToStringRegex = optionalToStringRegex;
    }

    public static <S> ObjectPropertyAssertion<S> of(Class<S> type) {
        return new ObjectPropertyAssertion<S>(type,
                new ApplicableGenerator(),
                new ApplicableRefinement(),
                new ApplicableCreator(),
                false,
                null);
    }

    public ObjectPropertyAssertion<T> refine(Refinement<?> refinement) {
        return new ObjectPropertyAssertion<T>(type,
                generator,
                this.refinement.with(refinement),
                creator,
                skipSynthetic,
                optionalToStringRegex);
    }

    public ObjectPropertyAssertion<T> generate(Generator<?> generator) {
        return new ObjectPropertyAssertion<T>(type,
                this.generator.with(generator),
                refinement,
                creator,
                skipSynthetic,
                optionalToStringRegex);
    }

    public ObjectPropertyAssertion<T> create(Creator<?> creator) {
        return new ObjectPropertyAssertion<T>(type,
                generator,
                refinement,
                this.creator.with(creator),
                skipSynthetic,
                optionalToStringRegex);
    }

    public ObjectPropertyAssertion<T> skipSynthetic() {
        return new ObjectPropertyAssertion<T>(type, generator, refinement, creator, true, optionalToStringRegex);
    }

    public ObjectPropertyAssertion<T> specificToString(String stringRegex) {
        return new ObjectPropertyAssertion<T>(type, generator, refinement, creator, skipSynthetic, stringRegex);
    }

    public void apply() throws IllegalAccessException, InvocationTargetException, InstantiationException {
        if (type.isEnum()) {
            return;
        }
        for (Constructor<?> constructor : type.getDeclaredConstructors()) {
            if (constructor.isSynthetic() && skipSynthetic) {
                continue;
            }
            constructor.setAccessible(true);
            Class<?>[] parameterTypes = constructor.getParameterTypes();
            Object[] actualArguments = new Object[parameterTypes.length];
            Object[] otherArguments = new Object[parameterTypes.length];
            int index = 0;
            for (Class<?> parameterType : parameterTypes) {
                putInstance(parameterType, actualArguments, otherArguments, index++);
            }
            int testIndex = 0;
            @SuppressWarnings("unchecked")
            T instance = (T) constructor.newInstance(actualArguments);
            assertThat(instance, is(instance));
            assertThat(instance, not(is((Object) null)));
            assertThat(instance, not(is(new Object())));
            Object similarInstance = constructor.newInstance(actualArguments);
            assertThat(instance.hashCode(), is(similarInstance.hashCode()));
            assertThat(instance, is(similarInstance));
            if (optionalToStringRegex != null) {
                assertThat(instance.toString(), new RegexMatcher(optionalToStringRegex));
            }
            for (Object otherArgument : otherArguments) {
                Object[] compareArguments = new Object[actualArguments.length];
                int argumentIndex = 0;
                for (Object actualArgument : actualArguments) {
                    if (argumentIndex == testIndex) {
                        compareArguments[argumentIndex] = otherArgument;
                    } else {
                        compareArguments[argumentIndex] = actualArgument;
                    }
                    argumentIndex++;
                }
                Object unlikeInstance = constructor.newInstance(compareArguments);
                assertThat(instance.hashCode(), not(is(unlikeInstance)));
                assertThat(instance, not(is(unlikeInstance)));
                testIndex++;
            }
        }
    }

    private void putInstance(Class<?> parameterType, Object actualArguments, Object otherArguments, int index) {
        Object actualArgument, otherArgument;
        if (parameterType == boolean.class) {
            actualArgument = DEFAULT_BOOLEAN;
            otherArgument = OTHER_BOOLEAN;
        } else if (parameterType == byte.class) {
            actualArgument = DEFAULT_BYTE;
            otherArgument = OTHER_BYTE;
        } else if (parameterType == char.class) {
            actualArgument = DEFAULT_CHAR;
            otherArgument = OTHER_CHAR;
        } else if (parameterType == short.class) {
            actualArgument = DEFAULT_SHORT;
            otherArgument = OTHER_SHORT;
        } else if (parameterType == int.class) {
            actualArgument = DEFAULT_INT;
            otherArgument = OTHER_INT;
        } else if (parameterType == long.class) {
            actualArgument = DEFAULT_LONG;
            otherArgument = OTHER_LONG;
        } else if (parameterType == float.class) {
            actualArgument = DEFAULT_FLOAT;
            otherArgument = OTHER_FLOAT;
        } else if (parameterType == double.class) {
            actualArgument = DEFAULT_DOUBLE;
            otherArgument = OTHER_DOUBLE;
        } else if (parameterType.isEnum()) {
            Object[] enumConstants = parameterType.getEnumConstants();
            if (enumConstants.length == 1) {
                throw new IllegalArgumentException("Enum with only one constant: " + parameterType);
            }
            actualArgument = enumConstants[0];
            otherArgument = enumConstants[1];
        } else if (parameterType.isArray()) {
            actualArgument = Array.newInstance(parameterType.getComponentType(), 1);
            otherArgument = Array.newInstance(parameterType.getComponentType(), 1);
            putInstance(parameterType.getComponentType(), actualArgument, otherArgument, 0);
        } else {
            actualArgument = creator.replace(parameterType, generator, false);
            refinement.apply(actualArgument);
            otherArgument = creator.replace(parameterType, generator, true);
            refinement.apply(otherArgument);
        }
        Array.set(actualArguments, index, actualArgument);
        Array.set(otherArguments, index, otherArgument);
    }

    public interface Refinement<T> {

        void apply(T mock);
    }

    public interface Generator<T> {

        Class<? extends T> generate();
    }

    public interface Creator<T> {

        T create();
    }

    private static class ApplicableRefinement {

        private final List<Refinement<?>> refinements;

        private ApplicableRefinement() {
            refinements = Collections.emptyList();
        }

        private ApplicableRefinement(List<Refinement<?>> refinements) {
            this.refinements = refinements;
        }

        @SuppressWarnings("unchecked")
        private void apply(Object mock) {
            for (Refinement refinement : refinements) {
                ParameterizedType generic = (ParameterizedType) refinement.getClass().getGenericInterfaces()[0];
                Class<?> restrained = generic.getActualTypeArguments()[0] instanceof ParameterizedType
                        ? (Class<?>) ((ParameterizedType) generic.getActualTypeArguments()[0]).getRawType()
                        : (Class<?>) generic.getActualTypeArguments()[0];
                if (restrained.isInstance(mock)) {
                    refinement.apply(mock);
                }
            }
        }

        private ApplicableRefinement with(Refinement<?> refinement) {
            return new ApplicableRefinement(join(refinements, refinement));
        }
    }

    private static class ApplicableGenerator {

        private final List<Generator<?>> generators;

        private ApplicableGenerator() {
            generators = Collections.emptyList();
        }

        private ApplicableGenerator(List<Generator<?>> generators) {
            this.generators = generators;
        }

        private Object generate(Class<?> type, boolean alternative) {
            for (Generator<?> generator : generators) {
                ParameterizedType generic = (ParameterizedType) generator.getClass().getGenericInterfaces()[0];
                Class<?> restrained = generic.getActualTypeArguments()[0] instanceof ParameterizedType
                        ? (Class<?>) ((ParameterizedType) generic.getActualTypeArguments()[0]).getRawType()
                        : (Class<?>) generic.getActualTypeArguments()[0];
                if (type.isAssignableFrom(restrained)) {
                    type = generator.generate();
                }
            }
            return type == String.class
                    ? alternative ? OTHER_STRING : DEFAULT_STRING
                    : mock(type);
        }

        private ApplicableGenerator with(Generator<?> generator) {
            return new ApplicableGenerator(join(generators, generator));
        }
    }

    private static class ApplicableCreator {

        private final List<Creator<?>> creators;

        private ApplicableCreator() {
            creators = Collections.emptyList();
        }

        private ApplicableCreator(List<Creator<?>> creators) {
            this.creators = creators;
        }

        private Object replace(Class<?> type, ApplicableGenerator generator, boolean alternative) {
            for (Creator<?> creator : creators) {
                ParameterizedType generic = (ParameterizedType) creator.getClass().getGenericInterfaces()[0];
                Class<?> restrained = generic.getActualTypeArguments()[0] instanceof ParameterizedType
                        ? (Class<?>) ((ParameterizedType) generic.getActualTypeArguments()[0]).getRawType()
                        : (Class<?>) generic.getActualTypeArguments()[0];
                if (type.isAssignableFrom(restrained)) {
                    return creator.create();
                }
            }
            return generator.generate(type, alternative);
        }

        private ApplicableCreator with(Creator<?> creator) {
            return new ApplicableCreator(join(creators, creator));
        }
    }

    private static class RegexMatcher extends TypeSafeMatcher<String> {

        private final String regex;

        public RegexMatcher(final String regex) {
            this.regex = regex;
        }

        @Override
        public void describeTo(final Description description) {
            description.appendText("matches regex='" + regex + "'");
        }

        @Override
        public boolean matchesSafely(final String string) {
            return string.matches(regex);
        }
    }

    private static <T> List<T> join(List<? extends T> list, T element) {
        List<T> result = new ArrayList<T>(list.size() + 1);
        result.addAll(list);
        result.add(element);
        return result;
    }
}


text:
package org.spongepowered.forge.mixin.core.minecraftforge;

import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.eventbus.api.BusBuilder;
import net.minecraftforge.eventbus.api.IEventBus;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.forge.launch.event.ForgeEventManager;
import org.spongepowered.forge.launch.event.SpongeEventBus;

@Mixin(MinecraftForge.class)
public abstract class MinecraftForgeMixin_Forge {

    @Redirect(method = "<clinit>", at = @At(value = "INVOKE",
            target = "Lnet/minecraftforge/eventbus/api/BusBuilder;build()Lnet/minecraftforge/eventbus/api/IEventBus;", remap = false))
    private static IEventBus forge$substituteForgeEventBus(final BusBuilder builder) {
        return new ForgeEventManager(new SpongeEventBus(builder));
    }

}

redpajama_set_name: RedPajamaGithub


text:
package software.amazon.awssdk.core.interceptor;

import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
import org.reactivestreams.Publisher;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.SdkResponse;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.internal.interceptor.DefaultFailedExecutionContext;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.http.ContentStreamProvider;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.Validate;

/**
 * A wrapper for a list of {@link ExecutionInterceptor}s that ensures the interceptors are executed in the correct order as it
 * is documented in the {@link ExecutionInterceptor} documentation.
 *
 * Interceptors are invoked in forward order up to {@link #beforeTransmission} and in reverse order after (and including)
 * {@link #afterTransmission}. This ensures the last interceptors to modify the request are the first interceptors to see the
 * response.
 */
@SdkProtectedApi
public class ExecutionInterceptorChain {
    private static final Logger LOG = Logger.loggerFor(ExecutionInterceptorChain.class);

    private final List<ExecutionInterceptor> interceptors;

    /**
     * Create a chain that will execute the provided interceptors in the order they are provided.
     */
    public ExecutionInterceptorChain(List<ExecutionInterceptor> interceptors) {
        this.interceptors = new ArrayList<>(Validate.paramNotNull(interceptors, "interceptors"));
        LOG.debug(() -> "Creating an interceptor chain that will apply interceptors in the following order: " + interceptors);
    }

    public void beforeExecution(Context.BeforeExecution context, ExecutionAttributes executionAttributes) {
        interceptors.forEach(i -> i.beforeExecution(context, executionAttributes));
    }

    public InterceptorContext modifyRequest(InterceptorContext context, ExecutionAttributes executionAttributes) {
        InterceptorContext result = context;
        for (ExecutionInterceptor interceptor : interceptors) {
            SdkRequest interceptorResult = interceptor.modifyRequest(result, executionAttributes);
            validateInterceptorResult(result.request(), interceptorResult, interceptor, "modifyRequest");

            result = result.copy(b -> b.request(interceptorResult));
        }
        return result;
    }

    public void beforeMarshalling(Context.BeforeMarshalling context, ExecutionAttributes executionAttributes) {
        interceptors.forEach(i -> i.beforeMarshalling(context, executionAttributes));
    }

    public void afterMarshalling(Context.AfterMarshalling context, ExecutionAttributes executionAttributes) {
        interceptors.forEach(i -> i.afterMarshalling(context, executionAttributes));
    }

    public InterceptorContext modifyHttpRequestAndHttpContent(InterceptorContext context,
                                                              ExecutionAttributes executionAttributes) {
        InterceptorContext result = context;
        for (ExecutionInterceptor interceptor : interceptors) {
            AsyncRequestBody asyncRequestBody = interceptor.modifyAsyncHttpContent(result, executionAttributes).orElse(null);
            RequestBody requestBody = interceptor.modifyHttpContent(result, executionAttributes).orElse(null);
            SdkHttpRequest interceptorResult = interceptor.modifyHttpRequest(result, executionAttributes);
            validateInterceptorResult(result.httpRequest(), interceptorResult, interceptor, "modifyHttpRequest");

            InterceptorContext.Builder builder = result.toBuilder();

            applySdkHttpFullRequestHack(result, builder);

            result = builder.httpRequest(interceptorResult)
                            .asyncRequestBody(asyncRequestBody)
                            .requestBody(requestBody)
                            .build();
        }
        return result;
    }

    private void applySdkHttpFullRequestHack(InterceptorContext context, InterceptorContext.Builder builder) {
        // Someone thought it would be a great idea to allow interceptors to return SdkHttpFullRequest to modify the payload
        // instead of using the modifyPayload method. This is for backwards-compatibility with those interceptors.
        // TODO: Update interceptors to use the proper payload-modifying method so that this code path is only used for older
        // client versions. Maybe if we ever decide to break @SdkProtectedApis (if we stop using Jackson?!) we can even remove
        // this hack!
        SdkHttpFullRequest sdkHttpFullRequest = (SdkHttpFullRequest) context.httpRequest();

        if (context.requestBody().isPresent()) {
            return;
        }

        Optional<ContentStreamProvider> contentStreamProvider = sdkHttpFullRequest.contentStreamProvider();

        if (!contentStreamProvider.isPresent()) {
            return;
        }

        long contentLength = Long.parseLong(sdkHttpFullRequest.firstMatchingHeader("Content-Length").orElse("0"));
        String contentType = sdkHttpFullRequest.firstMatchingHeader("Content-Type").orElse("");
        RequestBody requestBody = RequestBody.fromContentProvider(contentStreamProvider.get(),
                                                                  contentLength,
                                                                  contentType);
        builder.requestBody(requestBody);
    }

    public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) {
        interceptors.forEach(i -> i.beforeTransmission(context, executionAttributes));
    }

    public void afterTransmission(Context.AfterTransmission context, ExecutionAttributes executionAttributes) {
        reverseForEach(i -> i.afterTransmission(context, executionAttributes));
    }

    public InterceptorContext modifyHttpResponse(InterceptorContext context,
                                                 ExecutionAttributes executionAttributes) {
        InterceptorContext result = context;

        for (int i = interceptors.size() - 1; i >= 0; i--) {
            SdkHttpResponse interceptorResult =
                interceptors.get(i).modifyHttpResponse(result, executionAttributes);
            validateInterceptorResult(result.httpResponse(), interceptorResult, interceptors.get(i), "modifyHttpResponse");

            InputStream response = interceptors.get(i).modifyHttpResponseContent(result, executionAttributes).orElse(null);

            result = result.toBuilder().httpResponse(interceptorResult).responseBody(response).build();
        }

        return result;
    }

    public InterceptorContext modifyAsyncHttpResponse(InterceptorContext context,
                                                      ExecutionAttributes executionAttributes) {
        InterceptorContext result = context;

        for (int i = interceptors.size() - 1; i >= 0; i--) {
            ExecutionInterceptor interceptor = interceptors.get(i);

            Publisher<ByteBuffer> newResponsePublisher =
                interceptor.modifyAsyncHttpResponseContent(result, executionAttributes).orElse(null);

            result = result.toBuilder()
                           .responsePublisher(newResponsePublisher)
                           .build();
        }

        return result;
    }

    public void beforeUnmarshalling(Context.BeforeUnmarshalling context, ExecutionAttributes executionAttributes) {
        reverseForEach(i -> i.beforeUnmarshalling(context, executionAttributes));
    }

    public void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes) {
        reverseForEach(i -> i.afterUnmarshalling(context, executionAttributes));
    }

    public InterceptorContext modifyResponse(InterceptorContext context, ExecutionAttributes executionAttributes) {
        InterceptorContext result = context;
        for (int i = interceptors.size() - 1; i >= 0; i--) {
            SdkResponse interceptorResult = interceptors.get(i).modifyResponse(result, executionAttributes);
            validateInterceptorResult(result.response(), interceptorResult, interceptors.get(i), "modifyResponse");

            result = result.copy(b -> b.response(interceptorResult));
        }

        return result;
    }

    public void afterExecution(Context.AfterExecution context, ExecutionAttributes executionAttributes) {
        reverseForEach(i -> i.afterExecution(context, executionAttributes));
    }

    public DefaultFailedExecutionContext modifyException(DefaultFailedExecutionContext context,
                                                         ExecutionAttributes executionAttributes) {
        DefaultFailedExecutionContext result = context;
        for (int i = interceptors.size() - 1; i >= 0; i--) {
            Throwable interceptorResult = interceptors.get(i).modifyException(result, executionAttributes);
            validateInterceptorResult(result.exception(), interceptorResult, interceptors.get(i), "modifyException");
            result = result.copy(b -> b.exception(interceptorResult));
        }

        return result;
    }

    public void onExecutionFailure(Context.FailedExecution context, ExecutionAttributes executionAttributes) {
        interceptors.forEach(i -> i.onExecutionFailure(context, executionAttributes));
    }

    /**
     * Validate the result of calling an interceptor method that is attempting to modify the message to make sure its result is
     * valid.
     */
    private void validateInterceptorResult(Object originalMessage, Object newMessage,
                                           ExecutionInterceptor interceptor, String methodName) {
        if (!Objects.equals(originalMessage, newMessage)) {
            LOG.debug(() -> "Interceptor '" + interceptor + "' modified the message with its " + methodName + " method.");
            LOG.trace(() -> "Old: " + originalMessage + "\nNew: " + newMessage);
        }
        Validate.validState(newMessage != null,
                            "Request interceptor '%s' returned null from its %s interceptor.",
                            interceptor, methodName);
        Validate.isInstanceOf(originalMessage.getClass(), newMessage,
                              "Request interceptor '%s' returned '%s' from its %s method, but '%s' was expected.",
                              interceptor, newMessage.getClass(), methodName, originalMessage.getClass());
    }

    /**
     * Execute the provided action against the interceptors in this chain in the reverse order they are configured.
     */
    private void reverseForEach(Consumer<ExecutionInterceptor> action) {
        for (int i = interceptors.size() - 1; i >= 0; i--) {
            action.accept(interceptors.get(i));
        }
    }
}


text:
<?php
/**
 *
 * @author Jonathan Souza (jralison@jralison.com)
 */

namespace Jralison\Galpao\Components;

use Backend\Models\User;
use Cms\Classes\ComponentBase;
use RainLab\Blog\Models\Post as BlogPost;

class Colunista extends ComponentBase {

    private $colunista;
    private $noticias;
    private $total_noticias;

    public function componentDetails() {
        return [
            'name' => 'Colunista',
            'description' => 'Exibe uma lista de notícias do colunista e uma minibiografia dele.',
        ];
    }

    public function defineProperties() {
        return [
            'login' => [
                'label' => 'Colunista',
                'description' => 'Nome de usuário do colunista.',
                'default' => '{{ :user }}',
            ],
            'postsPerPage' => [
                'title' => 'Notícias por página',
                'type' => 'string',
                'validationPattern' => '^[0-9]+$',
                'validationMessage' => 'O número de notícias por página não é válido.',
                'default' => '10',
            ],
        ];
    }

    public function onRun() {
        $this->colunista = $this->page['colunista'] = User::where('login', '=', $this->property('login'))
            ->firstOrFail();

        $query = BlogPost::where('user_id', $this->colunista->id)->isPublished();
        $this->noticias = $this->page['noticias'] = $query->paginate($this->property('postsPerPage'));
    }

}


text:
<?php
defined('SYSPATH') or die ('no tiene acceso');
//descripcion del modelo productos
class Model_Menus extends ORM{
    protected $_table_names_plural = false;
    //protected $_sorting = array('fecha_publicacion' => 'DESC');
    public function submenus($c){
        $sql="SELECT * FROM menus m
        INNER JOIN submenus s ON s.id_menu=m.id
        WHERE m.controlador='$c'";
        return $this->_db->query(Database::SELECT,$sql,TRUE);
    }
}
?>


text:
chrome.devtools.panels.create('Logger', '../imgages/panel_icon.png', "../html/panel.html", function(extensionPanel) {
    var _window; // Going to hold the reference to panel.html's `window`

    var data = [];
    var port = chrome.runtime.connect({name: 'devtools'});
    port.onMessage.addListener(function(msg) {
        // Write information to the panel, if exists.
        // If we don't have a panel reference (yet), queue the data.
        if (_window) {
        	if(msg.type === "getDetailsResponse")
        		_window.updateView(msg);
        	else
        		_window.updateTable(msg);
        } else {
            data.push(msg);
        }
    });

    extensionPanel.onShown.addListener(function tmp(panelWindow) {
        extensionPanel.onShown.removeListener(tmp); // Run once only
        _window = panelWindow;

        // Release queued data
        var msg;

        while (msg = data.shift())
            _window.updateTable(msg);
        // Just to show that it's easy to talk to pass a message back:
        _window.respond = function(msg) {
            port.postMessage(msg);
        };
    });
});


text:
<!DOCTYPE html>

<meta charset="UTF-8">
<title>Login Page</title>
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="width=device-width, user-scalable=no">
<link rel="stylesheet" type="text/css" href="css/jquery.mobile-1.4.5.min.css" />
<link rel="stylesheet" type="text/css" href="css/pure-min.css" />
<link rel="stylesheet" type="text/css" href="css/index.css" />

<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/main.css">

FitSight™

Pair With Your Watch

On your watch, swipe to see your watch code
then tap this code when it appears in the list below

Pair Devices

				Tes 123

New Devices

				Tes 123

Scan Again</button>


text:
    <Menu active-name="1" theme="dark" width="auto">

      <Submenu name="0">
          <template slot="title">
              <Icon type="ios-keypad"></Icon>
              COMPOSE
          </template>
          <MenuItem name="0-1">
            <router-link :to="{ name: 'MarkdownEditor', params: { mode: 'new' } }" tag="span" class="layout-text">New Article</router-link>
          </MenuItem>
      </Submenu>

      <MenuItem name="1">
          <Icon type="coffee" :size="iconSize"></Icon>
          <router-link :to="{ name: 'ArticleList' }" tag="span" class="layout-text">Articles</router-link>
      </MenuItem>

      <MenuItem name="2">
          <Icon type="trash-b" :size="iconSize"></Icon>
          <router-link :to="{ name: 'Trash' }" tag="span" class="layout-text">Trash</router-link>
      </MenuItem>

      <MenuItem name="3">
          <Icon type="document" :size="iconSize"></Icon>
          <router-link :to="{ name: 'DraftsList' }" tag="span" class="layout-text">Draft</router-link>
      </MenuItem>

      <MenuItem name="widgets">
          <Icon type="document" :size="iconSize"></Icon>
          <router-link :to="{ name: 'WidgetsPage' }" tag="span" class="layout-text">Widgets</router-link>
      </MenuItem>

      <MenuItem name="4">
          <Icon type="gear-a" :size="iconSize"></Icon>
          <router-link :to="{ name: 'Settings' }" tag="span" class="layout-text">Settings</router-link>
      </MenuItem>
    </Menu>

      <router-view></router-view>


text:
package com.cacti.workshop.microservices.service;

import org.springframework.stereotype.Service;

/**
 * Created by domix on 8/13/16.
 */
@Service
public class CalculadoraService {
  public Integer sum(Integer ope1, Integer ope2) {
    return ope1 + ope2;
  }

  public Integer subs(Integer ope1, Integer ope2) {
    return ope1 - ope2;
  }
}


text:
var path      = require('path'),
    _         = require('lodash'),
    Q         = require('q'),
    fs        = require('q-io/fs'),
    moment    = require('moment'),
    inquirer  = require('inquirer');

//-----------------------------------------------------------------------------

var outputAnswers = {
  source: '', // template
  destination: '', // output
  restContext: null,
  debug: false,
  values: null,
  updateFileName: null
};

//---

var helpersSet = {
  capitalize: function(value) {
    return _.capitalize(value);
  },

  stringRegExpEscape: function(string) {
    return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  }
};

// To assign on outputAnswers.values.helpers
var commonHelpers = {
  capitalize: helpersSet.capitalize
};

//---

var templates = {

  'gulp_task': {
    type: 'file',
    source: '/gulp/config.js',
    destination: {
      // overwrite output destination
      dirname: 'tools/gulp/tasks'
    }
  },

  'angularjs_page': {
    type: 'directory',
    source: '/angularjs/page',
    destination: 'app' // concat with output destination
  },

  'angularjs_crud': {
    type: 'directory',
    source: '/angularjs/crud',
    destination: 'app', // concat with output destination
    helpers: {
      stringRegExpEscape: helpersSet.stringRegExpEscape
    }
  },

  'angularjs_resource': {
    type: 'directory',
    source: '/angularjs/resource',
    destination: 'app', // concat with output destination
    helpers: {
      stringRegExpEscape: helpersSet.stringRegExpEscape
    }
  }

};

//---

/*
  macro flow view:

  1 - which template
  2 - values for selected template
  3 - change default output

*/

var questions = {

  'templates': {

    'available': {
      type: 'list',
      name: 'selected',
      message: 'Select Template',
      choices: [
        {
          name: 'Angular.js',
          value: { type: 'question', key: 'angularjs' }
        },
        {
          name: 'Gulp Task',
          value: { type: 'template', key: 'gulp_task'}
        }
      ]
    },

    'angularjs': {
      type: 'list',
      name: 'selected',
      message: 'Select Angular.js Template',
      choices: [
        {
          name: 'Use Case (CRUD)',
          value: { type: 'template', key: 'angularjs_crud' }
        },
        {
          name: 'Resource',
          value: { type: 'template', key: 'angularjs_resource' }
        },
        {
          name: 'Page',
          value: { type: 'template', key: 'angularjs_page' }
        }
      ]
    }

  }

};

//-----------------------------------------------------------------------------
// @begin: file system utils

function checkIfExists( checkPath ) {
  return fs.exists( checkPath );
}

function renameOld( pathToRename ) {
  return fs.stat( pathToRename )
    .then(function( stat ) {

      var target = '';
      var infoString = '_old_';
      var now = moment().format('YYYYMMDDHHmmss');

      if( stat.isDirectory() ) {

        target = pathToRename + infoString + now;

      } else if( stat.isFile() ) {

        var dirname = path.dirname( pathToRename ),
            extname = path.extname( pathToRename ),
            filename = path.basename( pathToRename, extname );

        target = path.join( dirname, ( filename + infoString + now + extname ) );

      } else {

        throw new Error( 'Invalid : \n  ' + pathToRename );

      }

      return fs.rename( pathToRename, target )
        .then(function() {
          return 'renamed from: [' + pathToRename + '] to [' + target + ']';
        });

    });
}

// @end: file system utils
//-----------------------------------------------------------------------------

function checkTemplateHelpers() {

  var selectedTemplate = outputAnswers.template,
      updateFileName = null,
      helpers = {};

  _.assign( helpers, commonHelpers );

  if( selectedTemplate.helpers ) {

    _.assign( helpers, selectedTemplate.helpers );

    updateFileName = selectedTemplate.helpers.updateFileName;
    if(
      updateFileName &&
      _.isFunction( updateFileName )
    ) {

      outputAnswers.updateFileName = updateFileName;

    }

  }

  _.assign( outputAnswers.values, { helpers: helpers } );

  delete outputAnswers.template;

  selectedTemplate = null;
  updateFileName = null;
  helpers = null;

} // end: checkTemplateHelpers()

//-----------------------------------------------------------------------------

function hasWhiteSpace(s) {
  return /\s/g.test(s);
}

function inputQuestion(name, message, defaultAnswer, fnValidate) {
  return {
    type: 'input',
    name: name,
    message: message,
    validate: fnValidate,
    default: defaultAnswer,
  };
}

//-----------------------------------------------------------------------------

function ask(questions, cb) {
  var promise = null;

  if( !cb ) {
    var deferred = Q.defer();
    cb = deferred.resolve;
    promise = deferred.promise;
  }

  inquirer.prompt(questions, cb);

  return promise;
}

//-----------------------------------------------------------------------------
// @begin: askFor

var askFor = {

  template: function(key) {
    return ask(questions.templates[key])
      .then(function(answer) {
        if(answer.selected.type === 'question') {
          return askFor.template(answer.selected.key);
        }
        return answer;
      });
  },

  yes_no: function(msg, defaultAnswer) {
    if( _.isUndefined( defaultAnswer ) ) defaultAnswer = true;
    return ask({
      type: 'confirm',
      name: 'value',
      message: msg,
      default: defaultAnswer
    });
  },

  not_empty_answer: function(forValue, checkWhitespaces) {
    if( _.isUndefined( checkWhitespaces ) ) checkWhitespaces = true;
    return ask(inputQuestion(
      'input',
      'Define ' + forValue + ':',
      null,
      function( value ) {
        var msg = 'Please enter a ' + forValue;
        var valid =  !_.isEmpty(value) && !_.isNumber(value);
        if(valid && checkWhitespaces) {
          valid = (hasWhiteSpace(value) ? msg + ' without whitespaces' : true);
        }
        return valid || msg;
      }));
  },

  name: function() {
    return askFor.not_empty_answer('name');
  },

  values: {

    gulp_task: function() {
      return askFor.name()
        .then(function(answer) {
          return { 'name': answer.input };
        });
    },

    angularjs_page: function() {
      var output = {};

      return askFor.name()
        .then(function(answer) {
          output.name = answer.input;

          return ask(inputQuestion('input', 'Define route:', '/' + output.name));
        })
        .then(function(answer) {
          var route = answer.input;
          if( route.indexOf('/') === 0 ) {
            route = route.slice(1, route.length);
          }
          output.route = route;
        })
        .then(function() {
          return output;
        });
    },

    angularjs_crud: function() {
      return askFor.values.angularjs_page()
        .then(function(output) {

          return ask(inputQuestion(
            'input',
            'Define resource url:',
            outputAnswers.restContext + '/' + output.name
          ))
          .then(function(answer) {
            output.endpoint = answer.input;
          })
          .then(function() {
            return output;
          });

        });
    },

    angularjs_resource: function() {
      return askFor.name()
        .then(function(answer) {
          var output = {};

          output.name = answer.input;

          return output;
        })
        .then(function(output) {

          return ask(inputQuestion(
            'input',
            'Define resource url:',
            outputAnswers.restContext + '/' + output.name
          ))
          .then(function(answer) {
            output.endpoint = answer.input;
          })
          .then(function() {
            return output;
          });

        });
    }

  }, // @end: values

  output: {

    check: function() {
      return askFor.output[outputAnswers.template.type]();
    },

    file: function() {

      //-----------------------------------
      // @begin: define output attributes

      var outputDestination = outputAnswers.destination.dirname;
      var selectedTemplate = outputAnswers.template;
      var extname = null;
      var basename = null;

      var output = {
        dirname: outputDestination,
        file: null
      };

      if( selectedTemplate.destination ) {

        if( _.isString( selectedTemplate.destination ) ) {

          output.dirname = path.join( output.dirname, selectedTemplate.destination );

        } else {

          if( selectedTemplate.destination.dirname ) {
            output.dirname = selectedTemplate.destination.dirname;
          }

          if( selectedTemplate.destination.filename ) {
            extname = path.extname( selectedTemplate.destination.filename );
            output.file = {
              name: path.basename( selectedTemplate.destination.filename, extname ),
              ext: extname
            };
          }

        }

      }

      if( !output.file ) {
        if( outputAnswers.values.name ) {
          output.file = {
            name: outputAnswers.values.name,
            ext: path.extname( selectedTemplate.source )
          };
        } else {
          extname = path.extname( selectedTemplate.source );
          basename = path.basename( selectedTemplate.source );
          output.file = {
            name: path.basename( basename, extname ),
            ext: extname
          };
        }
      }

      //@end: define output attributes
      //-----------------------------------

      function getOutputPath() {
        return path.join(output.dirname, output.file.name + output.file.ext);
      }

      //-----------------------------------

      function updateOutput() {

        var whatToUpdate = {
          type: 'list',
          name: 'selected',
          message: 'Update',
          choices: [
            {
              name: 'Directory       : ' + output.dirname,
              value: 'dirname'
            },
            {
              name: 'File name       : ' + output.file.name,
              value: 'filename'
            },
            {
              name: 'File extension  : ' + output.file.ext,
              value: 'fileext'
            }
          ]
        };

        var update = {
          dirname: function() {
            // TODO: review and define another input validator
            return askFor.not_empty_answer('directory')
              .then(function( answer ) {
                output.dirname = answer.input;
              });
          },

          filename: function() {
            // TODO: review and define another input validator
            return askFor.not_empty_answer('file name')
              .then(function( answer ) {
                output.file.name = answer.input;
              });
          },

          fileext: function() {
            // TODO: review and define another input validator
            return askFor.not_empty_answer('file extension')
              .then(function( answer ) {
                var ext = answer.input;
                if( ext.indexOf('.') !== 0 ) ext = '.' + ext;
                output.file.ext = ext;
              });
          }
        };

        return ask(whatToUpdate)
          .then(function(answer) {
            return update[answer.selected]();
          })
          .then(function() {
            return askForChangeOutput();
          })
        ;
      } // @end: updateOutput()

      //-----------------------------------

      function askForChangeOutput( defaultAnswer ) {
        if( _.isUndefined( defaultAnswer ) ) defaultAnswer = false;

        var outputPath = getOutputPath();

        var questionMsg = 'Change output';
        questionMsg += '\n    directory : ' + output.dirname;
        questionMsg += '\n    file';
        questionMsg += '\n      name    : ' + output.file.name;
        questionMsg += '\n      ext     : ' + output.file.ext;
        questionMsg += '\n    path      : ' + outputPath;
        questionMsg += '\n>>> ';

        return askFor.yes_no(questionMsg, defaultAnswer)
          .then(function( answer ) {

            if( answer.value ) {

              return updateOutput();

            } else {

              return checkIfExists( outputPath )
                .then(function (flag) {

                  if( flag ) {
                    return askFor.yes_no('File already exists, overwrite?', false)
                      .then(function( answer ) {

                          if( answer.value ) { // overwrite file
                            return renameOld( outputPath );
                          } else { // ask to change output
                            return askForChangeOutput( true ); // set default answer to true
                          }

                      });
                  }

                  return 'finished';

                });

            }

          });

      } // @end: askForChangeOutput( defaultAnswer )

      //-----------------------------------

      return askForChangeOutput()
        .then(function() {

          // TODO: review : needed?
          var fileOutput = {
            dirname: output.dirname,
            filename: (output.file.name + output.file.ext)
          };

          // @begin: update outputAnswers
          checkTemplateHelpers();
          outputAnswers.destination = fileOutput.dirname;
          outputAnswers.updateFileName = fileOutput.filename;
          // @end: update outputAnswers

          return fileOutput;
        });

    }, // @end: output.file

    directory: function() {

      //-----------------------------------
      // @begin: define output attributes

      var outputDestination = outputAnswers.destination.dirname;
      var selectedTemplate = outputAnswers.template;

      var output = {

        directory: {
          base: outputDestination,
          sub: '',
          name: ''
        }

      };

      if( selectedTemplate.destination ) {

        if( _.isString( selectedTemplate.destination ) ) {

          output.directory.sub = selectedTemplate.destination;

        } else {

          if( selectedTemplate.destination.dirname ) {
            output.directory.base = selectedTemplate.destination.dirname;
          }

        }

      }

      if( outputAnswers.values && outputAnswers.values.name ) {
        output.directory.name = outputAnswers.values.name;
      }

      //@end: define output attributes
      //-----------------------------------

      function getOutputPath() {
        return path.join( output.directory.base, output.directory.sub, output.directory.name );
      }

      //-----------------------------------

      function updateOutput() {

        var whatToUpdate = {
          type: 'list',
          name: 'selected',
          message: 'Update',
          choices: [
            {
              name: 'Base directory  : ' + output.directory.base,
              value: 'base'
            },
            {
              name: 'Subdirectory    : ' + output.directory.sub,
              value: 'sub'
            }
          ]
        };

        var update = {
          base: function() {
            // TODO: review and define another input validator
            return askFor.not_empty_answer('base directory')
              .then(function( answer ) {
                output.directory.base = answer.input;
              });
          },

          sub: function() {
            // TODO: review and define another input validator
            return askFor.not_empty_answer('subdirectory')
              .then(function( answer ) {
                output.directory.sub = answer.input;
              });
          }
        };

        return ask(whatToUpdate)
          .then(function(answer) {
            return update[answer.selected]();
          })
          .then(function() {
            return askForChangeOutput();
          })
        ;
      } // @end: updateOutput()

      //-----------------------------------

      function askForChangeOutput( defaultAnswer ) {
        if( _.isUndefined( defaultAnswer ) ) defaultAnswer = false;

        var outputPath = getOutputPath();

        var questionMsg = 'Change output';
        questionMsg += '\n    directory';
        questionMsg += '\n      base     : ' + output.directory.base;
        questionMsg += '\n      sub      : ' + output.directory.sub;
        questionMsg += '\n      name     : ' + output.directory.name;
        questionMsg += '\n    path       : ' + outputPath;
        questionMsg += '\n>>> ';

        return askFor.yes_no(questionMsg, defaultAnswer)
          .then(function( answer ) {

            if( answer.value ) {

              return updateOutput();

            } else {

              return checkIfExists( outputPath )
                .then(function (flag) {

                  if( flag ) {
                    return askFor.yes_no('Directory already exists, overwrite?', false)
                      .then(function( answer ) {

                          if( answer.value ) { // overwrite file
                            return renameOld( outputPath );
                          } else { // ask to change output
                            return askForChangeOutput( true ); // set default answer to true
                          }

                      });
                  }

                  return 'finished';

                });

            }

          });

      } // @end: askForChangeOutput( defaultAnswer )

      //-----------------------------------

      return askForChangeOutput()
        .then(function() {

          function buildLocationAttribute() {
            var location = '';

            if( !_.isEmpty( output.directory.sub ) ) {
              location += output.directory.sub + '/';
            }

            location += outputAnswers.values.name;

            return location;
          }

          // @begin: update outputAnswers
          checkTemplateHelpers();
          outputAnswers.values.location = buildLocationAttribute();
          outputAnswers.destination = path.join( output.directory.base, output.directory.sub );
          // @end: update outputAnswers

          // TODO: review : needed?
          return output;
        });

    } // @end: output.directory

  } // @end: output

};

// @end: askFor
//-----------------------------------------------------------------------------

function start(options) {

  var path = require('path');

  //------------------------
  // @begin: check options

  /*
  var options = {
    source: '',
    destination: '',
    restContext: ''
  };
  */

  if( !options ) throw new Error('options not defined');

  outputAnswers.source = options.source || path.resolve(__dirname, 'templates');

  if( !options.destination )  throw new Error('options.destination not defined');
  outputAnswers.destination = { dirname: options.destination };

  outputAnswers.restContext = 'rest';
  if( options.restContext ) {
    var restContext = options.restContext;
    if( restContext.indexOf('/') === 0 ) {
      restContext = restContext.slice(1, restContext.length);
    }
    outputAnswers.restContext = restContext;
  }

  // @end: check options
  //------------------------

  return askFor.template('available')
    .then(function(answer) {

      //-------------------------------------------
      // @begin: define : source
      var template = templates[answer.selected.key];

      outputAnswers.template = template;

      outputAnswers.source = path.join( outputAnswers.source, template.source );
      // @end: define : source
      //-------------------------------------------

      return askFor.values[answer.selected.key]();

    })
    .then(function(answers) {

      outputAnswers.values = answers;

    })
    .then(function() {

      return askFor.output.check();

    })
    .then(function ( answers ) {

      return askFor.yes_no('Debug generate engine', false);

    })
    .then(function( answer ) {

      outputAnswers.debug = answer.value;
      delete outputAnswers.restContext;

      return outputAnswers;

    });

}

module.exports = start;

//-----------------------------------------------------------------------------


text:
namespace Google.Cloud.DataLabeling.V1Beta1.Snippets
{
    // [START datalabeling_v1beta1_generated_DataLabelingService_GetDataset_async_flattened_resourceNames]
    using Google.Cloud.DataLabeling.V1Beta1;
    using System.Threading.Tasks;

    public sealed partial class GeneratedDataLabelingServiceClientSnippets
    {
        /// <summary>Snippet for GetDatasetAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public async Task GetDatasetResourceNamesAsync()
        {
            // Create client
            DataLabelingServiceClient dataLabelingServiceClient = await DataLabelingServiceClient.CreateAsync();
            // Initialize request argument(s)
            DatasetName name = DatasetName.FromProjectDataset("[PROJECT]", "[DATASET]");
            // Make the request
            Dataset response = await dataLabelingServiceClient.GetDatasetAsync(name);
        }
    }
    // [END datalabeling_v1beta1_generated_DataLabelingService_GetDataset_async_flattened_resourceNames]
}