text:
import React from 'react'
import { shallow } from 'enzyme'
import HeaderContent from '../HeaderContent'

it('renders without crashing', () => {
  shallow(<HeaderContent />)
})

redpajama_set_name: RedPajamaGithub


text:
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';

import Icon from './Icon';
import PaginationButton from './PaginationButton';

const Pagination = ({
  items,
  className,
  children,
  maxButtons = items,
  leftBtn,
  rightBtn,
  onSelect,
  activePage: activePageProp
}) => {
  const [activePage, setActivePage] = useState(
    activePageProp > 0 && activePageProp <= items ? activePageProp : 1
  );

  useEffect(() => {
    setActivePage(activePageProp);
  }, [activePageProp]);

  const onClick = useCallback(
    pageIdx => {
      if (pageIdx > 0 && pageIdx <= items) {
        if (onSelect) onSelect(pageIdx);
        setActivePage(pageIdx);
      }
    },
    [onSelect, items]
  );

  const renderButtons = useMemo(() => {
    if (children) return children;

    const buttonsCount = Math.min(maxButtons, items);

    const maxPos = items - buttonsCount;
    const halfButtons = parseInt(buttonsCount / 2, 10);

    let hiddenPagesBefore = activePage - halfButtons;
    if (hiddenPagesBefore > maxPos) {
      hiddenPagesBefore = maxPos + 1;
    }

    let from = Math.max(hiddenPagesBefore, 1);
    let to = Math.min(items, from + maxButtons - 1);

    const buttons = [
      <PaginationButton
        disabled={activePage === 1}
        key={'pagination-0'}
        onSelect={() => onClick(activePage - 1)}
      >
        {leftBtn}
      </PaginationButton>
    ];

    for (let i = from; i <= to; i++) {
      buttons.push(
        <PaginationButton
          active={i === activePage}
          key={`pagination-${i}`}
          onSelect={() => onClick(i)}
        >
          {i}
        </PaginationButton>
      );
    }

    buttons.push(
      <PaginationButton
        key={`pagination-${items + 1}`}
        disabled={activePage === items}
        onSelect={() => onClick(activePage + 1)}
      >
        {rightBtn}
      </PaginationButton>
    );

    return buttons;
  }, [children, maxButtons, items, activePage, onClick, leftBtn, rightBtn]);

  return
{renderButtons}
;
};

Pagination.propTypes = {
  /**
   * Number of items in the component
   */
  items: PropTypes.number.isRequired,
  /**
   * The initial activePage
   */
  activePage: PropTypes.number,
  children: PropTypes.node,
  className: PropTypes.string,
  maxButtons: PropTypes.number,
  onSelect: PropTypes.func,
  leftBtn: PropTypes.node,
  rightBtn: PropTypes.node
};

Pagination.defaultProps = {
  activePage: 1,
  items: 10,
  leftBtn: <Icon>chevron_left</Icon>,
  rightBtn: <Icon>chevron_right</Icon>
};

export default Pagination;


text:
namespace oxygine
{
    DECLARE_SMART(NativeTexture, spNativeTexture);

    struct glyph
    {
        RectF src;

        int ch;

        short sw;
        short sh;

        short offset_x;
        short offset_y;

        short advance_x;
        short advance_y;

        spNativeTexture texture;
    };

    class Font: public ObjectBase
    {
    public:
        Font();
        ~Font();

        void init(const char* name, int size, int baselineDistance, int lineHeight);

        void addGlyph(const glyph& g);
        void sortGlyphs();

        void setScale(float scale) { _scale = scale; }

        const glyph*    getGlyph(int code) const;
        int             getBaselineDistance() const;
        int             getSize() const;
        float           getScale() const;
        int             getLineHeight() const;

    protected:
        const glyph* findGlyph(int code) const;

        virtual bool loadGlyph(int code, glyph&) { return false; }

        typedef std::vector<glyph> glyphs;
        glyphs _glyphs;

        float _scale;

        int _size;
        int _baselineDistance;
        int _lineHeight;
    };
}


text:
package io.reactivex.internal.operators.nbp;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;

import org.junit.*;
import org.mockito.InOrder;

import io.reactivex.*;
import io.reactivex.NbpObservable.*;
import io.reactivex.disposables.*;
import io.reactivex.schedulers.*;
import io.reactivex.subscribers.nbp.NbpTestSubscriber;

public class NbpOnSubscribeAmbTest {

    private TestScheduler scheduler;
    private Scheduler.Worker innerScheduler;

    @Before
    public void setUp() {
        scheduler = new TestScheduler();
        innerScheduler = scheduler.createWorker();
    }

    private NbpObservable<String> createObservable(final String[] values,
            final long interval, final Throwable e) {
        return NbpObservable.create(new NbpOnSubscribe<String>() {

            @Override
            public void accept(final NbpSubscriber<? super String> NbpSubscriber) {
                CompositeDisposable parentSubscription = new CompositeDisposable();

                NbpSubscriber.onSubscribe(parentSubscription);

                long delay = interval;
                for (final String value : values) {
                    parentSubscription.add(innerScheduler.schedule(() ->
                            NbpSubscriber.onNext(value)
                    , delay, TimeUnit.MILLISECONDS));
                    delay += interval;
                }
                parentSubscription.add(innerScheduler.schedule(() -> {
                        if (e == null) {
                            NbpSubscriber.onComplete();
                        } else {
                            NbpSubscriber.onError(e);
                        }
                }, delay, TimeUnit.MILLISECONDS));
            }
        });
    }

    @Test
    public void testAmb() {
        NbpObservable<String> observable1 = createObservable(new String[] {
                "1", "11", "111", "1111" }, 2000, null);
        NbpObservable<String> observable2 = createObservable(new String[] {
                "2", "22", "222", "2222" }, 1000, null);
        NbpObservable<String> observable3 = createObservable(new String[] {
                "3", "33", "333", "3333" }, 3000, null);

        NbpObservable<String> o = NbpObservable.amb(observable1,
                observable2, observable3);

        NbpSubscriber<String> NbpObserver = TestHelper.mockNbpSubscriber();
        o.subscribe(NbpObserver);

        scheduler.advanceTimeBy(100000, TimeUnit.MILLISECONDS);

        InOrder inOrder = inOrder(NbpObserver);
        inOrder.verify(NbpObserver, times(1)).onNext("2");
        inOrder.verify(NbpObserver, times(1)).onNext("22");
        inOrder.verify(NbpObserver, times(1)).onNext("222");
        inOrder.verify(NbpObserver, times(1)).onNext("2222");
        inOrder.verify(NbpObserver, times(1)).onComplete();
        inOrder.verifyNoMoreInteractions();
    }

    @Test
    public void testAmb2() {
        IOException expectedException = new IOException(
                "fake exception");
        NbpObservable<String> observable1 = createObservable(new String[] {},
                2000, new IOException("fake exception"));
        NbpObservable<String> observable2 = createObservable(new String[] {
                "2", "22", "222", "2222" }, 1000, expectedException);
        NbpObservable<String> observable3 = createObservable(new String[] {},
                3000, new IOException("fake exception"));

        NbpObservable<String> o = NbpObservable.amb(observable1,
                observable2, observable3);

        NbpSubscriber<String> NbpObserver = TestHelper.mockNbpSubscriber();
        o.subscribe(NbpObserver);

        scheduler.advanceTimeBy(100000, TimeUnit.MILLISECONDS);

        InOrder inOrder = inOrder(NbpObserver);
        inOrder.verify(NbpObserver, times(1)).onNext("2");
        inOrder.verify(NbpObserver, times(1)).onNext("22");
        inOrder.verify(NbpObserver, times(1)).onNext("222");
        inOrder.verify(NbpObserver, times(1)).onNext("2222");
        inOrder.verify(NbpObserver, times(1)).onError(expectedException);
        inOrder.verifyNoMoreInteractions();
    }

    @Test
    public void testAmb3() {
        NbpObservable<String> observable1 = createObservable(new String[] {
                "1" }, 2000, null);
        NbpObservable<String> observable2 = createObservable(new String[] {},
                1000, null);
        NbpObservable<String> observable3 = createObservable(new String[] {
                "3" }, 3000, null);

        NbpObservable<String> o = NbpObservable.amb(observable1,
                observable2, observable3);

        NbpSubscriber<String> NbpObserver = TestHelper.mockNbpSubscriber();
        o.subscribe(NbpObserver);

        scheduler.advanceTimeBy(100000, TimeUnit.MILLISECONDS);
        InOrder inOrder = inOrder(NbpObserver);
        inOrder.verify(NbpObserver, times(1)).onComplete();
        inOrder.verifyNoMoreInteractions();
    }

    @Test
    public void testSubscriptionOnlyHappensOnce() throws InterruptedException {
        final AtomicLong count = new AtomicLong();
        Consumer<Disposable> incrementer = s -> count.incrementAndGet();

        //this aync stream should emit first
        NbpObservable<Integer> o1 = NbpObservable.just(1).doOnSubscribe(incrementer)
                .delay(100, TimeUnit.MILLISECONDS).subscribeOn(Schedulers.computation());
        //this stream emits second
        NbpObservable<Integer> o2 = NbpObservable.just(1).doOnSubscribe(incrementer)
                .delay(100, TimeUnit.MILLISECONDS).subscribeOn(Schedulers.computation());
        NbpTestSubscriber<Integer> ts = new NbpTestSubscriber<>();
        NbpObservable.amb(o1, o2).subscribe(ts);
        ts.awaitTerminalEvent(5, TimeUnit.SECONDS);
        ts.assertNoErrors();
        assertEquals(2, count.get());
    }

    @Test
    public void testSynchronousSources() {
        // under async subscription the second NbpObservable would complete before
        // the first but because this is a synchronous subscription to sources
        // then second NbpObservable does not get subscribed to before first
        // subscription completes hence first NbpObservable emits result through
        // amb
        int result = NbpObservable.just(1).doOnNext(t -> {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    //
                }
        }).ambWith(NbpObservable.just(2)).toBlocking().single();
        assertEquals(1, result);
    }

}


text:
'use strict';

/*
 * Create an address, then send a postcard with a custom PDF back.
 * Run me! This example works out of the box, "batteries included".
 */

const fs = require('fs');

const lobFactory = require('../lib/index.js');
// this key is publicly available in the legacy docs, so it's hardcoded
// since the templates are associated with this dummy account
// you can replace this key with your own, and the IDs below with any
// saved templates you have
const Lob = new lobFactory('test_0dc8d51e0acffcb1880e0f19c79b2f5b0cc');

const file = fs.readFileSync(`${__dirname}/html/card.html`).toString();

// Create the address
Lob.addresses.create({
  name: 'Robin Joseph',
  email: 'test@gmail.com',
  phone: '123456789',
  address_line1: '123 Test Street',
  address_line2: 'Unit 199',
  address_city: 'Chicago',
  address_state: 'IL',
  address_zip: '60012',
  address_country: 'US'
}, (err, address) => {
  if (err) {
    console.log(err);
  } else {
    Lob.postcards.create({
      description: 'My Second Postcard',
      to: address.id,
      // you can replace these template IDs
      front: 'tmpl_b846a20859ae11a',
      back: 'tmpl_01b0d396a10c268',
      merge_variables: {
        name: 'Robin'
      }
    }, (err, postcard) => {
      if (err) {
        console.log(err);
      } else {
        console.log('The Lob API responded with this postcard object: ', postcard);
      }
    });
  }
});


text:
using System;
using Newtonsoft.Json;

namespace TCC2.API.Groups
{
    [JsonObject(MemberSerialization = MemberSerialization.OptIn)]
    public class SetGroupResult : ApiCallResult
    {
        [JsonProperty(PropertyName = "groupId")]
        public string GroupId { get; protected set; }

        protected override void ValidateInstance(IRequestDataProvider provider)
        {
            base.ValidateInstance(provider);

            const string displayName = "group ID";
            ValidateHasValue(GroupId, displayName);
            ValidateValueMatchesInputParam(GroupId, provider, "groupid", displayName);
        }
    }
}


text:
from django.db.models.signals import post_save
from django.dispatch import receiver
from website.models import Wedding, Section
from django.conf import settings

@receiver(post_save, sender=Wedding, dispatch_uid="website.wedding.created")
def wedding_created(sender, instance, **kwargs):

    if kwargs.get("created", False) == True:

    	for section, enabled in settings.WEDDING_SECTIONS:
    		Section.objects.create(wedding = instance, headline=section, enabled=enabled)


text:
import React, { Component } from "react";
import { xor, concat } from "lodash";
import PropTypes from "prop-types";
import { View, ART, Dimensions } from "react-native";
import * as scale from "d3-scale";
import * as shape from "d3-shape";
import * as d3Array from "d3-array";

