text:
package com.intellij.junit3;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import com.intellij.rt.execution.junit.ComparisonDetailsExtractor;
import com.intellij.rt.execution.junit.ComparisonFailureData;
import com.intellij.rt.execution.junit.DeafStream;
import com.intellij.rt.execution.junit.FileComparisonFailure;
import com.intellij.rt.execution.junit.IDEAJUnitListener;
import com.intellij.rt.execution.junit.IdeaTestRunner;
import com.intellij.rt.execution.junit.MapSerializerUtil;
import junit.framework.AssertionFailedError;
import junit.framework.ComparisonFailure;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestListener;
import junit.framework.TestResult;
import junit.framework.TestSuite;
import junit.textui.ResultPrinter;
import junit.textui.TestRunner;

public class JUnit3IdeaTestRunner extends TestRunner implements IdeaTestRunner {
  private SMTestListener myTestsListener;
  private ArrayList myListeners;

  public JUnit3IdeaTestRunner() {
    super(DeafStream.DEAF_PRINT_STREAM);
  }

  public void createListeners(ArrayList listeners, int count) {
    myTestsListener = new SMTestListener();
    myListeners = listeners;
  }

  public int startRunnerWithArgs(String[] args, String name, int count, boolean sendTree) {
    setPrinter(new MockResultPrinter());
    try {
      Test suite = TestRunnerUtil.getTestSuite(this, args);
      if (suite == null) return -1;
      return doRun(suite).wasSuccessful() ? 0 : -1;
    }
    catch (Exception e) {
      e.printStackTrace(System.err);
      return -2;
    }
  }

  public void clearStatus() {
    super.clearStatus();
  }

  public void runFailed(String message) {
    super.runFailed(message);
  }

  public Object getTestToStart(String[] args, String name) {
    return TestRunnerUtil.getTestSuite(this, args);
  }

  public List getChildTests(Object description) {
    return getTestCasesOf((Test)description);
  }

  public String getTestClassName(Object child) {
    return child instanceof TestSuite ? ((TestSuite)child).getName() : child.getClass().getName();
  }

  public String getStartDescription(Object child) {
    final Test test = (Test)child;
    if (test instanceof TestCase) {
      return test.getClass().getName() + "," + ((TestCase)test).getName();
    }
    return test.toString();
  }

  protected TestResult createTestResult() {
    TestResult testResult = super.createTestResult();
    testResult.addListener(myTestsListener);
    try {
      for (int i = 0; i < myListeners.size(); i++) {
        final IDEAJUnitListener junitListener = (IDEAJUnitListener)Class.forName((String)myListeners.get(i)).newInstance();
        testResult.addListener(new TestListener() {
          public void addError(Test test, Throwable t) {}

          public void addFailure(Test test, AssertionFailedError t) {}

          public void endTest(Test test) {
            if (test instanceof TestCase) {
              junitListener.testFinished(test.getClass().getName(), ((TestCase)test).getName());
            }
          }

          public void startTest(Test test) {
            if (test instanceof TestCase) {
              junitListener.testStarted(test.getClass().getName(), ((TestCase)test).getName());
            }
          }
        });
      }
    }
    catch (Exception e) {
      //do nothing
    }
    return testResult;
  }

  public TestResult doRun(Test suite, boolean wait) {  //todo
    final TestResult testResult = super.doRun(suite, wait);
    myTestsListener.finishSuite();

    return testResult;
  }

  static Vector getTestCasesOf(Test test) {
    Vector testCases = new Vector();
    if (test instanceof TestRunnerUtil.SuiteMethodWrapper) {
      test = ((TestRunnerUtil.SuiteMethodWrapper)test).getSuite();
    }
    if (test instanceof TestSuite) {
      TestSuite testSuite = (TestSuite)test;

      for (Enumeration each = testSuite.tests(); each.hasMoreElements();) {
        Object childTest = each.nextElement();
        if (childTest instanceof TestSuite && !((TestSuite)childTest).tests().hasMoreElements()) continue;
        testCases.addElement(childTest);
      }
    }
    return testCases;
  }

  public static class MockResultPrinter extends ResultPrinter {
    public MockResultPrinter() {
      super(DeafStream.DEAF_PRINT_STREAM);
    }
  }

  private static class SMTestListener implements TestListener {
    private String myClassName;
    private long myCurrentTestStart;

    public void addError(Test test, Throwable e) {
      testFailure(e, MapSerializerUtil.TEST_FAILED, getMethodName(test));
    }

    private void testFailure(Throwable failure, String messageName, String methodName) {
      final Map attrs = new HashMap();
      attrs.put("name", methodName);
      final long duration = System.currentTimeMillis() - myCurrentTestStart;
      if (duration > 0) {
        attrs.put("duration", Long.toString(duration));
      }
      try {
        final String trace = getTrace(failure);
        ComparisonFailureData notification = null;
        if (failure instanceof FileComparisonFailure) {
          final FileComparisonFailure comparisonFailure = (FileComparisonFailure)failure;
          notification = new ComparisonFailureData(comparisonFailure.getExpected(), comparisonFailure.getActual(),
                                                   comparisonFailure.getFilePath(), comparisonFailure.getActualFilePath());
        }
        else if (failure instanceof ComparisonFailure || failure.getClass().getName().equals("org.junit.ComparisonFailure")) {
          notification = new ComparisonFailureData(ComparisonDetailsExtractor.getExpected(failure), ComparisonDetailsExtractor.getActual(failure));
        }
        ComparisonFailureData.registerSMAttributes(notification, trace, failure.getMessage(), attrs, failure);
      }
      catch (Throwable e) {
        final StringWriter stringWriter = new StringWriter();
        final PrintWriter writer = new PrintWriter(stringWriter);
        e.printStackTrace(writer);
        ComparisonFailureData.registerSMAttributes(null, stringWriter.toString(), e.getMessage(), attrs, e);
      }
      finally {
        System.out.println("\n" + MapSerializerUtil.asString(messageName, attrs));
      }
    }

    public String getTrace(Throwable failure) {
      StringWriter stringWriter = new StringWriter();
      PrintWriter writer = new PrintWriter(stringWriter);
      failure.printStackTrace(writer);
      return stringWriter.toString();
    }

    private static String getMethodName(Test test) {
      final String toString = test.toString();
      final int braceIdx = toString.indexOf("(");
      return braceIdx > 0 ? toString.substring(0, braceIdx) : toString;
    }

    private static String getClassName(Test test) {
      final String toString = test.toString();
      final int braceIdx = toString.indexOf("(");
      return braceIdx > 0 && toString.endsWith(")") ? toString.substring(braceIdx + 1, toString.length() - 1) : null;
    }

    public void addFailure(Test test, AssertionFailedError e) {
      addError(test, e);
    }

    public void endTest(Test test) {
      final long duration = System.currentTimeMillis() - myCurrentTestStart;
      System.out.println("\n##teamcity[testFinished name=\'" + escapeName(getMethodName(test)) +
                         (duration > 0 ? "\' duration=\'"  + Long.toString(duration) : "") + "\']");
    }

    public void startTest(Test test) {
      myCurrentTestStart = System.currentTimeMillis();
      final String className = getClassName(test);
      if (className != null && !className.equals(myClassName)) {
        finishSuite();
        myClassName = className;
        System.out.println("##teamcity[testSuiteStarted name =\'" + escapeName(myClassName) +
                           "\' locationHint=\'java:suite://" + escapeName(className) + "\']");
      }
      final String methodName = getMethodName(test);
      System.out.println("##teamcity[testStarted name=\'" + escapeName(methodName) +
                         "\' locationHint=\'java:test://" + escapeName(className + "." + methodName) + "\']");
    }

    protected void finishSuite() {
      if (myClassName != null) {
        System.out.println("##teamcity[testSuiteFinished name=\'" + escapeName(myClassName) + "\']");
      }
    }

    private static String escapeName(String str) {
      return MapSerializerUtil.escapeStr(str, MapSerializerUtil.STD_ESCAPER);
    }
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright 2018 The Android Open Source Project
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~      http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->
<navigation
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        app:startDestination="@id/main_fragment">

    <fragment
            android:id="@+id/main_fragment"
            android:name=".MainFragment">
        <action
                android:id="@+id/start_login"
                app:destination="@id/login"/>
    </fragment>

    <include app:graph="@navigation/to_include_login_test"/>
</navigation>

redpajama_set_name: RedPajamaGithub


text:
package org.ldp4j.commons.testing.categories;

public interface Target extends TCK {

}


text:
/*
 * User: anna
 * Date: 27-Aug-2008
 */
package com.intellij.refactoring.inlineSuperClass;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.refactoring.inlineSuperClass.usageInfo.*;
import com.intellij.refactoring.memberPushDown.PushDownConflicts;
import com.intellij.refactoring.memberPushDown.PushDownProcessor;
import com.intellij.refactoring.util.DocCommentPolicy;
import com.intellij.refactoring.util.FixableUsageInfo;
import com.intellij.refactoring.util.FixableUsagesRefactoringProcessor;
import com.intellij.refactoring.util.classMembers.MemberInfo;
import com.intellij.refactoring.util.classMembers.MemberInfoStorage;
import com.intellij.usageView.UsageInfo;
import com.intellij.usageView.UsageViewDescriptor;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.Processor;
import com.intellij.util.containers.HashMap;
import com.intellij.util.containers.MultiMap;
import org.jetbrains.annotations.NotNull;

import java.util.List;
import java.util.Map;

public class InlineSuperClassRefactoringProcessor extends FixableUsagesRefactoringProcessor {
  public static final Logger LOG = Logger.getInstance("#" + InlineSuperClassRefactoringProcessor.class.getName());

  private final PsiClass mySuperClass;
  private final PsiClass[] myTargetClasses;
  private final MemberInfo[] myMemberInfos;

  public InlineSuperClassRefactoringProcessor(Project project, PsiClass superClass, final PsiClass... targetClasses) {
    super(project);
    mySuperClass = superClass;
    myTargetClasses = targetClasses;
    MemberInfoStorage memberInfoStorage = new MemberInfoStorage(mySuperClass, new MemberInfo.Filter<PsiMember>() {
      public boolean includeMember(PsiMember element) {
        return true;
      }
    });
    final List<MemberInfo> members = memberInfoStorage.getClassMemberInfos(mySuperClass);
    for (MemberInfo member : members) {
      member.setChecked(true);
    }
    myMemberInfos = members.toArray(new MemberInfo[members.size()]);
  }

  protected UsageViewDescriptor createUsageViewDescriptor(final UsageInfo[] usages) {
    return new InlineSuperClassUsageViewDescriptor(mySuperClass);
  }

