text:
package org.apache.calcite.piglet;

import com.google.common.collect.ImmutableMap;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import javax.annotation.Nonnull;

/**
 * Utility class to find the implementation method object for a given Pig UDF
 * class.
 */
class PigUdfFinder {
  /**
   * For Pig UDF classes where the "exec" method is declared in parent class,
   * the Calcite enumerable engine will generate incorrect Java code that
   * instantiates an object of the parent class, not object of the actual UDF
   * class. If the parent class is an abstract class, the auto-generated code
   * failed to compile (we can not instantiate an object of an abstract class).
   *
   * <p>Workaround is to write a wrapper for such UDFs to instantiate the
   * correct UDF object. See method {@link PigUdfs#bigdecimalsum} as an example
   * and add others if needed.
   */
  private final ImmutableMap<String, Method> udfWrapper;

  PigUdfFinder() {
    final Map<String, Method> map = new HashMap<>();
    for (Method method : PigUdfs.class.getMethods()) {
      if (Modifier.isPublic(method.getModifiers())
          && method.getReturnType() != Method.class) {
        map.put(method.getName(), method);
      }
    }
    udfWrapper = ImmutableMap.copyOf(map);
  }

  /**
   * Finds the implementation method object for a given Pig UDF class.
   *
   * @param clazz The Pig UDF class
   *
   * @throws IllegalArgumentException if not found
   */
  @Nonnull Method findPigUdfImplementationMethod(Class clazz) {
    // Find implementation method in the wrapper map
    Method returnedMethod =
        udfWrapper.get(clazz.getSimpleName().toLowerCase(Locale.US));
    if (returnedMethod != null) {
      return returnedMethod;
    }

    // Find exec method in the declaring class
    returnedMethod = findExecMethod(clazz.getDeclaredMethods());
    if (returnedMethod != null) {
      return returnedMethod;
    }

    // Find exec method in all parent classes.
    returnedMethod = findExecMethod(clazz.getMethods());
    if (returnedMethod != null) {
      return returnedMethod;
    }

    throw new IllegalArgumentException(
        "Could not find 'exec' method for PigUDF class of " + clazz.getName());
  }

  /**
   * Finds "exec" method from a given array of methods.
   */
  private static Method findExecMethod(Method[] methods) {
    if (methods == null) {
      return null;
    }

    Method returnedMethod = null;
    for (Method method : methods) {
      if (method.getName().equals("exec")) {
        // There may be two methods named "exec", one of them just returns a
        // Java object. We will need to look for the other one if existing.
        if (method.getReturnType() != Object.class) {
          return method;
        } else {
          returnedMethod = method;
        }
      }
    }
    return returnedMethod;
  }
}


text:
'''
Test Steps:
    1. upgrade zsha2 in host where vip located.
    2. check vip switch to another MN.

@author: SyZhao
'''

import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_state as test_state
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.operations.node_operations as node_ops
import zstackwoodpecker.zstack_test.zstack_test_vm as test_vm_header
import zstackwoodpecker.operations.resource_operations as res_ops
import time
import os

vm = None
vip_s_vm_cfg_lst = None
test_stub = test_lib.lib_get_test_stub()

def test():
    global vm
    global vip_s_vm_cfg_lst

    os.environ['ZSTACK_BUILT_IN_HTTP_SERVER_IP'] = os.environ['zstackHaVip']

    test_stub.ensure_hosts_connected()
    test_stub.ensure_bss_connected()
    test_stub.ensure_pss_connected()
    vm = test_stub.create_vm()

    vip_s_vm_cfg_lst = test_stub.get_s_vm_cfg_lst_vip_bind(test_lib.all_scenario_config, test_lib.scenario_file)
    if len(vip_s_vm_cfg_lst) != 1:
        test_util.test_fail('vip has been running on %d host(s)' % len(vip_s_vm_cfg_lst))

    test_util.test_logger("disconnect host [%s]" % (vip_s_vm_cfg_lst[0].ip_))
    #test_stub.down_host_network(vip_s_vm_cfg_lst[0].ip_, test_lib.all_scenario_config, "managment_net")
    zsha2_path="/root/zsha2"
    test_stub.exec_upgrade_zsha2(vip_s_vm_cfg_lst[0].ip_, "root", "password", zsha2_path)

    time.sleep(5)

    #expected_vip_s_vm_cfg_lst_ip = test_stub.get_expected_vip_s_vm_cfg_lst_after_switch(test_lib.all_scenario_config, test_lib.scenario_file, vip_s_vm_cfg_lst[0].ip_)
    #if not test_stub.check_if_vip_is_on_host(test_lib.all_scenario_config, test_lib.scenario_file, expected_vip_s_vm_cfg_lst_ip):
    #    test_util.test_fail("find vip should drift on ip %s, but is not on it." %(expected_vip_s_vm_cfg_lst_ip))

    vip_s_vm_cfg_lst_new = test_stub.get_s_vm_cfg_lst_vip_bind(test_lib.all_scenario_config, test_lib.scenario_file)
    if len(vip_s_vm_cfg_lst_new) != 1:
        test_util.test_fail('vip has been running on %d host(s)' % len(vip_s_vm_cfg_lst_new))

    test_stub.wrapper_of_wait_for_management_server_start(600)

    cond = res_ops.gen_query_conditions('uuid', '=', vm.vm.uuid)
    for i in range(0, 60):
        if res_ops.query_resource(res_ops.VM_INSTANCE, cond)[0].state == "Running":
            break
        time.sleep(1)

    vm.destroy()

    test_util.test_pass('Create VM Test Success')

#Will be called what ever test result is
def env_recover():
    test_stub.exec_zsha2_version(vip_s_vm_cfg_lst[0].ip_, "root", "password")
    #test_util.test_logger("recover host: %s" % (vip_s_vm_cfg_lst[0].ip_))
    #test_stub.up_host_network(vip_s_vm_cfg_lst[0].ip_, test_lib.all_scenario_config, "managment_net")
    #test_stub.recover_host(vip_s_vm_cfg_lst[0], test_lib.all_scenario_config, test_lib.deploy_config)
    #test_stub.wait_for_mn_ha_ready(test_lib.all_scenario_config, test_lib.scenario_file)

#Will be called only if exception happens in test().
def error_cleanup():
    global vm
    if vm:
        try:
            vm.destroy()
        except:
            pass

redpajama_set_name: RedPajamaGithub


text:
import tensorflow as tf
import tensorflow.contrib.slim as slim
import numpy as np

class ACNetworkLSTM:
    def __init__(self, settings, scope, step=0):
        with tf.variable_scope(scope):
            self.frame = tf.placeholder(shape=[None, settings.gameRes, settings.gameRes],
                                        dtype=tf.float32, name="frame")
            self.input = tf.reshape(self.frame, shape=[-1, settings.gameRes, settings.gameRes, 1])
            self.conv1 = slim.conv2d(
                activation_fn=tf.nn.elu,
                inputs=self.input,
                num_outputs=16,
                kernel_size=[16, 16],
                stride=[2, 2],
                scope="conv1"
            )
            self.conv2 = slim.conv2d(
                activation_fn=tf.nn.elu,
                inputs=self.conv1,
                num_outputs=32,
                kernel_size=[8, 8],
                stride=[2, 2],
                scope="conv2"
            )
            self.conv3 = slim.conv2d(
                activation_fn=tf.nn.elu,
                inputs=self.conv2,
                num_outputs=64,
                kernel_size=[4, 4],
                stride=[2, 2],
                scope="conv3"
            )

            conv3flat = self.flatten(self.conv3)
            conv2lstm = slim.fully_connected(conv3flat, 1024, activation_fn=tf.nn.elu)
            rnnIn = tf.expand_dims(conv2lstm, [0])

            lstmCell = tf.contrib.rnn.BasicLSTMCell(256, state_is_tuple=True)
            cInit = np.zeros(shape=(1, lstmCell.state_size.c), dtype=np.float32)
            hInit = np.zeros(shape=(1, lstmCell.state_size.h), dtype=np.float32)
            self.stateInit = [cInit, hInit]
            cIn = tf.placeholder(shape=[1, lstmCell.state_size.c], dtype=tf.float32, name="cIn")
            hIn = tf.placeholder(shape=[1, lstmCell.state_size.h], dtype=tf.float32, name="hIn")
            self.stateIn = [cIn, hIn]
            stepSize = tf.shape(self.input)[:1]
            stateIn = tf.contrib.rnn.LSTMStateTuple(cIn, hIn)
            lstmOutputs, lstmState = tf.nn.dynamic_rnn(
                lstmCell,
                rnnIn,
                initial_state=stateIn,
                sequence_length=stepSize,
                time_major=False
            )
            lstmC, lstmH = lstmState
            self.stateOut = [lstmC[:1, :], lstmH[:1, :]]
            rnnOut = tf.reshape(lstmOutputs, [-1, 256])

            hidden = slim.fully_connected(rnnOut, 512, activation_fn=tf.nn.elu, scope="fc1")
            hidden2 = slim.fully_connected(hidden, 512, activation_fn=tf.nn.elu, scope="fc2")
            p0 = slim.fully_connected(hidden2, 256, activation_fn=tf.nn.elu, scope="p0")
            v0 = slim.fully_connected(hidden2, 256, activation_fn=tf.nn.elu, scope="v0")
            self.value = slim.fully_connected(v0, 1,
                                              activation_fn=None,
                                              weights_initializer=self.weightInit(1.0),
                                              scope="vOut")
            self.policy = slim.fully_connected(p0, settings.actionSize,
                                               activation_fn=None,
                                               weights_initializer=self.weightInit(0.01),
                                               scope="p1")

            with tf.variable_scope("pOut"):
                self.logits = tf.nn.softmax(self.policy)
                self.logLogits = tf.nn.log_softmax(self.policy)

            if scope != 'global':
                with tf.variable_scope("training"):
                    self.actions = tf.placeholder(shape=[None], dtype=tf.int32, name="actions")
                    self.actionsOnehot = tf.one_hot(self.actions, settings.actionSize, dtype=tf.float32)
                    self.targetV = tf.placeholder(shape=[None], dtype=tf.float32, name="targetV")
                    self.advantages = tf.placeholder(shape=[None], dtype=tf.float32, name="advantages")

                    # Loss functions
                    self.valueLoss = 0.5 * tf.reduce_sum(tf.square(self.targetV - tf.reshape(self.value, [-1])))
                    self.entropy = tf.reduce_sum(tf.multiply(self.logits, -self.logLogits))
                    self.policyLoss = -tf.reduce_sum(tf.reduce_sum(self.logLogits * self.actionsOnehot, [1]) * self.advantages)
                    self.loss = (settings.valueWeight * self.valueLoss +
                                 self.policyLoss -
                                 self.entropy * settings.entropyWeight)

                    # Get gradients from local network using local losses
                    localVars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope)
                    self.gradients = tf.gradients(self.loss, localVars)
                    self.varNorms = tf.global_norm(localVars)
                    self.grads, self.gradNorms = tf.clip_by_global_norm(self.gradients, 40)

                    self.lr = tf.train.exponential_decay(settings.learningRate,
                                                         step,
                                                         settings.lrDecayStep,
                                                         settings.lrDecayRate)
                    optimizer = tf.train.AdamOptimizer(self.lr);

                    # Apply local gradients to global network
                    globalVars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'global')
                    self.applyGradsGlobal = optimizer.apply_gradients(zip(self.grads, globalVars), global_step=step)

    def weightInit(self, std=1.0):
        def _initializer(shape, dtype=None, partition_info=None):
            out = np.random.randn(*shape).astype(np.float32)
            out *= std / np.sqrt(np.square(out).sum(axis=0, keepdims=True))
            return tf.constant(out)
        return _initializer

    def flatten(self, x):
        return tf.reshape(x, [-1, np.prod(x.get_shape().as_list()[1:])])