import gps from "../../../store/services/helpers/gps";
import styles from "./styles";
import {
  ELEVATION_COLORS,
  ELEVATION_GRADE
} from "../../../store/constants/elevation";

const { Surface, Shape } = ART;
const d3 = {
  scale,
  shape,
  d3Array
};

// TODO: how? where? what?
const getRange = percent => {
  if (Math.abs(percent) < 5) {
    return ELEVATION_GRADE.SMALL;
  } else if (Math.abs(percent) >= 5 && Math.abs(percent) < 7) {
    return ELEVATION_GRADE.EASY;
  } else if (Math.abs(percent) >= 7 && Math.abs(percent) < 10) {
    return ELEVATION_GRADE.MEDIUM;
  } else if (Math.abs(percent) >= 10 && Math.abs(percent) < 15) {
    return ELEVATION_GRADE.DIFFICULT;
  } else if (Math.abs(percent) >= 15) {
    return ELEVATION_GRADE.HARD;
  }
  return ELEVATION_GRADE.UNKNOWN;
};

// eslint-disable-next-line no-extend-native
Array.prototype.groupBy = function(fn) {
  return this.reduce((accu, item, index, array) => {
    const key = fn(item, item, array);
    // eslint-disable-next-line no-param-reassign
    accu[key] = accu[key] || [];
    accu[key].push(item);
    return accu;
  }, {});
};

export default class ElevationProfile extends Component {
  static propTypes = {
    path: PropTypes.shape({
      edges: PropTypes.arrayOf(
        PropTypes.shape({
          src: PropTypes.shape({
            longitude: PropTypes.number,
            latitude: PropTypes.number,
            altitude: PropTypes.number
          }),
          dest: PropTypes.shape({
            longitude: PropTypes.number,
            latitude: PropTypes.number,
            altitude: PropTypes.number
          }),
          length: PropTypes.number
        })
      )
    }).isRequired
  };

  static createXScale(start, end, rangeWidth) {
    return d3.scale
      .scaleLinear()
      .domain([start, end])
      .range([0, rangeWidth]);
  }

  static createYScale(minY, maxY, rangeHeight) {
    return (
      d3.scale
        .scaleLinear()
        .domain([minY, maxY])
        // We invert our range so it outputs using the axis that React uses.
        .range([rangeHeight, 0])
    );
  }

  static createColorScale() {
    return d3.scale
      .scaleThreshold()
      .domain([1, 2, 3, 4])
      .range([
        ELEVATION_COLORS.SMALL,
        ELEVATION_COLORS.EASY,
        ELEVATION_COLORS.MEDIUM,
        ELEVATION_COLORS.DIFFICULT,
        ELEVATION_COLORS.HARD
      ]);
  }

  static createAxis(edges, graphWidth, graphHeight) {
    const totalDistance = edges[edges.length - 1].distanceDone;
    const intervalBetweenCheckPoints = 10;
    const totalCheckPoints = Math.floor(
      totalDistance / intervalBetweenCheckPoints
    );

    const checkPoints = [];
    for (let i = 0; i <= totalCheckPoints; i += 1) {
      checkPoints.push(intervalBetweenCheckPoints * i);
    }

    const ticksIndices = gps.getCheckpointsIndices(checkPoints, 0.1, ...edges);
    const AxisData = ticksIndices.map(tickIndex => edges[tickIndex]);
    // TODO: draw line dans ta face!

    const scaleX = ElevationProfile.createXScale(0, edges.length, graphWidth);
    const scaleY = ElevationProfile.createYScale(0, 0, graphHeight);

    const lineShape = d3.shape
      .line()
      // For every x and y-point in our line shape we are given an item from our
      // array which we pass through our scale function so we map the domain value
      // to the range value.
      .x(d => scaleX(d.index))
      .y(scaleY(0));

    return {
      // Pass in our array of data to our line generator to produce the `d={}`
      // attribute value that will go into our `<Shape />` component.
      path: lineShape(AxisData)
    };
  }

  static createAreaGraph(edges, graphWidth, graphHeight) {
    const groupedEdgesByRange = edges.groupBy(item => getRange(item.percent));

    // eslint-disable-next-line
    const data = Object.entries(groupedEdgesByRange).map(([grade, section]) => {
      const indices = section.map(item => item.index);
      const missingValueIndices = xor(
        Array.from(Array(edges.length).keys()),
        indices
      );
      const fakeData = missingValueIndices.map(item => ({
        index: item,
        fake: true
      }));
      return concat(section, fakeData).sort((a, b) => a.index - b.index);
    });

    // Create our x-scale.
    const scaleX = ElevationProfile.createXScale(0, edges.length, graphWidth);

    const colorScale = ElevationProfile.createColorScale();

    // Collect all y values.
    const altitudes = edges.map(location => location.src.altitude);

    // Get the min and max y value.
    const extentY = d3Array.extent(altitudes);

    // Create our y-scale.
    const scaleY = ElevationProfile.createYScale(0, extentY[1], graphHeight);

    return Object.entries(data).map(([grade, section]) => {
      const areaShape = d3.shape
        .area()
        // For every x and y-point in our line shape we are given an item from our
        // array which we pass through our scale function so we map the domain value
        // to the range value.
        .x(d => scaleX(d.index))
        .y1(d => scaleY(d.src.altitude))
        .y0(extentY[1])
        .defined(d => !d.fake)
        .curve(d3.shape.curveLinear);

      return {
        path: areaShape(section),
        color: colorScale(grade)
      };
    });
  }

  render() {
    const { path } = this.props;
    const { width } = Dimensions.get("window");

    const areas = ElevationProfile.createAreaGraph(path.edges, width, 100);

    return (
      <View style={styles.container}>
        <Surface width={width} height={100}>
          {areas.map(area => (
            <Shape
              d={area.path}
              stroke={area.color}
              fill={area.color}
              strokeWidth={0.15}
            />
          ))}
        </Surface>
      </View>
    );
  }
}


text:
package com.opengamma.strata.math.impl.interpolation;

import static org.testng.Assert.assertEquals;

import java.util.function.Function;

import org.testng.annotations.Test;

import com.opengamma.strata.collect.array.DoubleMatrix;
import com.opengamma.strata.math.impl.function.DoubleFunction1D;
import com.opengamma.strata.math.impl.function.RealPolynomialFunction1D;
import com.opengamma.strata.math.impl.regression.LeastSquaresRegressionResult;
import com.opengamma.strata.math.impl.statistics.descriptive.MeanCalculator;
import com.opengamma.strata.math.impl.statistics.descriptive.SampleStandardDeviationCalculator;

/**
 * Test.
 */
@Test
public class PolynomialsLeastSquaresFitterTest {
  private static final double EPS = 1e-14;

  private final Function<double[], Double> _meanCal = new MeanCalculator();
  private final Function<double[], Double> _stdCal = new SampleStandardDeviationCalculator();

  /**
   * Checks coefficients of polynomial f(x) are recovered and residuals, { y_i -f(x_i) }, are accurate
   */
  public void PolynomialFunctionRecoverTest() {

    final PolynomialsLeastSquaresFitter regObj = new PolynomialsLeastSquaresFitter();
    final double[] coeff = new double[] {3.4, 5.6, 1., -4. };

    DoubleFunction1D func = new RealPolynomialFunction1D(coeff);

    final int degree = coeff.length - 1;

    final int nPts = 7;
    double[] xValues = new double[nPts];
    double[] yValues = new double[nPts];

    for (int i = 0; i < nPts; ++i) {
      xValues[i] = -5. + 10 * i / (nPts - 1);
      yValues[i] = func.applyAsDouble(xValues[i]);
    }

    double[] yValuesNorm = new double[nPts];

    final double mean = _meanCal.apply(xValues);
    final double std = _stdCal.apply(xValues);
    final double ratio = mean / std;

    for (int i = 0; i < nPts; ++i) {
      final double tmp = xValues[i] / std - ratio;
      yValuesNorm[i] = func.applyAsDouble(tmp);
    }

    /**
     * Tests for regress(..)
     */

    LeastSquaresRegressionResult result = regObj.regress(xValues, yValues, degree);

    double[] coeffResult = result.getBetas();

    for (int i = 0; i < degree + 1; ++i) {
      assertEquals(coeff[i], coeffResult[i], EPS * Math.abs(coeff[i]));
    }

    final double[] residuals = result.getResiduals();
    func = new RealPolynomialFunction1D(coeffResult);
    double[] yValuesFit = new double[nPts];
    for (int i = 0; i < nPts; ++i) {
      yValuesFit[i] = func.applyAsDouble(xValues[i]);
    }

    for (int i = 0; i < nPts; ++i) {
      assertEquals(Math.abs(yValuesFit[i] - yValues[i]), 0., Math.abs(yValues[i]) * EPS);
    }

    for (int i = 0; i < nPts; ++i) {
      assertEquals(Math.abs(yValuesFit[i] - yValues[i]), Math.abs(residuals[i]), Math.abs(yValues[i]) * EPS);
    }

    double sum = 0.;
    for (int i = 0; i < nPts; ++i) {
      sum += residuals[i] * residuals[i];
    }
    sum = Math.sqrt(sum);

    /**
     * Tests for regressVerbose(.., false)
     */

    PolynomialsLeastSquaresFitterResult resultVer = regObj.regressVerbose(xValues, yValues, degree, false);
    coeffResult = resultVer.getCoeff();
    func = new RealPolynomialFunction1D(coeffResult);
    for (int i = 0; i < nPts; ++i) {
      yValuesFit[i] = func.applyAsDouble(xValues[i]);
    }

    assertEquals(nPts - (degree + 1), resultVer.getDof(), 0);
    for (int i = 0; i < degree + 1; ++i) {
      assertEquals(coeff[i], coeffResult[i], EPS * Math.abs(coeff[i]));
    }

    for (int i = 0; i < nPts; ++i) {
      assertEquals(Math.abs(yValuesFit[i] - yValues[i]), 0., Math.abs(yValues[i]) * EPS);
    }

    assertEquals(sum, resultVer.getDiffNorm(), EPS);

    /**
     * Tests for regressVerbose(.., true)
     */

    PolynomialsLeastSquaresFitterResult resultNorm = regObj.regressVerbose(xValues, yValuesNorm, degree, true);

    coeffResult = resultNorm.getCoeff();
    final double[] meanAndStd = resultNorm.getMeanAndStd();

    assertEquals(nPts - (degree + 1), resultNorm.getDof(), 0);
    assertEquals(mean, meanAndStd[0], EPS);
    assertEquals(std, meanAndStd[1], EPS);
    for (int i = 0; i < degree + 1; ++i) {
      assertEquals(coeff[i], coeffResult[i], EPS * Math.abs(coeff[i]));
    }

    func = new RealPolynomialFunction1D(coeffResult);
    for (int i = 0; i < nPts; ++i) {
      final double tmp = xValues[i] / std - ratio;
      yValuesFit[i] = func.applyAsDouble(tmp);
    }

    for (int i = 0; i < nPts; ++i) {
      assertEquals(Math.abs(yValuesFit[i] - yValuesNorm[i]), 0., Math.abs(yValuesNorm[i]) * EPS);
    }

    sum = 0.;
    for (int i = 0; i < nPts; ++i) {
      sum += (yValuesFit[i] - yValuesNorm[i]) * (yValuesFit[i] - yValuesNorm[i]);
    }
    sum = Math.sqrt(sum);

    assertEquals(sum, resultNorm.getDiffNorm(), EPS);

  }

  /**
   *
   */
  public void RmatrixTest() {

    final PolynomialsLeastSquaresFitter regObj1 = new PolynomialsLeastSquaresFitter();
    final double[] xValues = new double[] {-1., 0, 1. };
    final double[] yValues = new double[] {1., 0, 1. };
    final double[][] rMatrix = new double[][] {
        {-Math.sqrt(3.), 0., -2. / Math.sqrt(3.)},
        {0., -Math.sqrt(2.), 0.},
        {0., 0., -Math.sqrt(2. / 3.)}
    };

    final int degree = 2;

    PolynomialsLeastSquaresFitterResult resultVer = regObj1.regressVerbose(xValues, yValues, degree, false);
    DoubleMatrix rMatResult = resultVer.getRMat();

    for (int i = 0; i < 3; ++i) {
      for (int j = 0; j < 3; ++j) {
        assertEquals(rMatrix[i][j], rMatResult.get(i, j), EPS);
      }
    }

    final PolynomialsLeastSquaresFitter regObj2 = new PolynomialsLeastSquaresFitter();
    PolynomialsLeastSquaresFitterResult resultNorm = regObj2.regressVerbose(xValues, yValues, degree, true);
    rMatResult = resultNorm.getRMat();

    for (int i = 0; i < 3; ++i) {
      for (int j = 0; j < 3; ++j) {
        assertEquals(rMatrix[i][j], rMatResult.get(i, j), EPS);
      }
    }

  }