  protected void findUsages(@NotNull final List<FixableUsageInfo> usages) {
    final JavaPsiFacade facade = JavaPsiFacade.getInstance(myProject);
    final PsiElementFactory elementFactory = facade.getElementFactory();
    final PsiResolveHelper resolveHelper = facade.getResolveHelper();
    ReferencesSearch.search(mySuperClass).forEach(new Processor<PsiReference>() {
      public boolean process(final PsiReference reference) {
        final PsiElement element = reference.getElement();
        if (element instanceof PsiJavaCodeReferenceElement) {
          final PsiImportStaticStatement staticImportStatement = PsiTreeUtil.getParentOfType(element, PsiImportStaticStatement.class);
          if (staticImportStatement != null) {
            usages.add(new ReplaceStaticImportUsageInfo(staticImportStatement, myTargetClasses));
          } else {
            final PsiImportStatement importStatement = PsiTreeUtil.getParentOfType(element, PsiImportStatement.class);
            if (importStatement != null) {
              usages.add(new RemoveImportUsageInfo(importStatement));
            }
            else {
              final PsiElement parent = element.getParent();
              if (parent instanceof PsiReferenceList) {
                final PsiElement pparent = parent.getParent();
                if (pparent instanceof PsiClass) {
                  final PsiClass inheritor = (PsiClass)pparent;
                  if (parent.equals(inheritor.getExtendsList()) || parent.equals(inheritor.getImplementsList())) {
                    usages.add(new ReplaceExtendsListUsageInfo((PsiJavaCodeReferenceElement)element, mySuperClass, inheritor));
                  }
                }
              } else {
                final PsiClass targetClass = myTargetClasses[0];
                final PsiClassType targetClassType = elementFactory
                  .createType(targetClass, TypeConversionUtil.getSuperClassSubstitutor(mySuperClass, targetClass, PsiSubstitutor.EMPTY));

                if (parent instanceof PsiTypeElement) {
                  final PsiType superClassType = ((PsiTypeElement)parent).getType();
                  PsiSubstitutor subst = getSuperClassSubstitutor(superClassType, targetClassType, resolveHelper, targetClass);
                  usages.add(new ReplaceWithSubtypeUsageInfo(((PsiTypeElement)parent), elementFactory.createType(targetClass, subst), myTargetClasses));
                }
                else if (parent instanceof PsiNewExpression) {
                  final PsiClassType newType = elementFactory.createType(targetClass,
                                                                         getSuperClassSubstitutor(((PsiNewExpression)parent).getType(),
                                                                                targetClassType, resolveHelper,
                                                                                targetClass));
                  usages.add(new ReplaceConstructorUsageInfo(((PsiNewExpression)parent), newType, myTargetClasses));
                }
                else if (parent instanceof PsiJavaCodeReferenceElement) {
                  usages.add(new ReplaceReferenceUsageInfo(((PsiJavaCodeReferenceElement)parent).getQualifier(), myTargetClasses));
                }
              }
            }
          }
        }
        return true;
      }
    });
    for (PsiClass targetClass : myTargetClasses) {
      for (MemberInfo memberInfo : myMemberInfos) {
        final PsiMember member = memberInfo.getMember();
        for (PsiReference reference : ReferencesSearch.search(member, member.getUseScope(), true)) {
          final PsiElement element = reference.getElement();
          if (element instanceof PsiReferenceExpression &&
              ((PsiReferenceExpression)element).getQualifierExpression() instanceof PsiSuperExpression && PsiTreeUtil.isAncestor(
            targetClass, element, false)) {
            usages.add(new RemoveQualifierUsageInfo((PsiReferenceExpression)element));
          }
        }
      }
      for (PsiMethod constructor : targetClass.getConstructors()) {
        final PsiCodeBlock constrBody = constructor.getBody();
        LOG.assertTrue(constrBody != null);
        final PsiStatement[] statements = constrBody.getStatements();
        if (statements.length > 0) {
          final PsiStatement firstConstrStatement = statements[0];
          if (firstConstrStatement instanceof PsiExpressionStatement) {
            final PsiExpression expression = ((PsiExpressionStatement)firstConstrStatement).getExpression();
            if (expression instanceof PsiMethodCallExpression) {
              final PsiReferenceExpression methodExpression = ((PsiMethodCallExpression)expression).getMethodExpression();
              if (methodExpression.getText().equals(PsiKeyword.SUPER)) {
                final PsiMethod superConstructor = ((PsiMethodCallExpression)expression).resolveMethod();
                if (superConstructor != null && superConstructor.getBody() != null) {
                  usages.add(new InlineSuperCallUsageInfo((PsiMethodCallExpression)expression));
                }
              }
            }
          }
        }
      }
    }
  }

  @Override
  protected boolean preprocessUsages(final Ref<UsageInfo[]> refUsages) {
    final MultiMap<PsiElement, String> conflicts = new MultiMap<PsiElement, String>();
    final PushDownConflicts pushDownConflicts = new PushDownConflicts(mySuperClass, myMemberInfos);
    for (PsiClass targetClass : myTargetClasses) {
      for (MemberInfo info : myMemberInfos) {
        final PsiMember member = info.getMember();
        pushDownConflicts.checkMemberPlacementInTargetClassConflict(targetClass, member);
      }
        //todo check accessibility conflicts
    }
    for (PsiElement element : pushDownConflicts.getConflicts().keySet()) {
      conflicts.put(element, pushDownConflicts.getConflicts().get(element));
    }
    checkConflicts(refUsages, conflicts);
    return showConflicts(conflicts);
  }

  @Override
  protected boolean showConflicts(final MultiMap<PsiElement, String> conflicts) {
    if (!conflicts.isEmpty() && ApplicationManager.getApplication().isUnitTestMode()) {
      throw new RuntimeException(StringUtil.join(conflicts.values(), "\n"));
    }
    return super.showConflicts(conflicts);
  }

  protected void performRefactoring(final UsageInfo[] usages) {
    new PushDownProcessor(mySuperClass.getProject(), myMemberInfos, mySuperClass, new DocCommentPolicy(DocCommentPolicy.ASIS)).run();
    replaceInnerTypeUsages();
    super.performRefactoring(usages);
    try {
      mySuperClass.delete();
    }
    catch (IncorrectOperationException e) {
      LOG.error(e);
    }
  }

  private void replaceInnerTypeUsages() {
    final JavaPsiFacade facade = JavaPsiFacade.getInstance(myProject);
    final PsiElementFactory elementFactory = facade.getElementFactory();
    final PsiResolveHelper resolveHelper = facade.getResolveHelper();
    final Map<UsageInfo, PsiElement> replacementMap = new HashMap<UsageInfo, PsiElement>();
    for (final PsiClass targetClass : myTargetClasses) {
      final PsiSubstitutor superClassSubstitutor =
        TypeConversionUtil.getSuperClassSubstitutor(mySuperClass, targetClass, PsiSubstitutor.EMPTY);
      final PsiClassType targetClassType = elementFactory.createType(targetClass, superClassSubstitutor);
      targetClass.accept(new JavaRecursiveElementWalkingVisitor() {
        @Override
        public void visitTypeElement(final PsiTypeElement typeElement) {
          super.visitTypeElement(typeElement);
          final PsiType superClassType = typeElement.getType();
          if (PsiUtil.resolveClassInType(superClassType) == mySuperClass) {
            PsiSubstitutor subst = getSuperClassSubstitutor(superClassType, targetClassType, resolveHelper, targetClass);
            replacementMap.put(new UsageInfo(typeElement), elementFactory.createTypeElement(elementFactory.createType(targetClass, subst)));
          }
        }

        @Override
        public void visitNewExpression(final PsiNewExpression expression) {
          super.visitNewExpression(expression);
          final PsiType superClassType = expression.getType();
          if (PsiUtil.resolveClassInType(superClassType) == mySuperClass) {
            PsiSubstitutor subst = getSuperClassSubstitutor(superClassType, targetClassType, resolveHelper, targetClass);
            try {
              replacementMap.put(new UsageInfo(expression), elementFactory.createExpressionFromText("new " + elementFactory.createType(
                targetClass, subst).getCanonicalText() + expression.getArgumentList().getText(), expression));
            }
            catch (IncorrectOperationException e) {
              LOG.error(e);
            }
          }
        }
      });
    }
    try {
      for (Map.Entry<UsageInfo,PsiElement> elementEntry : replacementMap.entrySet()) {
        final PsiElement element = elementEntry.getKey().getElement();
        if (element != null) {
          element.replace(elementEntry.getValue());
        }
      }
    }
    catch (IncorrectOperationException e) {
      LOG.error(e);
    }
  }

  private static PsiSubstitutor getSuperClassSubstitutor(final PsiType superClassType, final PsiClassType targetClassType, final PsiResolveHelper resolveHelper, PsiClass targetClass) {
    PsiSubstitutor subst = PsiSubstitutor.EMPTY;
    for (PsiTypeParameter typeParameter : PsiUtil.typeParametersIterable(targetClass)) {
      subst = subst.put(typeParameter,
                        resolveHelper.getSubstitutionForTypeParameter(typeParameter, targetClassType, superClassType, false,
                                                                      PsiUtil.getLanguageLevel(targetClass)));
    }
    return subst;
  }