text:
<?php
/**
 * TeamAdmin class file
 *
 * PHP Version 7.0
 *
 * @category Admin
 * @package  CoreBundle\Admin
 * @author   Guillaume <guillaume.torres91@gmail.com>
 * @license  All right reserved
 * @link     Null
 */
namespace CoreBundle\Admin;

use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use TeamBundle\Entity\Team;
use UserBundle\Entity\User;

/**
 * Class TeamAdmin
 *
 * @category Admin
 * @package  CoreBundle\Admin
 * @author   Guillaume <guillaume.torres91@gmail.com>
 * @license  All right reserved
 * @link     Null
 */
class TeamAdmin extends AbstractAdmin
{
    protected $baseRoutePattern = 'team';
    protected $translationDomain = 'Admin';

    /**
     * @param Team $object Team object
     *
     * @return string
     */
    public function toString($object)
    {
        return $object instanceof Team
            ? $object->getName()
            : 'Team';
    }

    /**
     * @param FormMapper $formMapper Form mapper
     */
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->add('name', TextType::class)
            ->add('group', 'entity', array(
                    'class' => 'MatchBundle\Entity\GroupMatch',
                    'multiple' => false,
                    'required' => false,
                )
            );
    }

    /**
     * @param DatagridMapper $datagridMapper Datagrid mapper
     */
    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper
            ->add('name')
            ->add('group');
    }

    /**
     * @param ListMapper $listMapper List mapper
     */
    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper->addIdentifier('name');
        $listMapper->add('group');
    }

}


text:
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { compose, createStore } from 'redux';
import { reducer } from './ReduxCore/Redux/reducer';
import { initStoreState, StoreState } from './ReduxCore/Redux/state';
import AppLayout from './AppLayout';
import injectTapEventPlugin = require('react-tap-event-plugin');
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import { Provider, Store } from 'react-redux';
import createHistory from 'history/createBrowserHistory';

injectTapEventPlugin();