  /**
   * An error is thrown if rescaling of xValues is NOT used and we try to access data, mean and standard deviation
   */
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void NormalisationErrorTest() {

    final PolynomialsLeastSquaresFitter regObj = new PolynomialsLeastSquaresFitter();

    final int degree = 4;

    final double[] xValues = new double[] {0, 1, 2, 3, 5, 6 };
    final double[] yValues = new double[] {1, 2, 3, 4, 2, 1 };

    PolynomialsLeastSquaresFitterResult result = regObj.regressVerbose(xValues, yValues, degree, false);
    result.getMeanAndStd();

  }

  /**
   * Number of data points should be larger than (degree + 1) of a polynomial
   */
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void DataShortTest() {

    final PolynomialsLeastSquaresFitter regObj = new PolynomialsLeastSquaresFitter();

    final int degree = 6;

    final double[] xValues = new double[] {0, 1, 2, 3, 5, 6 };
    final double[] yValues = new double[] {1, 2, 3, 4, 2, 1 };

    regObj.regress(xValues, yValues, degree);

  }

  /**
   *
   */
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void DataShortVerboseFalseTest() {

    final PolynomialsLeastSquaresFitter regObj = new PolynomialsLeastSquaresFitter();

    final int degree = 6;

    final double[] xValues = new double[] {0, 1, 2, 3, 5, 6 };
    final double[] yValues = new double[] {1, 2, 3, 4, 2, 1 };

    regObj.regressVerbose(xValues, yValues, degree, false);

  }

  /**
   *
   */
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void DataShortVerboseTrueTest() {

    final PolynomialsLeastSquaresFitter regObj = new PolynomialsLeastSquaresFitter();

    final int degree = 6;

    final double[] xValues = new double[] {0, 1, 2, 3, 5, 6 };
    final double[] yValues = new double[] {1, 2, 3, 4, 2, 1 };

    regObj.regressVerbose(xValues, yValues, degree, true);

  }

  /**
   * Degree of polynomial must be positive
   */
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void MinusDegreeTest() {

    final PolynomialsLeastSquaresFitter regObj = new PolynomialsLeastSquaresFitter();

    final int degree = -4;

    final double[] xValues = new double[] {0, 1, 2, 3, 5, 6 };
    final double[] yValues = new double[] {1, 2, 3, 4, 2, 1 };

    regObj.regress(xValues, yValues, degree);

  }

  /**
   *
   */
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void MinusDegreeVerboseFalseTest() {

    final PolynomialsLeastSquaresFitter regObj = new PolynomialsLeastSquaresFitter();

    final int degree = -4;

    final double[] xValues = new double[] {0, 1, 2, 3, 5, 6 };
    final double[] yValues = new double[] {1, 2, 3, 4, 2, 1 };

    regObj.regressVerbose(xValues, yValues, degree, false);

  }

  /**
   *
   */
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void MinusDegreeVerboseTrueTest() {

    final PolynomialsLeastSquaresFitter regObj = new PolynomialsLeastSquaresFitter();

    final int degree = -4;

    final double[] xValues = new double[] {0, 1, 2, 3, 5, 6 };
    final double[] yValues = new double[] {1, 2, 3, 4, 2, 1 };

    regObj.regressVerbose(xValues, yValues, degree, true);

  }

  /**
   * xValues length should be the same as yValues length
   */
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void WrongDataLengthTest() {

    final PolynomialsLeastSquaresFitter regObj = new PolynomialsLeastSquaresFitter();

    final int degree = 4;

    final double[] xValues = new double[] {0, 1, 2, 3, 5, 6 };
    final double[] yValues = new double[] {1, 2, 3, 4, 2, 1, 2 };

    regObj.regress(xValues, yValues, degree);

  }

  /**
   *
   */
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void WrongDataLengthVerboseFalseTest() {

    final PolynomialsLeastSquaresFitter regObj = new PolynomialsLeastSquaresFitter();

    final int degree = 4;

    final double[] xValues = new double[] {0, 1, 2, 3, 5, 6 };
    final double[] yValues = new double[] {1, 2, 3, 4, 2, 1, 2 };

    regObj.regressVerbose(xValues, yValues, degree, false);

  }

  /**
   *
   */
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void WrongDataLengthVerboseTureTest() {

    final PolynomialsLeastSquaresFitter regObj = new PolynomialsLeastSquaresFitter();

    final int degree = 4;

    final double[] xValues = new double[] {0, 1, 2, 3, 5, 6 };
    final double[] yValues = new double[] {1, 2, 3, 4, 2, 1, 2 };

    regObj.regressVerbose(xValues, yValues, degree, true);

  }

  /**
   * An error is thrown if too many repeated data are found
   */
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void RepeatDataTest() {

    final PolynomialsLeastSquaresFitter regObj = new PolynomialsLeastSquaresFitter();

    final int degree = 4;

    final double[] xValues = new double[] {0, 1, 2, 3, 1, 1 };
    final double[] yValues = new double[] {1, 2, 3, 4, 2, 2 };

    regObj.regress(xValues, yValues, degree);

  }

  /**
   *
   */
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void RepeatDataVerboseFalseTest() {

    final PolynomialsLeastSquaresFitter regObj = new PolynomialsLeastSquaresFitter();

    final int degree = 4;

    final double[] xValues = new double[] {0, 1, 2, 3, 1, 1 };
    final double[] yValues = new double[] {1, 2, 3, 4, 2, 2 };

    regObj.regressVerbose(xValues, yValues, degree, false);

  }

  /**
   *
   */
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void RepeatDataVerboseTrueTest() {

    final PolynomialsLeastSquaresFitter regObj = new PolynomialsLeastSquaresFitter();

    final int degree = 4;

    final double[] xValues = new double[] {0, 1, 2, 3, 1, 1 };
    final double[] yValues = new double[] {1, 2, 3, 4, 2, 2 };

    regObj.regressVerbose(xValues, yValues, degree, true);

  }

  /**
   *
   */
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void ExtremeValueTest() {

    final PolynomialsLeastSquaresFitter regObj = new PolynomialsLeastSquaresFitter();

    final int degree = 4;

    final double[] xValues = new double[] {0, 1e-307, 2e-307, 3e18, 4 };
    final double[] yValues = new double[] {1, 2, 3, 4, 5 };

    regObj.regress(xValues, yValues, degree);

  }

  /**
   *
   */
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void ExtremeValueVerboseFalseTest() {

    final PolynomialsLeastSquaresFitter regObj = new PolynomialsLeastSquaresFitter();

    final int degree = 4;

    final double[] xValues = new double[] {0, 1e-307, 2e-307, 3e18, 4 };
    final double[] yValues = new double[] {1, 2, 3, 4, 5 };

    regObj.regressVerbose(xValues, yValues, degree, false);

  }

  /**
   *
   */
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void ExtremeValueVerboseTrueAlphaTest() {

    final PolynomialsLeastSquaresFitter regObj = new PolynomialsLeastSquaresFitter();

    final int degree = 4;

    final double[] xValues = new double[] {0, 1e-307, 2e-307, 3e-307, 4 };
    final double[] yValues = new double[] {1, 2, 3, 4, 5 };

    regObj.regressVerbose(xValues, yValues, degree, true);

  }

  /**
   *
   */
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void NullTest() {

    final PolynomialsLeastSquaresFitter regObj = new PolynomialsLeastSquaresFitter();

    final int degree = 4;

    final int nPts = 5;
    double[] xValues = new double[nPts];
    double[] yValues = new double[nPts];

    xValues = null;
    yValues = null;

    regObj.regress(xValues, yValues, degree);

  }

  /**
   *
   */
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void NullVerboseFalseTest() {

    final PolynomialsLeastSquaresFitter regObj = new PolynomialsLeastSquaresFitter();

    final int degree = 4;

    final int nPts = 5;
    double[] xValues = new double[nPts];
    double[] yValues = new double[nPts];

    xValues = null;
    yValues = null;

    regObj.regressVerbose(xValues, yValues, degree, false);

  }

  /**
   *
   */
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void NullVerboseTrueTest() {

    final PolynomialsLeastSquaresFitter regObj = new PolynomialsLeastSquaresFitter();

    final int degree = 4;

    final int nPts = 5;
    double[] xValues = new double[nPts];
    double[] yValues = new double[nPts];

    xValues = null;
    yValues = null;

    regObj.regressVerbose(xValues, yValues, degree, true);

  }

  /**
   *
   */
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void InfinityTest() {

    final PolynomialsLeastSquaresFitter regObj = new PolynomialsLeastSquaresFitter();

    final int degree = 4;

    final int nPts = 5;
    double[] xValues = new double[nPts];
    double[] yValues = new double[nPts];

    final double zero = 0.;

    for (int i = 0; i < nPts; ++i) {
      xValues[i] = 1. / zero;
      yValues[i] = 1. / zero;
    }

    regObj.regress(xValues, yValues, degree);

  }

  /**
   *
   */
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void InfinityVerboseFalseTest() {

    final PolynomialsLeastSquaresFitter regObj = new PolynomialsLeastSquaresFitter();

    final int degree = 4;

    final int nPts = 5;
    double[] xValues = new double[nPts];
    double[] yValues = new double[nPts];

    final double zero = 0.;

    for (int i = 0; i < nPts; ++i) {
      xValues[i] = 1. / zero;
      yValues[i] = 1. / zero;
    }

    regObj.regressVerbose(xValues, yValues, degree, false);

  }

  /**
   *
   */
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void InfinityVerboseTrueTest() {

    final PolynomialsLeastSquaresFitter regObj = new PolynomialsLeastSquaresFitter();

    final int degree = 4;

    final int nPts = 5;
    double[] xValues = new double[nPts];
    double[] yValues = new double[nPts];

    final double zero = 0.;

    for (int i = 0; i < nPts; ++i) {
      xValues[i] = 1. / zero;
      yValues[i] = 1. / zero;
    }

    regObj.regressVerbose(xValues, yValues, degree, true);

  }

  /**
   *
   */
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void NaNTest() {

    final PolynomialsLeastSquaresFitter regObj = new PolynomialsLeastSquaresFitter();

    final int degree = 4;

    final int nPts = 5;
    double[] xValues = new double[nPts];
    double[] yValues = new double[nPts];

    for (int i = 0; i < nPts; ++i) {
      xValues[i] = Double.NaN;
      yValues[i] = Double.NaN;
    }

    regObj.regress(xValues, yValues, degree);

  }

  /**
   *
   */
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void NaNVerboseFalseTest() {

    final PolynomialsLeastSquaresFitter regObj = new PolynomialsLeastSquaresFitter();

    final int degree = 4;

    final int nPts = 5;
    double[] xValues = new double[nPts];
    double[] yValues = new double[nPts];

    for (int i = 0; i < nPts; ++i) {
      xValues[i] = Double.NaN;
      yValues[i] = Double.NaN;
    }

    regObj.regressVerbose(xValues, yValues, degree, false);

  }

  /**
   *
   */
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void NaNVerboseTrueTest() {

    final PolynomialsLeastSquaresFitter regObj = new PolynomialsLeastSquaresFitter();

    final int degree = 4;

    final int nPts = 5;
    double[] xValues = new double[nPts];
    double[] yValues = new double[nPts];

    for (int i = 0; i < nPts; ++i) {
      xValues[i] = Double.NaN;
      yValues[i] = Double.NaN;
    }

    regObj.regressVerbose(xValues, yValues, degree, true);

  }

  /**
   *
   */
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void LargeNumberTest() {

    final PolynomialsLeastSquaresFitter regObj = new PolynomialsLeastSquaresFitter();

    final int degree = 4;

    double[] xValues = new double[] {1, 2, 3, 4e2, 5, 6, 7 };
    double[] yValues = new double[] {1, 2, 3, 4, 5, 6, 7 };

    regObj.regress(xValues, yValues, degree);

  }

  /**
   *
   */
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void LargeNumberVerboseFalseTest() {

    final PolynomialsLeastSquaresFitter regObj = new PolynomialsLeastSquaresFitter();

    final int degree = 4;

    double[] xValues = new double[] {1, 2, 3, 4e2, 5, 6, 7 };
    double[] yValues = new double[] {1, 2, 3, 4, 5, 6, 7 };

    regObj.regressVerbose(xValues, yValues, degree, false);

  }