  protected String getCommandName() {
    return InlineSuperClassRefactoringHandler.REFACTORING_NAME;
  }
}


text:
'use strict';

var React = require('react-native');
var { once } = require('./utils');
var {
  Animated,
  Children,
  Easing,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
  cloneElement
} = React;

var onLayout = once(function(e) {
  this.setState({layout: e.nativeEvent.layout})
});

var Option = React.createClass({
  propTypes: {
    /**
     * This will be displayed as the label text for
     * this option.
     */
    children: React.PropTypes.string.isRequired,
    /**
     * Mark the default option with `default={true}`.
     */
    default: React.PropTypes.bool,
    /**
     * These styles will be applied to option container and
     * will overwrite default styles.
     */
    style: View.propTypes.style,
    /**
     * These styles will be applied to the options label
     * text and will overwrite default styles.
     */
    textStyle: Text.propTypes.style,
    /**
     * The actual option value.
     */
    value: React.PropTypes.string.isRequired
  },

  render() {
    var { style, textStyle, children } = this.props;
    return (
      <View style={[styles.option, style]}>
        <Text style={[styles.optionText, textStyle]}>{children}</Text>
      </View>
    );
  }
});

var Select = React.createClass({
  propTypes: {
    /**
     * Pass the options you want to show as children
     * to the Select component.
     */
    children: React.PropTypes.arrayOf(React.PropTypes.element),
    /**
     * This prop is not required but recommended. Pass the
     * layout of the `Select` parent element to enable open
     * and close animations. In some cases this is necessary
     * to get a corrent representation of the options overlay.
     *
     * ### Example
     *
     * ```
     *  <View onLayout={({nativeEvent: e}) =>
     *    this.setState({layout: e.layout})}
     *  >
     *    <Select parentLayout={this.state.layout}>
     *      <Option value="option_1">Option 1</Option>
     *      // ...
     *    </Select>
     *  </View>
     * ```
     */
    parentLayout: React.PropTypes.shape({
      height: React.PropTypes.number.isRequired,
      width: React.PropTypes.number.isRequired
    }),
    /**
     * Assign a label to the selection button. The label
     * will be displayed nearby the current selected value.
     */
    label: React.PropTypes.string,
    /**
     * Assign a function which will be called when the user
     * selects an option. Example: `onSelect={(value) => ...}`
     */
    onSelect: React.PropTypes.func,
    /**
     * These styles will be applied to the slected text
     * label and will overwrite the default styles.
     */
    selectedTextStyle: Text.propTypes.style
  },

  getInitialState() {
    var { children } = this.props;
    var defaultOption = children.find((child) => !!child.props.default);
    return {
      open: false,
      openVal: new Animated.Value(0),
      selected: defaultOption || children[0]
    };
  },

  _open() {
    this.setState({open: true})
    Animated.timing(this.state.openVal, {
      toValue: 1, duration: 200, easing: Easing.elastic()
    }).start();
  },

  _close() {
    Animated.timing(this.state.openVal, {
      toValue: 0, duration: 200, easing: Easing.out(Easing.elastic())
    }).start(() => this.setState({open: false}));
  },

  _select(selected) {
    this.setState({selected});
    this.props.onSelect && this.props.onSelect(selected.props.value);
    this._close();
  },

  _renderToggle() {
    var { open, selected } = this.state;
    var { label, selectedTextStyle } = this.props;
    var textStyle = [styles.selected, selectedTextStyle, {fontSize: 14}];
    return (
      <TouchableOpacity onPress={open ? this._close : this._open}>
        {open ? (<Text style={styles.closeButtonText}>×</Text>) : (
          <View style={styles.selectButton}>
            <Text>{label}</Text>
            {cloneElement(selected, {textStyle})}
          </View>
        )}
      </TouchableOpacity>
    );
  },

  _renderOptions() {
    var { children, selectedTextStyle } = this.props;
    var { value: selectedValue } = this.state.selected.props;
    var textStyle = [styles.selected, selectedTextStyle];
    return (
      <View style={styles.options}>
        {children.map((child, i) => child.props.value === selectedValue ?
          cloneElement(child, {key: i, textStyle}) : (
            <TouchableOpacity key={i} onPress={() => this._select(child)}>
              {child}
            </TouchableOpacity>
          )
        )}
      </View>
    );
  },

  render() {
    var { layout, open, openVal: val } = this.state;
    var { parentLayout: parent } = this.props;

    if (open && parent) {
      var { x, y } = layout;
      var openStyle = [styles.open, {
        height: val.interpolate({inputRange: [0, 1], outputRange: [0, parent.height]}),
        left: val.interpolate({inputRange: [0, 1], outputRange: [x, 0]}),
        top: val.interpolate({inputRange: [0, 1], outputRange: [y, 0]}),
        width: val.interpolate({inputRange: [0, 1], outputRange: [0, parent.width]}),
        borderRadius: val.interpolate({
          inputRange: [0, 1],
          outputRange: [100, 0]
        })
      }];
    }

    return (
      <Animated.View style={openStyle} onLayout={onLayout.bind(this)}>
        {this._renderToggle()}
        {open && this._renderOptions()}
      </Animated.View>
    );
  }
});

var styles = StyleSheet.create({
  open: {
    backgroundColor: 'rgba(255, 255, 255, .9)',
    borderRadius: 0,
    bottom: 0,
    flexDirection: 'column',
    left: 0,
    overflow: 'hidden',
    position: 'absolute',
    right: 0,
    top: 0
  },
  options: {
    alignSelf: 'center',
    backgroundColor: 'transparent',
    padding: 20
  },
  selectButton: {
    alignItems: 'center',
    flexDirection: 'row'
  },
  closeButtonText: {
    alignSelf: 'flex-end',
    color: 'black',
    fontSize: 30,
    fontWeight: 'bold',
    margin: 5,
    marginRight: 10
  },
  optionText: {
    fontSize: 16,
    margin: 5
  },
  selected: {
    fontWeight: 'bold'
  }
});

module.exports = { Option, Select };


text:
#include "buffer.h"
#include "dprint.h"
#include <errors.h>

void bufferInit(Buffer_t *b, void *space, uint16_t len) {
    b->data = (uint8_t *) space;
    b->length = 0;
    b->capacity = len;
}

void bufferDump(Buffer_t *b) {
#if USE_PRINT
    debugPrintf(PRINT_FUNCTION, "buffer size %d\n\r", b->length);
    debugHexdump(b->data, b->length);
#endif
}


text:
namespace cc {

scoped_refptr<IOSurfaceLayer> IOSurfaceLayer::Create() {
  return make_scoped_refptr(new IOSurfaceLayer());
}

IOSurfaceLayer::IOSurfaceLayer() : Layer(), io_surface_id_(0) {}

IOSurfaceLayer::~IOSurfaceLayer() {}

void IOSurfaceLayer::SetIOSurfaceProperties(uint32_t io_surface_id,
                                            const gfx::Size& size) {
  io_surface_id_ = io_surface_id;
  io_surface_size_ = size;
  UpdateDrawsContent(HasDrawableContent());
  SetNeedsCommit();
}

scoped_ptr<LayerImpl> IOSurfaceLayer::CreateLayerImpl(
    LayerTreeImpl* tree_impl) {
  return IOSurfaceLayerImpl::Create(tree_impl, layer_id_).PassAs<LayerImpl>();
}

bool IOSurfaceLayer::HasDrawableContent() const {
  return io_surface_id_ && Layer::HasDrawableContent();
}

void IOSurfaceLayer::PushPropertiesTo(LayerImpl* layer) {
  Layer::PushPropertiesTo(layer);

  IOSurfaceLayerImpl* io_surface_layer =
      static_cast<IOSurfaceLayerImpl*>(layer);
  io_surface_layer->SetIOSurfaceProperties(io_surface_id_, io_surface_size_);
}

bool IOSurfaceLayer::Update(ResourceUpdateQueue* queue,
                            const OcclusionTracker<Layer>* occlusion) {
  bool updated = Layer::Update(queue, occlusion);

  // This layer doesn't update any resources from the main thread side,
  // but repaint rects need to be sent to the layer impl via commit.
  return updated || !update_rect_.IsEmpty();
}

}  // namespace cc


text:
title: "Keskiviikon tunnille"
tags: ena3 läksyt
---

1. Tee relatiivipronominiharjoitukset 11 ja 12 s. 143-144.

2. Lue teksti 6 vielä uudelleen ajatuksen kanssa ja tee siitä suomenkielinen "tiivistelmä. Tekstissä on 10 kappaletta, tiivistä tekstin sisältö niin, että jokaisesta kappaleesta listaat muutamalla sanalla pääsisällön. Älä kirjoita kokonaisia lauseita, jottei mene kääntämiseksi, vaan keskity ymmärtämään olennainen. Tee tiivistäminen listauksena tai mind-mappina.


text:
package com.siyeh.ig.junit;

import com.intellij.codeInsight.AnnotationUtil;
import com.intellij.psi.*;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.psiutils.TestUtils;
import org.jetbrains.annotations.NotNull;

import java.util.*;

import static com.intellij.codeInsight.AnnotationUtil.CHECK_HIERARCHY;

public class TestMethodIsPublicVoidNoArgInspectionBase extends BaseInspection {

  enum Problem {
    STATIC, NOT_PUBLIC_VOID, PARAMETER
  }

  public final List<String> ignorableAnnotations = new ArrayList<>(Collections.singletonList("mockit.Mocked"));

  @Override
  @NotNull
  public String getDisplayName() {
    return InspectionGadgetsBundle.message(
      "test.method.is.public.void.no.arg.display.name");
  }

  @Override
  @NotNull
  public String getID() {
    return "TestMethodWithIncorrectSignature";
  }

  @Override
  @NotNull
  public String buildErrorString(Object... infos) {
    final Problem problem = (Problem)infos[0];
    switch (problem) {
      case PARAMETER:
        return InspectionGadgetsBundle.message("test.method.is.public.void.no.arg.problem.descriptor1");
      case NOT_PUBLIC_VOID:
        return InspectionGadgetsBundle.message("test.method.is.public.void.no.arg.problem.descriptor2");
      case STATIC:
        return InspectionGadgetsBundle.message("test.method.is.public.void.no.arg.problem.descriptor3");
      default:
        throw new AssertionError();
    }
  }

  @Override
  public BaseInspectionVisitor buildVisitor() {
    return new TestMethodIsPublicVoidNoArgVisitor();
  }

  private class TestMethodIsPublicVoidNoArgVisitor extends BaseInspectionVisitor {

    @Override
    public void visitMethod(@NotNull PsiMethod method) {
      if (method.isConstructor()) {
        return;
      }
      if (!TestUtils.isJUnit3TestMethod(method) && !TestUtils.isJUnit4TestMethod(method)) {
        return;
      }
      final PsiClass containingClass = method.getContainingClass();
      if (containingClass == null || AnnotationUtil.isAnnotated(containingClass, TestUtils.RUN_WITH, CHECK_HIERARCHY)) {
        return;
      }
      final PsiParameterList parameterList = method.getParameterList();
      if (method.hasModifierProperty(PsiModifier.STATIC)) {
        registerMethodError(method, Problem.STATIC, method);
        return;
      }
      if (parameterList.getParametersCount() != 0) {
        final PsiParameter[] parameters = parameterList.getParameters();
        boolean annotated = true;
        for (PsiParameter parameter : parameters) {
          if (!AnnotationUtil.isAnnotated(parameter, ignorableAnnotations, 0)) {
            annotated = false;
            break;
          }
        }
        if (!annotated) {
          registerMethodError(method, Problem.PARAMETER, method);
          return;
        }
      }
      final PsiType returnType = method.getReturnType();
      if (!PsiType.VOID.equals(returnType) || !method.hasModifierProperty(PsiModifier.PUBLIC)) {
        registerMethodError(method, Problem.NOT_PUBLIC_VOID, method);
      }
    }
  }
}


text:
ConsoleApplication::ConsoleApplication(ExecutableInitialization
                                            initialization)
    : SerialExecutable(new StandardStream,
                       initialization)
{
    setObjectName("ConsoleApplication");
}

ConsoleApplication::~ConsoleApplication()
{
    NEEDDO("Kill children and clean up mess");
}


text:
#include "coroutine.h"
#include "natsu_rpc.h"
#include "natsu_config.h"
#include "natsu_snowflake.h"
#include "format.h"
#include "gci-json.h"
#include <curl/curl.h>

namespace natsu
{

struct RpcChannelData
{
    int64_t id;
    MessagePtr msg;
};

std::map<uint64_t, std::shared_ptr<co_chan<MessagePtr>>> kClientRpcChannel;
std::map<std::string, std::shared_ptr<co_chan<RpcChannelData>>> kServiceRpcChannel;
std::map<std::string, std::function<MessagePtr(MessagePtr)>> kRpcMethod;

enum { PACKET_SIZE_MAX = 4096, };
const int kHeaderLen = 12;
const int kMaxChannelSize = 1024;

int64_t generate()
{
    return SnowFlake::instance().generate();
}

void register_rpc_handler(const std::string& name, std::function<MessagePtr(MessagePtr)> func)
{
    kRpcMethod[name] = func;
}

// proto format, payload was protobuf
// now checksum data is used adler32 (depen on zlib library)
/*
----------------------------------------------------------
|               pkt len(4)          	                 |
|--------------------------------------------------------|
|				request id (8)                           |
|--------------------------------------------------------|
|               playload name len(4)                     |
|               playload name  			                 |
|--------------------------------------------------------|
|               payload data (protobuf) 	             |
|--------------------------------------------------------|
|               checksum(4)        		                 |
|--------------------------------------------------------|
*/

// class RpcPacket
// unpack stream to message and pack message to stream
class RpcPacketParser
{
public:
    // WARN: Decode() & GetMessage() is not threadsafe
    // 	     caller need locked before called

    // unpcak tcp stream data
    // when this called, then can call GetMessage()
    void Decode(const char* data, size_t len)
    {
        buffer_.append(data, len);
        while (ParseStream()) {};
    }