// tslint:disable
const composeEnhancers =
    (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
// tslint:enable

export const history = createHistory();

export const store: Store<StoreState> = createStore(
    reducer,
    initStoreState(),
    composeEnhancers()
);

// push first route manually for the history stack
history.push(window.location.pathname);

ReactDOM.render(
    <Provider store={store}>
        <MuiThemeProvider>
            <AppLayout/>
        </MuiThemeProvider>
    </Provider>,
    document.getElementById('root') as HTMLElement
);


text:
faint::ResizeDialogOptions g_resizeDialogOptions;

namespace faint{ class StatusInterface; }

namespace{

using namespace faint;

static utf8_string to_str(ResizeDialogOptions::ResizeType type){
  switch(type){
  case ResizeDialogOptions::RESCALE:
    return "RESCALE";
  case ResizeDialogOptions::RESIZE_TOP_LEFT:
    return "RESIZE_TOP_LEFT";
  case ResizeDialogOptions::RESIZE_CENTER:
    return "RESIZE_CENTER";
  default:
    assert(false);
    return "";
  }
}

class TestResizeDialogContext : public faint::ResizeDialogContext {
public:
  TestResizeDialogContext(const ResizeDialogOptions& options,
    wxTextCtrl* log,
    const utf8_string& title,
    const Paint& bg,
    bool allowNearest,
    bool allowResize)
    : m_allowNearest(allowNearest),
      m_allowResize(allowResize),
      m_bg(bg),
      m_log(log),
      m_options(options),
      m_title(title)
  {}

  bool AllowNearestNeighbour() const override{
    return m_allowNearest;
  }

  bool AllowResize() const override{
    return m_allowResize;
  }

  Paint GetBackground() const override{
    return m_bg;
  }

  ResizeDialogOptions GetOptions() const override{
    return m_options;
  }

  void SetDefaultOptions(const ResizeDialogOptions& o) override{
    m_options = o;
    auto s(no_sep("SetDefaultOptions", bracketed(
      comma_sep(to_str(o.defaultButton),
        lbl("nearest", o.nearest? "true" : "false"),
        lbl("proportional", o.proportional ? "true" : "false")))));

    append_text(m_log, s + "\n");
  }

  utf8_string GetTitle() const override{
    return m_title;
  }

  Either<IntSize, Size> GetSize() const override{
    return Size(640, 480);
  }

  void Resize(const IntRect& r, const Paint& bg) override{
    auto s(no_sep("Resize", bracketed(
      comma_sep(str(r.TopLeft()), str(r.GetSize()), str(bg)))));
    append_text(m_log, s + "\n");
  }

  void Rescale(Size sz, ScaleQuality quality) override{
    auto s(no_sep("Rescale", bracketed(
      comma_sep(str(sz, 2_dec),
        quality == ScaleQuality::BILINEAR ?
        "Bilinear" :
        "Nearest"))));
    append_text(m_log, s + "\n");
  }

  bool SupportedSize(const Size&) override{
    return true;
  }

  bool m_allowNearest;
  bool m_allowResize;
  Paint m_bg;
  wxTextCtrl* m_log;
  ResizeDialogOptions m_options;
  utf8_string m_title;
};

static auto make_ctx(wxTextCtrl* log,
  const utf8_string& title,
  const Paint& bg,
  bool allowNearest,
  bool scaleOnly){
  return std::make_unique<TestResizeDialogContext>(
    ResizeDialogOptions(),
    log,
    title,
    bg,
    allowNearest,
    scaleOnly);
}

} // namespace

void gui_test_resize_dialog(wxWindow* p,
  faint::StatusInterface&,
  faint::DialogContext& dialogContext,
  const faint::Art& art)
{
  using namespace faint;

  auto log = faint::create_multiline_text_control(p, IntSize(400, 400));

  using namespace layout;
  auto dialog_button =
    [=, &dialogContext, &art](const utf8_string& title,
      const Paint& bg,
      bool allowNearest,
      bool allowResize)
    {
      auto b = create_button(p, title.c_str(),
        [=, &dialogContext, &art](){
          if (!is_empty(log)){
            append_text(log, "\n");
          }
          append_text(log, "Show: " + title + "\n");
          show_resize_dialog(dialogContext,
            art,
            make_ctx(log, title, bg, allowNearest, allowResize));
        });
      return b;
    };

  set_sizer(p, create_column({
    dialog_button("Full image", Paint(Color(120, 120, 0, 120)), true, true),
    dialog_button("Object", Paint(Color(120, 120, 0, 120)), false, false),
    dialog_button("Raster selection", Paint(Color(120, 120, 0, 120)), true, false),
    raw(log)}));
}


text:
'use strict';

(function() {
  var module = angular.module('fireStation.gauge', []);

  module.filter('ordinal', function() {
      return function(i) {
            var j = i % 10,
                k = i % 100;
            if (j == 1 && k != 11) {
                return i + "st";
            }
            if (j == 2 && k != 12) {
                return i + "nd";
            }
            if (j == 3 && k != 13) {
                return i + "rd";
            }
            return i + "th";
        }
  });

  module.directive('gauge',
      function() {
        return {
          restrict: 'E',
          replace: true,
          templateUrl: '/static/firestation/js/directives/partial/gauge.tpl.html',
          scope: {
             metricTitle: '@?',
             description: '@?',
             value: '@?',
             min: '@?',
             max: '@?',
             learnMore: '@?'
          },
          // The linking function will add behavior to the template
          link: function(scope, element, attrs) {
            var element = element;
            var needle = $(element[0].querySelector('.needle'));
            scope.inverse = attrs.hasOwnProperty('inverse');

            // the pickHex function (from less.js) takes rgb values
            var green = [116, 172, 73];
            var yellow = [254, 190, 0];
            var red = [246, 84, 47];

           function pickHex(color1, color2, weight) {
                var p = weight;
                var w = p * 2 - 1;
                var w1 = (w/1+1) / 2;
                var w2 = 1 - w1;
                var rgb = [Math.round(color1[0] * w1 + color2[0] * w2),
                    Math.round(color1[1] * w1 + color2[1] * w2),
                    Math.round(color1[2] * w1 + color2[2] * w2)];
                return rgb;
            }

            scope.$watch('value', function() {
               var color;
               var location = scope.value / (scope.max - scope.min);
               var needleRotation = (180 * location) - 90;

               // the setTimeout helps with the transition effect.
               setTimeout(function() {
                   needle.css({transform: 'rotate(' + needleRotation + 'deg)'});
               }, 1);

               if (location < .5) {
                color = pickHex(yellow, green, location / .5);
               } else {
                color = pickHex(red, yellow, (location - .5) /.5);
               }

               var colorString = 'rgb('+color[0] + ',' + color[1] + ',' + color[2] +')';
               $('.gauge-result-color').css({'background': colorString});
               needle.css({'border-bottom': '60px solid ' + colorString});
            });

          }
        };
      });

  module.directive('barGauge',
      function() {
        return {
          restrict: 'E',
          replace: true,
          templateUrl: '/static/firestation/js/directives/partial/bar-gauge.tpl.html',
          scope: {
             value: '@?',
             min: '@?',
             max: '@?'
          },
          // The linking function will add behavior to the template
          link: function(scope, element, attrs) {
            var element = element;
            var gauge = $(element[0].querySelector('.bar-gauge'));
            var needle = $(element[0].querySelector('.bar-gauge-needle'));
            scope.inverse = attrs.hasOwnProperty('inverse');

            scope.$watch('value', function() {
               if (scope.min == null || scope.min === '' || scope.max == null || scope.max === ''
                   || scope.value == null || scope.value === '') {
                 needle.css({display: 'none'});
                 return
               } else {
                 var location = scope.value / scope.max;
                 needle.css({left: location * (gauge.width() - 5) + 'px'});
               }
            });

          }
        };
      });

    module.directive('numberGauge',
      function() {
        return {
          restrict: 'E',
          replace: true,
          templateUrl: '/static/firestation/js/directives/partial/number-gauge.tpl.html',
          scope: {
             value: '@',
             metricTitle: '@?',
             description: '@?'
          },
          // The linking function will add behavior to the template
          link: function(scope, element, attrs) {
            scope.inverse = attrs.hasOwnProperty('inverse');
            scope.color = '#f6542f';

            if (scope.value === '1') {
                scope.color = "#74AC49";
            } else if (scope.value === '2') {
                scope.color = "#CBB71B";
            } else if (scope.value === '3') {
                scope.color = "#FA9014";
            }

          }
        };
      });

    module.filter('numberGaugePosition', function() {
      return function(i) {
            if (i === 1) {
                return 'lowest';
            } else if (i === 2) {
                return 'second lowest';
            } else if (i === 3) {
                return 'second highest';
            } else if (i === 4) {
                return 'highest';
            }
        }
  });
}());


text:
package org.jboss.pnc.datastore;

import org.jboss.pnc.model.Artifact;
import org.jboss.pnc.model.BuildConfigSetRecord;
import org.jboss.pnc.model.BuildConfiguration;
import org.jboss.pnc.model.BuildConfigurationAudited;
import org.jboss.pnc.model.BuildRecord;
import org.jboss.pnc.model.User;
import org.jboss.pnc.spi.BuildCoordinationStatus;
import org.jboss.pnc.spi.coordinator.BuildSetTask;
import org.jboss.pnc.spi.coordinator.BuildTask;
import org.jboss.pnc.spi.datastore.Datastore;
import org.jboss.pnc.spi.datastore.predicates.UserPredicates;
import org.jboss.pnc.spi.datastore.repositories.ArtifactRepository;
import org.jboss.pnc.spi.datastore.repositories.BuildConfigSetRecordRepository;
import org.jboss.pnc.spi.datastore.repositories.BuildConfigurationAuditedRepository;
import org.jboss.pnc.spi.datastore.repositories.BuildConfigurationRepository;
import org.jboss.pnc.spi.datastore.repositories.BuildRecordRepository;
import org.jboss.pnc.spi.datastore.repositories.SequenceHandlerRepository;
import org.jboss.pnc.spi.datastore.repositories.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Inject;
import java.lang.invoke.MethodHandles;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import static org.jboss.pnc.common.util.CollectionUtils.ofNullableCollection;
import static org.jboss.pnc.common.util.StreamCollectors.toFlatList;
import static org.jboss.pnc.spi.datastore.predicates.ArtifactPredicates.withIdentifierAndSha256;
import static org.jboss.pnc.spi.datastore.predicates.ArtifactPredicates.withOriginUrl;

@Stateless
public class DefaultDatastore implements Datastore {

    public static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

    private ArtifactRepository artifactRepository;

    private BuildRecordRepository buildRecordRepository;

    private BuildConfigurationRepository buildConfigurationRepository;

    private BuildConfigurationAuditedRepository buildConfigurationAuditedRepository;

    private BuildConfigSetRecordRepository buildConfigSetRecordRepository;

    private UserRepository userRepository;

    private SequenceHandlerRepository sequenceHandlerRepository;

    public DefaultDatastore() {
    }

    @Inject
    public DefaultDatastore(ArtifactRepository artifactRepository,
                            BuildRecordRepository buildRecordRepository,
                            BuildConfigurationRepository buildConfigurationRepository,
                            BuildConfigurationAuditedRepository buildConfigurationAuditedRepository,
                            BuildConfigSetRecordRepository buildConfigSetRecordRepository,
                            UserRepository userRepository,
                            SequenceHandlerRepository sequenceHandlerRepository) {
        this.artifactRepository = artifactRepository;
        this.buildRecordRepository = buildRecordRepository;
        this.buildConfigurationRepository = buildConfigurationRepository;
        this.buildConfigurationAuditedRepository = buildConfigurationAuditedRepository;
        this.buildConfigSetRecordRepository = buildConfigSetRecordRepository;
        this.userRepository = userRepository;
        this.sequenceHandlerRepository = sequenceHandlerRepository;
    }

    private static final String ARITFACT_ORIGIN_URL_IDENTIFIER_CONFLICT_MESSAGE = "Another artifact with the same originUrl but a different identifier already exists";
    private static final String ARITFACT_ORIGIN_URL_CHECKSUM_CONFLICT_MESSAGE = "Another artifact with the same originUrl but a different checksum already exists";

    @Override
    public Map<Artifact, String> checkForConflictingArtifacts(Collection<Artifact> artifacts) {
        Map<Artifact, String> conflicts = new HashMap<>();
        for (Artifact artifact : artifacts) {
            // Check for matching URL with different identifier or checksum
            if (artifact.getOriginUrl() != null) {
                Artifact artifactFromDb = artifactRepository.queryByPredicates(withOriginUrl(artifact.getOriginUrl()));
                if (artifactFromDb.getIdentifier().equals(artifact.getIdentifier())) {
                    conflicts.put(artifact, ARITFACT_ORIGIN_URL_IDENTIFIER_CONFLICT_MESSAGE);
                }
                if (artifactFromDb.getSha256().equals(artifact.getSha256())) {
                    conflicts.put(artifact, ARITFACT_ORIGIN_URL_CHECKSUM_CONFLICT_MESSAGE);
                }
            }
        }
        return conflicts;
    }

    @Override
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public BuildRecord storeCompletedBuild(BuildRecord.Builder buildRecordBuilder) {
        BuildRecord buildRecord = buildRecordBuilder.build();
        refreshBuildConfiguration(buildRecord);
        buildRecord.setDependencies(saveArtifacts(buildRecord.getDependencies()));
        buildRecord.setBuiltArtifacts(saveArtifacts(buildRecord.getBuiltArtifacts()));
        buildRecord = buildRecordRepository.save(buildRecord);

        return buildRecord;
    }

    /**
     * Checks the given list against the existing database and creates a new list containing
     * artifacts which have been saved to or loaded from the database.
     *
     * @param artifacts of in-memory artifacts to either insert to the database or find the matching record in the db
     * @return Set of up to date JPA artifact entities
     */
    private Set<Artifact> saveArtifacts(Collection<Artifact> artifacts) {
        Set<Artifact> savedArtifacts = new HashSet<>();
        for (Artifact artifact : artifacts) {

            Artifact artifactFromDb = artifactRepository
                    .queryByPredicates(withIdentifierAndSha256(artifact.getIdentifier(), artifact.getSha256()));
            if (artifactFromDb == null) {
                artifactFromDb = artifactRepository.save(artifact);
            }
            savedArtifacts.add(artifactFromDb);
        }
        return savedArtifacts;
    }

    @Override
    public User retrieveUserByUsername(String username) {
        return userRepository.queryByPredicates(UserPredicates.withUserName(username));
    }

    private void refreshBuildConfiguration(BuildRecord buildRecord) {
        if (buildRecord.getLatestBuildConfiguration() != null) {
            BuildConfiguration configurationFromDB = buildConfigurationRepository.queryById(buildRecord
                    .getLatestBuildConfiguration().getId());
            buildRecord.setLatestBuildConfiguration(configurationFromDB);
        }
    }

    @Override
    public void createNewUser(User user) {
        userRepository.save(user);
    }

    @Override
    public int getNextBuildRecordId() {

        Long nextId = sequenceHandlerRepository.getNextID(BuildRecord.SEQUENCE_NAME);
        logger.debug("Build Record nextId: {}", nextId);

        return nextId.intValue();
    }

    /**
     * Save a build config set record to the db.  This requires a new transaction to ensure that
     * the record is immediately committed to the database so that it's available to use by the
     * foreign keys set in the individual build records.
     */
    @Override
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public BuildConfigSetRecord saveBuildConfigSetRecord(BuildConfigSetRecord buildConfigSetRecord) {
        return buildConfigSetRecordRepository.save(buildConfigSetRecord);
    }

    /**
     * Get the latest audited revision for the given build configuration ID
     *
     * @param buildConfigurationId
     * @return The latest revision of the given build configuration
     */
    @Override
    public BuildConfigurationAudited getLatestBuildConfigurationAudited(Integer buildConfigurationId) {
        List<BuildConfigurationAudited> buildConfigRevs = buildConfigurationAuditedRepository.findAllByIdOrderByRevDesc(buildConfigurationId);
        if (buildConfigRevs.isEmpty()) {
            // TODO should we throw an exception?  In theory, this should never happen.
            return null;
        }
        return buildConfigRevs.get(0);
    }

    @Override
    public BuildConfigSetRecord getBuildConfigSetRecordById(Integer buildConfigSetRecordId) {
        return buildConfigSetRecordRepository.queryById(buildConfigSetRecordId);
    }

    @Override
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public boolean requiresRebuild(BuildTask task) {
        BuildSetTask taskSet = task.getBuildSetTask();
        final BuildConfiguration buildConfiguration = task.getBuildConfiguration();
        BuildConfiguration refreshedConfig = buildConfigurationRepository.queryById(buildConfiguration.getId());

        if (refreshedConfig.getLatestSuccesfulBuildRecord() == null) {
            return true;
        }
        if (taskSet != null) {
            List<BuildConfiguration> nonRejectedBuildsInGroup = taskSet.getBuildTasks().stream()
                    .filter(t -> t.getStatus() != BuildCoordinationStatus.REJECTED_ALREADY_BUILT)
                    .map(BuildTask::getBuildConfiguration)
                    .collect(Collectors.toList());
            boolean hasInGroupDependency = refreshedConfig.dependsOnAny(nonRejectedBuildsInGroup);
            if (hasInGroupDependency) {
                return true;
            }
        }
        return hasARebuiltDependency(refreshedConfig);
    }

    private boolean hasARebuiltDependency(BuildConfiguration config) {
        BuildRecord record = config.getLatestSuccesfulBuildRecord();
        if (record == null) {
            return false;
        }

        Collection<BuildRecord> lastBuiltFrom = getRecordsUsedFor(record);

        return lastBuiltFrom.stream()
                .anyMatch(this::hasNewerVersion);
    }

    private boolean hasNewerVersion(BuildRecord record) {
        BuildConfiguration buildConfig = record.getLatestBuildConfiguration();
        BuildRecord newestRecord = buildConfig.getLatestSuccesfulBuildRecord();
        return !record.getId().equals(newestRecord.getId());
    }

    private Collection<BuildRecord> getRecordsUsedFor(BuildRecord record) {
        return ofNullableCollection(record.getDependencies())
                .stream()
                .map(Artifact::getBuildRecords)
                .collect(toFlatList());
    }

}


text:
var randInt = require('../random/randInt');

    /**
     * Remove random item(s) from the Array and return it.
     * Returns an Array of items if [nItems] is provided or a single item if
     * it isn't specified.
     */
    function pick(arr, nItems){
        if (nItems != null) {
            var result = [];
            if (nItems > 0 && arr && arr.length) {
                nItems = nItems > arr.length? arr.length : nItems;
                while (nItems--) {
                    result.push( pickOne(arr) );
                }
            }
            return result;
        }
        return (arr && arr.length)? pickOne(arr) : void(0);
    }

    function pickOne(arr){
        var idx = randInt(0, arr.length - 1);
        return arr.splice(idx, 1)[0];
    }

    module.exports = pick;


text:
using System;
using System.ComponentModel;

namespace Azure.Analytics.Synapse.Artifacts.Models
{
    /// <summary> Specify the credential type (key or cert) is used for service principal. </summary>
    public readonly partial struct ODataAadServicePrincipalCredentialType : IEquatable<ODataAadServicePrincipalCredentialType>
    {
        private readonly string _value;

        /// <summary> Initializes a new instance of <see cref="ODataAadServicePrincipalCredentialType"/>. </summary>
        /// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception>
        public ODataAadServicePrincipalCredentialType(string value)
        {
            _value = value ?? throw new ArgumentNullException(nameof(value));
        }

        private const string ServicePrincipalKeyValue = "ServicePrincipalKey";
        private const string ServicePrincipalCertValue = "ServicePrincipalCert";

        /// <summary> ServicePrincipalKey. </summary>
        public static ODataAadServicePrincipalCredentialType ServicePrincipalKey { get; } = new ODataAadServicePrincipalCredentialType(ServicePrincipalKeyValue);
        /// <summary> ServicePrincipalCert. </summary>
        public static ODataAadServicePrincipalCredentialType ServicePrincipalCert { get; } = new ODataAadServicePrincipalCredentialType(ServicePrincipalCertValue);
        /// <summary> Determines if two <see cref="ODataAadServicePrincipalCredentialType"/> values are the same. </summary>
        public static bool operator ==(ODataAadServicePrincipalCredentialType left, ODataAadServicePrincipalCredentialType right) => left.Equals(right);
        /// <summary> Determines if two <see cref="ODataAadServicePrincipalCredentialType"/> values are not the same. </summary>
        public static bool operator !=(ODataAadServicePrincipalCredentialType left, ODataAadServicePrincipalCredentialType right) => !left.Equals(right);
        /// <summary> Converts a string to a <see cref="ODataAadServicePrincipalCredentialType"/>. </summary>
        public static implicit operator ODataAadServicePrincipalCredentialType(string value) => new ODataAadServicePrincipalCredentialType(value);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override bool Equals(object obj) => obj is ODataAadServicePrincipalCredentialType other && Equals(other);
        /// <inheritdoc />
        public bool Equals(ODataAadServicePrincipalCredentialType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override int GetHashCode() => _value?.GetHashCode() ?? 0;
        /// <inheritdoc />
        public override string ToString() => _value;
    }
}


text:
    defined(__ARM_ARCH_7R__) || \
    defined(__ARM_ARCH_7__)
# define CAN_USE_ARMV7_INSTRUCTIONS 1
# ifndef CAN_USE_VFP3_INSTRUCTIONS
#  define CAN_USE_VFP3_INSTRUCTIONS
# endif
#endif

// Target architecture detection. This may be set externally. If not, detect
// in the same way as the host architecture, that is, target the native
// environment as presented by the compiler.
#if !V8_TARGET_ARCH_X64 && !V8_TARGET_ARCH_IA32 && !V8_TARGET_ARCH_X87 && \
    !V8_TARGET_ARCH_ARM && !V8_TARGET_ARCH_ARM64 && !V8_TARGET_ARCH_MIPS
#if defined(_M_X64) || defined(__x86_64__)
#define V8_TARGET_ARCH_X64 1
#elif defined(_M_IX86) || defined(__i386__)
#define V8_TARGET_ARCH_IA32 1
#elif defined(__AARCH64EL__)
#define V8_TARGET_ARCH_ARM64 1
#elif defined(__ARMEL__)
#define V8_TARGET_ARCH_ARM 1
#elif defined(__MIPSEB__) || defined(__MIPSEL__)
#define V8_TARGET_ARCH_MIPS 1
#else
#error Target architecture was not detected as supported by v8
#endif
#endif

// Determine architecture pointer size.
#if V8_TARGET_ARCH_IA32
#define V8_TARGET_ARCH_32_BIT 1
#elif V8_TARGET_ARCH_X64
#if !V8_TARGET_ARCH_32_BIT && !V8_TARGET_ARCH_64_BIT
#if defined(__x86_64__) && !defined(__LP64__)
#define V8_TARGET_ARCH_32_BIT 1
#else
#define V8_TARGET_ARCH_64_BIT 1
#endif
#endif
#elif V8_TARGET_ARCH_ARM
#define V8_TARGET_ARCH_32_BIT 1
#elif V8_TARGET_ARCH_ARM64
#define V8_TARGET_ARCH_64_BIT 1
#elif V8_TARGET_ARCH_MIPS
#define V8_TARGET_ARCH_32_BIT 1
#elif V8_TARGET_ARCH_X87
#define V8_TARGET_ARCH_32_BIT 1
#else
#error Unknown target architecture pointer size
#endif

// Check for supported combinations of host and target architectures.
#if V8_TARGET_ARCH_IA32 && !V8_HOST_ARCH_IA32
#error Target architecture ia32 is only supported on ia32 host
#endif
#if (V8_TARGET_ARCH_X64 && V8_TARGET_ARCH_64_BIT && \
     !(V8_HOST_ARCH_X64 && V8_HOST_ARCH_64_BIT))
#error Target architecture x64 is only supported on x64 host
#endif
#if (V8_TARGET_ARCH_X64 && V8_TARGET_ARCH_32_BIT && \
     !(V8_HOST_ARCH_X64 && V8_HOST_ARCH_32_BIT))