  /**
   *
   */
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void LargeNumberVerboseTrueTest() {

    final PolynomialsLeastSquaresFitter regObj = new PolynomialsLeastSquaresFitter();

    final int degree = 6;

    double[] xValues = new double[] {1, 2, 3, 4e17, 5, 6, 7 };
    double[] yValues = new double[] {1, 2, 3, 4, 5, 6, 7 };

    regObj.regressVerbose(xValues, yValues, degree, true);

  }

}


text:
importScripts('cache-polyfill.js');

var CACHE_NAME = 'reader-v1',
    urls = [
        '/reader/',
        '/reader/index.html',
        '/reader/assets/build/reader.min.js',
        '/reader/assets/build/styles.css'
    ];

self.addEventListener('install', function (event) {
    event.waitUntil(
        caches.open(CACHE_NAME).then(function (cache) {
            return cache.addAll(urls).then(function () {
                console.log('Resources are cached.');
            });
        }).catch(function (error) {
            console.error('Install failed:', error);
        })
    );
});

self.addEventListener('activate', function (event) {
    event.waitUntil(
        caches.keys().then(function(cacheNames) {
            return Promise.all(
                cacheNames.map(function(cacheName) {
                    if (cacheName !== CACHE_NAME) {
                        return caches.delete(cacheName);
                    }
                })
            );
        })
    );
});

self.addEventListener('fetch', function (event) {
    event.respondWith(
        caches.match(event.request)
            .then(function (response) {
                var fetchRequest;

                if (response) {
                    console.log('Response:', response);
                    return response;
                }
                fetchRequest = event.request.clone();

                return fetch(fetchRequest).then(
                    function (response) {
                        var responseToCache;

                        if (!response || response.status !== 200 || response.type !== 'basic') {
                            return response;
                        }
                        responseToCache = response.clone();
                        caches.open(CACHE_NAME).then(function (cache) {
                            cache.put(event.request, responseToCache);
                        }).catch(function (error) {
                            console.error('Fetch failed:', error);
                        });

                        return response;
                    }
                ).catch(function () {
                    console.log('Fetch failed:', error);
                });
            })
    );
});


text:
#region License
//  Copyright 2015-2021 John Källén
//
//  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.
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Pytocs.Core.CodeModel
{
    public class CodeArrayIndexerExpression : CodeExpression
    {
        public CodeArrayIndexerExpression(CodeExpression exp, CodeExpression[] indices)
        {
            this.TargetObject = exp;
            this.Indices = indices;
        }

        public CodeExpression TargetObject { get; set; }
        public CodeExpression[] Indices { get; set; }

        public override void Accept(ICodeExpressionVisitor visitor)
        {
            visitor.VisitArrayIndexer(this);
        }

        public override T Accept<T>(ICodeExpressionVisitor<T> visitor)
        {
            return visitor.VisitArrayIndexer(this);
        }
    }
}


text:
#include "./weighted_l1-inl.h"

namespace mxnet {
namespace op {
template<>
Operator *CreateOp<cpu>(WeightedL1Param param) {
  return new WeightedL1Op<cpu>(param);
}

Operator *WeightedL1Prop::CreateOperator(Context ctx) const {
  DO_BIND_DISPATCH(CreateOp, param_);
}

DMLC_REGISTER_PARAMETER(WeightedL1Param);

MXNET_REGISTER_OP_PROPERTY(WeightedL1, WeightedL1Prop)
.describe("Perform a L1 loss with mask on input.")
.add_argument("data", "Symbol", "L1 loss with mask.")
.add_arguments(WeightedL1Param::__FIELDS__());

}  // namespace op
}  // namespace mxnet


text:
#include <inttypes.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>

#include "scion.h"

uint16_t scmp_checksum(uint8_t *buf)
{
    chk_input *input = mk_chk_input(6);
    SCMPL4Header *scmp_l4;
    uint8_t l4_type;
    uint16_t payload_len, ret, blank_sum = 0;

    // Address header (without padding)
    chk_add_chunk(input, buf + DST_IA_OFFSET, get_addrs_len(buf));

    uint8_t *ptr = buf;
    l4_type = get_l4_proto(&ptr);
    scmp_l4 = (SCMPL4Header *)ptr;
    // L4 protocol type
    chk_add_chunk(input, &l4_type, 1);
    // SCMP class, type & length
    ptr = chk_add_chunk(input, ptr, 6);
    // Use blank checksum field
    chk_add_chunk(input, (uint8_t *)(&blank_sum), 2);
    ptr += 2;
    // SCMP Timestamp
    ptr = chk_add_chunk(input, ptr, 8);
    // Length in SCMP header includes header size, so subtract it.
    payload_len = ntohs(scmp_l4->len) - sizeof(SCMPL4Header);
    chk_add_chunk(input, ptr, payload_len);

    ret = checksum(input);
    rm_chk_input(input);
    return ret;
}

void update_scmp_checksum(uint8_t *buf)
{
    SCMPL4Header *scmp_hdr = (SCMPL4Header *)buf;
    get_l4_proto((uint8_t **)&scmp_hdr);
    scmp_hdr->checksum = scmp_checksum(buf);
}

/*
 * Parse the scmp payload.
 * scmp_hdr: Pointer to the start of the SCMP L4 header in the packet.
 * return value: a newly allocated SCMPPayload structure, with all fields
 *               either pointing to the relevant part of the packet, or NULL if
 *               not present.
 */
SCMPPayload *scmp_parse_payload(SCMPL4Header *scmp_hdr) {
    SCMPPayload *pld = (SCMPPayload *)malloc(sizeof(SCMPPayload));
    void *ptr = scmp_hdr + 1;
    pld->meta = (SCMPMetaHeader *)ptr;
    ptr = pld->meta + 1;
    pld->info = pld->meta->info_len ? ptr : NULL;
    ptr += pld->meta->info_len * LINE_LEN;
    pld->cmnhdr = pld->meta->cmnhdr_len ? ptr : NULL;
    ptr += pld->meta->cmnhdr_len * LINE_LEN;
    pld->addr = pld->meta->addr_len ? ptr : NULL;
    ptr += pld->meta->addr_len * LINE_LEN;
    pld->path = pld->meta->path_len ? ptr : NULL;
    ptr += pld->meta->path_len * LINE_LEN;
    pld->exts = pld->meta->exts_len ? ptr : NULL;
    ptr += pld->meta->exts_len * LINE_LEN;
    pld->l4hdr = pld->meta->l4_len ? ptr : NULL;
    return pld;
}


text:
import unittest

from ctree.c.nodes import *
from ctree.transformations import PyBasicConversions
import ast

class TestUnaryOps(unittest.TestCase):
    def setUp(self):
        self.foo = SymbolRef("foo")

    def _check(self, op_cls, expected_string):
        node = op_cls(self.foo)
        self.assertEqual(str(node), expected_string)

    def test_plus(self):
        self._check(Add, "+ foo")

    def test_minus(self):
        self._check(Sub, "- foo")

    def test_bitnot(self):
        self._check(BitNot, "~ foo")

    def test_not(self):
        self._check(Not, "! foo")

    def test_ref(self):
        self._check(Ref, "& foo")

    def test_deref(self):
        self._check(Deref, "* foo")

    def test_preinc(self):
        self._check(PreInc, "++ foo")

    def test_predec(self):
        self._check(PreDec, "-- foo")

    def test_postinc(self):
        self._check(PostInc, "foo ++")

    def test_postdec(self):
        self._check(PostDec, "foo --")

    def test_sizeof(self):
        self._check(SizeOf, "sizeof foo")

class TestPyBasicConversionsUnaryOps(unittest.TestCase):
    def _check(self, op, expected_string):
        self.assertEqual(str(op), expected_string)

    def test_plus(self):
        op = ast.parse("+ foo")
        op = PyBasicConversions().visit(op).find(UnaryOp)
        self._check(op, "+ foo")

    def test_minus(self):
        op = ast.parse("- foo")
        op = PyBasicConversions().visit(op).find(UnaryOp)
        self._check(op, "- foo")

    def test_bitnot(self):
        op = ast.parse("~ foo")
        op = PyBasicConversions().visit(op).find(UnaryOp)
        self._check(op, "~ foo")

    def test_not(self):
        op = ast.parse("not foo")
        op = PyBasicConversions().visit(op).find(UnaryOp)
        self._check(op, "! foo")

    def test_CUnaryOp(self):
        op = Not(SymbolRef("foo"))
        op = PyBasicConversions().visit(op).find(UnaryOp)
        self._check(str(op), "! foo")


text:
.. _blockchain_filler:

=================================
Blockchain Tests Source Code
=================================
Location: `/src/BlockchainTestsFiller
<https://github.com/ethereum/tests/tree/develop/src/BlockchainTestsFiller>`_

Blockchain tests can include multiple blocks and each of those blocks can include
multiple transactions. These blocks can be either valid or invalid.

Subfolders
==========

================= ========================================
InvalidBlocks     Tests containing blocks that are expected to fail on import
ValidBlocks       Normal blockchain tests
TransitionTests   Blockchain tests with exotic network rules switching forks at block #5
================= ========================================

.. bc_src:
.. include:: ../test_filler/test_src.rst

.. _bc_struct:
.. include:: ../test_filler/test_structure.rst

.. _struct_bc_genesis:
.. include:: ../test_filler/test_genesis.rst

.. _struct_bc_pre:
.. include:: ../test_filler/test_pre.rst

.. _struct_bc_blocks:
.. include:: ../test_filler/test_blocks.rst

.. _struct_bc_transaction:
.. include:: ../test_filler/test_transaction_blockchain.rst

.. _struct_bc_expect:
.. include:: ../test_filler/test_expect_blockchain.rst


text:
This concludes the Sonic Pi introductory tutorial. Hopefully you've learned something along the way. Don't worry if you feel you didn't understand everything - just play and have fun and you'll pick things up along the way. Feel free to dive back in when you have a question that might be covered in one of the sections.

If you have any questions that haven't been covered in the tutorial, then please jump onto the Sonic Pi forums http://groups.google.com/group/sonic-pi/ and ask your question there. You'll find someone friendly and willing to lend a hand.

Finally, I also invite you to take a deeper look at the rest of the documentation in this help system. There are a number of features that haven't been covered in this tutorial that are waiting for your discovery.

So, play, have fun, share your code, perform for your friends and remember:

*There are no mistakes, only opportunities*

Sam Aaron


text:
package org.miod.parser;

import org.miod.parser.generated.MiodParserBaseVisitor;
import org.miod.program.errors.CompilerError;
import org.miod.program.errors.CompilerWarning;
import org.miod.program.symbol_table.SymbolLocation;

/** Methods return true to continue parsing.
 *
 * @author yur
 */
public interface ErrorListener {

    boolean hasErrors();
    void onError(CompilerError e);
    void onWarning(CompilerWarning w);
    void onUnknownIdentifier(MiodParserBaseVisitor visitor, String name, SymbolLocation loc);
    /*
    void onUnknownIdentifier(String name, SymLocation loc);
    void onTypeMismatch(SymLocation loc);
    void onRedeclaration(String name, SymLocation loc);
    void onSyntaxError(String msg);
    */
}


text:
#ifndef APOC_VIDEO_STANDARD_RENDER_HANDLER_H
#define APOC_VIDEO_STANDARD_RENDER_HANDLER_H

#include <Apoc/Video/RenderHandler.h>
#include <Apoc/Math/Matrix.h>

/**
 * \brief The standard render handler.
 */
class StandardRenderHandler : public RenderHandler
{
private:
	Vector ambient;

	GLuint shadowFramebuffer;
	GLuint shadowTex;

	GLuint renderProgram;
	ShaderArray<RenderHandler::PointLight> *pointLightArray;
	ShaderArray<RenderHandler::DirLight> *dirLightArray;
	ShaderArray<RenderHandler::SpotLight> *spotLightArray;
	Matrix lightMatrix;

	// default textures
	GLuint defImageTex;
	GLuint defSpecularMap;
	GLuint defNormalMap;
	GLuint defIllumMap;
	GLuint defWarpMap;

	int screenWidth, screenHeight;

	// fog
	Vector fogColor;
	float fogDensity;

	int debugMode;

public:
	/**
	 * \brief Standard render params.
	 */
	struct RenderParams
	{

	};