    // get unpacked google protobuf message poniter
    // if there's no message decoded, it will return Null poniter
    // so caller need called by loop and judge the result
    // example: while( message = decoder.GetMessage() != NULL)
    //		    {   ......   }
    MessagePtr GetMessage(int64_t& rid)
    {
        std::map<int64_t, Message*>::iterator it = message_.begin();
        if (it != message_.end())
        {
            rid = it->first;
            google::protobuf::Message* message = it->second;
            message_.erase(it);
            return MessagePtr(message);
        }

        return MessagePtr();
    }

public:
    // encode a google protobuf message to stream
    // this function is static because it's no dependcy
    // NOTE: stream poniter returned will not be Null, but can be empty
    static std::shared_ptr<std::string> Encode(const Message* message, int64_t rid)
    {
        std::shared_ptr<std::string> result(new std::string());
        result->resize(sizeof(int32_t));
        result->append(reinterpret_cast<char*>(&rid), sizeof rid);
        const std::string& type_name = message->GetTypeName();
        int32_t name_len = static_cast<int32_t>(type_name.size() + 1);
        result->append(reinterpret_cast<char*>(&name_len), sizeof name_len);
        result->append(type_name.c_str(), name_len);
        bool succeed = message->AppendToString(result.get());
        if (succeed)
        {
            const char* begin = result->c_str() + kHeaderLen;
            int32_t checkSum = adler32(1, reinterpret_cast<const Bytef*>(begin), result->size() - kHeaderLen);
            result->append(reinterpret_cast<char*>(&checkSum), sizeof checkSum);
            int32_t len = result->size() - kHeaderLen;
            std::copy(reinterpret_cast<char*>(&len), reinterpret_cast<char*>(&len) + sizeof len, result->begin());
        }
        else
        {
            result->clear();
        }

        return result;
    }

private:
    bool ParseStream()
    {
        if (buffer_.size() < 12)
            return false;

        unsigned int packetlen = 0;
        ::memcpy(&packetlen, buffer_.c_str(), sizeof(packetlen));
        if (buffer_.size() < packetlen)
        {
            return false;
        }

        if (packetlen > PACKET_SIZE_MAX)
        {
            buffer_.clear();
            return false;
        }

        int64_t rid = 0;
        ::memcpy(&rid, buffer_.c_str() + sizeof(int32_t), sizeof(rid));

        Message* message = DecodeMessage(buffer_.c_str() + kHeaderLen, packetlen);
        buffer_.erase(0, packetlen + kHeaderLen);

        if (message)
            message_[rid] = message;
        return true;
    }

    inline Message* DecodeMessage(const char* buf, size_t bufferlength)
    {
        google::protobuf::Message* result = NULL;
        int32_t len = static_cast<int32_t>(bufferlength);
        if (len >= 10)
        {
            int32_t expected_checksum = 0;
            ::memcpy(&expected_checksum, buf + bufferlength - sizeof(expected_checksum), sizeof(expected_checksum));
            const char* begin = buf;
            int32_t checksum = adler32(1, reinterpret_cast<const Bytef*>(begin), len - sizeof(expected_checksum));
            if (checksum == expected_checksum)
            {
                int32_t name_len = 0;
                ::memcpy(&name_len, buf, sizeof(name_len));

                if (name_len >= 2 && name_len <= len - 8)
                {
                    std::string type_name(buf + sizeof(name_len), name_len);
                    Message* message = CreateMessage(type_name);
                    if (message)
                    {
                        const char* data = buf + sizeof(name_len) + name_len;
                        int32_t data_len = len - name_len - 2 * sizeof(name_len);
                        if (message->ParseFromArray(data, data_len))
                        {
                            result = message;
                        }
                        else
                        {
                            // parse error
                            delete message;
                        }
                    }//else { // unknown message type }

                }//else { // invalid name len }

            }//else { // check sum error }
            else
            {
                fprintf(stderr, "checksum error\n");
            }
        }

        return result;
    }

    // Create a google protobuf Message by message name
    // if there is no message named like typeName, it will return NULL
    Message* CreateMessage(const std::string& typeName)
    {
        Message* message = NULL;
        const google::protobuf::Descriptor* descriptor = google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(typeName);
        if (descriptor)
        {
            const Message* prototype = google::protobuf::MessageFactory::generated_factory()->GetPrototype(descriptor);
            if (prototype)
            {
                message = prototype->New();
            }
        }

        return message;
    }

private:
    std::string buffer_;
    std::map<int64_t, Message*> message_;
};

class EtcdProvider
{
public:
    //provide_service_etcd
    void provide_service_etcd(const std::string& servicename, const std::string& etcdaddr)
    {
        int sock = socket(AF_INET, SOCK_STREAM, 0);
        int rep = 1;
        setsockopt( sock, SOL_SOCKET, SO_REUSEADDR, &rep, sizeof(rep));

        while(true)
        {
            int port  = 5000 + rand() % 5000;
            sockaddr_in addr;
            addr.sin_family = AF_INET;
            addr.sin_port = htons(port);
            addr.sin_addr.s_addr = inet_addr("0.0.0.0");
            socklen_t len = sizeof(addr);
            if (-1 == bind(sock, (sockaddr*)&addr, len))
            {
                fprintf(stderr, "rpc bind [%d] error: %s\n", port, strerror(errno));
                close(sock);
                co_sleep(3000);
                sock = socket(AF_INET, SOCK_STREAM, 0);
                setsockopt( sock, SOL_SOCKET, SO_REUSEADDR, &rep, sizeof(rep));
                continue;
            }

            if (-1 == ::listen(sock, 5))
            {
                fprintf(stderr, "rpc listen error: %s\n", strerror(errno));
                close(sock);
                co_sleep(3000);
                sock = socket(AF_INET, SOCK_STREAM, 0);
                setsockopt( sock, SOL_SOCKET, SO_REUSEADDR, &rep, sizeof(rep));
                continue;
            }

            NatsuConfig::config("rpc_instance_id", format("%lld", generate()));
            fprintf(stderr, "etcd provider provide %s\n", NatsuConfig::config("rpc_instance_id").c_str());
            co_timer_add(std::chrono::seconds(1), std::bind(&EtcdProvider::register_to_etcd, this, servicename, etcdaddr, port));
            break;
        }

        while(true)
        {
            sockaddr_in addr;
            socklen_t len = sizeof(addr);
            int sockfd = accept(sock, (sockaddr*)&addr, &len);
            if (sockfd == -1)
            {
                if (EAGAIN == errno || EINTR == errno)
                    continue;

                fprintf(stderr, "accept error: %s\n", strerror(errno));
                break ;
            }

            go std::bind(&EtcdProvider::handle, this, sockfd);
        }

        close(sock);
    }

private:
    void register_to_etcd(const std::string& sname, const std::string& addr, unsigned short port)
    {
        //curl -L http://127.0.0.1:2379/v2/keys/foo -XPUT -d value=bar -d ttl=5
        std::string request_url = format("http://%s/v2/keys/natsu/%s/provider/%s", addr.c_str(), sname.c_str(),
                                         NatsuConfig::config("rpc_instance_id").c_str());

        CURL* curl = curl_easy_init();
        if (curl)
        {
            curl_easy_setopt(curl, CURLOPT_URL, request_url.c_str());
            curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT"); /* !!! */
            std::string data = format("value=%s:%d&ttl=15",NatsuConfig::config("local_ipv4").c_str(), port);
            curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str());
            curl_easy_setopt(curl, CURLOPT_TIMEOUT, 5);

            CURLcode res = curl_easy_perform(curl);
            if(res != CURLE_OK)
            {
                std::string err = curl_easy_strerror(res);
                fprintf(stderr, "register_to_etcd request etcd error : %s\n", err.c_str());
            }

            curl_easy_cleanup(curl);
        }

        co_timer_add(std::chrono::seconds(10), std::bind(&EtcdProvider::register_to_etcd, this, sname, addr, port));
    }

    void handle(int sockfd)
    {
        fprintf(stderr, "provider accept producer connection %d\n", sockfd);
        co_chan<std::shared_ptr<std::string>> channel_write(kMaxChannelSize);
        co_mutex locker;
        locker.lock();
        go std::bind(&EtcdProvider::sendrpc, this, sockfd, channel_write, locker);

        char buf[1024];
        while(true)
        {
            int n = read(sockfd, buf, sizeof(buf));
            if (n == -1)
            {
                fprintf(stderr, "provider read failed %d\n", errno);
                if (EAGAIN == errno || EINTR == errno)
                    continue;

                break;
            }
            else if (n == 0)
            {
                fprintf(stderr, "provider read timeout\n");
                break;
            }
            else
            {
                rpc_parser_.Decode(buf, n);
                MessagePtr message;
                while( true )
                {
                    int64_t rid = 0;
                    message = rpc_parser_.GetMessage(rid);
                    if(message.get())
                        go std::bind(&EtcdProvider::handle_parse, this, message, rid, channel_write);
                    else
                        break;
                }

            }
        }

        locker.lock();
        close(sockfd);
        fprintf(stderr, "provider find producer lost %d\n", sockfd);
    }

    void handle_parse(MessagePtr message, int64_t rid, co_chan<std::shared_ptr<std::string>>& channel_write)
    {
        fprintf(stderr, "got one rpc request and handle it\n");
        if(!message) return;

        if(kRpcMethod.find(message->GetTypeName()) != kRpcMethod.end())
        {
            std::function<MessagePtr(MessagePtr)> func = kRpcMethod[message->GetTypeName()];
            MessagePtr resp = func(message);
            if(resp)
            {
                std::shared_ptr<std::string> buf = rpc_parser_.Encode(resp.get(), rid);
                channel_write << buf;
            }
            else
            {
                fprintf(stderr, "handle rpc failed\n");
            }
        }
    }

    void sendrpc(int sockfd, co_chan<std::shared_ptr<std::string>>& channel_write, co_mutex locker)
    {
        while(true)
        {
            std::shared_ptr<std::string> buf;
            channel_write >> buf;
            if(!buf) continue;
            size_t pos = 0;
            size_t len = buf->size();
            while(pos < len)
            {
                ssize_t n = write(sockfd, buf->c_str() + pos, buf->size() - pos);
                if(n == -1)
                {
                    break;
                }

                pos += n;
            }
        }

        locker.unlock();
    }

private:
    RpcPacketParser rpc_parser_;
};

static std::map<std::string, std::shared_ptr<EtcdProvider>> kProvider;

class EtcdProducer
{
public:
    void produce_service_etcd(const std::string& servicename, const std::string& etcdaddr)
    {
        service_name_ = servicename;
        co_timer_add(std::chrono::seconds(1), std::bind(&EtcdProducer::produce_from_etcd, this, servicename, etcdaddr));
        co_timer_add(std::chrono::seconds(10), std::bind(&EtcdProducer::handle_produce_timeout, this));
    }

    MessagePtr invoke(MessagePtr& ptr)
    {
        uint64_t id = generate();
        RpcChannelData data;
        data.id = id;
        std::shared_ptr<co_chan<MessagePtr>> newchannel(new co_chan<MessagePtr>);
        data.msg = ptr;
        natsu::kClientRpcChannel[id] = newchannel;
        (*natsu::kServiceRpcChannel[service_name_]) << data;
        MessagePtr rsp;
        (*newchannel) >> rsp;
        natsu::kClientRpcChannel.erase(id);
        return rsp;
    }

private:
    void handle_produce_timeout()
    {
        uint64_t diff = 15000;
        diff = diff << 22;
        uint64_t n = generate();
        std::map<uint64_t, std::shared_ptr<co_chan<MessagePtr>>>::iterator it = kClientRpcChannel.begin();
        for(; it != kClientRpcChannel.end(); ++it)
        {
            if((n - it->first) > diff)
            {
                fprintf(stderr, "%lu timeout and return null\n", it->first);
                MessagePtr ptr;
                (*it->second) << ptr;
            }
        }

        co_timer_add(std::chrono::seconds(10), std::bind(&EtcdProducer::handle_produce_timeout, this));
    }