#error Target architecture x32 is only supported on x64 host with x32 support
#endif
#if (V8_TARGET_ARCH_ARM && !(V8_HOST_ARCH_IA32 || V8_HOST_ARCH_ARM))
#error Target architecture arm is only supported on arm and ia32 host
#endif
#if (V8_TARGET_ARCH_ARM64 && !(V8_HOST_ARCH_X64 || V8_HOST_ARCH_ARM64))
#error Target architecture arm64 is only supported on arm64 and x64 host
#endif
#if (V8_TARGET_ARCH_MIPS && !(V8_HOST_ARCH_IA32 || V8_HOST_ARCH_MIPS))
#error Target architecture mips is only supported on mips and ia32 host
#endif

// Determine architecture endianness.
#if V8_TARGET_ARCH_IA32
#define V8_TARGET_LITTLE_ENDIAN 1
#elif V8_TARGET_ARCH_X64
#define V8_TARGET_LITTLE_ENDIAN 1
#elif V8_TARGET_ARCH_ARM
#define V8_TARGET_LITTLE_ENDIAN 1
#elif V8_TARGET_ARCH_ARM64
#define V8_TARGET_LITTLE_ENDIAN 1
#elif V8_TARGET_ARCH_MIPS
#if defined(__MIPSEB__)
#define V8_TARGET_BIG_ENDIAN 1
#else
#define V8_TARGET_LITTLE_ENDIAN 1
#endif
#elif V8_TARGET_ARCH_X87
#define V8_TARGET_LITTLE_ENDIAN 1
#else
#error Unknown target architecture endianness
#endif

#if V8_OS_MACOSX || defined(__FreeBSD__) || defined(__OpenBSD__)
#define USING_BSD_ABI
#endif

#endif  // V8_BASE_BUILD_CONFIG_H_


text:
package com.gooddata.executeafm.resultspec;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo.As;
import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;
import com.fasterxml.jackson.annotation.JsonTypeName;

/**
 * Holds metric position
 */
@JsonTypeInfo(include = As.WRAPPER_OBJECT, use = Id.NAME)
@JsonTypeName("measureLocatorItem")
public class MeasureLocatorItem implements LocatorItem {
    private final String measureIdentifier;

    @JsonCreator
    public MeasureLocatorItem(
            @JsonProperty("measureIdentifier") final String measureIdentifier) {
        this.measureIdentifier = measureIdentifier;
    }

    public String getMeasureIdentifier() {
        return measureIdentifier;
    }

    @Override
    public String toString() {
        return measureIdentifier;
    }
}


text:
import * as React from 'react';
import { ButtonToolbar, Button, IconButton, Drawer, Icon, RadioGroup, Radio } from 'rsuite';
import DefaultPage from '@/components/Page';

export default function Page() {
  return (
    <DefaultPage
      examples={['basic', 'backdrop', 'placement', 'size', 'full']}
      dependencies={{ ButtonToolbar, Button, IconButton, Drawer, Icon, RadioGroup, Radio }}
    />
  );
}


text:
@interface addThenModify : NSObject

@end


text:
exports.__esModule = true;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = require("react");

var _react2 = _interopRequireDefault(_react);

var _reactSideEffect = require("react-side-effect");

var _reactSideEffect2 = _interopRequireDefault(_reactSideEffect);

var _deepEqual = require("deep-equal");

var _deepEqual2 = _interopRequireDefault(_deepEqual);

var _objectAssign = require("object-assign");

var _objectAssign2 = _interopRequireDefault(_objectAssign);

var _HelmetConstants = require("./HelmetConstants.js");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var HELMET_ATTRIBUTE = "data-react-helmet";

var encodeSpecialCharacters = function encodeSpecialCharacters(str) {
    return String(str).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
};

var getInnermostProperty = function getInnermostProperty(propsList, property) {
    for (var i = propsList.length - 1; i >= 0; i--) {
        var props = propsList[i];

        if (props[property]) {
            return props[property];
        }
    }
    return null;
};

var getTitleFromPropsList = function getTitleFromPropsList(propsList) {
    var innermostTitle = getInnermostProperty(propsList, "title");
    var innermostTemplate = getInnermostProperty(propsList, "titleTemplate");

    if (innermostTemplate && innermostTitle) {
        // use function arg to avoid need to escape $ characters
        return innermostTemplate.replace(/%s/g, function () {
            return innermostTitle;
        });
    }

    var innermostDefaultTitle = getInnermostProperty(propsList, "defaultTitle");

    return innermostTitle || innermostDefaultTitle || "";
};

var getOnChangeClientState = function getOnChangeClientState(propsList) {
    return getInnermostProperty(propsList, "onChangeClientState") || function () {};
};

var getAttributesFromPropsList = function getAttributesFromPropsList(tagType, propsList) {
    return propsList.filter(function (props) {
        return typeof props[tagType] !== "undefined";
    }).map(function (props) {
        return props[tagType];
    }).reduce(function (tagAttrs, current) {
        return _extends({}, tagAttrs, current);
    }, {});
};

var getBaseTagFromPropsList = function getBaseTagFromPropsList(primaryAttributes, propsList) {
    return propsList.filter(function (props) {
        return typeof props[_HelmetConstants.TAG_NAMES.BASE] !== "undefined";
    }).map(function (props) {
        return props[_HelmetConstants.TAG_NAMES.BASE];
    }).reverse().reduce(function (innermostBaseTag, tag) {
        if (!innermostBaseTag.length) {
            var keys = Object.keys(tag);

            for (var i = 0; i < keys.length; i++) {
                var attributeKey = keys[i];
                var lowerCaseAttributeKey = attributeKey.toLowerCase();

                if (primaryAttributes.indexOf(lowerCaseAttributeKey) !== -1 && tag[lowerCaseAttributeKey]) {
                    return innermostBaseTag.concat(tag);
                }
            }
        }

        return innermostBaseTag;
    }, []);
};