	StandardRenderHandler(int screenWidth, int screenHeight);
	virtual void render();
	virtual void getAttrLocations(GLint &attrVertex, GLint &attrTexCoords, GLint &attrNormal);
	virtual GLint getUniformLocation(const char *name);
	virtual GLint getAttrLocation(const char *name);
	virtual void bindProgram();
	virtual ShaderArray<PointLight> *getPointLightArray();
	virtual ShaderArray<DirLight> *getDirLightArray();
	virtual ShaderArray<SpotLight> *getSpotLightArray();
	virtual void bindDefaultTextures();
	virtual void setAmbientLight(Vector ambient);
	virtual void setFog(Vector color, float density);
	virtual void setDebugMode(int mode);
	virtual void setAttenuation(Vector att);
};

#endif


text:
"""Compute class and mean-per-class accuracy for CuBERT SO."""
from plur.eval.cubert_classification_eval import CuBertClassificationEval
from plur.stage_1.cubert_swapped_operand_classification_dataset import CuBertSwappedOperandClassificationDataset

class CuBertSwappedOperandClassificationEval(CuBertClassificationEval):
  """Eval class for CuBERT SO dataset."""

  def __init__(self,
               prediction_file: str,
               target_file: str,
               top_n: int = 1) -> None:
    """As per superclass."""
    assert top_n == 1
    super().__init__(
        prediction_file=prediction_file,
        target_file=target_file,
        all_classes=CuBertSwappedOperandClassificationDataset.ALL_CLASSES,
        top_n=top_n)


text:
### Welcome to the Mashshare GitHub Repository

Social sharing optimization is essential for every website that aims to be succesfull regarding traffic and social interaction.
Mashshare aspires to give you all the necessary tools for best possible sharing interaction out of your content from one source. It´s not only a set of big prominent fast loading share buttons, it optimizes your content in the background with open graph tags and optimizes all your contest in the best way to get the maximum amount of shares.