    void produce_from_etcd(const std::string& servicename, const std::string& etcdaddr)
    {
        std::string request_url = format("http://%s/v2/keys/natsu/%s/provider/", etcdaddr.c_str(), servicename.c_str());
        //fprintf(stderr, "rpc get: %s\n", request_url.c_str());
        CURL* curl = curl_easy_init();
        std::string body;
        if (curl)
        {
            curl_easy_setopt(curl, CURLOPT_URL, request_url.c_str());
            curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
            curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &EtcdProducer::writer);
            curl_easy_setopt(curl, CURLOPT_WRITEDATA, &body);
            curl_easy_setopt(curl, CURLOPT_TIMEOUT, 5);

            CURLcode res = curl_easy_perform(curl);
            if(res != CURLE_OK)
            {
                std::string err = curl_easy_strerror(res);
                fprintf(stderr, "produce_from_etcd request etcd error : %s\n", err.c_str());
            }
            else
            {
                //parse etcd response and update ip list
                /*
                {"action":"get",
                	"node":{ "key":"/natsu/im/provider","dir":true,"nodes":
                		[{   "key":"/natsu/im/provider/6182415165179297793",
                			"value":"127.0.0.1:9383",
                			"expiration":"2016-09-16T06:20:41.169943308Z",
                			"ttl":9,
                			"modifiedIndex":5,
                			"createdIndex":5
                		}],
                		"modifiedIndex":4,"createdIndex":4
                	}
                }

                //or
                {"action":"get","node":{"key":"/natsu/im/provider","dir":true,"modifiedIndex":4,"createdIndex":4}}

                //or
                {"errorCode":100,"message":"Key not found","cause":"/natsu/ims","index":25}
                */

                try
                {
                    ggicci::Json object = ggicci::Json::Parse(body.c_str());
                    if(object.Contains("action"))
                    {
                        if(object["action"].AsString() == "get" && object.Contains("node"))
                        {
                            ggicci::Json object_node = object["node"];
                            if(object_node.Contains("nodes"))
                            {
                                std::map<std::string,std::string> result;
                                std::map<std::string,std::string> nodelist = service_node_;
                                service_node_.clear();
                                ggicci::Json object_nodes = object_node["nodes"];
                                for(int i = 0; i < object_nodes.Size(); i++)
                                {
                                    ggicci::Json object_item = object_nodes[i];
                                    result[object_item["key"].AsString()] = object_item["value"].AsString();
                                    service_node_[object_item["key"].AsString()] = object_item["value"].AsString();

                                    if(nodelist.find(object_item["key"].AsString()) == nodelist.end())
                                    {
                                        fprintf(stderr, "got one server : %s=%s\n",object_item["key"].AsString().c_str(), object_item["value"].AsString().c_str());
                                        go std::bind(&EtcdProducer::comm_one_server, this, object_item["key"].AsString());
                                    }

                                    service_node_.clear();
                                    service_node_ = result;
                                }

                                //log
                                std::map<std::string,std::string>::iterator it = nodelist.begin();
                                for (; it != nodelist.end(); ++it)
                                {
                                    if(service_node_.find(it->first) == service_node_.end())
                                    {
                                        fprintf(stderr, "del one server : %s=%s\n", it->first.c_str(), it->second.c_str());
                                    }
                                }

                            }
                        }
                    }
                }
                catch(...)
                {
                    fprintf(stderr, "etcd response exception :%s\n", body.c_str());
                }
            }

            curl_easy_cleanup(curl);
        }

        co_timer_add(std::chrono::seconds(10), std::bind(&EtcdProducer::produce_from_etcd, this, servicename, etcdaddr));
    }

    static long writer(void *data, int size, int nmemb, std::string &content)
    {
        long sizes = size * nmemb;
        std::string temp;
        temp = std::string((char*)data,sizes);
        content += temp;
        return sizes;
    }

    void comm_one_server(const std::string& node)
    {
        if(service_node_.find(node) == service_node_.end())
        {
            fprintf(stderr, "comm_one_server no this node %s\n", node.c_str());
            return ;
        }

        std::string addr = service_node_[node];
        std::string ip = addr.substr(0, addr.find(":"));
        std::string port = addr.substr(addr.find(":") + 1);

        //connect to addr
        struct sockaddr_in client_addr;
        bzero(&client_addr,sizeof(client_addr));
        client_addr.sin_family = AF_INET;
        client_addr.sin_addr.s_addr = htons(INADDR_ANY);
        client_addr.sin_port = htons(0);

        int sockfd = socket(AF_INET,SOCK_STREAM,0);

        if(bind(sockfd,(struct sockaddr*)&client_addr,sizeof(client_addr)))
        {
            fprintf(stderr, "etcd produce bind failed!\n");
            co_timer_add(std::chrono::seconds(10), std::bind(&EtcdProducer::comm_one_server, this, node));
            close(sockfd);
            return ;
        }

        struct sockaddr_in server_addr;
        bzero(&server_addr,sizeof(server_addr));
        server_addr.sin_family = AF_INET;
        if(inet_aton(ip.c_str(), &server_addr.sin_addr) == 0)
        {
            fprintf(stderr,"etcd produce inet_aton failed %s!\n", ip.c_str());
            co_timer_add(std::chrono::seconds(10), std::bind(&EtcdProducer::comm_one_server, this, node));
            close(sockfd);
            return ;
        }

        server_addr.sin_port = htons(atoi(port.c_str()));
        socklen_t server_addr_length = sizeof(server_addr);
        if(connect(sockfd,(struct sockaddr*)&server_addr, server_addr_length) < 0)
        {
            fprintf(stderr,"etcd produce connect failed %s:%s!\n", ip.c_str(),port.c_str());
            co_timer_add(std::chrono::seconds(10), std::bind(&EtcdProducer::comm_one_server, this, node));
            close(sockfd);
            return ;
        }

        co_mutex locker;
        locker.lock();
        go std::bind(&EtcdProducer::handle_parse, this, sockfd, locker);

        while(true)
        {
            RpcChannelData data;
            (*kServiceRpcChannel[service_name_]) >> data;
            fprintf(stderr, "process one rpc request\n");
            std::shared_ptr<std::string> bin = RpcPacketParser::Encode(data.msg.get(), data.id);
            if(!bin)
            {
                fprintf(stderr, "encoding rpc data failed\n");
                continue;
            }

            size_t pos = 0;
            size_t len = bin->size();
            while(pos < len)
            {
                ssize_t n = write(sockfd, bin->c_str() + pos, bin->size() - pos);
                if(n == -1)
                {
                    fprintf(stderr, "%s send failed\n", node.c_str() );
                    co_timer_add(std::chrono::seconds(10), std::bind(&EtcdProducer::comm_one_server, this, node));
                    locker.lock();
                    close(sockfd);
                    return ;
                }

                pos += n;
            }
        }
    }

    void handle_parse(int sockfd, co_mutex locker)
    {
        RpcPacketParser rpc_parser_;
        char buf[1024];
        while(true)
        {
            int n = read(sockfd, buf, sizeof(buf));
            if (n == -1)
            {
                if (EAGAIN == errno || EINTR == errno)
                    continue;

                break;
            }
            else if (n == 0)
            {
                break;
            }
            else
            {
                rpc_parser_.Decode(buf, n);
                MessagePtr message;
                while( true )
                {
                    int64_t rid = 0;
                    message = rpc_parser_.GetMessage(rid);
                    if(message.get())
                    {
                        if(kClientRpcChannel.find(rid) != kClientRpcChannel.end())
                        {
                            (*kClientRpcChannel[rid]) << message;
                        }
                        else
                        {
                            fprintf(stderr, "unable find %ld message\n", rid);
                        }
                    }
                    else
                        break;
                }
            }
        }

        locker.unlock();
    }

private:
    std::map<std::string,std::string> service_node_;
    std::string service_name_;
};

static std::map<std::string, std::shared_ptr<EtcdProducer>> kProducer;

MessagePtr invoke_rpc(const std::string& service, MessagePtr ptr)
{
    MessagePtr rsp;
    if(kProducer.find(service) != kProducer.end())
    {
        rsp = kProducer[service]->invoke(ptr);
    }

    return rsp;
}

void provide_service(const std::string& servicename, const std::string& etcdaddr)
{
    kProvider[servicename] = std::shared_ptr<EtcdProvider>(new EtcdProvider());
    go std::bind(&EtcdProvider::provide_service_etcd, kProvider[servicename], servicename, etcdaddr);
}

void produce_service(const std::string& servicename, const std::string& etcdaddr)
{
    kProducer[servicename] = std::shared_ptr<EtcdProducer>(new EtcdProducer());
    kServiceRpcChannel[servicename] = std::shared_ptr<co_chan<RpcChannelData>>(new co_chan<RpcChannelData>);
    go std::bind(&EtcdProducer::produce_service_etcd, kProducer[servicename], servicename, etcdaddr);
}

}


text:
package com.spencerwi.changetrackingfields;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import java.util.function.Consumer;

import static java.util.Collections.emptyList;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.core.Is.is;
import static org.mockito.Mockito.verify;

@RunWith(org.mockito.runners.MockitoJUnitRunner.class)
public class ObservableFieldTest {
    private ObservableField<Integer> sut;

    @Mock private Consumer<Integer> callback;

    @Before
    public void setUp() throws Exception { MockitoAnnotations.initMocks(this); }

    @Test
    public void canBeCreated(){
        final int initialValue = 4;
        sut = new ObservableField<>(initialValue);

        assertThat(sut.getCurrentValue(), is(initialValue));
    }

    @Test
    public void canBeUpdated(){
        final int initialValue = 4,
                      newValue = 5;
        sut = new ObservableField<>(initialValue);
        assertThat(sut.getCurrentValue(), is(initialValue));

        sut.update(newValue);

        assertThat(sut.getCurrentValue(), is(newValue));
    }

    @Test
    public void canRegisterAnOnUpdateCallback(){
        sut = new ObservableField<>(4);
        assertThat(sut.onUpdateCallbacks, is(emptyList()));

        sut.onUpdate(callback);
        assertThat(sut.onUpdateCallbacks, contains(callback));
    }

    @Test
    public void notifiesCallbacksOnUpdate(){
        sut = new ObservableField<>(4);
        sut.onUpdate(callback);

        int newValue = 5;
        sut.update(newValue);

        verify(callback).accept(newValue);
    }

    @Test
    public void canUnregisterACallback(){
        sut = new ObservableField<>(4);
        Consumer<Integer> callback = (value -> System.out.println(value));
        sut.onUpdate(callback);
        assertThat(sut.onUpdateCallbacks, contains(callback));

        sut.unregister(callback);

        assertThat(sut.onUpdateCallbacks, not(contains(callback)));
    }
}


text:
package io.reflectoring.coderadar.rest.unit.project;

import static org.mockito.Mockito.mock;

import io.reflectoring.coderadar.domain.Project;
import io.reflectoring.coderadar.projectadministration.port.driver.project.get.ListProjectsUseCase;
import io.reflectoring.coderadar.rest.domain.GetProjectResponse;
import io.reflectoring.coderadar.rest.project.ListProjectsController;
import io.reflectoring.coderadar.rest.unit.UnitTestTemplate;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

class ListProjectsControllerTest extends UnitTestTemplate {

  private final ListProjectsUseCase listProjectsUseCase = mock(ListProjectsUseCase.class);

  @Test
  void listAllProjects() {
    ListProjectsController testSubject = new ListProjectsController(listProjectsUseCase);

    Project project1 = new Project();
    Project project2 = new Project();
    Project project3 = new Project();

    List<Project> projects = new ArrayList<>();
    projects.add(project1);
    projects.add(project2);
    projects.add(project3);

    Mockito.when(listProjectsUseCase.listProjects()).thenReturn(projects);

    ResponseEntity<List<GetProjectResponse>> responseEntity = testSubject.listProjects();
    Assertions.assertNotNull(responseEntity.getBody());
    Assertions.assertEquals(3L, responseEntity.getBody().size());
    Assertions.assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
  }
}