var getTagsFromPropsList = function getTagsFromPropsList(tagName, primaryAttributes, propsList) {
    // Calculate list of tags, giving priority innermost component (end of the propslist)
    var approvedSeenTags = {};

    return propsList.filter(function (props) {
        return typeof props[tagName] !== "undefined";
    }).map(function (props) {
        return props[tagName];
    }).reverse().reduce(function (approvedTags, instanceTags) {
        var instanceSeenTags = {};

        instanceTags.filter(function (tag) {
            var primaryAttributeKey = void 0;
            var keys = Object.keys(tag);
            for (var i = 0; i < keys.length; i++) {
                var attributeKey = keys[i];
                var lowerCaseAttributeKey = attributeKey.toLowerCase();

                // Special rule with link tags, since rel and href are both primary tags, rel takes priority
                if (primaryAttributes.indexOf(lowerCaseAttributeKey) !== -1 && !(primaryAttributeKey === _HelmetConstants.TAG_PROPERTIES.REL && tag[primaryAttributeKey].toLowerCase() === "canonical") && !(lowerCaseAttributeKey === _HelmetConstants.TAG_PROPERTIES.REL && tag[lowerCaseAttributeKey].toLowerCase() === "stylesheet")) {
                    primaryAttributeKey = lowerCaseAttributeKey;
                }
                // Special case for innerHTML which doesn't work lowercased
                if (primaryAttributes.indexOf(attributeKey) !== -1 && (attributeKey === _HelmetConstants.TAG_PROPERTIES.INNER_HTML || attributeKey === _HelmetConstants.TAG_PROPERTIES.CSS_TEXT || attributeKey === _HelmetConstants.TAG_PROPERTIES.ITEM_PROP)) {
                    primaryAttributeKey = attributeKey;
                }
            }

            if (!primaryAttributeKey || !tag[primaryAttributeKey]) {
                return false;
            }

            var value = tag[primaryAttributeKey].toLowerCase();

            if (!approvedSeenTags[primaryAttributeKey]) {
                approvedSeenTags[primaryAttributeKey] = {};
            }

            if (!instanceSeenTags[primaryAttributeKey]) {
                instanceSeenTags[primaryAttributeKey] = {};
            }

            if (!approvedSeenTags[primaryAttributeKey][value]) {
                instanceSeenTags[primaryAttributeKey][value] = true;
                return true;
            }

            return false;
        }).reverse().forEach(function (tag) {
            return approvedTags.push(tag);
        });

        // Update seen tags with tags from this instance
        var keys = Object.keys(instanceSeenTags);
        for (var i = 0; i < keys.length; i++) {
            var attributeKey = keys[i];
            var tagUnion = (0, _objectAssign2.default)({}, approvedSeenTags[attributeKey], instanceSeenTags[attributeKey]);

            approvedSeenTags[attributeKey] = tagUnion;
        }

        return approvedTags;
    }, []).reverse();
};

var updateTitle = function updateTitle(title, attributes) {
    document.title = title || document.title;
    updateAttributes(_HelmetConstants.TAG_NAMES.TITLE, attributes);
};

var updateAttributes = function updateAttributes(tagName, attributes) {
    var htmlTag = document.getElementsByTagName(tagName)[0];
    var helmetAttributeString = htmlTag.getAttribute(HELMET_ATTRIBUTE);
    var helmetAttributes = helmetAttributeString ? helmetAttributeString.split(",") : [];
    var attributesToRemove = [].concat(helmetAttributes);
    var attributeKeys = Object.keys(attributes);

    for (var i = 0; i < attributeKeys.length; i++) {
        var attribute = attributeKeys[i];
        var value = attributes[attribute] || "";
        htmlTag.setAttribute(attribute, value);

        if (helmetAttributes.indexOf(attribute) === -1) {
            helmetAttributes.push(attribute);
        }

        var indexToSave = attributesToRemove.indexOf(attribute);
        if (indexToSave !== -1) {
            attributesToRemove.splice(indexToSave, 1);
        }
    }

    for (var _i = attributesToRemove.length - 1; _i >= 0; _i--) {
        htmlTag.removeAttribute(attributesToRemove[_i]);
    }

    if (helmetAttributes.length === attributesToRemove.length) {
        htmlTag.removeAttribute(HELMET_ATTRIBUTE);
    } else {
        htmlTag.setAttribute(HELMET_ATTRIBUTE, helmetAttributes.join(","));
    }
};

var updateTags = function updateTags(type, tags) {
    var headElement = document.head || document.querySelector("head");
    var tagNodes = headElement.querySelectorAll(type + "[" + HELMET_ATTRIBUTE + "]");
    var oldTags = Array.prototype.slice.call(tagNodes);
    var newTags = [];
    var indexToDelete = void 0;

    if (tags && tags.length) {
        tags.forEach(function (tag) {
            var newElement = document.createElement(type);

            for (var attribute in tag) {
                if (tag.hasOwnProperty(attribute)) {
                    if (attribute === "innerHTML") {
                        newElement.innerHTML = tag.innerHTML;
                    } else if (attribute === "cssText") {
                        if (newElement.styleSheet) {
                            newElement.styleSheet.cssText = tag.cssText;
                        } else {
                            newElement.appendChild(document.createTextNode(tag.cssText));
                        }
                    } else {
                        var value = typeof tag[attribute] === "undefined" ? "" : tag[attribute];
                        newElement.setAttribute(attribute, value);
                    }
                }
            }

            newElement.setAttribute(HELMET_ATTRIBUTE, "true");

            // Remove a duplicate tag from domTagstoRemove, so it isn't cleared.
            if (oldTags.some(function (existingTag, index) {
                indexToDelete = index;
                return newElement.isEqualNode(existingTag);
            })) {
                oldTags.splice(indexToDelete, 1);
            } else {
                newTags.push(newElement);
            }
        });
    }

    oldTags.forEach(function (tag) {
        return tag.parentNode.removeChild(tag);
    });
    newTags.forEach(function (tag) {
        return headElement.appendChild(tag);
    });

    return {
        oldTags: oldTags,
        newTags: newTags
    };
};

var generateHtmlAttributesAsString = function generateHtmlAttributesAsString(attributes) {
    return Object.keys(attributes).reduce(function (str, key) {
        var attr = typeof attributes[key] !== "undefined" ? key + "=\"" + attributes[key] + "\"" : "" + key;
        return str ? str + " " + attr : attr;
    }, "");
};

var generateTitleAsString = function generateTitleAsString(type, title, attributes) {
    var attributeString = generateHtmlAttributesAsString(attributes);
    return attributeString ? "<" + type + " " + HELMET_ATTRIBUTE + "=\"true\" " + attributeString + ">" + encodeSpecialCharacters(title) + "</" + type + ">" : "<" + type + " " + HELMET_ATTRIBUTE + "=\"true\">" + encodeSpecialCharacters(title) + "</" + type + ">";
};

var generateTagsAsString = function generateTagsAsString(type, tags) {
    return tags.reduce(function (str, tag) {
        var attributeHtml = Object.keys(tag).filter(function (attribute) {
            return !(attribute === "innerHTML" || attribute === "cssText");
        }).reduce(function (string, attribute) {
            var attr = typeof tag[attribute] === "undefined" ? attribute : attribute + "=\"" + encodeSpecialCharacters(tag[attribute]) + "\"";
            return string ? string + " " + attr : attr;
        }, "");

        var tagContent = tag.innerHTML || tag.cssText || "";

        var isSelfClosing = [_HelmetConstants.TAG_NAMES.NOSCRIPT, _HelmetConstants.TAG_NAMES.SCRIPT, _HelmetConstants.TAG_NAMES.STYLE].indexOf(type) === -1;

        return str + "<" + type + " " + HELMET_ATTRIBUTE + "=\"true\" " + attributeHtml + (isSelfClosing ? "/>" : ">" + tagContent + "</" + type + ">");
    }, "");
};

var generateTitleAsReactComponent = function generateTitleAsReactComponent(type, title, attributes) {
    // assigning into an array to define toString function on it
    var initProps = _defineProperty({
        key: title
    }, HELMET_ATTRIBUTE, true);
    var props = Object.keys(attributes).reduce(function (obj, key) {
        obj[_HelmetConstants.REACT_TAG_MAP[key] || key] = attributes[key];
        return obj;
    }, initProps);

    return [_react2.default.createElement(_HelmetConstants.TAG_NAMES.TITLE, props, title)];
};

var generateTagsAsReactComponent = function generateTagsAsReactComponent(type, tags) {
    return tags.map(function (tag, i) {
        var mappedTag = _defineProperty({
            key: i
        }, HELMET_ATTRIBUTE, true);

        Object.keys(tag).forEach(function (attribute) {
            var mappedAttribute = _HelmetConstants.REACT_TAG_MAP[attribute] || attribute;

            if (mappedAttribute === "innerHTML" || mappedAttribute === "cssText") {
                var content = tag.innerHTML || tag.cssText;
                mappedTag.dangerouslySetInnerHTML = { __html: content };
            } else {
                mappedTag[mappedAttribute] = tag[attribute];
            }
        });

        return _react2.default.createElement(type, mappedTag);
    });
};

var getMethodsForTag = function getMethodsForTag(type, tags) {
    switch (type) {
        case _HelmetConstants.TAG_NAMES.TITLE:
            return {
                toComponent: function toComponent() {
                    return generateTitleAsReactComponent(type, tags.title, tags.titleAttributes);
                },
                toString: function toString() {
                    return generateTitleAsString(type, tags.title, tags.titleAttributes);
                }
            };
        case _HelmetConstants.TAG_NAMES.HTML:
            return {
                toComponent: function toComponent() {
                    return tags;
                },
                toString: function toString() {
                    return generateHtmlAttributesAsString(tags);
                }
            };
        default:
            return {
                toComponent: function toComponent() {
                    return generateTagsAsReactComponent(type, tags);
                },
                toString: function toString() {
                    return generateTagsAsString(type, tags);
                }
            };
    }
};

var mapStateOnServer = function mapStateOnServer(_ref) {
    var htmlAttributes = _ref.htmlAttributes,
        title = _ref.title,
        titleAttributes = _ref.titleAttributes,
        baseTag = _ref.baseTag,
        metaTags = _ref.metaTags,
        linkTags = _ref.linkTags,
        scriptTags = _ref.scriptTags,
        noscriptTags = _ref.noscriptTags,
        styleTags = _ref.styleTags;
    return {
        htmlAttributes: getMethodsForTag(_HelmetConstants.TAG_NAMES.HTML, htmlAttributes),
        title: getMethodsForTag(_HelmetConstants.TAG_NAMES.TITLE, { title: title, titleAttributes: titleAttributes }),
        base: getMethodsForTag(_HelmetConstants.TAG_NAMES.BASE, baseTag),
        meta: getMethodsForTag(_HelmetConstants.TAG_NAMES.META, metaTags),
        link: getMethodsForTag(_HelmetConstants.TAG_NAMES.LINK, linkTags),
        script: getMethodsForTag(_HelmetConstants.TAG_NAMES.SCRIPT, scriptTags),
        noscript: getMethodsForTag(_HelmetConstants.TAG_NAMES.NOSCRIPT, noscriptTags),
        style: getMethodsForTag(_HelmetConstants.TAG_NAMES.STYLE, styleTags)
    };
};