More information can be found at [mashshare.net](https://www.mashshare.net/).

## Note ##

This is the latest developer version of Mashshare.
if you just want to use Mashshare install the productive version which you get at [wordpress.org](http://wordpress.org/plugins/mashsharer/)

## Installation ##

For detailed setup instructions, visit the official [Documentation](http://www.mashshare.net/documentation/) page.

1. You can clone the GitHub repository: `https://github.com/mashshare/Mashshare.git`
2. Or download it directly as a ZIP file: `https://github.com/mashshare/Mashshare/archive/master.zip`

This will download the latest developer copy of Mashshare.

## Bugs ##
If you find an issue, let us know [here](https://github.com/mashshare/Mashshare/issues?state=open)!

## Support ##
This is a developer's portal for Mashshare and should _not_ be used for support.
Please visit the [support forums](https://www.mashshare.net/support).

## Contributions ##
Anyone is welcome to contribute to Mashshare. Please read the [guidelines for contributing](https://github.com/mashshare/Mashshare/blob/master/CONTRIBUTING.md) to this repository.

There are various ways you can contribute:

1. Raise an [Issue](https://github.com/mashshare/Mashshare/issues) on GitHub
2. Send us a Pull Request with your bug fixes and/or new features
3. Translate Mashshare into different languages
4. Provide feedback and suggestions on [enhancements](https://github.com/mashshare/Mashshare/issues?direction=desc&labels=Enhancement&page=1&sort=created&state=open)


text:
package mycompany.joglog;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Starter extends Application {

	@Override
	public void start(Stage primaryStage) throws Exception {
		Parent login = FXMLLoader.load(getClass().getResource("View.fxml"));

		Scene scene = new Scene(login);
            primaryStage.setScene(scene);
            primaryStage.show();

	}

	public static void main(String[] args) {
		launch(args);
	}

}


text:
import {__core_private__ as r} from '@angular/core';

export type ViewMetadata = typeof r._ViewMetadata;
export const ViewMetadata: typeof r.ViewMetadata = r.ViewMetadata;

import {__core_private_testing__ as r2} from '@angular/core/testing';

export type TestingCompiler = typeof r2._TestingCompiler;
export const TestingCompiler: typeof r2.TestingCompiler = r2.TestingCompiler;

export type TestingCompilerFactory = typeof r2._TestingCompilerFactory;
export const TestingCompilerFactory: typeof r2.TestingCompilerFactory = r2.TestingCompilerFactory;


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE190_Integer_Overflow__char_rand_preinc_61b.c
Label Definition File: CWE190_Integer_Overflow.label.xml
Template File: sources-sinks-61b.tmpl.c
*/
/*
 * @description
 * CWE: 190 Integer Overflow
 * BadSource: rand Set data to result of rand()
 * GoodSource: Set data to a small, non-zero number (two)
 * Sinks: increment
 *    GoodSink: Ensure there will not be an overflow before incrementing data
 *    BadSink : Increment data, which can cause an overflow
 * Flow Variant: 61 Data flow: data returned from one function to another in different source files
 *
 * */

#include "std_testcase.h"

#ifndef OMITBAD

char CWE190_Integer_Overflow__char_rand_preinc_61b_badSource(char data)
{
    /* POTENTIAL FLAW: Use a random value */
    data = (char)RAND32();
    return data;
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B() uses the GoodSource with the BadSink */
char CWE190_Integer_Overflow__char_rand_preinc_61b_goodG2BSource(char data)
{
    /* FIX: Use a small, non-zero value that will not cause an overflow in the sinks */
    data = 2;
    return data;
}

/* goodB2G() uses the BadSource with the GoodSink */
char CWE190_Integer_Overflow__char_rand_preinc_61b_goodB2GSource(char data)
{
    /* POTENTIAL FLAW: Use a random value */
    data = (char)RAND32();
    return data;
}

#endif /* OMITGOOD */


text:
/**
 * This file is part of the CernVM File System.
 */

#include <string>
#include <stack>

#include "catalog.h"
#include "util.h"
#include "download.h"
#include "logging.h"
#include "compression.h"

#include "manifest.h"
#include "manifest_fetch.h"
#include "signature.h"

namespace swissknife {

/**
 * This class traverses the complete catalog hierarchy of a CVMFS repository
 * recursively. The user can specify a callback which is called for each catalog
 * on the way.
 * We are doing a depth first, pre-order traversal here. (I.e. if you simply print
 * the catalogs in the provided order you obtain a nice catalog tree.)
 * Note: Since all CVMFS catalog files together can grow to several gigabytes in
 *       file size, each catalog is loaded, processed and removed immediately
 *       afterwards.
 *
 * CAUTION: currently the Catalog* pointer passed into the callback becomes in-
 *          valid directly after the callback method returns. Therefore you
 *          MUST NOT store it for later use.
 *
 * TODO: Use the Observable template buried in Pull Request 46 instead of imple-
 *       menting your own callback infrastructure here.
 */
template<class T>
class CatalogTraversal
{
 public:
  /**
   * Callback signature which has to be implemented by the delegate object
   * @param catalog             the catalog object which needs to be processed
   * @param catalog_hash        the SHA-1 content hash of the catalog
   * @param tree_level          the depth in the nested catalog tree
   *                            (starting at zero)
   */
  typedef void (T::*Callback)(const catalog::Catalog* catalog,
                              const hash::Any&        catalog_hash,
                              const unsigned          tree_level);

 protected:
  typedef struct CatalogJob_ {
    CatalogJob_(const std::string& path,
                const hash::Any&   hash,
                const unsigned     tree_level) :
      path(path),
      hash(hash),
      tree_level(tree_level) {}
    CatalogJob_(const catalog::Catalog::NestedCatalog& nested_catalog,
                const unsigned                         tree_level) :
      path(nested_catalog.path.ToString()),
      hash(nested_catalog.hash),
      tree_level(tree_level) {}

    const std::string path;
    const hash::Any   hash;
    const unsigned    tree_level;
  } CatalogJob;
  typedef std::stack<CatalogJob> CatalogJobStack;

 public:

  /**
   * Constructs a new catalog traversal engine.
   * @param delegate           the object to be notified when a catalog needs
   *                           to be processed
   * @param catalog_callback   a function pointer to the callback to be called
   *                           on the delegate object
   * @param repo_url           the path to the repository to be traversed:
   *                           -> either absolute path to the local catalogs
   *                           -> or an URL to a remote repository
   * @param repo_name          fully qualified repository name (used for remote
   *                           repository signature check) (optional)
   * @param repo_keys          a comma separated list of public key file
   *                           locations to verify the repository manifest file
   */
	CatalogTraversal(T*                 delegate,
                   Callback           catalog_callback,
                   const std::string& repo_url,
                   const std::string& repo_name = "",
                   const std::string& repo_keys = "") :
    delegate_(delegate),
    catalog_callback_(catalog_callback),
    repo_url_(MakeCanonicalPath(repo_url)),
    repo_name_(repo_name),
    repo_keys_(repo_keys),
    is_remote_(repo_url.substr(0, 7) == "http://")
  {
    if (is_remote_)
      download::Init(1, true);
  }

  virtual ~CatalogTraversal() {
    if (is_remote_)
      download::Fini();
  }

  /**
   * Starts the traversal process.
   * After calling this methods CatalogTraversal will go through all catalogs
   * and call the given callback method on the provided delegate object for each
   * found catalog.
   * If something goes wrong in the process, the traversal will be cancelled.
   * @return  true, when all catalogs were successfully processed. On failure
   *          the traversal is cancelled and false is returned
   */
  bool Traverse() {
    assert(catalog_callback_ != NULL);

    // get the manifest of the repository to learn about the entry point or the
    // root catalog of the repository to be traversed
    manifest::Manifest *manifest = LoadManifest();
    if (!manifest) {
      LogCvmfs(kLogCatalogTraversal, kLogStderr,
        "Failed to load manifest for repository %s", repo_name_.c_str());
      return false;
    }

    // add the root catalog of the repository as the first element on the job
    // stack
    CatalogJob job("", manifest->catalog_hash(), 0);
    catalog_stack_.push(job);

    delete manifest;

    // start the magic
    return TraverseRecursively();
  }

 protected:
  bool TraverseRecursively() {

    // the CatalogTraversal works with a stack, where new nested catalogs are
    // pushed onto while processing their parent (depth first traversal).
    // When all catalogs are processed, this stack will naturally be empty and
    // the traversal can terminate
    while(!catalog_stack_.empty())
    {
      // get the top most catalog for the next processing step
      CatalogJob job = catalog_stack_.top();
      catalog_stack_.pop();

      // process it (potentially generating new catalog jobs on the stack)
      const bool success = ProcessCatalogJob(job);
      if (!success)
        return false;
    }

    // well done
    return true;
  }

  bool ProcessCatalogJob(const CatalogJob &job) {
    // load a catalog
    std::string tmp_file;
    if (!FetchCatalog(job.hash, &tmp_file)) {
      LogCvmfs(kLogCatalogTraversal, kLogStdout, "failed to load catalog %s",
               job.hash.ToString().c_str());
      return false;
    }

    // open the catalog
    catalog::Catalog *catalog = catalog::AttachFreely(job.path, tmp_file);
    unlink(tmp_file.c_str());
    if (catalog == NULL) {
      LogCvmfs(kLogCatalogTraversal, kLogStdout, "failed to open catalog %s",
               job.hash.ToString().c_str());
      return false;
    }

    // provide the user with the catalog
    (delegate_->*catalog_callback_)(catalog, job.hash, job.tree_level);

    // Inception! Go to the next recursion level
    catalog::Catalog::NestedCatalogList *nested_catalogs =
      catalog->ListNestedCatalogs();
    for (catalog::Catalog::NestedCatalogList::const_iterator i =
         nested_catalogs->begin(), iEnd = nested_catalogs->end();
         i != iEnd; ++i)
    {
      catalog_stack_.push(CatalogJob(*i, job.tree_level + 1));
    }

    // we are done with this catalog
    delete catalog;

    // sucessfully traversed
    return true;
  }

  manifest::Manifest* LoadManifest() {
    manifest::Manifest *manifest = NULL;

    // grab manifest file
    if (!is_remote_) {
      // locally
      manifest = manifest::Manifest::LoadFile(repo_url_ + "/.cvmfspublished");

    } else {
      // remote
      const std::string url = repo_url_ + "/.cvmfspublished";

      // initialize signature module
      signature::Init();
      const bool success = signature::LoadPublicRsaKeys(repo_keys_);
      if (!success) {
        LogCvmfs(kLogCatalogTraversal, kLogStderr,
          "cvmfs public key(s) could not be loaded.");
        signature::Fini();
        return NULL;
      }

      // download manifest file
      struct manifest::ManifestEnsemble manifest_ensemble;
      manifest::Failures retval = manifest::Fetch(
                                    repo_url_,
                                    repo_name_,
                                    0,
                                    NULL,
                                    &manifest_ensemble);

      // we don't need the signature module from now on
      signature::Fini();

      // check if manifest was loaded correctly
      if (retval == manifest::kFailNameMismatch)
        LogCvmfs(kLogCatalogTraversal, kLogStderr,
          "repository name mismatch. No name provided?");
      if (retval == manifest::kFailBadSignature   ||
          retval == manifest::kFailBadCertificate ||
          retval == manifest::kFailBadWhitelist)
        LogCvmfs(kLogCatalogTraversal, kLogStderr,
          "repository signature mismatch. No key(s) provided?");

      if (retval == manifest::kFailOk)
        manifest = new manifest::Manifest(*manifest_ensemble.manifest);
    }

    return manifest;
  }

  inline bool FetchCatalog(const hash::Any& catalog_hash,
                                  std::string *catalog_file) {
    return (is_remote_) ? DownloadCatalog  (catalog_hash, catalog_file)
                        : DecompressCatalog(catalog_hash, catalog_file);
  }

  /**
   * Downloads a catalog from a remote repository and extracts it in one shot
   * @param catalog_hash   the SHA-1 hash of the catalog to be downloaded
   * @param catalog_file   output parameter for the loaded catalog file
   * @return               true, if catalog was successfully downloaded
   */
  bool DownloadCatalog(const hash::Any& catalog_hash,
                       std::string *catalog_file) {
    catalog_file->clear();

    const std::string source = "data" + catalog_hash.MakePath(1,2) + "C";
    const std::string dest = "/tmp/" + catalog_hash.ToString();
    const std::string url = repo_url_ + "/" + source;

    download::JobInfo download_catalog(&url, true, false, &dest, &catalog_hash);
    download::Failures retval = download::Fetch(&download_catalog);

    if (retval != download::kFailOk) {
      LogCvmfs(kLogCatalogTraversal, kLogStdout, "failed to download catalog %s (%d)",
             catalog_hash.ToString().c_str(), retval);
      return false;
    }

    *catalog_file = dest;
    return true;
  }

  /**
   * Decompresses a catalog that resides on local storage.
   * @param catalog_hash   the SHA-1 hash of the catalog to be extracted
   * @return               the path to the extracted catalog file
   */
  bool DecompressCatalog(const hash::Any& catalog_hash,
                         std::string *catalog_file) {
    catalog_file->clear();

    const std::string source =
      repo_url_ + "/data" + catalog_hash.MakePath(1,2) + "C";
    const std::string dest = "/tmp/" + catalog_hash.ToString();

    if (!zlib::DecompressPath2Path(source, dest))
      return false;

    *catalog_file = dest;
    return true;
  }

  /**
   * Checks if a file exists, both remotely or locally, depending on the type
   * of repository currently traversed
   * @param file   the file to be checked for existence
   * @return       true if the file exists, false otherwise
   */
  bool Exists(const std::string &file) {
    if (is_remote_) {
      download::JobInfo head(&file, false);
      return download::Fetch(&head) == download::kFailOk;
    } else {
      return FileExists(file);
    }
  }

 private:
  T                *delegate_;
  Callback          catalog_callback_;
  const std::string repo_url_;
  const std::string repo_name_;
  const std::string repo_keys_;
  const bool        is_remote_;
  CatalogJobStack   catalog_stack_;
};

}


text:
@implementation GrowlMusicVideoPrefs

- (NSString *) mainNibName {
	return @"GrowlMusicVideoPrefs";
}

- (void) mainViewDidLoad {
	[slider_opacity setAltIncrementValue:5.0];
}

- (void) didSelect {
	SYNCHRONIZE_GROWL_PREFS();
}

#pragma mark -

+ (NSColor *) loadColor:(NSString *)key defaultColor:(NSColor *)defaultColor {
	NSData *data = nil;
	NSColor *color;
	READ_GROWL_PREF_VALUE(key, GrowlMusicVideoPrefDomain, NSData *, &data);
	if(data)
		CFMakeCollectable(data);

	if (data && [data isKindOfClass:[NSData class]]) {
		color = [NSUnarchiver unarchiveObjectWithData:data];
	} else {
		color = defaultColor;
	}
	[data release];

	return color;
}

#pragma mark Accessors

- (CGFloat) duration {
	CGFloat value = GrowlMusicVideoDurationPrefDefault;
	READ_GROWL_PREF_FLOAT(MUSICVIDEO_DURATION_PREF, GrowlMusicVideoPrefDomain, &value);
	return value;
}
- (void) setDuration:(CGFloat)value {
	WRITE_GROWL_PREF_FLOAT(MUSICVIDEO_DURATION_PREF, value, GrowlMusicVideoPrefDomain);
	UPDATE_GROWL_PREFS();
}

- (unsigned) effect {
	int effect = 0;
	READ_GROWL_PREF_INT(MUSICVIDEO_EFFECT_PREF, GrowlMusicVideoPrefDomain, &effect);
	switch (effect) {
		default:
			effect = MUSICVIDEO_EFFECT_SLIDE;

		case MUSICVIDEO_EFFECT_SLIDE:
		case MUSICVIDEO_EFFECT_WIPE:
		case MUSICVIDEO_EFFECT_FADING:
			;

	}
	return (unsigned)effect;
}
- (void) setEffect:(unsigned)newEffect {
	switch (newEffect) {
		default:
			NSLog(@"(Music Video) Invalid effect number %u (slide is %u; wipe is %u)", newEffect, MUSICVIDEO_EFFECT_SLIDE, MUSICVIDEO_EFFECT_WIPE);
			break;

		case MUSICVIDEO_EFFECT_SLIDE:
		case MUSICVIDEO_EFFECT_WIPE:
		case MUSICVIDEO_EFFECT_FADING:
			WRITE_GROWL_PREF_INT(MUSICVIDEO_EFFECT_PREF, newEffect, GrowlMusicVideoPrefDomain);
			UPDATE_GROWL_PREFS();
	}
}

- (CGFloat) opacity {
	CGFloat value = MUSICVIDEO_DEFAULT_OPACITY;
	READ_GROWL_PREF_FLOAT(MUSICVIDEO_OPACITY_PREF, GrowlMusicVideoPrefDomain, &value);
	return value;
}
- (void) setOpacity:(CGFloat)value {
	WRITE_GROWL_PREF_FLOAT(MUSICVIDEO_OPACITY_PREF, value, GrowlMusicVideoPrefDomain);
	UPDATE_GROWL_PREFS();
}

- (int) size {
	int value = 0;
	READ_GROWL_PREF_INT(MUSICVIDEO_SIZE_PREF, GrowlMusicVideoPrefDomain, &value);
	return value;
}
- (void) setSize:(int)value {
	WRITE_GROWL_PREF_INT(MUSICVIDEO_SIZE_PREF, value, GrowlMusicVideoPrefDomain);
	UPDATE_GROWL_PREFS();
}

#pragma mark Combo box support

- (NSInteger) numberOfItemsInComboBox:(NSComboBox *)aComboBox {
#pragma unused(aComboBox)
	return [[NSScreen screens] count];
}

- (id) comboBox:(NSComboBox *)aComboBox objectValueForItemAtIndex:(NSInteger)idx {
#pragma unused(aComboBox)
#ifdef __LP64__
	return [NSNumber numberWithInteger:idx];
#else
	return [NSNumber numberWithInt:idx];
#endif
}

- (int) screen {
	int value = 0;
	READ_GROWL_PREF_INT(MUSICVIDEO_SCREEN_PREF, GrowlMusicVideoPrefDomain, &value);
	return value;
}
- (void) setScreen:(int)value {
	WRITE_GROWL_PREF_INT(MUSICVIDEO_SCREEN_PREF, value, GrowlMusicVideoPrefDomain);
	UPDATE_GROWL_PREFS();
}

- (NSColor *) textColorVeryLow {
	return [GrowlMusicVideoPrefs loadColor:GrowlMusicVideoVeryLowTextColor
							  defaultColor:[NSColor whiteColor]];
}

- (void) setTextColorVeryLow:(NSColor *)value {
	NSData *theData = [NSArchiver archivedDataWithRootObject:value];
    WRITE_GROWL_PREF_VALUE(GrowlMusicVideoVeryLowTextColor, theData, GrowlMusicVideoPrefDomain);
    UPDATE_GROWL_PREFS();
}

- (NSColor *) textColorModerate {
	return [GrowlMusicVideoPrefs loadColor:GrowlMusicVideoModerateTextColor
							  defaultColor:[NSColor whiteColor]];
}

- (void) setTextColorModerate:(NSColor *)value {
	NSData *theData = [NSArchiver archivedDataWithRootObject:value];
    WRITE_GROWL_PREF_VALUE(GrowlMusicVideoModerateTextColor, theData, GrowlMusicVideoPrefDomain);
    UPDATE_GROWL_PREFS();
}

- (NSColor *) textColorNormal {
	return [GrowlMusicVideoPrefs loadColor:GrowlMusicVideoNormalTextColor
							  defaultColor:[NSColor whiteColor]];
}

- (void) setTextColorNormal:(NSColor *)value {
	NSData *theData = [NSArchiver archivedDataWithRootObject:value];
    WRITE_GROWL_PREF_VALUE(GrowlMusicVideoNormalTextColor, theData, GrowlMusicVideoPrefDomain);
    UPDATE_GROWL_PREFS();
}

- (NSColor *) textColorHigh {
	return [GrowlMusicVideoPrefs loadColor:GrowlMusicVideoHighTextColor
							  defaultColor:[NSColor whiteColor]];
}

- (void) setTextColorHigh:(NSColor *)value {
	NSData *theData = [NSArchiver archivedDataWithRootObject:value];
    WRITE_GROWL_PREF_VALUE(GrowlMusicVideoHighTextColor, theData, GrowlMusicVideoPrefDomain);
    UPDATE_GROWL_PREFS();
}

- (NSColor *) textColorEmergency {
	return [GrowlMusicVideoPrefs loadColor:GrowlMusicVideoEmergencyTextColor
							  defaultColor:[NSColor whiteColor]];
}

- (void) setTextColorEmergency:(NSColor *)value {
	NSData *theData = [NSArchiver archivedDataWithRootObject:value];
    WRITE_GROWL_PREF_VALUE(GrowlMusicVideoEmergencyTextColor, theData, GrowlMusicVideoPrefDomain);
    UPDATE_GROWL_PREFS();
}

- (NSColor *) backgroundColorVeryLow {
	return [GrowlMusicVideoPrefs loadColor:GrowlMusicVideoVeryLowBackgroundColor
							  defaultColor:[NSColor blackColor]];
}

- (void) setBackgroundColorVeryLow:(NSColor *)value {
	NSData *theData = [NSArchiver archivedDataWithRootObject:value];
    WRITE_GROWL_PREF_VALUE(GrowlMusicVideoVeryLowBackgroundColor, theData, GrowlMusicVideoPrefDomain);
    UPDATE_GROWL_PREFS();
}

- (NSColor *) backgroundColorModerate {
	return [GrowlMusicVideoPrefs loadColor:GrowlMusicVideoModerateBackgroundColor
							  defaultColor:[NSColor blackColor]];
}

- (void) setBackgroundColorModerate:(NSColor *)value {
	NSData *theData = [NSArchiver archivedDataWithRootObject:value];
    WRITE_GROWL_PREF_VALUE(GrowlMusicVideoModerateBackgroundColor, theData, GrowlMusicVideoPrefDomain);
    UPDATE_GROWL_PREFS();
}

- (NSColor *) backgroundColorNormal {
	return [GrowlMusicVideoPrefs loadColor:GrowlMusicVideoNormalBackgroundColor
						 defaultColor:[NSColor blackColor]];
}

- (void) setBackgroundColorNormal:(NSColor *)value {
	NSData *theData = [NSArchiver archivedDataWithRootObject:value];
    WRITE_GROWL_PREF_VALUE(GrowlMusicVideoNormalBackgroundColor, theData, GrowlMusicVideoPrefDomain);
    UPDATE_GROWL_PREFS();
}

- (NSColor *) backgroundColorHigh {
	return [GrowlMusicVideoPrefs loadColor:GrowlMusicVideoHighBackgroundColor
							  defaultColor:[NSColor blackColor]];
}

- (void) setBackgroundColorHigh:(NSColor *)value {
	NSData *theData = [NSArchiver archivedDataWithRootObject:value];
    WRITE_GROWL_PREF_VALUE(GrowlMusicVideoHighBackgroundColor, theData, GrowlMusicVideoPrefDomain);
    UPDATE_GROWL_PREFS();
}

- (NSColor *) backgroundColorEmergency {
	return [GrowlMusicVideoPrefs loadColor:GrowlMusicVideoEmergencyBackgroundColor
							  defaultColor:[NSColor blackColor]];
}

- (void) setBackgroundColorEmergency:(NSColor *)value {
	NSData *theData = [NSArchiver archivedDataWithRootObject:value];
    WRITE_GROWL_PREF_VALUE(GrowlMusicVideoEmergencyBackgroundColor, theData, GrowlMusicVideoPrefDomain);
    UPDATE_GROWL_PREFS();
}
@end


text:
"""Utility functions for augmenting data
"""
import random
import numpy as np
import os
import scipy
import logging
from sklearn.decomposition import PCA

from yass.template import align_get_shifts_with_ref, shift_chans
from yass.geometry import order_channels_by_distance

def crop_and_align_templates(fname_templates, save_dir, CONFIG):
    """Crop (spatially) and align (temporally) templates

    Parameters
    ----------

    Returns
    -------
    """
    logger = logging.getLogger(__name__)

    if not os.path.exists(save_dir):
        os.mkdir(save_dir)

    # load templates
    templates = np.load(fname_templates)

    n_units, n_times, n_channels = templates.shape
    mcs = templates.ptp(1).argmax(1)
    spike_size = (CONFIG.spike_size_nn - 1)*2 + 1

    ########## TEMPORALLY ALIGN TEMPLATES #################

    # template on max channel only
    templates_max_channel = np.zeros((n_units, n_times))
    for k in range(n_units):
        templates_max_channel[k] = templates[k, :, mcs[k]]

    # align them
    ref = np.mean(templates_max_channel, axis=0)
    upsample_factor = 8
    nshifts = spike_size//2

    shifts = align_get_shifts_with_ref(
        templates_max_channel, ref, upsample_factor, nshifts)

    templates_aligned = shift_chans(templates, shifts)

    # crop out the edges since they have bad artifacts
    templates_aligned = templates_aligned[:, nshifts//2:-nshifts//2]

    ########## Find High Energy Center of Templates #################

    templates_max_channel_aligned = np.zeros((n_units, templates_aligned.shape[1]))
    for k in range(n_units):
        templates_max_channel_aligned[k] = templates_aligned[k, :, mcs[k]]

    # determin temporal center of templates and crop around it
    total_energy = np.sum(np.square(templates_max_channel_aligned), axis=0)
    center = np.argmax(np.convolve(total_energy, np.ones(spike_size//2), 'same'))
    templates_aligned = templates_aligned[:, (center-spike_size//2):(center+spike_size//2+1)]

    ########## spatially crop (only keep neighbors) #################

    neighbors = CONFIG.neigh_channels
    n_neigh = np.max(np.sum(CONFIG.neigh_channels, axis=1))
    templates_cropped = np.zeros((n_units, spike_size, n_neigh))

    for k in range(n_units):

        # get neighbors for the main channel in the kth template
        ch_idx = np.where(neighbors[mcs[k]])[0]

        # order channels
        ch_idx, _ = order_channels_by_distance(mcs[k], ch_idx, CONFIG.geom)

        # new kth template is the old kth template by keeping only
        # ordered neighboring channels
        templates_cropped[k, :, :ch_idx.shape[0]] = templates_aligned[k][:, ch_idx]

    fname_templates_cropped = os.path.join(save_dir, 'templates_cropped.npy')
    np.save(fname_templates_cropped, templates_cropped)

    return fname_templates_cropped

def denoise_templates(fname_templates, save_dir):

    # load templates
    templates = np.load(fname_templates)

    n_templates, n_times, n_chan = templates.shape

    # remove templates with ptp < 5 (if there are enough templates)
    ptps = templates.ptp(1).max(1)
    if np.sum(ptps > 5) > 100:
        templates = templates[ptps>5]
        n_templates = templates.shape[0]

    denoised_templates = np.zeros(templates.shape)

    #templates on max channels (index 0)
    templates_mc = templates[:, :, 0]
    ptp_mc = templates_mc.ptp(1)
    templates_mc = templates_mc/ptp_mc[:, None]

    # denoise max channel templates
    # bug fix = PCA(n_components=5); sometimes test dataset may have too few templates... not realistic though
    pca_mc = PCA(n_components=min(min(templates_mc.shape[0],
                                      templates_mc.shape[1]),
                                  5))
    score = pca_mc.fit_transform(templates_mc)
    deno_temp = pca_mc.inverse_transform(score)
    denoised_templates[:, :, 0] = deno_temp*ptp_mc[:, None]

    # templates on neighboring channels
    templates_neigh = templates[:, :, 1:]
    templates_neigh = templates_neigh.transpose(0, 2, 1).reshape(-1, n_times)
    ptp_neigh = templates_neigh.ptp(1)
    idx_non_zero = ptp_neigh > 0

    # get pca trained
    pca_neigh = PCA(n_components=5)
    pca_neigh.fit(templates_neigh[idx_non_zero]/ptp_neigh[idx_non_zero][:, None])

    # denoise them
    for j in range(1, n_chan):
        temp = templates[:, :, j]
        temp_ptp = np.abs(temp.min(1))
        idx = temp_ptp > 0
        if np.any(idx):
            temp = (temp[idx]/temp_ptp[idx, None])
            denoised_templates[idx, :, j] = pca_neigh.inverse_transform(
                pca_neigh.transform(temp))*temp_ptp[idx, None]

    fname_out = os.path.join(save_dir, 'denoised_templates.npy')
    np.save(fname_out, denoised_templates)

    return fname_out

class Detection_Training_Data(object):

    def __init__(self,
                 fname_templates_cropped,
                 fname_spatial_sig,
                 fname_temporal_sig):

        self.spatial_sig = np.load(fname_spatial_sig)
        self.temporal_sig = np.load(fname_temporal_sig)
        self.templates = np.load(fname_templates_cropped)
        self.standardize_templates()

        self.spike_size = self.temporal_sig.shape[0]

    def standardize_templates(self):

        # standardize templates
        ptps = np.ptp(self.templates[: ,:, 0], 1)
        self.templates = self.templates/ptps[:, None, None]

    def make_training_data(self, n_data):

        n_templates, n_times, n_channels = self.templates.shape

        center = n_times//2
        t_idx_in = slice(center - self.spike_size//2,
                         center + (self.spike_size//2) + 1)

        # sample templates
        idx1 = np.random.choice(n_templates, n_data)
        idx2 = np.random.choice(n_templates, n_data)
        wf1 = self.templates[idx1]
        wf2 = self.templates[idx2]

        # sample scale
        s1 = np.exp(np.random.randn(n_data)*0.8 + 2)
        s2 = np.exp(np.random.randn(n_data)*0.8 + 2)

        # minimum scale
        min_scale = 3
        s1[s1 < min_scale] = min_scale
        s2[s2 < min_scale] = min_scale

        # turn off some
        c1 = np.random.binomial(1, 0.5, n_data)
        c2 = np.random.binomial(1, 0.7, n_data)

        # multiply them
        wf1 = wf1*s1[:, None, None]*c1[:, None, None]
        wf2 = wf2*s2[:, None, None]*c2[:, None, None]

        # choose shift amount
        shift = np.random.randint(low=3, high=self.spike_size-1, size=(n_data,))
        shift *= np.random.choice([-1, 1], size=n_data, p=[0.2, 0.8])

        # make colliding wf
        wf_col = np.zeros(wf2.shape)
        for j in range(n_data):
            temp = np.roll(wf2[j], shift[j], axis=0)
            chan_shuffle_idx = np.random.choice(
                n_channels, n_channels, replace=False)
            wf_col[j] = temp[:, chan_shuffle_idx]

        noise = make_noise(n_data, self.spatial_sig, self.temporal_sig)

        wf = wf1[:, t_idx_in] + wf_col[:, t_idx_in] + noise
        label = c1

        return wf, label, wf1[:, t_idx_in]

class Denoising_Training_Data(object):

    def __init__(self,
                 fname_templates_cropped,
                 fname_spatial_sig,
                 fname_temporal_sig):

        self.spatial_sig = np.load(fname_spatial_sig)
        self.temporal_sig = np.load(fname_temporal_sig)
        self.templates = np.load(fname_templates_cropped)
        self.templates = self.templates.transpose(0,2,1).reshape(
            -1, self.templates.shape[1])
        self.remove_small_templates()
        self.standardize_templates()
        self.jitter_templates()

        self.spike_size = self.temporal_sig.shape[0]

    def remove_small_templates(self):

        ptp = self.templates.ptp(1)
        self.templates = self.templates[ptp > 3]

    def standardize_templates(self):

        # standardize templates
        ptp = self.templates.ptp(1)
        self.templates = self.templates/ptp[:, None]

        ref = np.mean(self.templates, 0)
        shifts = align_get_shifts_with_ref(
            self.templates, ref)
        self.templates = shift_chans(self.templates, shifts)

    def jitter_templates(self, up_factor=8):

        n_templates, n_times = self.templates.shape

        # upsample best fit template
        up_temp = scipy.signal.resample(
            x=self.templates,
            num=n_times*up_factor,
            axis=1)
        up_temp = up_temp.T

        idx = (np.arange(0, n_times)[:,None]*up_factor + np.arange(up_factor))
        up_shifted_temps = up_temp[idx].transpose(2,0,1)
        up_shifted_temps = np.concatenate(
            (up_shifted_temps,
             np.roll(up_shifted_temps, shift=1, axis=1)),
            axis=2)
        self.templates = up_shifted_temps.transpose(0,2,1).reshape(-1, n_times)

        ref = np.mean(self.templates, 0)
        shifts = align_get_shifts_with_ref(
            self.templates, ref, upsample_factor=1)
        self.templates = shift_chans(self.templates, shifts)

    def make_training_data(self, n):

        n_templates, n_times = self.templates.shape

        center = n_times//2
        t_idx_in = slice(center - self.spike_size//2,
                         center + (self.spike_size//2) + 1)

        # sample templates
        idx1 = np.random.choice(n_templates, n)
        idx2 = np.random.choice(n_templates, n)
        wf1 = self.templates[idx1]
        wf2 = self.templates[idx2]

        # sample scale
        s1 = np.exp(np.random.randn(n)*0.8 + 2)
        s2 = np.exp(np.random.randn(n)*0.8 + 2)

        # turn off some
        c1 = np.random.binomial(1, 1-0.05, n)
        c2 = np.random.binomial(1, 1-0.05, n)

        # multiply them
        wf1 = wf1*s1[:, None]*c1[:, None]
        wf2 = wf2*s2[:, None]*c2[:, None]

        # choose shift amount
        shift = np.random.randint(low=0, high=3, size=(n,))

        # choose shift amount
        shift2 = np.random.randint(low=5, high=self.spike_size, size=(n,))

        shift *= np.random.choice([-1, 1], size=n)
        shift2 *= np.random.choice([-1, 1], size=n, p=[0.2, 0.8])

        # make colliding wf
        wf_clean = np.zeros(wf1.shape)
        for j in range(n):
            temp = np.roll(wf1[j], shift[j])
            wf_clean[j] = temp

        # make colliding wf
        wf_col = np.zeros(wf2.shape)
        for j in range(n):
            temp = np.roll(wf2[j], shift2[j])
            wf_col[j] = temp

        noise_wf = make_noise(n, self.spatial_sig, self.temporal_sig)[:, :, 0]

        wf_clean = wf_clean[:, t_idx_in]
        return (wf_clean + wf_col[:, t_idx_in] + noise_wf,
                wf_clean)

def make_noise(n, spatial_SIG, temporal_SIG):
    """Make noise

    Parameters
    ----------
    n: int
        Number of noise events to generate

    Returns
    ------
    numpy.ndarray
        Noise
    """
    n_neigh, _ = spatial_SIG.shape
    waveform_length, _ = temporal_SIG.shape

    # get noise
    noise = np.random.normal(size=(n, waveform_length, n_neigh))

    for c in range(n_neigh):
        noise[:, :, c] = np.matmul(noise[:, :, c], temporal_SIG)
        reshaped_noise = np.reshape(noise, (-1, n_neigh))

    the_noise = np.reshape(np.matmul(reshaped_noise, spatial_SIG),
                           (n, waveform_length, n_neigh))

    return the_noise


text:
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Evento.Repository.Grpc
{
    internal class SerializationUtils
    {

        public static string EventClrTypeHeader = "EventClrTypeName";

        public static T DeserializeObject<T>(ReadOnlyMemory<byte> data)
        {
            return (T)(DeserializeObject(data, typeof(T).AssemblyQualifiedName));
        }

        public static object DeserializeObject(ReadOnlyMemory<byte> data, string typeName)
        {
            try
            {
                var jsonString = Encoding.UTF8.GetString(data.Span);
                return JsonConvert.DeserializeObject(jsonString, Type.GetType(typeName));
            }
            catch (Exception)
            {
                return null;
            }
        }

        public static object DeserializeObject(ReadOnlyMemory<byte> data, ReadOnlyMemory<byte> metadata)
        {
            try
            {
                var dict = DeserializeObject<Dictionary<string, string>>(metadata);
                if (!dict.ContainsKey("$correlationId"))
                    throw new Exception("The metadata must contains a $correlationId");
                var bodyString = Encoding.UTF8.GetString(data.Span);
                var o1 = JObject.Parse(bodyString);
                var o2 = JObject.Parse(JsonConvert.SerializeObject(new { metadata = dict }));
                o1.Merge(o2, new JsonMergeSettings {MergeArrayHandling = MergeArrayHandling.Union});
                return JsonConvert.DeserializeObject(o1.ToString(),
                    Type.GetType(DeserializeObject<Dictionary<string, string>>(metadata)[EventClrTypeHeader]));
            }
            catch (Exception)
            {
                return null;
            }
        }

        //public static object DeserializeEvent(RecordedEvent originalEvent)
        //{
        //    if (originalEvent.Metadata != null && !originalEvent.EventStreamId.StartsWith("$"))
        //    {
        //        var metadata = DeserializeObject<Dictionary<string, dynamic>>(originalEvent.Metadata);
        //        if (metadata != null && metadata.ContainsKey(EventClrTypeHeader))
        //        {
        //            var eventData = DeserializeObject(originalEvent.Data, metadata[EventClrTypeHeader]);
        //            return eventData;
        //        }
        //        else
        //        {
        //            var eventData = DeserializeObject(originalEvent.Data, EventClrTypeHeader);
        //            return eventData;
        //        }
        //    }
        //    return null;
        //}
    }
}


text:
module Eadsax
  class List
    include SAXMachine
    element :defitem, :class => Defitem
    element :head
    element :item
    element :listhead, :class => Listhead
  end
end


text:
package uk.co.webamoeba.mockito.collections.core.integrationtests.support;

public class ClassWithInheritedCollectionOfCollaborators extends ClassWithCollectionOfCollaborators {

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>gem5: cpu/testers/memtest/memtest.hh File Reference</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Modules

Namespaces

Classes

Files

Related Pages

      <form action="search.php" method="get">

             Search for
            <input type="text" name="query" value="" size="20" accesskey="s"/>

      </form>

File List

File Members

cpu/testers/memtest/memtest.hh File Reference
#include <set>

#include "base/statistics.hh"

#include "mem/mem_object.hh"

#include "mem/port.hh"

#include "mem/port_proxy.hh"

#include "params/MemTest.hh"

#include "sim/eventq.hh"

#include "sim/sim_exit.hh"

#include "sim/sim_object.hh"

#include "sim/stats.hh"

Go to the source code of this file.

Classes

class  	MemTest

class  	MemTest::TickEvent

class  	MemTest::CpuPort

class  	MemTest::MemTestSenderState

<address style="align: right;">
Generated on Fri Apr 17 12:39:10 2015 for gem5 by  doxygen 1.4.7</address>


text:
package com.consol.citrus.message.correlation;

import com.consol.citrus.context.TestContext;
import com.consol.citrus.endpoint.PollableEndpointConfiguration;
import com.consol.citrus.exceptions.CitrusRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Extension of default correlation manager adds polling mechanism for find operation on object store.
 * In case object is not found in store retry is automatically performed. Polling interval and overall retry timeout
 * is usually defined in endpoint configuration.
 *
 * @author Christoph Deppisch
 * @since 2.1
 */
public class PollingCorrelationManager<T> extends DefaultCorrelationManager<T> {

    private final String retryLogMessage;

    private final PollableEndpointConfiguration endpointConfiguration;

    /** Logger */
    private static Logger log = LoggerFactory.getLogger(PollingCorrelationManager.class);

    /** Retry logger */
    private static final Logger RETRY_LOG = LoggerFactory.getLogger("com.consol.citrus.RetryLogger");

    /**
     * Constructor using fields.
     * @param endpointConfiguration
     * @param retryLogMessage
     */
    public PollingCorrelationManager(PollableEndpointConfiguration endpointConfiguration, String retryLogMessage) {
        this.retryLogMessage = retryLogMessage;
        this.endpointConfiguration = endpointConfiguration;
    }

    /**
     * Convenience method for using default timeout settings of endpoint configuration.
     * @param correlationKey
     * @return
     */
    public T find(String correlationKey) {
        return find(correlationKey, endpointConfiguration.getTimeout());
    }

    @Override
    public String getCorrelationKey(String correlationKeyName, TestContext context) {
        if (log.isDebugEnabled()) {
            log.debug(String.format("Get correlation key for '%s'", correlationKeyName));
        }

        String correlationKey = null;
        if (context.getVariables().containsKey(correlationKeyName)) {
            correlationKey = context.getVariable(correlationKeyName);
        }

        long timeLeft = 1000L;
        long pollingInterval = 300L;
        while (correlationKey == null && timeLeft > 0) {
            timeLeft -= pollingInterval;

            if (RETRY_LOG.isDebugEnabled()) {
                RETRY_LOG.debug("Correlation key not available yet - retrying in " + (timeLeft > 0 ? pollingInterval : pollingInterval + timeLeft) + "ms");
            }

            try {
                Thread.sleep(timeLeft > 0 ? pollingInterval : pollingInterval + timeLeft);
            } catch (InterruptedException e) {
                RETRY_LOG.warn("Thread interrupted while waiting for retry", e);
            }

            if (context.getVariables().containsKey(correlationKeyName)) {
                correlationKey = context.getVariable(correlationKeyName);
            }
        }

        if (correlationKey == null) {
            throw new CitrusRuntimeException(String.format("Failed to get correlation key for '%s'", correlationKeyName));
        }

        return correlationKey;
    }

    @Override
    public T find(String correlationKey, long timeout) {
        long timeLeft = timeout;
        long pollingInterval = endpointConfiguration.getPollingInterval();

        T stored = super.find(correlationKey, timeLeft);

        while (stored == null && timeLeft > 0) {
            timeLeft -= pollingInterval;

            if (RETRY_LOG.isDebugEnabled()) {
                RETRY_LOG.debug(retryLogMessage + " - retrying in " + (timeLeft > 0 ? pollingInterval : pollingInterval + timeLeft) + "ms");
            }

            try {
                Thread.sleep(timeLeft > 0 ? pollingInterval : pollingInterval + timeLeft);
            } catch (InterruptedException e) {
                RETRY_LOG.warn("Thread interrupted while waiting for retry", e);
            }

            stored = super.find(correlationKey, timeLeft);
        }

        return stored;
    }

    /**
     * Gets the retry log message
     * @return
     */
    public String getRetryLogMessage() {
        return retryLogMessage;
    }
}


text:
set :application, "gastosmini"
set :repository,  "https://larry.aspgems.com:8083/ayto-madrid/#{application}/trunk"
set :user, "#{application}"
ssh_options[:config] = false
set :use_sudo, false
set :keep_releases, 2
set :rails_env, "production"

set(:scm_username) { Capistrano::CLI.ui.ask("Type is your svn username: ") }
set(:scm_password){ Capistrano::CLI.password_prompt("Type your svn password for user #{scm_username}: ") }

set :deploy_via, :export
set :deploy_to, "/home/#{user}/app"

role :app, "hal.aspgems.com"
role :web, "hal.aspgems.com"
role :db,  "hal.aspgems.com", :primary => true

files=%w(database.yml mailer.rb gastosmini.yml local_config.rb)
dirs=%w(config system/images)
after "deploy:update","deploy:symlink_config"
after "deploy:setup","deploy:create_dirs"

# Here comes the app config

namespace :deploy do

  task :symlink_config, :roles => :app do
    files.each do |f|
      run "ln -nfs #{shared_path}/config/#{f} #{current_path}/config/#{f}"
    end
  end

  task :restart, :roles => :app do
    run "touch  #{current_path}/tmp/restart.txt"
  end

  task :create_dirs, :roles => :app do
    dirs.each do |d|
      run "mkdir -p #{shared_path}/#{d}"
    end
  end

  desc "Enables maintenance mode in the app"
  task :maintenance_on, :roles => :app do
    run "cp current/public/system/maintenance.html.disabled current/public/system/maintenance.html"
  end

  desc "Disables maintenance mode in the app"
  task :maintenance_off, :roles => :app do
    run "rm current/public/system/maintenance.html"
  end
end

# Here comes the application namespace for custom tasks

namespace application do

end


text:
body { background-color: #777 }
.class { color: #f00 }


text:
package git

import (
	"fmt"

	"github.com/Unknwon/com"
)

type ArchiveType int

const (
	ZIP ArchiveType = iota + 1
	TARGZ
)

func (c *Commit) CreateArchive(path string, archiveType ArchiveType) error {
	var format string
	switch archiveType {
	case ZIP:
		format = "zip"
	case TARGZ:
		format = "tar.gz"
	default:
		return fmt.Errorf("unknown format: %v", archiveType)
	}

	_, stderr, err := com.ExecCmdDir(c.repo.Path, "git", "archive", "--format="+format, "-o", path, c.ID.String())
	if err != nil {
		return fmt.Errorf("%s", stderr)
	}
	return nil
}


text:
'use strict'

// Match magic bytes with file extension
const lookupFileType = (test = '', extra = {}) => {
  // File types to accept and respective magic bytes
  // http://www.astro.keele.ac.uk/oldusers/rno/Computing/File_magic.html#Image
  const accepts = Object.assign({
    jpg: 'ffd8ffe0',
    png: '89504e47',
    gif: '47494638'
  }, extra)

  return Object.keys(accepts).find(k => accepts[k] === test)
}

// Extract magic
const readMagicBytes = chunk => chunk.toString('hex', 0, 4)

// File type parsing composed and invalidated
const isMagicMissing = chunk => lookupFileType(readMagicBytes(chunk)) === undefined

module.exports = isMagicMissing


text:
\echo --start_ignore
set gp_enable_column_oriented_table=on;
\echo --end_ignore
DROP TABLE IF EXISTS mpp21090_pttab_addcol_addpt_dropcol_int8;
CREATE TABLE mpp21090_pttab_addcol_addpt_dropcol_int8
(
    col1 int8,
    col2 int8,
    col3 char,
    col4 int
)
DISTRIBUTED by (col1)
PARTITION BY RANGE(col2)(partition partone start(1) end(1000000000000000001)  WITH (APPENDONLY=true, COMPRESSLEVEL=5, ORIENTATION=column),partition parttwo start(1000000000000000001) end(2000000000000000001) WITH (APPENDONLY=true, COMPRESSLEVEL=5, ORIENTATION=row),partition partthree start(2000000000000000001) end(3000000000000000001));

INSERT INTO mpp21090_pttab_addcol_addpt_dropcol_int8 VALUES(2000000000000000000,2000000000000000000,'a',0);

ALTER TABLE mpp21090_pttab_addcol_addpt_dropcol_int8 ADD COLUMN col5 int8 DEFAULT 2000000000000000000;
ALTER TABLE mpp21090_pttab_addcol_addpt_dropcol_int8 ADD PARTITION partfour start(3000000000000000001) end(4000000000000000001);

INSERT INTO mpp21090_pttab_addcol_addpt_dropcol_int8 SELECT 3500000000000000000,3500000000000000000,'b',1, 3500000000000000000;
SELECT * FROM mpp21090_pttab_addcol_addpt_dropcol_int8 ORDER BY 1,2,3;

ALTER TABLE mpp21090_pttab_addcol_addpt_dropcol_int8 DROP COLUMN col1;

INSERT INTO mpp21090_pttab_addcol_addpt_dropcol_int8 SELECT 3500000000000000000,'c',1, 3500000000000000000;
SELECT * FROM mpp21090_pttab_addcol_addpt_dropcol_int8 ORDER BY 1,2,3;

UPDATE mpp21090_pttab_addcol_addpt_dropcol_int8 SET col5 = 1000000000000000000 WHERE col2 = 3500000000000000000 and col3='c';
SELECT * FROM mpp21090_pttab_addcol_addpt_dropcol_int8 ORDER BY 1,2,3;

-- Update partition key
UPDATE mpp21090_pttab_addcol_addpt_dropcol_int8 SET col2 = 1000000000000000000 WHERE col2 = 3500000000000000000 and col3='c';
SELECT * FROM mpp21090_pttab_addcol_addpt_dropcol_int8 ORDER BY 1,2,3;

DELETE FROM mpp21090_pttab_addcol_addpt_dropcol_int8 WHERE col2 = 1000000000000000000;
SELECT * FROM mpp21090_pttab_addcol_addpt_dropcol_int8 ORDER BY 1,2,3;