text:
package org.switchyard.config.model.selector;

/**
 * Static OperationSelector model.
 */
public interface StaticOperationSelectorModel extends OperationSelectorModel {

    /** operationName attribute. */
    public static final String OPERATION_NAME = "operationName";

    /**
     * Get operation name.
     * @return operation name
     */
    String getOperationName();

    /**
     * Set operation name.
     * @param name operation name
     * @return this OperationSelectorModel for chaining
     */
    StaticOperationSelectorModel setOperationName(String name);
}


text:
/**
 * Created by mario on 11/05/15.
 */

/**
 * @getProtocol - this function returns the parts of a passed url. This function is used to determine the protocol of the passed URL.
 * @params path type string - the full path containing the files to be manipulated.
 */

'use strict';

var url = require("url");

var proto = {};

proto.getProtocol = function (path) {
    var parts;

    parts = url.parse(path, true);
    return parts;
};

module.exports = proto;


text:
var teaserWidth  = 407;
var teaserHeight = 229;
var teaserMargin = 40;

var zielX = 373;
var zielY = 193;
var zielHeightAndMargin = 773;

var baseOffsetX = zielX;
var baseOffsetY = zielY;

var scrollOffset = 20;
var currentScrollOffset = 0;
var maxScrollOffset = 0;

var currentVideoA;
var videoPlayer;
var isVideoPlaying = false;

var selectedStart = 0;

var currentColumn = Array(0,0,0,0,0,0,0,0,0);

var currentIndexX = 0;
var currentIndexY = 0;
var isHalfZoomed = false;
var isFullZoomed = false;

function makeZoomable(rowClass) {
	var elements = $(rowClass + " .items a").get();
	for(var element in elements) {
		registerClickEvent(elements[element]);
	}
}

function makeArrows()
{
	$(".move-left").click(function(event)
	{
		event.preventDefault();
		var indexY = $(this).parent().find(".popular-news").index(".popular-news");
		currentColumn[indexY]--;
		if(currentColumn[indexY] < 0)
		{
			currentColumn[indexY] = 0;
		}
		adjustColumn($(this).parent().find(".popular-news"));
	});
	$(".move-right").click(function(event)
	{
		event.preventDefault();
		var indexY = $(this).parent().find(".popular-news").index(".popular-news");
		currentColumn[indexY]++;
		if(currentColumn[indexY] > 7)
		{
			currentColumn[indexY] = 7;
		}
		adjustColumn($(this).parent().find(".popular-news"));
	});

	$("#zoomed-move-left").click(function(event)
	{
		event.preventDefault();
		currentColumn[currentIndexY]--;
		if(currentColumn[currentIndexY] < 0)
		{
			currentColumn[currentIndexY] = 0;
		}
		adjustColumn($($(".popular-news").get(currentIndexY)));
	});
}

var space = false;
$(function() {

  makeArrows();

  $(document).keyup(function(evt) {
    if (evt.keyCode == 32) {
      	space = false;
    }
  }).keydown(function(evt) {
    if (evt.keyCode == 32) {
      space = true;
	  if (isVideoPlaying){
		  videoPlayer.pause()
		  isVideoPlaying = false
	  } else {
		  unpauseVideo(currentVideoA)
		  isVideoPlaying = true
	  }
    }
  });
});

function mouseOverStar(){
	console.log("Over a Star!")
}

function onVideoClick(){
	videoPlayer.pause()
}

function onVideoPause(){
	$('.video-container').css("z-index", "-1");
	if(isFullZoomed)
	{
		zoomHalfTo(currentVideoA, true);
	}
}

function playVideo(a){
		var MP4Link = a.href;
		var description = $(a).find($("span p")).text();
		videoPlayer = $('.videoPlayer')[0];

		$('.video-container').css("z-index", "100");
		videoPlayer.src = MP4Link;

		videoPlayer.onpause = onVideoPause;

		$('.video-overlay-h1').text(description);
}

function unpauseVideo(a){
		var description = $(a).find($("span p")).text();
		videoPlayer = $('.videoPlayer')[0];

		$('.video-container').css("z-index", "100");
		videoPlayer.play();

		videoPlayer.onpause = onVideoPause

		$('.video-overlay-h1').text(description)
}

function playVideoTimeout(){
	playVideo(currentVideoA)
}

function registerClickEvent(a)
{
	a.onclick = function(event) {
		event.preventDefault();
		event.stopPropagation();

		if($("main").hasClass("zoom"))
		{
			zoomHalfTo(a, false);
		}
		else
		{
			showVideo(a);
		}
	};
}

function showVideo(a)
{
	zoomFullTo(a);
	currentVideoA = a;
	setTimeout(playVideoTimeout, 600);
}

function goToNextVideo()
{
	currentColumn[currentIndexY] = currentColumn[currentIndexY] + 1;
	adjustColumn($(currentVideoA).parent().parent());
	showVideo($(currentVideoA).parent().parent().find("a").get(currentColumn[currentIndexY]));
}

function mouseOverStar1(){
	$('.deathstar').css("background-image", 'url("/static/img/star_selected.png")');
	$('.moonstar').css("background-image", 'url("/static/img/star_non_selected.png")');
	$('.daystar').css("background-image", 'url("/static/img/star_non_selected.png")');
}

function mouseOverStar2(){
	$('.deathstar').css("background-image", 'url("/static/img/star_selected.png")');
	$('.moonstar').css("background-image", 'url("/static/img/star_selected.png")');
	$('.daystar').css("background-image", 'url("/static/img/star_non_selected.png")');
}

function mouseOverStar3(){
	$('.deathstar').css("background-image", 'url("/static/img/star_selected.png")');
	$('.moonstar').css("background-image", 'url("/static/img/star_selected.png")');
	$('.daystar').css("background-image", 'url("/static/img/star_selected.png")');
}

function mouseClick1() {
	window.event.preventDefault();
	window.event.stopPropagation();
	var clickedEntityId = $('#entityIdSpan').text();
	goToNextVideo();
	$.ajax({
		type: "GET",
		url: "/rate/" + clickedEntityId + "/1"
	})
}

function mouseClick2() {
	window.event.preventDefault();
	window.event.stopPropagation();
	var clickedEntityId = $('#entityIdSpan').text();
	goToNextVideo();
	$.ajax({
		type: "GET",
		url: "/rate/" + clickedEntityId + "/2"
	})
}

function mouseClick3() {
	window.event.preventDefault();
	window.event.stopPropagation();
	var clickedEntityId = $('#entityIdSpan').text();
	goToNextVideo();
	$.ajax({
		type: "GET",
		url: "/rate/" + clickedEntityId + "/3"
	})
}

function onXClick(){
	window.event.preventDefault();
	window.event.stopPropagation();
	$('.video-container').css("z-index", "-1");
	videoPlayer.pause();
	zoomOut();
}

function onZoomXClick(){
	window.event.preventDefault();
	window.event.stopPropagation();
	var content = $('.close_zoom_x');
	content.css({opacity: 1.0, visibility: "visible"}).animate({opacity: 0}, 20);

	zoomOut();
}

function zoomHalfTo(a, showStars)
{
	var indexX = $(a).index();
	var indexY = $(a).parent().parent().index(".popular-news");

	if(indexX == currentIndexX && indexY == currentIndexY
	   && isHalfZoomed)
	{
		showVideo(a);
		return;
	}

	isHalfZoomed = true;
	isFullZoomed = false;

	var zoomFactor = 1170.0 / teaserWidth;
	zoomTo(a, zoomFactor, zielX, zielY);

	if(showStars)
	{
		if(!$(a).hasClass("showStars"))
		{
			$(a).addClass("showStars");
		}
		$(a).removeClass("showDescription");
	}
	else
	{
		$(a).removeClass("showStars");
		if(!$(a).hasClass("showDescription"))
		{
			$(a).addClass("showDescription");
		}
	}

	var content = $('.close_zoom_x');
	content.css({opacity: 1.0, visibility: "visible"}).animate({opacity: 1}, 20);

	$("#zoomed-move-left").css("display", "block");
	adjustZoomedArrowVisible();
}

function zoomFullTo(a)
{
	var zoomFactor = 1920.0 / teaserWidth;
	zoomTo(a, zoomFactor, 0, 0);

	$(".popular-news .items a").removeClass("showStars");
	$(".popular-news .items a").removeClass("showDescription");

	isHalfZoomed = false;
	isFullZoomed = true;
	$("#zoomed-move-left").css("display", "none");

}

function zoomTo(a, zoomFactor, destX, destY)
{
	var indexX = $(a).index();
	var indexY = $(a).parent().parent().index(".popular-news");

	currentIndexX = indexX;
	currentIndexY = indexY;

	if(indexX != currentColumn[indexY])
	{
		currentColumn[indexY] = indexX;
		adjustColumn($(a).parent().parent());
	}

	$("main .zoomer").css("transform-origin", "" + getOffsetX(indexX, destX, zoomFactor) + "px " + (getOffsetY(indexY, destY, zoomFactor) - currentScrollOffset) + "px");
	$("main .categories-container").css("margin-top", "-" + getMarginY(indexY) + "px");
	$("main .zoomer").css("transform", "scale(" + zoomFactor + ")");

	if(!$("main").hasClass("zoom")) {
		$("main").addClass("zoom");
	}
	else
	{
		if(!$("main").hasClass("withOrigin")) {
			$("main").addClass("withOrigin");
		}
	}
}

function zoomOut()
{
	if($("main").hasClass("zoom")) {
		$("main").removeClass("zoom");
		$("main .categories-container").css("margin-top", "0px");
		$("main .zoomer").css("transform", "scale(1)");
	}
	$(".popular-news .items a").removeClass("showStars");
	$(".popular-news .items a").removeClass("showDescription");
	isHalfZoomed = false;
	isFullZoomed = false;
	$("#zoomed-move-left").css("display", "none");
}

function adjustColumn(jQueryElement)
{
	var indexY = jQueryElement.index(".popular-news");
	jQueryElement.find(".items").css("margin-left", (-currentColumn[indexY] * (teaserWidth + teaserMargin)) + "px");
	jQueryElement.parent().find(".move-left").css("opacity", currentColumn[indexY] > 0 ? 1 : 0);
	adjustZoomedArrowVisible();
}

function adjustZoomedArrowVisible()
{
	$("#zoomed-move-left").css("opacity", currentColumn[currentIndexY] > 0 ? 1 : 0);
}

function getStartY(indexY) {
	return (indexY*(teaserHeight+teaserMargin)) + baseOffsetY + currentScrollOffset;
}

function getMarginY(indexY) {
	return indexY*zielHeightAndMargin;
}

function getOffsetX(indexX, destX, zoomFactor) {
	return (destX - (baseOffsetX*zoomFactor)) / (1-zoomFactor);
}

function getOffsetY(indexY, destY, zoomFactor) {
	return (destY - (getStartY(indexY)*zoomFactor)) / (1-zoomFactor);
}

$(document).ready(function(){
    $(window).bind('mousewheel DOMMouseScroll', function(event){
	    if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) {
	    	scollUp();
	    }
	    else {
	    	scrollDown();
	    }
	});
    maxScrollOffset = - ($(".around-popular").size()*(teaserHeight+teaserMargin)) - baseOffsetY + 1080;
});