var Helmet = function Helmet(Component) {
    var _class, _temp;

    return _temp = _class = function (_React$Component) {
        _inherits(HelmetWrapper, _React$Component);

        function HelmetWrapper() {
            _classCallCheck(this, HelmetWrapper);

            return _possibleConstructorReturn(this, (HelmetWrapper.__proto__ || Object.getPrototypeOf(HelmetWrapper)).apply(this, arguments));
        }

        _createClass(HelmetWrapper, [{
            key: "shouldComponentUpdate",
            value: function shouldComponentUpdate(nextProps) {
                return !(0, _deepEqual2.default)(this.props, nextProps);
            }
        }, {
            key: "render",
            value: function render() {
                return _react2.default.createElement(Component, this.props);
            }
        }], [{
            key: "canUseDOM",

            // Component.peek comes from react-side-effect:
            // For testing, you may use a static peek() method available on the returned component.
            // It lets you get the current state without resetting the mounted instance stack.
            // Don't use it for anything other than testing.
            set: function set(canUseDOM) {
                Component.canUseDOM = canUseDOM;
            }
            /**
             * @param {Object} htmlAttributes: {"lang": "en", "amp": undefined}
             * @param {String} title: "Title"
             * @param {String} defaultTitle: "Default Title"
             * @param {String} titleTemplate: "MySite.com - %s"
             * @param {Object} titleAttributes: {"itemprop": "name"}
             * @param {Object} base: {"target": "_blank", "href": "http://mysite.com/"}
             * @param {Array} meta: [{"name": "description", "content": "Test description"}]
             * @param {Array} link: [{"rel": "canonical", "href": "http://mysite.com/example"}]
             * @param {Array} script: [{"type": "text/javascript", "src": "http://mysite.com/js/test.js"}]
             * @param {Array} noscript: [{"innerHTML": "<img src='http://mysite.com/js/test.js'"}]
             * @param {Array} style: [{"type": "text/css", "cssText": "div{ display: block; color: blue; }"}]
             * @param {Function} onChangeClientState: "(newState) => console.log(newState)"
             */

        }]);

        return HelmetWrapper;
    }(_react2.default.Component), _class.propTypes = {
        htmlAttributes: _react2.default.PropTypes.object,
        title: _react2.default.PropTypes.string,
        defaultTitle: _react2.default.PropTypes.string,
        titleTemplate: _react2.default.PropTypes.string,
        titleAttributes: _react2.default.PropTypes.object,
        base: _react2.default.PropTypes.object,
        meta: _react2.default.PropTypes.arrayOf(_react2.default.PropTypes.object),
        link: _react2.default.PropTypes.arrayOf(_react2.default.PropTypes.object),
        script: _react2.default.PropTypes.arrayOf(_react2.default.PropTypes.object),
        noscript: _react2.default.PropTypes.arrayOf(_react2.default.PropTypes.object),
        style: _react2.default.PropTypes.arrayOf(_react2.default.PropTypes.object),
        onChangeClientState: _react2.default.PropTypes.func
    }, _class.peek = Component.peek, _class.rewind = function () {
        var mappedState = Component.rewind();
        if (!mappedState) {
            // provide fallback if mappedState is undefined
            mappedState = mapStateOnServer({
                htmlAttributes: {},
                title: "",
                titleAttributes: {},
                baseTag: [],
                metaTags: [],
                linkTags: [],
                scriptTags: [],
                noscriptTags: [],
                styleTags: []
            });
        }

        return mappedState;
    }, _temp;
};

var reducePropsToState = function reducePropsToState(propsList) {
    return {
        htmlAttributes: getAttributesFromPropsList(_HelmetConstants.TAG_NAMES.HTML, propsList),
        title: getTitleFromPropsList(propsList),
        titleAttributes: getAttributesFromPropsList("titleAttributes", propsList),
        baseTag: getBaseTagFromPropsList([_HelmetConstants.TAG_PROPERTIES.HREF], propsList),
        metaTags: getTagsFromPropsList(_HelmetConstants.TAG_NAMES.META, [_HelmetConstants.TAG_PROPERTIES.NAME, _HelmetConstants.TAG_PROPERTIES.CHARSET, _HelmetConstants.TAG_PROPERTIES.HTTPEQUIV, _HelmetConstants.TAG_PROPERTIES.PROPERTY, _HelmetConstants.TAG_PROPERTIES.ITEM_PROP], propsList),
        linkTags: getTagsFromPropsList(_HelmetConstants.TAG_NAMES.LINK, [_HelmetConstants.TAG_PROPERTIES.REL, _HelmetConstants.TAG_PROPERTIES.HREF], propsList),
        scriptTags: getTagsFromPropsList(_HelmetConstants.TAG_NAMES.SCRIPT, [_HelmetConstants.TAG_PROPERTIES.SRC, _HelmetConstants.TAG_PROPERTIES.INNER_HTML], propsList),
        noscriptTags: getTagsFromPropsList(_HelmetConstants.TAG_NAMES.NOSCRIPT, [_HelmetConstants.TAG_PROPERTIES.INNER_HTML], propsList),
        styleTags: getTagsFromPropsList(_HelmetConstants.TAG_NAMES.STYLE, [_HelmetConstants.TAG_PROPERTIES.CSS_TEXT], propsList),
        onChangeClientState: getOnChangeClientState(propsList)
    };
};

var handleClientStateChange = function handleClientStateChange(newState) {
    var htmlAttributes = newState.htmlAttributes,
        title = newState.title,
        titleAttributes = newState.titleAttributes,
        baseTag = newState.baseTag,
        metaTags = newState.metaTags,
        linkTags = newState.linkTags,
        scriptTags = newState.scriptTags,
        noscriptTags = newState.noscriptTags,
        styleTags = newState.styleTags,
        onChangeClientState = newState.onChangeClientState;

    updateAttributes("html", htmlAttributes);

    updateTitle(title, titleAttributes);

    var tagUpdates = {
        baseTag: updateTags(_HelmetConstants.TAG_NAMES.BASE, baseTag),
        metaTags: updateTags(_HelmetConstants.TAG_NAMES.META, metaTags),
        linkTags: updateTags(_HelmetConstants.TAG_NAMES.LINK, linkTags),
        scriptTags: updateTags(_HelmetConstants.TAG_NAMES.SCRIPT, scriptTags),
        noscriptTags: updateTags(_HelmetConstants.TAG_NAMES.NOSCRIPT, noscriptTags),
        styleTags: updateTags(_HelmetConstants.TAG_NAMES.STYLE, styleTags)
    };

    var addedTags = {};
    var removedTags = {};

    Object.keys(tagUpdates).forEach(function (tagType) {
        var _tagUpdates$tagType = tagUpdates[tagType],
            newTags = _tagUpdates$tagType.newTags,
            oldTags = _tagUpdates$tagType.oldTags;

        if (newTags.length) {
            addedTags[tagType] = newTags;
        }
        if (oldTags.length) {
            removedTags[tagType] = tagUpdates[tagType].oldTags;
        }
    });

    onChangeClientState(newState, addedTags, removedTags);
};

var NullComponent = function NullComponent() {
    return null;
};

var HelmetSideEffects = (0, _reactSideEffect2.default)(reducePropsToState, handleClientStateChange, mapStateOnServer)(NullComponent);

exports.default = Helmet(HelmetSideEffects);
module.exports = exports["default"];


text:
from __future__ import unicode_literals

import accounts.models
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import django_countries.fields
import phonenumber_field.modelfields

class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='User',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('password', models.CharField(max_length=128, verbose_name='password')),
                ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
                ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
                ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
                ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
                ('email', models.EmailField(error_messages={'unique': 'A user with that username already exists.'}, max_length=254, unique=True, verbose_name='email address')),
                ('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')),
                ('last_name', models.CharField(blank=True, max_length=30, verbose_name='last name')),
                ('birthday', models.DateField()),
                ('nationality', django_countries.fields.CountryField(max_length=2)),
                ('gender', models.CharField(choices=[('M', 'Male'), ('F', 'Female'), ('O', 'Others')], max_length=1)),
                ('phone_number', phonenumber_field.modelfields.PhoneNumberField(max_length=128)),
            ],
            options={
                'abstract': False,
            },
            managers=[
                ('objects', accounts.models.UserManager()),
            ],
        ),
        migrations.CreateModel(
            name='School',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=100)),
                ('country', django_countries.fields.CountryField(max_length=2)),
            ],
        ),
        migrations.AddField(
            model_name='user',
            name='school',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='accounts.School'),
        ),
    ]


text:
==========================
Rule ``phpdoc_to_comment``
==========================

Docblocks should only be used on structural elements.

Examples
--------

Example #1
~~~~~~~~~~

.. code-block:: diff

   --- Original
   +++ New
   @@ -1,7 +1,7 @@
    <?php
    $first = true;// needed because by default first docblock is never fixed.

   -/** This should not be a docblock */
   +/* This should not be a docblock */
    foreach($connections as $key => $sqlite) {
        $sqlite->open($path);
    }

Rule sets
---------

The rule is part of the following rule sets:

@Symfony
  Using the ``@Symfony`` rule set will enable the ``phpdoc_to_comment`` rule.

@PhpCsFixer
  Using the ``@PhpCsFixer`` rule set will enable the ``phpdoc_to_comment`` rule.


text:
require 'vk/api/objects'
require 'vk/schema/namespace'

module Vk
  module API
    class Wall < Vk::Schema::Namespace
      # @see https://github.com/VKCOM/vk-api-schema/blob/master/objects.json
      class WallpostToId < Vk::Schema::Object
        # @return [Integer] Post ID
        attribute :id, API::Types::Coercible::Int.optional.default(nil)
        # @return [Integer] Post author ID
        attribute :from_id, API::Types::Coercible::Int.optional.default(nil)
        # @return [Integer] Wall owner's ID
        attribute :to_id, API::Types::Coercible::Int.optional.default(nil)
        # @return [Integer] Date of publishing in Unixtime
        attribute :date, API::Types::Coercible::Int.optional.default(nil)
        # @return [Integer] wall post ID (if comment)
        attribute :post_id, API::Types::Coercible::Int.optional.default(nil)
        # @return [API::Wall::PostType] @see https://github.com/VKCOM/vk-api-schema/blob/master/objects.json
        attribute :post_type, API::Wall::PostType.optional.default(nil)
        # @return [String] Post text
        attribute :text, API::Types::Coercible::String.optional.default(nil)
        # @return [Integer] Post signer ID
        attribute :signer_id, API::Types::Coercible::Int.optional.default(nil)
        # @return [Array] @see https://github.com/VKCOM/vk-api-schema/blob/master/objects.json
        attribute :attachments, API::Types::Coercible::Array.member(API::Wall::WallpostAttachment).optional.default(nil)
        # @return [API::Base::Geo] @see https://github.com/VKCOM/vk-api-schema/blob/master/objects.json
        attribute :geo, Dry::Types[API::Base::Geo].optional.default(nil)
        # @return [API::Wall::PostSource] @see https://github.com/VKCOM/vk-api-schema/blob/master/objects.json
        attribute :post_source, Dry::Types[API::Wall::PostSource].optional.default(nil)
        # @return [API::Base::CommentsInfo] @see https://github.com/VKCOM/vk-api-schema/blob/master/objects.json
        attribute :comments, Dry::Types[API::Base::CommentsInfo].optional.default(nil)
        # @return [API::Base::LikesInfo] @see https://github.com/VKCOM/vk-api-schema/blob/master/objects.json
        attribute :likes, Dry::Types[API::Base::LikesInfo].optional.default(nil)
        # @return [API::Base::RepostsInfo] @see https://github.com/VKCOM/vk-api-schema/blob/master/objects.json
        attribute :reposts, Dry::Types[API::Base::RepostsInfo].optional.default(nil)
        # @return [Integer] ID of the source post owner
        attribute :copy_owner_id, API::Types::Coercible::Int.optional.default(nil)
        # @return [Integer] ID of the source post
        attribute :copy_post_id, API::Types::Coercible::Int.optional.default(nil)
      end
    end
  end
end


text:
import Router from 'express-promise-router';
import _ from 'lodash';
import * as Mapper from 'jsonapi-mapper';
import Joi from 'joi';
import escape from 'escape-html';
import httpErrors from 'http-errors';

import models from '../../../models';
import frameViews from '../../../frameViews';

const mapper = new Mapper.Bookshelf();

// TODO: It might be a good idea to cache rendered frame content in the DB

const postFrameSchema = Joi.object().keys({
  data: Joi.object().keys({
    type: Joi.string().valid(['frames']),
    attributes: Joi.object().keys({
      title: Joi.string(),
      type: Joi.string().optional(),
      content: Joi.object().optional(),
      height: Joi.number().optional(),
      width: Joi.number().optional(),
      x: Joi.number().optional(),
      y: Joi.number().optional(),
    }),
    relationships: Joi.object().keys({
      notebook: Joi.object().keys({
        data: Joi.object().keys({
          type: Joi.string().valid(['notebooks']),
          id: Joi.string().regex(/^[0-9]+$/, 'numbers'),
        })
      })
    }),
  }),
  meta: Joi.object().optional(),
});

const patchFrameSchema = Joi.object().keys({
  data: Joi.object().keys({
    type: Joi.string().valid(['frames']),
    id: Joi.string().regex(/^[0-9]+$/, 'numbers'),
    attributes: Joi.object().keys({
      title: Joi.string().optional(),
      type: Joi.string().optional(),
      content: Joi.object().optional(),
      height: Joi.number().optional(),
      width: Joi.number().optional(),
      x: Joi.number().optional(),
      y: Joi.number().optional(),
    }),
    relationships: Joi.object().optional().keys({
      notebook: Joi.object().keys({
        data: Joi.object().keys({
          type: Joi.string().valid(['notebooks']),
          id: Joi.string().regex(/^[0-9]+$/, 'numbers'),
        })
      })
    }),
  }),
  meta: Joi.object().optional(),
});

const wrapBookshelfErrors = (err) => {
  if(
    err instanceof models.bookshelf.NotFoundError ||
    err instanceof models.bookshelf.EmptyError ||
    err instanceof models.bookshelf.NoRowsUpdatedError ||
    err instanceof models.bookshelf.NoRowsDeletedError
  ) {
    throw httpErrors.NotFound();
  }
  if(err.message.indexOf('violates foreign key constraint') > -1) {
    throw httpErrors.BadRequest('invalid foreign key');
  }
  throw err;
};

const renderFrame = (frameJson) =>
  frameViews
    .render(frameJson.attributes)
    .catch(err => `

        Error rendering frame content.

${escape(err.message)}
`)
    .then(renderedContent =>
      _.merge({}, frameJson, { attributes: { renderedContent } }));

const mapFrameToJson = (frame) => {
  const frameJson = mapper.map(frame, 'frames', {
    enableLinks: false,
    attributes: { omit: ['id', 'notebookId'] },
    relations: { included: false },
  });
  frameJson.data.relationships = _.assign({}, frameJson.data.relationships, {
    notebook: { data: { type: 'notebooks', id: String(frame.attributes.notebookId) } }
  });
  return frameJson;
};

const broadcastFrame = (frame) => {
  global.wss.fireFrameUpdate(_.omit(frame, ['included']));
  return frame;
};

// GET /api/v2/frames
const indexFrames = (req, res) =>
  models('Frame').fetchJsonApi({ include: ['notebook'] })
    .then(frames => mapper.map(frames, 'frames', {
      enableLinks: false,
      attributes: { omit: ['id', 'notebookId'] },
      relations: { included: req.jsonApi.include },
    }))
    .then(frames => res.json(frames));

// POST /api/v2/frames
const createFrame = (req, res) =>
  Joi.validate(req.body, postFrameSchema, { presence: 'required' })
    .catch(err => { throw httpErrors.BadRequest(err.message); })
    .then((body) =>
      new Promise((resolve) => resolve(_.assign({}, body.data.attributes,
        { notebookId: parseInt(body.data.relationships.notebook.data.id, 10) })))
        .then(attrs => models('Frame').forge(attrs).save())
        .catch(wrapBookshelfErrors)
        .then(mapFrameToJson)
        .then(frame => renderFrame(frame.data)
          .then(renderedContent => _.assign({}, frame, { data: renderedContent })))
        .then(broadcastFrame)
        .then(frameJson => res.status(201).json(frameJson))
    );

// GET /api/v2/frames/1
const showFrame = (req, res) =>
  new Promise(resolve => resolve(parseInt(req.params.id, 10)))
    .then(id =>
      models('Frame').where({ id })
        .fetchJsonApi({ include: ['notebook'], require: true }, false)
    )
    .catch(wrapBookshelfErrors)
    .then(frame => mapper.map(frame, 'frames', {
      enableLinks: false,
      attributes: { omit: ['id', 'notebookId'] },
      relations: { included: false },
    }))
    .then(frameJson =>
      renderFrame(frameJson.data)
        .then(data => _.assign({}, frameJson, { data })))
    .then(frameJson => res.json(frameJson));

// PATCH /api/v2/frames/3
const updateFrame = (req, res) =>
  Joi.validate(req.body, patchFrameSchema, { presence: 'required' })
    .catch(err => { throw httpErrors.BadRequest(err.message); })
    .then((body) => {
      const id = parseInt(req.params.id, 10);
      return models('Frame').where({ id }).fetch({ require: true })
        .catch(wrapBookshelfErrors)
        .then(frame => frame.save(body.data.attributes))
        .then(mapFrameToJson)
        .then(frame => renderFrame(frame.data)
          .then(renderedContent => _.assign({}, frame, { data: renderedContent })))
        .then(broadcastFrame)
        .then(frameJson => res.json(frameJson));
    });

// DELETE /api/v2/frames/3
const destroyFrame = (req, res) =>
  new Promise(resolve => resolve(parseInt(req.params.id, 10)))
    .then(id => models('Frame').forge({ id }).destroy({ require: true }))
    .catch(wrapBookshelfErrors)
    .then(() => res.status(204).send());

const router = Router();

router.route('/')
  .get(indexFrames)
  .post(createFrame);
router.route('/:id')
  .get(showFrame)
  .patch(updateFrame)
  .delete(destroyFrame);

export default router;


text:
import PropTypes from 'prop-types'
import { Uppy as UppyCore } from '@uppy/core'

// The `uppy` prop receives the Uppy core instance.
const uppy = PropTypes.instanceOf(UppyCore)

// A list of plugins to mount inside this component.
const plugins = PropTypes.arrayOf(PropTypes.string)

// Language strings for this component.
const locale = PropTypes.shape({
  strings: PropTypes.object, // eslint-disable-line react/forbid-prop-types
  pluralize: PropTypes.func,
})

// List of meta fields for the editor in the Dashboard.
const metaField = PropTypes.shape({
  id: PropTypes.string.isRequired,
  name: PropTypes.string.isRequired,
  placeholder: PropTypes.string,
})
const metaFields = PropTypes.oneOfType([
  PropTypes.arrayOf(metaField),
  PropTypes.func,
])

// A size in pixels (number) or with some other unit (string).
const cssSize = PropTypes.oneOfType([
  PropTypes.string,
  PropTypes.number,
])

// Common props for dashboardy components (Dashboard and DashboardModal).
const dashboard = {
  uppy,
  inline: PropTypes.bool,
  plugins,
  width: cssSize,
  height: cssSize,
  showProgressDetails: PropTypes.bool,
  hideUploadButton: PropTypes.bool,
  hideProgressAfterFinish: PropTypes.bool,
  note: PropTypes.string,
  metaFields,
  proudlyDisplayPoweredByUppy: PropTypes.bool,
  disableStatusBar: PropTypes.bool,
  disableInformer: PropTypes.bool,
  disableThumbnailGenerator: PropTypes.bool,
  // pass-through to ThumbnailGenerator
  thumbnailWidth: PropTypes.number,
  locale,
}

export {
  uppy,
  locale,
  dashboard,
  plugins,
  metaFields,
  cssSize,
}


text:
function codes=StandardMiCodes()
% STANDARDMICODES return Matlab standard codes for data formats
% Example:
% CODES=STANDARDMICODES();
%
% Author: Malcolm Lidierth 07/06
% Copyright © King's College London 2006
% Revisions:

codes={'int8' 'uint8' 'int16' 'uint16' 'int32' 'uint32' 'single'...
    'unknown' 'double' 'unknown' 'unknown' 'int64' 'uint64'...
    'matrix' 'compressed' 'UTF8' 'UTF16' 'UTF32'};
return
end


text:
import Ember from 'ember';

export function progressStyleHelper([percent, id, colors]/*, hash*/) {
  let color = colors[id % colors.length];
  return new Ember.Handlebars.SafeString(`width: ${percent}%; background-color: ${color};`);
}

export default Ember.Helper.helper(progressStyleHelper);


text:
BreakoutSshd
============

** TODO: Add description **


text:
<?php
/**
 * @file
 * Contains \Drupal\suffix_main\Controller\ApplyController.
 */
namespace Drupal\suffix_main\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\suffix_main\UserStorage;
use Drupal\suffix_main\ApplyStorage;
class ApplyController extends APIBaseController {
    public function __construct()
    {
//        $this->checkSignature();
    }

    public function apply(){
        $queryData = $this->getRequest();
        $validateRule = $this->validateRule();
        $this->fieldVerify($validateRule,$queryData);
        $queryData = self::dataFormat($queryData,$validateRule);
//        $applyInfo = ApplyStorage::getApplyInfo(array('mobile'=>$queryData['mobile'],'create_time'=>array(0=>1514788801,1=>'>')));
        $insertData = $this->getDefaultValue();
        $insertData['username'] = $queryData['username'];
        $insertData['mobile'] = $queryData['mobile'];
        $oldUser = UserStorage::getOneUserByMobile($queryData['mobile']);
        if(!empty($oldUser)){
            $oldUser = $this->json_deal($oldUser);
            $insertData['uid'] = $oldUser['user_id'];
        }
        if($queryData['longitude'] && $queryData['latitude']){//31.255923,121.462056  根据经纬度 获取预约所在省市区
            $cityInfo = $this->getCityInfo($queryData['latitude'],$queryData['longitude']);
            $preg = '/renderReverse&&renderReverse\((.*)\)/';
            preg_match($preg,$cityInfo,$match);
            $cityInfo = json_decode($match[1],true);
            $cityInfoRes = $cityInfo['result'];
            $insertData['province'] = $cityInfoRes['addressComponent']['province'];
            $insertData['city'] = $cityInfoRes['addressComponent']['city'];
            $insertData['district'] = $cityInfoRes['addressComponent']['district'];
            $insertData['latitude'] = $queryData['latitude'];
            $insertData['longitude'] = $queryData['longitude'];
        }
        if($queryData['product_id']){
            //购物车预约逻辑
        }
//        var_export($insertData);die;
        $res = ApplyStorage::insertApplyInfo($insertData);
        $this->success($res);
    }