function scollUp() {
	if($("main").hasClass("zoom") || currentScrollOffset >= 0) {
		return;
	}
    $(".zoomer").css("top", $(".zoomer").position().top + scrollOffset);
    $(".categories-container").css("top", $(".categories-container").position().top + scrollOffset);
    currentScrollOffset += scrollOffset;
    scrollHeadlineFading();
}

function scrollDown() {
	if($("main").hasClass("zoom") || currentScrollOffset <= maxScrollOffset) {
		return;
	}
    $(".zoomer").css("top", $(".zoomer").position().top - scrollOffset);
    $(".categories-container").css("top", $(".categories-container").position().top - scrollOffset);
    currentScrollOffset -= scrollOffset;
    scrollHeadlineFading();
}

function scrollHeadlineFading() {
    if(currentScrollOffset >= -80 && currentScrollOffset <= 0) {
    	$(".titleContainer").css("opacity", ((currentScrollOffset+80)/80));
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="430dp"
        android:fillViewport="true">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <ListView
                android:id="@+id/listview_contact_list"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
            <TextView
                android:id="@+id/textview_empty_list"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAlignment="center"
                android:layout_marginTop="40dp"
                android:gravity="center"
                android:textSize="20dp"
                android:text="표시할 내용이 없습니다"
                android:visibility="visible"/>
        </RelativeLayout>

    </ScrollView>
</LinearLayout>


text:
import React from "react";
import ReactDom from 'react-dom';
import {connect, Provider} from 'react-redux';
import { pickHeader } from "../isomorphic/pick-header";

const Loading = () =>
Loading..

class ThemerBase extends React.Component {
  state = {
    component: Loading
  }

  getHeaderTheme = props => {
    const headerTheme = props.qt.config["theme-attributes"]["header_theme"];
    pickHeader(headerTheme).then(component => {
      this.setState({ component: component.default })
    });
  }

  componentDidMount() {
    this.getHeaderTheme(this.props);
  }

  componentWillReceiveProps(newProps) {
    this.getHeaderTheme(newProps);
  }

  render() {
    const Component = this.state.component;
    return <Component {...this.props}/>;
  }
}

function mapStateToProps(state) {
  return state;
}

export const HeaderThemer = connect(mapStateToProps, () => ({}))(ThemerBase);


text:
require 'mailjet/connection'
require 'mailjet/resource'
require 'active_support/hash_with_indifferent_access'
require 'active_support/core_ext/class'
require 'active_support/core_ext/string'
require 'active_support/core_ext/module/delegation'
require 'active_support/concern'
require 'active_support/json/decoding'

# This option automatically transforms the date output by the API into something a bit more readable.
# Setting this option to 'true' -- or having it at all -- may effect a users app by globally implementing this
# date transformation feature which may not be desired by the developer for whatever reason.
#
# ActiveSupport.parse_json_times = false

module Mailjet
  module Resource
    extend ActiveSupport::Concern

    included do
      cattr_accessor :resource_path, :public_operations, :read_only, :filters, :properties, :action, :non_json_urls
      cattr_writer :connection

      def self.connection
        @non_json_urls = ["v3/send/message"] #urls that don't accept JSON input
        class_variable_get(:@@connection) || default_connection
      end

      def self.default_connection
        Mailjet::Connection.new(
          "#{Mailjet.config.end_point}/#{resource_path}",
          Mailjet.config.api_key,
          Mailjet.config.secret_key,
          public_operations: public_operations,
          read_only: read_only)
      end

      def self.default_headers
        if @non_json_urls.include?(self.resource_path)#don't use JSON if Send API
          default_headers = { accept: :json, accept_encoding: :deflate }
        else
          default_headers = { accept: :json, accept_encoding: :deflate, content_type: :json } #use JSON if *not* Send API
        end
        return default_headers.merge(user_agent: "mailjet-api-v3-ruby/#{Gem.loaded_specs["mailjet"].version}")
      end
    end

    module ClassMethods
      def first(params = {})
        all(params.merge!(limit: 1)).first
      end

      def all(params = {})
        params = format_params(params)
        attribute_array = parse_api_json(connection.get(default_headers.merge(params: params)))
        attribute_array.map{ |attributes| instanciate_from_api(attributes) }
      end

      def count
        response_json = connection.get(default_headers.merge(params: {limit: 1, countrecords: 1}))
        response_hash = ActiveSupport::JSON.decode(response_json)
        response_hash['Total']
      end

      def find(id, job_id = nil)
         # if action method, ammend url to appropriate id
         self.resource_path = create_action_resource_path(id, job_id) if self.action
         #
        attributes = parse_api_json(connection[id].get(default_headers)).first
        instanciate_from_api(attributes)
      rescue Mailjet::ApiError => e
        if e.code == 404
          nil
        else
          raise e
        end
      end

      def create(attributes = {})
         # if action method, ammend url to appropriate id
         self.resource_path = create_action_resource_path(attributes[:id]) if self.action
         #
        self.new(attributes).tap do |resource|
          resource.save!
          resource.persisted = true
        end
      end

      def delete(id)
         # if action method, ammend url to appropriate id
         self.resource_path = create_action_resource_path(id) if self.action
         #
        connection[id].delete(default_headers)
      end

      def instanciate_from_api(attributes = {})
        self.new(attributes.merge(persisted: true))
      end

      def parse_api_json(response_json)
        response_hash = ActiveSupport::JSON.decode(response_json)
        #Take the response from the API and put it through a method -- taken from the ActiveSupport library -- which converts
        #the date-time from "2014-05-19T15:31:09Z" to "Mon, 19 May 2014 15:31:09 +0000" format.
        response_hash = convert_dates_from(response_hash)
        #
        #
        response_data_array = response_hash['Data']
        response_data_array.map{ |response_data| underscore_keys(response_data) }
      end

      def create_action_resource_path(id, job_id = nil)
         url_elements = self.resource_path.split("/")
         url_elements.delete_at(url_elements.length-1) if url_elements.last.to_i > 0 #if there is a trailing number for the job id from last call, delete it
         if self.action != "managemanycontacts" || (self.action == "managemanycontacts" && url_elements[2] == "contactslist")
           url_elements[3] = id.to_s
        end
         url_elements << job_id.to_s if job_id #if job_id exists, ammend it to end of the URI
         url = url_elements.join("/")
         return url
      end

      # Method -- taken from the ActiveSupport library -- which converts the date-time from
      #"2014-05-19T15:31:09Z" to "Mon, 19 May 2014 15:31:09 +0000" format.
      #We may have to change this in the future if ActiveSupport's JSON implementation changes
      def convert_dates_from(data)
        case data
        when nil
          nil
       when /^(?:\d{4}-\d{2}-\d{2}|\d{4}-\d{1,2}-\d{1,2}[T \t]+\d{1,2}:\d{2}:\d{2}(\.[0-9]*)?(([ \t]*)Z|[-+]\d{2}?(:\d{2})?))$/
          begin
            DateTime.parse(data)
          rescue ArgumentError
            data
          end
        when Array
          data.map! { |d| convert_dates_from(d) }
        when Hash
          data.each do |key, value|
            data[key] = convert_dates_from(value)
          end
        else
          data
        end
      end

      def format_params(params)
        if params[:sort]
          params[:sort] = params[:sort].map do |attribute, direction|
            attribute = attribute.to_s.camelcase
            direction = direction.to_s.upcase
            "#{attribute} #{direction}"
          end.join(', ')
        end
        params
      end

      def camelcase_keys(hash)
        map_keys(hash, :camelcase)
      end

      def underscore_keys(hash)
        map_keys(hash, :underscore)
      end

      def map_keys(hash, method)
        hash.inject({}) do |_hash, (key, value)|
          new_key = key.to_s.send(method)
          _hash[new_key] = value
          _hash
        end
      end
    end

    attr_accessor :attributes, :persisted

    def initialize(_attributes = nil)
      @attributes = ActiveSupport::HashWithIndifferentAccess.new(_attributes.reverse_merge(persisted: false))
    end

    def persisted?
      attributes[:persisted]
    end

    def save
      if persisted?
        response = connection[id].put(formatted_payload, default_headers)
      else
        response = connection.post(formatted_payload, default_headers)
      end

      self.attributes = parse_api_json(response).first
      return true
    rescue Mailjet::ApiError => e
      if e.code.to_s == "304"
        return true # When you save a record twice it should not raise error
      else
        raise e
      end
    end

    def save!
      save || raise(StandardError.new("Resource not persisted"))
    end

    def attributes=(attribute_hash = {})
      attribute_hash.each do |attribute_name, value|
        self.send("#{attribute_name}=", value)
      end
    end

    def update_attributes(attribute_hash = {})
      self.attributes = attribute_hash
      save
    end

    def delete
      self.class.delete(id)
    end

    private

    def connection
      self.class.connection
    end

    def default_headers
      self.class.default_headers
    end

    def formatted_payload
      payload = attributes.reject { |k,v| v.blank? }
      payload = payload.slice(*properties)
      payload = camelcase_keys(payload)
      payload.inject({}) do |h, (k, v)|
        v = v.utc.as_json if v.respond_to? :utc
        h.merge!({k => v})
      end
    end

    def camelcase_keys(hash)
      self.class.camelcase_keys(hash)
    end

    def underscore_keys(hash)
      self.class.underscore_keys(hash)
    end

    def parse_api_json(response_json)
      self.class.parse_api_json(response_json)
    end

    #my code!
    def convert_dates_from(data)
      self.class.convert_dates_from(data)
    end
    #end my code

    def method_missing(method_symbol, *arguments) #:nodoc:
      method_name = method_symbol.to_s

      if method_name =~ /(=|\?)$/
        case $1
        when "="
          attributes[$`] = arguments.first
        when "?"
          attributes[$`]
        end
      else
        return attributes[method_name] if attributes.include?(method_name)
        # not set right now but we know about it
        # return nil if known_attributes.include?(method_name)
        super
      end
    end
  end
end


text:
struct ComponentSpace {
	ComponentSpace(unsigned nelements);

	__device__ unsigned numberOfElements();
	__device__ unsigned numberOfComponents();
	__device__ bool isBoss(unsigned element);
	__device__ unsigned find(unsigned lelement, bool compresspath = true);
	__device__ bool unify(unsigned one, unsigned two);
	__device__ void print1x1();
	__host__   void print();
        __host__   void copy(ComponentSpace &two);
        void dump_to_file(const char *F);
	void allocate();
	void init();
	unsigned numberOfComponentsHost();

	unsigned nelements;
	unsigned *ncomponents,			// number of components.
		 *complen, 			// lengths of components.
		 *ele2comp;			// components of elements.
};
ComponentSpace::ComponentSpace(unsigned nelements) {
	this->nelements = nelements;

	allocate();
	init();
}

void ComponentSpace::dump_to_file(const char *F)
{
  static FILE *f;
  static unsigned *mem;

  if(!f)
    {
      f = fopen(F, "w");
      mem = (unsigned *) calloc(nelements, sizeof(unsigned));
    }

  assert(cudaMemcpy(mem, ele2comp, nelements * sizeof(unsigned), cudaMemcpyDeviceToHost) == cudaSuccess);

  int i;
  for(i = 0; i < nelements; i++)
    {
      fprintf(f, "%d %d\n", i, mem[i]);
    }
  fprintf(f, "\n");
}

void ComponentSpace::copy(ComponentSpace &two)
{
  assert(cudaMemcpy(two.ncomponents, ncomponents, sizeof(unsigned), cudaMemcpyDeviceToDevice) == 0);
  assert(cudaMemcpy(two.ele2comp, ele2comp, sizeof(unsigned) * nelements, cudaMemcpyDeviceToDevice) == 0);
  assert(cudaMemcpy(two.complen, complen, sizeof(unsigned) * nelements, cudaMemcpyDeviceToDevice) == 0);
}
__device__ void ComponentSpace::print1x1() {
	printf("\t\t-----------------\n");
	for (unsigned ii = 0; ii < nelements; ++ii) {
		printf("\t\t%d -> %d\n", ii, ele2comp[ii]);
	}
	printf("\t\t-----------------\n");
}
__global__ void print1x1(ComponentSpace cs) {
	cs.print1x1();
}
__host__ void ComponentSpace::print() {
        __set_CUDAConfig(1, 1);
	//::print1x1<<<1,1>>>(*this);
	::print1x1(*this);
	CudaTest("cs.print1x1 failed");
}
__device__ unsigned ComponentSpace::numberOfElements() {
	return nelements;
}
__device__ unsigned ComponentSpace::numberOfComponents() {
	return *ncomponents;
}
unsigned ComponentSpace::numberOfComponentsHost() {
	unsigned hncomponents = 0;
	cudaMemcpy(&hncomponents, ncomponents, sizeof(unsigned), cudaMemcpyDeviceToHost);
	return hncomponents;
}
void ComponentSpace::allocate() {
	if (cudaMalloc((void **)&ncomponents, 1 * sizeof(unsigned)) != cudaSuccess)
		CudaTest("allocating ncomponents failed");
	if (cudaMalloc((void **)&complen, nelements * sizeof(unsigned)) != cudaSuccess)
		CudaTest("allocating complen failed");
	if (cudaMalloc((void **)&ele2comp, nelements * sizeof(unsigned)) != cudaSuccess)
		CudaTest("allocating ele2comp failed");
}
__global__ void dinitcs(unsigned nelements, unsigned *complen, unsigned *ele2comp) {
	unsigned id = blockIdx.x * blockDim.x + threadIdx.x;
	if (id < nelements) {
		//elements[id] 	= id;
		complen[id]	= 1;
		ele2comp[id]	= id;
	}
}
void ComponentSpace::init() {
	// init the elements.
	unsigned blocksize = MAXBLOCKSIZE;	////
	unsigned nblocks = (nelements + blocksize - 1) / blocksize;
	//dinitcs<<<nblocks, blocksize>>>(nelements, complen, ele2comp);
        __set_CUDAConfig(nblocks, blocksize);
	dinitcs(nelements, complen, ele2comp);
	CudaTest("dinitcs failed");

	// init number of components.
	cudaMemcpy(ncomponents, &nelements, sizeof(unsigned), cudaMemcpyHostToDevice);
}
__device__ bool ComponentSpace::isBoss(unsigned element) {
  return atomicCAS(&ele2comp[element],element,element) == element;
}
__device__ unsigned ComponentSpace::find(unsigned lelement, bool compresspath/*= true*/) {
	// do we need to worry about concurrency in this function?
	// for other finds, no synchronization necessary as the data-structure is a tree.
	// for other unifys, synchornization is not required considering that unify is going to affect only bosses, while find is going to affect only non-bosses.
	unsigned element = lelement;
	while (isBoss(element) == false) {
	  element = ele2comp[element];
	}
	if (compresspath) ele2comp[lelement] = element;	// path compression.
	return element;
}
__device__ bool ComponentSpace::unify(unsigned one, unsigned two) {
	// if the client makes sure that one component is going to get unified as a source with another destination only once, then synchronization is unnecessary.
	// while this is true for MST, due to load-balancing in if-block below, a node may be source multiple times.
	// if a component is source in one thread and destination is another, then it is okay for MST.
    do {
      if(!isBoss(one)) return false;
      if(!isBoss(two)) return false;

      unsigned onecomp = one;
      unsigned twocomp = two;
      //unsigned onecomp = find(one, false);
      //unsigned twocomp = find(two, false);

      if (onecomp == twocomp) return false; // "duplicate" edges due to symmetry

	unsigned boss = twocomp;
	unsigned subordinate = onecomp;
	//if (complen[onecomp] > complen[twocomp]) {	// one is larger, make it the representative: can create cycles.
	if (boss < subordinate) {			// break cycles by id.
		boss = onecomp;
		subordinate = twocomp;
	}
	// merge subordinate into the boss.
	//ele2comp[subordinate] = boss;

	unsigned oldboss = atomicCAS(&ele2comp[subordinate], subordinate, boss);
	if (oldboss != subordinate) {	// someone else updated the boss.
		// we need not restore the ele2comp[subordinate], as union-find ensures correctness and complen of subordinate doesn't matter.
		one = oldboss;
		two = boss;
		return false;
	} else {
		dprintf("\t\tunifying %d -> %d (%d)\n", subordinate, boss);
		atomicAdd(&complen[boss], complen[subordinate]);
		//complen[boss] += complen[subordinate];
		// complen[subordinate] doesn't matter now, since find() will find its boss.

		// a component has reduced.
		unsigned ncomp = atomicSub(ncomponents, 1);
		//atomicDec(ncomponents, nelements);
		dprintf("\t%d: ncomponents = %d\n", threadIdx.x, ncomp);
		return true;
	}
    } while (true);
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<title>Mesquite FAQ</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

                  Introduction

                  Why?

                  How to Cite

                  Publication

                  Support

                  Credits

                  Help

                  FAQ

                  Web Site

                Files

                Menus

                Windows

				Charts

                Scripts/Macros

                Modules

				How

                Characters

                Taxa

                Trees

                Glossary

New

                  Features

Table of

			       Contents

			  Character

			      Evolution

			  Diversification

			  Molecular

			      Data

			  Gene trees

			  Simulations &

			      Randomizations

			  Continuous

			      Characters

			  Use with

			      Other Programs

			  Studies

Mesquite FAQ

How do I find the most parsimonious
			tree in Mesquite?

How do I show the length of a tree?

How do I trace a character on a tree?

How do I analyze population structure using
			Slatkin & Maddison's s statistic?

How do I create a
			publication-quality tree?

How do I find the most parsimonious tree in Mesquite?

Mesquite is not designed for rigorous tree searches, but it can perform NNI and SPR tree searches.
				To search for the most parsimonious tree(s) for a character matrix, select Taxa&Trees >
				Make New Trees Block from > Tree Search > Heuristic (Add & rearrange).  If you have more
				than one block of taxa in the file, you will be asked to choose the block of taxa you would like to perform a
				tree search for.  Select "Treelength" as the criterion for the tree search.  Select "Current
				Parsimony Models" as the source of current parsimony models.  You have two options for the rearranger
				to use: NNI or SPR.  NNI (Nearest-Neighbor Interchange) generally produces a tree faster than SPR (Subtree
				Pruning and Regrafting), but NNI has a greater chance of failing to find the most parsimonious tree(s) than
				SPR.  You will be prompted to set the maximum number of equally good trees to store during search (MAXTREES).
				Increasing MAXTREES will result in an increase in search times, accompanied by a greater probability of
				finding the most parsimonious trees (and lower settings of MAXTREES will result in quicker, but less
				thorough treesearches).  If multiple character matrices (for the Taxa block you are performing a tree search
				for) are included in the file, you will be prompted to choose the character matrix to use for the tree
				search.  Once the tree search is complete, you will be asked if you would like to open a window to view the
				trees.

How do I show the length of a tree?

Begin by opening a New Tree Window for the tree you are interested in.  From this tree window, select
				Analysis > Tree Legend... Choose "Treelength" as the information to be displayed
				in tree legend.  Select "Current Parsimony Models" as the source of current parsimony models.
				If multiple character matrices (for the Taxa block you measuring Tree Length for) are included in the file, you
				will be prompted to choose the character matrix to use for the tree length.  The tree length will shown in
				the legend that opens in the tree window.

How do I trace a character on a tree?

Tracing the evolution of a character is not entirely trivial, and depends on a variety of choices
				you make, including which characters to trace, the method of character reconstruction (e.g.,
                parsimony,
				likelihood,
                stochastic character mapping), etc.  Here
				we provide brief instructions on reconstructing a single character on a tree, but we encourage you
				to read more about the details of Tracing Character History.

Begin by opening a New Tree Window for the tree you are interested in.  From this tree window, select
				Analysis > Trace Character History and "Stored Characters" as
				the source of characters to reconstruct.   (If you have "Use Stored Characters/Matrices by Default" turned on in the Defaults submenu if the File menu, Mesquite won't ask you and will simply use Stored Characters.) You will then be prompted to choose the reconstruction method.
				Parsimony models can reconstruct ancestral states for continuous and categorical data, including molecular data,
				while Likelihood and Stochastic Character Mapping methods can currently only be used for (non-molecular)
				categorical data.  If you are using Likelihood or Stochastic Character Mapping as the reconstruction
				method, select "Current Probability Models" as the source of current probability models.  If
				multiple character matrices are included in the file, you will be prompted to choose the character matrix
				to use as the source of characters to trace (Note: Mesquite will provide a list of
				all the character matrices for the corresponding Taxa block, including those for which models of
				character evolution are not currently available in Mesquite; e.g. even if you have selected
				"Likelihood" as the Character Mapping method, molecular and continuous Character Matrices, if they are
				present in the file, will be listed.).  Choose the desired character matrix, and the first character will be
				traced on the tree.  To scroll between characters, use the arrow on the Trace Character legend.  For
				molecular and Categorical characters, you can change the colors of character states by double-clicking
				on the colored box in the Trace Character legend.  Default colors for character states can be restored by
				selecting Trace > Revert to Default Colors

Additional information on the tools found in the Trace menu can be found
				in the Mesquite manual under the Trace Character History section.

How do I analyze population structure using Slatkin & Maddison's s statistic?

We strongly urge you to read about population genetic tools in Mesquite, especially the section
				containing an example using Slatkin & Maddison's
				s statistic to test hypotheses concerning divergence times.  There is also a
				guide which provides basic step-by-step instructions
				on performing this type of analysis.  Additionally, the paper describing the statistic (Slatkin &
				Maddison, 1989, Genetics 123:603-613) is highly recommended reading.

How do I create a publication-quality tree?

Mesquite is not designed for rigorous tree-estimation procedures, such a Maximum Parsimony, Maximum
				Likelihood, or Bayesian tree estimation.  However, trees generated from programs such as PAUP, PHYLIP,
				and MrBayes can be read into and manipulated in Mesquite.  This guide to producing quality trees will help you perform these
				manipulations to create a tree suitable for scientific publication.

Mesquite
              Home Page | Mesquite
              Manual

Copyright
                © 2002-2007 by Wayne
                P. Maddison and David
                R. Maddison.

 All rights reserved.


text:
var Rx = require('./rx').default;

var addEventListenerObs = Rx.Observable.bindCallback(window.addEventListener);

module.exports = {
	hasInlineState: () => location.search.match(/^\?inline/) && window.opener,
	resetInlineStateLocation: () => history.replaceState({}, 'UCSC Xena',
			location.pathname + location.search.replace(/\?inline/, '')),
	parseInlineState: message => JSON.parse(message),
	fetchInlineState: () => {
		var obs = addEventListenerObs('message')
//			.filter(({origin}) =>
//					origin.match(/^https?:\/\/(xena|genome-cancer)\.ucsc\.edu/))
			.map(({data}) => data);

		window.opener.postMessage({type: 'xenaRequestState'}, '*');
		return obs;
	}
};