    public function getApplyList(){
        $queryData = $this->getRequest();
        $validateRule = array(
            'city'=>array(
                'rule'=>'all',
                'declare'=>'城市'
            ),
        );
        $this->fieldVerify($validateRule,$queryData);
        $queryData = self::dataFormat($queryData,$validateRule);
        $param = array();
        if($queryData['city']){
            $param['city'] = $queryData['city'];
        }
        $list = ApplyStorage::applyList($param,array(),array('field'=>'create_time','order'=>'DESC'));
        $this->success($list);
    }

    public function getUserByMobile(){
        $queryData = $this->getRequest();
        $validateRule = array(
            'mobile'=>array(
                'rule'=>'require',
                'declare'=>'手机号'
            ),
        );
        $this->fieldVerify($validateRule,$queryData);
        $queryData = self::dataFormat($queryData,$validateRule);
        $info = UserStorage::getOneUserByMobile($queryData['mobile']);
        $this->success($info);
    }

    private function getDefaultValue(){//补全插入数据字段
        return array(
            'username' => '',
            'mobile' => '',
            'uid'=>0,
            'gender' => 0,
            'product_id'=>0,
            'province' => '',
            'city' => '',
            'district' => '',
            'address' => '',
            'longitude' => '',
            'latitude' => '',
            'remark' => '',
            'create_time' => time()
        );
    }

    private function validateRule(){
        return array(
            'username'=>array(
                'rule'=>'require',
                'declare'=>'用户名'
            ),
            'mobile'=>array(
                'rule'=>'require',
                'declare'=>'手机号'
            ),
            'product_id'=>array(
                'rule'=>'all|number',
                'declare'=>'产品ID'
            ),
            'gender'=>array(
                'rule'=>'all|number',
                'declare'=>'性别'
            ),
            'longitude'=>array(
                'rule'=>'all',
                'declare'=>'经度'
            ),
            'latitude'=>array(
                'rule'=>'all',
                'declare'=>'纬度'
            ),
        );
    }

}


text:
using System.Text;
using Carbon.Data.Sql;

namespace Carbon.Rds.Management
{
    internal static class DbGrantExtensions
    {
        public static string ToRevokeCommand(this DbGrant grant)
        {
            var sb = new StringBuilder();

            sb.Append("REVOKE ");
            sb.Append(string.Join(", ", grant.Privileges));
            sb.Append(" ON ");

            if (grant.Resource.Type == DbObjectType.Procedure)
            {
                sb.Append("PROCEDURE ");
            }
            else if (grant.Resource.Type == DbObjectType.Function)
            {
                sb.Append("FUNCTION ");
            }

            sb.Append(grant.Resource.SchemaName);
            sb.Append('.');
            sb.Append(grant.Resource.ObjectName);

            sb.Append(" FROM ");

            // `name`@`%`
            grant.Principal.WriteSqlTo(sb);

            sb.Append(';');

            return sb.ToString();
        }
    }
}


text:
Untitled

  <textarea ui-codemirror="options" ng-model="code"></textarea>
  <button class="btn btn-primary" ng-click="run(code)"> Run</button>
  <button class="btn btn-success" ng-click="save(name, code)"> Save</button>
  Examples

{{result.stdout}}

{{result.stderr}}

{{result.error}}


text:
import { expect } from "chai";
import { ActionsObservable } from "redux-observable";

import * as constants from "../../../src/notebook/constants";

import {
  setLanguageInfo,
  acquireKernelInfo,
  watchExecutionStateEpic,
  newKernelObservable,
  newKernelEpic,
  newKernelByNameEpic
} from "../../../src/notebook/epics/kernel-launch";

import { createMessage } from "../../../packages/messaging";

const Rx = require("rxjs/Rx");

describe("setLanguageInfo", () => {
  it("creates a SET_LANGUAGE_INFO action", () => {
    const langInfo = {
      codemirror_mode: {
        name: "ipython",
        version: 3
      },
      file_extension: ".py",
      mimetype: "text/x-python",
      name: "python",
      nbconvert_exporter: "python",
      pygments_lexer: "ipython3",
      version: "3.5.1"
    };

    expect(setLanguageInfo(langInfo)).to.deep.equal({
      type: constants.SET_LANGUAGE_INFO,
      langInfo
    });
  });
});

describe("acquireKernelInfo", () => {
  it("sends a kernel_info_request and processes kernel_info_reply", done => {
    const sent = new Rx.Subject();
    const received = new Rx.Subject();

    const mockSocket = Rx.Subject.create(sent, received);

    sent.subscribe(msg => {
      expect(msg.header.msg_type).to.equal("kernel_info_request");

      const response = createMessage("kernel_info_reply");
      response.parent_header = msg.header;
      response.content = {
        language_info: {
          language: "python"
        }
      };

      // TODO: Get the Rx handling proper here
      setTimeout(() => received.next(response), 100);
    });

    const obs = acquireKernelInfo({ shell: mockSocket });

    obs.subscribe(langAction => {
      expect(langAction).to.deep.equal({
        langInfo: { language: "python" },
        type: constants.SET_LANGUAGE_INFO
      });
      done();
    });
  });
});

describe("watchExecutionStateEpic", () => {
  it("returns an Observable with an initial state of idle", done => {
    const action$ = ActionsObservable.of({
      type: constants.NEW_KERNEL,
      channels: {
        iopub: Rx.Observable.of({
          header: { msg_type: "status" },
          content: { execution_state: "idle" }
        })
      }
    });
    const obs = watchExecutionStateEpic(action$);
    obs.toArray().subscribe(
      // Every action that goes through should get stuck on an array
      actions => {
        const types = actions.map(({ type }) => type);
        expect(types).to.deep.equal([
          constants.SET_EXECUTION_STATE,
          constants.SET_EXECUTION_STATE
        ]);
      },
      () => expect.fail(), // It should not error in the stream
      () => done()
    );
  });
});

describe("newKernelObservable", () => {
  it("returns an observable", () => {
    const obs = newKernelObservable("python3", process.cwd());
    expect(obs.subscribe).to.not.be.null;
  });
});

describe("newKernelEpic", () => {
  it("throws an error if given a bad action", done => {
    const actionBuffer = [];
    const action$ = ActionsObservable.of({
      type: constants.LAUNCH_KERNEL
    }).share();
    const obs = newKernelEpic(action$);
    obs.subscribe(
      x => {
        expect(x.type).to.equal(constants.ERROR_KERNEL_LAUNCH_FAILED);
        actionBuffer.push(x.type);
        done();
      },
      err => expect.fail(err, null),
      () => {
        expect.fail("Should not complete");
      }
    );
  });
  it("calls newKernelObservable if given the correct action", done => {
    const actionBuffer = [];
    const action$ = ActionsObservable.of({
      type: constants.LAUNCH_KERNEL,
      kernelSpec: { spec: "hokey" },
      cwd: "~"
    });
    const obs = newKernelEpic(action$);
    obs.subscribe(
      x => {
        actionBuffer.push(x.type);
        if (actionBuffer.length === 2) {
          expect(actionBuffer).to.deep.equal([
            constants.SET_KERNEL_INFO,
            constants.NEW_KERNEL
          ]);
          done();
        }
      },
      err => expect.fail(err, null),
      () => {
        expect.fail();
      }
    );
  });
});

describe("newKernelByNameEpic", () => {
  it("creates a LAUNCH_KERNEL action in response to a LAUNCH_KERNEL_BY_NAME action", done => {
    const action$ = ActionsObservable.of({
      type: constants.LAUNCH_KERNEL_BY_NAME,
      kernelSpecName: "python3",
      cwd: "~"
    });
    const obs = newKernelByNameEpic(action$);
    obs.toArray().subscribe(
      actions => {
        const types = actions.map(({ type }) => type);
        expect(types).to.deep.equal([constants.LAUNCH_KERNEL]);
      },
      err => expect.fail(err, null),
      () => done()
    );
  });
});


text:
import React from 'react';

import {
	propTypes as cellPropTypes,
	defaultProps as cellDefaultProps
} from './Cell';
import Cell from './Cell';

const propTypes = cellPropTypes;
const defaultProps = cellDefaultProps;

const ContentCell = (props) => {
	const classNames = ['mdo-content-cell'];

	if (props.className) {
		classNames.push(props.className);
	}

	return <Cell {...props} className={classNames.join(' ')}/>;
};

ContentCell.propTypes = propTypes;
ContentCell.defaultProps = defaultProps;

export default ContentCell;


text:
pub use self::numeric_helpers::Float;

/// Describes numeric types and traits for a Plugin.
pub mod numeric_helpers {
    pub use num::traits::*;
}

#[derive(Debug, Copy, Clone)]
/// Defines a high-level Plugin Error.
pub enum Error {
    /// Failure at receiving the correct device memory from the SharedTensor.
    MissingMemoryForDevice(&'static str),
    /// Failure at the execution of the Operation.
    Operation(&'static str),
    /// Failure at the Plugin.
    Plugin(&'static str),
}

impl ::std::fmt::Display for Error {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        match *self {
            Error::MissingMemoryForDevice(ref err) => write!(f, "MissingMemoryForDevice error: {}", err),
            Error::Operation(ref err) => write!(f, "Operation error: {}", err),
            Error::Plugin(ref err) => write!(f, "Plugin error: {}", err),
        }
    }
}

impl ::std::error::Error for Error {
    fn description(&self) -> &str {
        match *self {
            Error::MissingMemoryForDevice(ref err) => err,
            Error::Operation(ref err) => err,
            Error::Plugin(ref err) => err,
        }
    }

    fn cause(&self) -> Option<&::std::error::Error> {
        match *self {
            Error::MissingMemoryForDevice(_) => None,
            Error::Operation(_) => None,
            Error::Plugin(_) => None,
        }
    }
}

impl From<Error> for ::error::Error {
    fn from(err: Error) -> ::error::Error {
        ::error::Error::Plugin(err)
    }
}


text:
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

using System;
using System.Globalization;
using Microsoft.Web.WebPages.OAuth.Properties;

namespace Microsoft.Web.WebPages.OAuth
{
    /// <summary>
    /// Represents an OAuth & OpenID account.
    /// </summary>
    public class OAuthAccount
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="OAuthAccount"/> class.
        /// </summary>
        /// <param name="provider">The provider.</param>
        /// <param name="providerUserId">The provider user id.</param>
        public OAuthAccount(string provider, string providerUserId)
        {
            if (String.IsNullOrEmpty(provider))
            {
                throw new ArgumentException(
                    String.Format(CultureInfo.CurrentCulture, WebResources.Argument_Cannot_Be_Null_Or_Empty, "provider"),
                    "provider");
            }

            if (String.IsNullOrEmpty(providerUserId))
            {
                throw new ArgumentException(
                    String.Format(CultureInfo.CurrentCulture, WebResources.Argument_Cannot_Be_Null_Or_Empty, "providerUserId"),
                    "providerUserId");
            }

            Provider = provider;
            ProviderUserId = providerUserId;
        }

        /// <summary>
        /// Gets the provider name.
        /// </summary>
        public string Provider { get; private set; }

        /// <summary>
        /// Gets the provider user id.
        /// </summary>
        public string ProviderUserId { get; private set; }
    }
}