text:
class TestRenderWidgetHostView : public RenderWidgetHostView {
 public:
  explicit TestRenderWidgetHostView(RenderWidgetHost* rwh);

  virtual void InitAsPopup(RenderWidgetHostView* parent_host_view,
                           const gfx::Rect& pos) {}
  virtual RenderWidgetHost* GetRenderWidgetHost() const { return NULL; }
  virtual void DidBecomeSelected() {}
  virtual void WasHidden() {}
  virtual void SetSize(const gfx::Size& size) {}
  virtual gfx::NativeView GetNativeView() { return NULL; }
  virtual void MovePluginWindows(
      const std::vector<webkit_glue::WebPluginGeometry>& moves) {}
#if defined(OS_WIN)
  virtual void ForwardMouseEventToRenderer(UINT message,
                                           WPARAM wparam,
                                           LPARAM lparam) {}
#endif
  virtual void Focus() {}
  virtual void Blur() {}
  virtual bool HasFocus() { return true; }
  virtual void AdvanceFocus(bool reverse) {}
  virtual void Show() { is_showing_ = true; }
  virtual void Hide() { is_showing_ = false; }
  virtual gfx::Rect GetViewBounds() const { return gfx::Rect(); }
  virtual void SetIsLoading(bool is_loading) {}
  virtual void UpdateCursor(const WebCursor& cursor) {}
  virtual void UpdateCursorIfOverSelf() {}
  virtual void IMEUpdateStatus(int control, const gfx::Rect& caret_rect) {}
  virtual void DidPaintBackingStoreRects(
      const std::vector<gfx::Rect>& rects) {}
  virtual void DidScrollBackingStoreRect(
      const gfx::Rect& rect, int dx, int dy) {}
  virtual void RenderViewGone() { delete this; }
  virtual void WillDestroyRenderWidget(RenderWidgetHost* rwh) { }
  virtual void Destroy() {}
  virtual void PrepareToDestroy() {}
  virtual void SetTooltipText(const std::wstring& tooltip_text) {}
  virtual BackingStore* AllocBackingStore(const gfx::Size& size);
#if defined(OS_MACOSX)
  virtual void ShowPopupWithItems(gfx::Rect bounds,
                                  int item_height,
                                  int selected_item,
                                  const std::vector<WebMenuItem>& items) {}
  virtual gfx::Rect GetWindowRect();
  virtual gfx::Rect GetRootWindowRect();
  virtual void SetActive(bool active);
#endif

#if defined(OS_NIX)
  virtual void CreatePluginContainer(gfx::PluginWindowHandle id) { }
  virtual void DestroyPluginContainer(gfx::PluginWindowHandle id) { }
#endif

  bool is_showing() const { return is_showing_; }

 private:
  RenderWidgetHost* rwh_;
  bool is_showing_;
};

// TestRenderViewHost ----------------------------------------------------------

// TODO(brettw) this should use a TestTabContents which should be generalized
// from the TabContents test. We will probably also need that class' version of
// CreateRenderViewForRenderManager when more complicate tests start using this.
class TestRenderViewHost : public RenderViewHost {
 public:
  TestRenderViewHost(SiteInstance* instance,
                     RenderViewHostDelegate* delegate,
                     int routing_id);
  virtual ~TestRenderViewHost();

  // Testing functions ---------------------------------------------------------

  // Calls the RenderViewHosts' private OnMessageReceived function with the
  // given message.
  void TestOnMessageReceived(const IPC::Message& msg);

  // Calls OnMsgNavigate on the RenderViewHost with the given information,
  // setting the rest of the parameters in the message to the "typical" values.
  // This is a helper function for simulating the most common types of loads.
  void SendNavigate(int page_id, const GURL& url);

  // If set, *delete_counter is incremented when this object destructs.
  void set_delete_counter(int* delete_counter) {
    delete_counter_ = delete_counter;
  }

  // Sets whether the RenderView currently exists or not. This controls the
  // return value from IsRenderViewLive, which the rest of the system uses to
  // check whether the RenderView has crashed or not.
  void set_render_view_created(bool created) {
    render_view_created_ = created;
  }

  // RenderViewHost overrides --------------------------------------------------

  virtual bool CreateRenderView(URLRequestContextGetter* request_context);
  virtual bool IsRenderViewLive() const;

 private:
  FRIEND_TEST(RenderViewHostTest, FilterNavigate);

  // Tracks if the caller thinks if it created the RenderView. This is so we can
  // respond to IsRenderViewLive appropriately.
  bool render_view_created_;

  // See set_delete_counter() above. May be NULL.
  int* delete_counter_;

  DISALLOW_COPY_AND_ASSIGN(TestRenderViewHost);
};

// TestRenderViewHostFactory ---------------------------------------------------

// Manages creation of the RenderViewHosts using our special subclass. This
// automatically registers itself when it goes in scope, and unregisters itself
// when it goes out of scope. Since you can't have more than one factory
// registered at a time, you can only have one of these objects at a time.
class TestRenderViewHostFactory : public RenderViewHostFactory {
 public:
  explicit TestRenderViewHostFactory(RenderProcessHostFactory* rph_factory)
      : render_process_host_factory_(rph_factory) {
    RenderViewHostFactory::RegisterFactory(this);
  }
  virtual ~TestRenderViewHostFactory() {
    RenderViewHostFactory::UnregisterFactory();
  }

  virtual void set_render_process_host_factory(
      RenderProcessHostFactory* rph_factory) {
    render_process_host_factory_ = rph_factory;
  }

  virtual RenderViewHost* CreateRenderViewHost(
      SiteInstance* instance,
      RenderViewHostDelegate* delegate,
      int routing_id) {
    // See declaration of render_process_host_factory_ below.
    instance->set_render_process_host_factory(render_process_host_factory_);
    return new TestRenderViewHost(instance, delegate, routing_id);
  }

 private:
  // This is a bit of a hack. With the current design of the site instances /
  // browsing instances, it's difficult to pass a RenderProcessHostFactory
  // around properly.
  //
  // Instead, we set it right before we create a new RenderViewHost, which
  // happens before the RenderProcessHost is created. This way, the instance
  // has the correct factory and creates our special RenderProcessHosts.
  RenderProcessHostFactory* render_process_host_factory_;

  DISALLOW_COPY_AND_ASSIGN(TestRenderViewHostFactory);
};

// RenderViewHostTestHarness ---------------------------------------------------

class RenderViewHostTestHarness : public testing::Test {
 public:
  RenderViewHostTestHarness()
      : rph_factory_(),
        rvh_factory_(&rph_factory_),
        contents_(NULL) {}
  virtual ~RenderViewHostTestHarness() {}

  NavigationController& controller() {
    return contents_->controller();
  }

  TestTabContents* contents() {
    return contents_.get();
  }

  TestRenderViewHost* rvh() {
    return static_cast<TestRenderViewHost*>(contents_->render_view_host());
  }

  TestRenderViewHost* pending_rvh() {
    return static_cast<TestRenderViewHost*>(
        contents_->render_manager()->pending_render_view_host());
  }

  TestRenderViewHost* active_rvh() {
    return pending_rvh() ? pending_rvh() : rvh();
  }

  TestingProfile* profile() {
    return profile_.get();
  }

  MockRenderProcessHost* process() {
    return static_cast<MockRenderProcessHost*>(rvh()->process());
  }

  // Frees the current tab contents for tests that want to test destruction.
  void DeleteContents() {
    contents_.reset();
  }

  // Creates a pending navigation to the given oURL with the default parameters
  // and the commits the load with a page ID one larger than any seen. This
  // emulates what happens on a new navigation.
  void NavigateAndCommit(const GURL& url);

 protected:
  // testing::Test
  virtual void SetUp();
  virtual void TearDown();

  // This profile will be created in SetUp if it has not already been created.
  // This allows tests to override the profile if they so choose in their own
  // SetUp function before calling the base class's (us) SetUp().
  scoped_ptr<TestingProfile> profile_;

  MessageLoopForUI message_loop_;

  MockRenderProcessHostFactory rph_factory_;
  TestRenderViewHostFactory rvh_factory_;

  scoped_ptr<TestTabContents> contents_;

  scoped_ptr<UserDataManager> user_data_manager_;

  DISALLOW_COPY_AND_ASSIGN(RenderViewHostTestHarness);
};

#endif  // CHROME_BROWSER_RENDERER_HOST_TEST_TEST_RENDER_VIEW_HOST_H_


text:
package ubic.gemma.core.util.biomart;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Before;
import org.junit.Test;

import ubic.gemma.core.loader.util.biomart.BiomartEnsemblNcbiFetcher;
import ubic.gemma.model.genome.Taxon;

import java.io.File;
import java.io.IOException;
import java.net.ConnectException;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

/**
 * Tests that biomart fetcher works correctly. That is firstly that a file can be downloaded it calls the biomart
 * service safety net so if the url changes test will fail. Secondly that taxons and biomart queries can be correctly
 * formated.
 *
 * @author ldonnison
 */
public class BioMartEnsemblNcbiFetcherTest {

    private static final Log log = LogFactory.getLog( BioMartEnsemblNcbiFetcherTest.class );
    private BiomartEnsemblNcbiFetcher biomartEnsemblNcbiFetcher = null;

    @Before
    public void setUp() {
        biomartEnsemblNcbiFetcher = new BiomartEnsemblNcbiFetcher();
    }

    /*
     * Tests that given a taxon returns the correct attributes
     */
    @Test
    public void testAttributesToRetrieveFromBioMart() {
        String[] attributes = biomartEnsemblNcbiFetcher.attributesToRetrieveFromBioMartForProteinQuery( "hsapiens" );
        assertNotNull( attributes );
        assertTrue( attributes.length == 5 );
        // should be set for human
        assertNotNull( attributes[4] );
    }

    /*
     * Tests that given a scientific named taxon taxon name is formatted correctly for biomart
     */
    @Test
    public void testGetBioMartTaxonName() {
        Taxon taxon = Taxon.Factory.newInstance();
        taxon.setScientificName( "Homo sapiens" );

        String biomartFormatedString = biomartEnsemblNcbiFetcher.getBiomartTaxonName( taxon );
        assertNotNull( biomartFormatedString );
        assertTrue( biomartFormatedString.equals( "hsapiens" ) );

    }

    /*
     * Tests that a file can be downloaded from biomart in this case a rat file as it is quite small Test method for
     */
    @Test
    public void testGetEnsemblNcibidata() {

        try {
            File ratBiomartFile = biomartEnsemblNcbiFetcher.fetchFileForProteinQuery( "rnorvegicus" );
            assertNotNull( ratBiomartFile );
            assertTrue( ratBiomartFile.canRead() );

        } catch ( ConnectException e ) {
            BioMartEnsemblNcbiFetcherTest.log.warn( "Connection error, skipping test" );
        } catch ( IOException e ) {
            if ( e.getMessage().startsWith( "Error from BioMart" ) ) {
                BioMartEnsemblNcbiFetcherTest.log.warn( e.getMessage() );
            }
        }

    }

    /*
     * Method that downloads all the files for biomart uncomment if there are problems But will take some time to run
     *
     * @Test public void fetchAllTaxa(){ Collection<Taxon> taxa = new ArrayList<Taxon>(); Taxon taxon =
     * Taxon.Factory.newInstance( "Rattus norvegicus", "", "", "", "", 0, true, true, null, null ); Taxon taxon1 =
     * Taxon.Factory.newInstance( "Homo sapiens", "", "", "", "", 0, true, true, null, null ); Taxon taxon2 =
     * Taxon.Factory.newInstance( "Daneo rerio", "", "", "", "", 0, true, true, null, null ); Taxon taxon3 =
     * Taxon.Factory.newInstance( "Mus musculus", "", "", "", "", 0, true, true, null, null ); taxa.add(taxon);
     * taxa.add(taxon1); taxa.add(taxon2); taxa.add(taxon3); try { BioMartEnsemblNcbiFetcher test = new
     * BioMartEnsemblNcbiFetcher(); test.fetch(taxa); } catch ( Exception e ) { e.printStackTrace(); fail(); } }
     */

}

redpajama_set_name: RedPajamaGithub


text:
module Vulkan
    class VkDrawIndirectCommand < FFI::Struct
        layout vertexCount:     :uint32_t,
               instanceCount:   :uint32_t,
               firstVertex:     :uint32_t,
               firstInstance:   :uint32_t
    end
end


text:
package lab;

/**
 * Assertions
 */
public class TestingHelper {
    public static void assertEqual(String left, String right) {
        System.out.printf("CLAIM: [%s] == [%s]\n", left, right);
        assert left.equals(right);
    }

}


text:
package com.ergonlabs.common.ui.internal.calendar;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.GridView;

/**
 * Created by stefanrusek on 6/11/14.
 */
public class NoScrollGridView extends GridView {
    public NoScrollGridView(Context context) {
        super(context);
    }

    public NoScrollGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public NoScrollGridView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int heightSpec = MeasureSpec.makeMeasureSpec(MEASURED_SIZE_MASK, MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, heightSpec);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright 2015 The Chromium Authors. All rights reserved.
     Use of this source code is governed by a BSD-style license that can be
     found in the LICENSE file. -->

<resources xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- The application name displayed to the user. -->
    <string name="app_name" translatable="false">Chromium</string>
    <string name="bookmark_widget_title" translatable="false">Chromium bookmarks</string>
    <string name="search_widget_title" translatable="false">Chromium search</string>
    <string name="quick_action_search_widget_title" translatable="false">Chromium quick action search</string>
    <string name="dino_widget_title" translatable="false">Chromium dino</string>
</resources>


text:
package org.bpel4chor.splitprocess.test.pwdg.util;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;

import org.apache.log4j.Logger;
import org.bpel4chor.utils.RandomIdGenerator;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class RandomIdGeneratorTest {

	Logger logger = Logger.getLogger(RandomIdGeneratorTest.class);

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception {
	}

	@Before
	public void setUp() throws Exception {
	}

	@After
	public void tearDown() throws Exception {
	}

	@Test
	public void testGetIdInt() {
		String id1 = RandomIdGenerator.getId();
		String id2 = RandomIdGenerator.getId();
		assertNotNull(id1);
		assertNotNull(id2);
		assertEquals(RandomIdGenerator.idLength(), id1.length());
		assertEquals(RandomIdGenerator.idLength(), id2.length());
		assertFalse(id1.equals(id2));
		String id3 = RandomIdGenerator.getId();
		assertNotNull(id3);
		assertFalse(id1.equals(id3));
	}

	// this test make takes a while
	@Test
	public void testLimitOfTheIdGenerator() throws Exception {
		logger.info("Begin Stress Test for limit of RandomIdGenerator, this may take a while");
		int usedidSize = RandomIdGenerator.usedSize();
		for (int i = 0; i < RandomIdGenerator.maxSize() - usedidSize; i++) {
			String id = RandomIdGenerator.getId();
			assertNotNull(id);
			assertEquals(RandomIdGenerator.idLength(), id.length());
		}

		try {
			RandomIdGenerator.getId();
			fail();
		} catch (Exception e) {
			if(e instanceof RuntimeException)
				logger.info("Expected Stress Test Result: "+e.toString());
			else
				throw new Exception(e);
		}

	}
}


text:
import { Directive, ElementRef, EventEmitter, HostListener, Output, Renderer } from '@angular/core';
import { NgControl } from '@angular/forms';

import { Config } from '../../config/config';
import { Platform } from '../../platform/platform';

/**
 * @private
 */
@Directive({
  selector: '.text-input'
})
export class NativeInput {
  _relocated: boolean;
  _clone: boolean;
  _blurring: boolean;
  _unrefBlur: Function;

  @Output() focusChange: EventEmitter<boolean> = new EventEmitter<boolean>();
  @Output() valueChange: EventEmitter<string> = new EventEmitter<string>();
  @Output() keydown: EventEmitter<string> = new EventEmitter<string>();

  constructor(
    public _elementRef: ElementRef,
    public _renderer: Renderer,
    config: Config,
    private _plt: Platform,
    public ngControl: NgControl
  ) {
    this._clone = config.getBoolean('inputCloning', false);
    this._blurring = config.getBoolean('inputBlurring', false);
  }

  @HostListener('input', ['$event'])
  _change(ev: any) {
    this.valueChange.emit(ev.target.value);
  }

  @HostListener('keydown', ['$event'])
  _keyDown(ev: any) {
    if (ev) {
      ev.target && this.keydown.emit(ev.target.value);
    }
  }

  @HostListener('focus')
  _focus() {
    var self = this;

    self.focusChange.emit(true);

    if (self._blurring) {
      // automatically blur input if:
      // 1) this input has focus
      // 2) the newly tapped document element is not an input
      console.debug(`native-input, blurring enabled`);

      var unregTouchEnd = this._plt.registerListener(this._plt.doc(), 'touchend', (ev: TouchEvent) => {
        var tapped = <HTMLElement>ev.target;
        if (tapped && self.element()) {
          if (tapped.tagName !== 'INPUT' && tapped.tagName !== 'TEXTAREA' && !tapped.classList.contains('input-cover')) {
            self.element().blur();
          }
        }
      }, {
        capture: true,
        zone: false
      });

      self._unrefBlur = function() {
        console.debug(`native-input, blurring disabled`);
        unregTouchEnd();
      };
    }
  }

  @HostListener('blur')
  _blur() {
    this.focusChange.emit(false);
    this.hideFocus(false);

    this._unrefBlur && this._unrefBlur();
    this._unrefBlur = null;
  }

  labelledBy(val: string) {
    this._renderer.setElementAttribute(this._elementRef.nativeElement, 'aria-labelledby', val);
  }

  isDisabled(val: boolean) {
    this._renderer.setElementAttribute(this._elementRef.nativeElement, 'disabled', val ? '' : null);
  }

  setFocus() {
    // let's set focus to the element
    // but only if it does not already have focus
    if (this._plt.getActiveElement() !== this.element()) {
      this.element().focus();
    }
  }

  beginFocus(shouldFocus: boolean, inputRelativeY: number) {
    if (this._relocated !== shouldFocus) {
      const focusedInputEle = this.element();
      if (shouldFocus) {
        // we should focus into this element

        if (this._clone) {
          // this platform needs the input to be cloned
          // this allows for the actual input to receive the focus from
          // the user's touch event, but before it receives focus, it
          // moves the actual input to a location that will not screw
          // up the app's layout, and does not allow the native browser
          // to attempt to scroll the input into place (messing up headers/footers)
          // the cloned input fills the area of where native input should be
          // while the native input fakes out the browser by relocating itself
          // before it receives the actual focus event
          cloneInputComponent(this._plt, focusedInputEle);

          // move the native input to a location safe to receive focus
          // according to the browser, the native input receives focus in an
          // area which doesn't require the browser to scroll the input into place
          (<any>focusedInputEle.style)[this._plt.Css.transform] = `translate3d(-9999px,${inputRelativeY}px,0)`;
          focusedInputEle.style.opacity = '0';
        }

        // let's now set focus to the actual native element
        // at this point it is safe to assume the browser will not attempt
        // to scroll the input into view itself (screwing up headers/footers)
        this.setFocus();

      } else {
        // should remove the focus
        if (this._clone) {
          // should remove the cloned node
          removeClone(this._plt, focusedInputEle);
        }
      }

      this._relocated = shouldFocus;
    }
  }

  hideFocus(shouldHideFocus: boolean) {
    let focusedInputEle = this.element();

    console.debug(`native-input, hideFocus, shouldHideFocus: ${shouldHideFocus}, input value: ${focusedInputEle.value}`);

    if (shouldHideFocus) {
      cloneInputComponent(this._plt, focusedInputEle);
      (<any>focusedInputEle.style)[this._plt.Css.transform] = 'scale(0)';

    } else {
      removeClone(this._plt, focusedInputEle);
    }
  }

  setValue(val: any) {
    this._elementRef.nativeElement['value'] = val;
  }

  getValue(): string {
    return this.element().value;
  }

  setMin(val: any) {
    this._elementRef.nativeElement['min'] = val;
  }

  setMax(val: any) {
    this._elementRef.nativeElement['max'] = val;
  }

  setStep(val: any) {
    this._elementRef.nativeElement['step'] = val;
  }

  setElementClass(cssClass: string, shouldAdd: boolean) {
    this._renderer.setElementClass(this._elementRef.nativeElement, cssClass, shouldAdd);
  }

  element(): HTMLInputElement {
    return this._elementRef.nativeElement;
  }

  ngOnDestroy() {
    this._unrefBlur && this._unrefBlur();
  }

}

function cloneInputComponent(plt: Platform, srcNativeInputEle: HTMLInputElement) {
  // given a native <input> or <textarea> element
  // find its parent wrapping component like <ion-input> or <ion-textarea>
  // then clone the entire component
  const srcComponentEle = <HTMLElement>srcNativeInputEle.closest('ion-input,ion-textarea');
  if (srcComponentEle) {
    // DOM READ
    const srcTop = srcComponentEle.offsetTop;
    const srcLeft = srcComponentEle.offsetLeft;
    const srcWidth = srcComponentEle.offsetWidth;
    const srcHeight = srcComponentEle.offsetHeight;

    // DOM WRITE
    // not using deep clone so we don't pull in unnecessary nodes
    const clonedComponentEle = <HTMLElement>srcComponentEle.cloneNode(false);
    clonedComponentEle.classList.add('cloned-input');
    clonedComponentEle.setAttribute('aria-hidden', 'true');
    clonedComponentEle.style.pointerEvents = 'none';
    clonedComponentEle.style.position = 'absolute';
    clonedComponentEle.style.top = srcTop + 'px';
    clonedComponentEle.style.left = srcLeft + 'px';
    clonedComponentEle.style.width = srcWidth + 'px';
    clonedComponentEle.style.height = srcHeight + 'px';

    const clonedNativeInputEle = <HTMLInputElement>srcNativeInputEle.cloneNode(false);
    clonedNativeInputEle.value = srcNativeInputEle.value;
    clonedNativeInputEle.tabIndex = -1;

    clonedComponentEle.appendChild(clonedNativeInputEle);
    srcComponentEle.parentNode.appendChild(clonedComponentEle);

    srcComponentEle.style.pointerEvents = 'none';
  }

  (<any>srcNativeInputEle.style)[plt.Css.transform] = 'scale(0)';
}

function removeClone(plt: Platform, srcNativeInputEle: HTMLElement) {
  const srcComponentEle = <HTMLElement>srcNativeInputEle.closest('ion-input,ion-textarea');
  if (srcComponentEle && srcComponentEle.parentElement) {
    const clonedInputEles = srcComponentEle.parentElement.querySelectorAll('.cloned-input');
    for (var i = 0; i < clonedInputEles.length; i++) {
      clonedInputEles[i].parentNode.removeChild(clonedInputEles[i]);
    }

    srcComponentEle.style.pointerEvents = '';
  }
  (<any>srcNativeInputEle.style)[plt.Css.transform] = '';
  srcNativeInputEle.style.opacity = '';
}

/**
 * @private
 */
@Directive({
  selector: '[next-input]'
})
export class NextInput {
  @Output() focused: EventEmitter<boolean> = new EventEmitter<boolean>();

  @HostListener('focus')
  receivedFocus() {
    console.debug('native-input, next-input received focus');
    this.focused.emit(true);
  }

}


text:
<?php

namespace Hyper\AdsBundle\Form;

use Symfony\Component\Form\FormBuilderInterface;
use FOS\UserBundle\Form\Type\ProfileFormType as BaseType;

class EditProfileType extends BaseType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);
    }

    public function getName()
    {
        return 'hyper_user_editprofile';
    }
}


text:
class CommentsController < ApplicationController
  load_and_authorize_resource
  skip_load_resource :only => [:index]

  # GET /comments
  # GET /comments.xml
  def index
    @comments = Comment.select("id, content, created_at").order("created_at DESC").all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @comments }
    end
  end

  # GET /comments/1
  # GET /comments/1.xml
  def show
    # @comment = Comment.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @comment }
    end
  end

  # GET /comments/new
  # GET /comments/new.xml
  def new
    # @comment = Comment.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @comment }
    end
  end

  # GET /comments/1/edit
  def edit
    # @comment = Comment.find(params[:id])
  end

  # POST /comments
  # POST /comments.xml
  def create
    # @comment = Comment.new(params[:comment])

    respond_to do |format|
      if gotcha_valid? && @comment.save
        format.html { redirect_to(comments_path, :notice => 'Comment was successfully created.') }
        format.xml  { render :xml => @comment, :status => :created, :location => @comment }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @comment.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /comments/1
  # PUT /comments/1.xml
  def update
    # @comment = Comment.find(params[:id])

    respond_to do |format|
      if @comment.update_attributes(params[:comment])
        format.html { redirect_to(comments_path, :notice => 'Comment was successfully updated.') }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @comment.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /comments/1
  # DELETE /comments/1.xml
  def destroy
    # @comment = Comment.find(params[:id])
    @comment.destroy

    respond_to do |format|
      format.html { redirect_to(comments_url) }
      format.xml  { head :ok }
    end
  end
end


text:
///////////////////////////////////////////////////////////////////////////////
//                                                                           //
// MIT X11 license, Copyright (c) 2005-2006 by:                              //
//                                                                           //
// Authors:                                                                  //
//      Michael Dominic K. <michaldominik@gmail.com>                         //
//      Senko Rasic <senko@senko.net>                                        //
//                                                                           //
// Permission is hereby granted, free of charge, to any person obtaining a   //
// copy of this software and associated documentation files (the             //
// "Software"), to deal in the Software without restriction, including       //
// without limitation the rights to use, copy, modify, merge, publish,       //
// distribute, sublicense, and/or sell copies of the Software, and to permit //
// persons to whom the Software is furnished to do so, subject to the        //
// following conditions:                                                     //
//                                                                           //
// The above copyright notice and this permission notice shall be included   //
// in all copies or substantial portions of the Software.                    //
//                                                                           //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS   //
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF                //
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN //
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,  //
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR     //
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE //
// USE OR OTHER DEALINGS IN THE SOFTWARE.                                    //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////

#include "GdvInspector.h"

// PRIVATE ////////////////////////////////////////////////////////////////////

enum {
        ARG_0,
        ARG_MIME,
        ARG_HASVIDEO,
        ARG_HASAUDIO,
        ARG_VIDEOFORMAT,
        ARG_AUDIOFORMAT,
        ARG_URL,
        ARG_LENGTH,
        ARG_TAGS,
        ARG_ERROR
};

static void                    gdv_inspector_dispose (GdvInspector *this);

static void                    gdv_inspector_finalize (GdvInspector *this);

static void                    gdv_inspector_init (GdvInspector *this);

static void                    gdv_inspector_class_init (GdvInspectorClass *klass);

static void                    gdv_inspector_get_property (GdvInspector *this, guint propid,
                                                           GValue *value, GParamSpec *pspec);

static void                    no_more_pads (GstElement *element, GdvInspector *this);

static gboolean                bus_callback (GstBus *bus, GstMessage *message,
                                             GdvInspector *this);

static gboolean                stop_inspecting (GdvInspector *this);

static void                    caps_notify (GstPad *pad, gpointer param,
                                            GdvInspector *this);

static void                    new_pad (GstElement *element, GstPad *pad, gboolean b, GdvInspector *this);

static gboolean                check_if_done (GdvInspector *this);

static gboolean                check_length (GdvInspector *this);

static void                    have_type (GstElement *typefind, gpointer data, GstCaps *caps, GdvInspector  *this);

static void                    unknown_type (GstElement *element, GstPad *pad, GstCaps *caps, GdvInspector *this);

static void                    parse_caps (GdvInspector *this, GstCaps *caps);

// GLOBAL /////////////////////////////////////////////////////////////////////

static GstPipelineClass*       ParentClass = NULL;

// PUBLIC /////////////////////////////////////////////////////////////////////

/* GObject get type */
GType                          gdv_inspector_get_type (void)
{
        static GType objecttype = 0;

        if (!objecttype) {

                static const GTypeInfo objectinfo = {
                        sizeof (GdvInspectorClass),
                        NULL,
                        NULL,
                        (GClassInitFunc) gdv_inspector_class_init,
                        NULL,
                        NULL,
                        sizeof (GdvInspector),
                        8,
                        (GInstanceInitFunc) gdv_inspector_init,
                };
                objecttype = g_type_register_static (GST_TYPE_PIPELINE, "GdvInspector", &objectinfo, 0);
        }

        return objecttype;
}

/* Create a new object */
GdvInspector*                   gdv_inspector_new (const gchar *filename)
{
        g_return_val_if_fail (filename != NULL, NULL);
        GDV_DEBUG_EXT ("Creating a new GdvInspector for %s", filename);

        GdvInspector *this = NULL;

        this = g_object_new (GDV_TYPE_INSPECTOR, NULL);
        if (this == NULL)
                goto failure;

        // Set the file location
        g_object_set (G_OBJECT (this->_Filesrc), "location", filename, NULL);

        // Set the Uri
        this->_Url = g_strdup (filename);
        return this;

        // FAILURE //
        failure:
        if (this != NULL)
                gst_object_unref (GST_OBJECT (this));

        return NULL;
}

/* Set the idle callback that will be called once we're done */
void                            gdv_inspector_set_done_func (GdvInspector *this, gpointer func)
{
        g_return_if_fail (GDV_IS_INSPECTOR (this));

        this->_DoneFunc = func;
}

/* Set the idle callback that will be called if the error occurs */
void                            gdv_inspector_set_error_func (GdvInspector *this, gpointer func)
{
        g_return_if_fail (GDV_IS_INSPECTOR (this));

        this->_ErrorFunc = func;
}

/* Start the process of inspecting */
void                            gdv_inspector_start (GdvInspector *this)
{
        g_return_if_fail (GDV_IS_INSPECTOR (this));

        // Bus watch
        this->_Watch = gst_bus_add_watch (gst_pipeline_get_bus (GST_PIPELINE (this)),
                                          (gpointer) bus_callback, this);

        GDV_DEBUG_ELEMENT ("Starting inspecting", NULL);
        gst_element_set_state (GST_ELEMENT (this), GST_STATE_PLAYING);
}

GType                          gdv_inspector_get_tag_type (GdvInspector *this, gchar *tag)
{
        g_assert (this != NULL); g_assert (tag != NULL); g_assert (GDV_IS_INSPECTOR(this));

        switch (gst_tag_get_type (tag)) {
                case G_TYPE_INT:
                case G_TYPE_LONG:
                case G_TYPE_INT64:
                    return G_TYPE_INT64;

                case G_TYPE_UINT:
                case G_TYPE_ULONG:
                case G_TYPE_UINT64:
                    return G_TYPE_UINT64;

                case G_TYPE_STRING:
                    return G_TYPE_STRING;
        }
        return G_TYPE_INVALID;
}

/* FIXME We don't do it via GObject because we'd have to marshall the entire structure. This is easier. */
gboolean                       gdv_inspector_get_int_tag (GdvInspector *this, gchar *tag, gint64 *value)
{

        g_assert (this != NULL); g_assert (tag != NULL); g_assert (GDV_IS_INSPECTOR(this));

        GDV_DEBUG_ELEMENT ("Requesting integer tag %s", tag, NULL);

        switch (gst_tag_get_type (tag)) {

                case G_TYPE_INT: {
                        gint val;
                        if (!gst_tag_list_get_int (this->_Tags, tag, &val)) return FALSE;
                        *value = (gint64) val;
                }
                break;
                case G_TYPE_LONG: {
                        glong val;
                        if (!gst_tag_list_get_long (this->_Tags, tag, &val)) return FALSE;
                        *value = (gint64) val;
                }
                break;
                case G_TYPE_INT64: {
                        gint64 val;
                        if (!gst_tag_list_get_int64 (this->_Tags, tag, &val)) return FALSE;
                        *value = (gint64) val;
                }
                break;
                default:
                        // that's ok, be graceful
                        // g_warning ("Requesting nonexistent/non-integer tag %s", tag);
                        return FALSE;
        }
        return TRUE;
}

/* Abort the current inspecting operation in progress */
void                            gdv_inspector_abort (GdvInspector *this)
{
        g_return_if_fail (GDV_IS_INSPECTOR (this));

        if (this->_Executed == TRUE)
                return;

        // FIXME: Mutex here!
        this->_DoneFunc = NULL;
        this->_ErrorFunc = NULL;

        gst_element_set_state ((GstElement *) this, GST_STATE_NULL);
}

gboolean                       gdv_inspector_get_uint_tag (GdvInspector *this, gchar *tag, guint64 *value)
{

        g_assert (this != NULL); g_assert (tag != NULL); g_assert (GDV_IS_INSPECTOR(this));

        GDV_DEBUG_ELEMENT ("Requesting unsigned integer tag %s", tag, NULL);

        switch (gst_tag_get_type (tag)) {

                case G_TYPE_UINT: {
                        guint val;
                        if (!gst_tag_list_get_uint (this->_Tags, tag, &val)) return FALSE;
                        *value = (guint64) val;
                }
                break;
                case G_TYPE_ULONG: {
                        gulong val;
                        if (!gst_tag_list_get_ulong (this->_Tags, tag, &val)) return FALSE;
                        *value = (guint64) val;
                }
                break;
                case G_TYPE_UINT64: {
                        guint64 val;
                        if (!gst_tag_list_get_uint64 (this->_Tags, tag, &val)) return FALSE;
                        *value = (guint64) val;
                }
                break;
                default:
                        // that's ok, be graceful
                        // g_warning ("Requesting nonexistent/non-unsigned-integer tag %s", tag);
                        return FALSE;
        }
        return TRUE;
}

gboolean                       gdv_inspector_get_string_tag (GdvInspector *this, gchar *tag, gchar **value)
{

        g_assert (this != NULL); g_assert (tag != NULL); g_assert (GDV_IS_INSPECTOR(this));

        GDV_DEBUG_ELEMENT ("Requesting string tag %s", tag, NULL);

        if (gst_tag_get_type (tag) == G_TYPE_STRING) {
                gchar *val;
                if (!gst_tag_list_get_string (this->_Tags, tag, &val)) return FALSE;
                *value = val;
                return TRUE;
                // FIXME the caller should free this afterwards
        }

        // that's ok, be graceful
        // g_warning ("Requesting nonexistent/non-unsigned-integer tag %s", tag);
        return FALSE;
}

// Private ////////////////////////////////////////////////////////////////////

/* GObject dispose */
static void                    gdv_inspector_dispose (GdvInspector *this)
{
        g_return_if_fail (GDV_IS_INSPECTOR (this));

        GDV_DEBUG_ELEMENT ("Disposing...", NULL);

        /*
        if (this->_VideoFormat != NULL) {
                g_object_unref (this->_VideoFormat);
                this->_VideoFormat = NULL;
        }

        if (this->_AudioFormat != NULL) {
                g_object_unref (this->_AudioFormat);
                this->_AudioFormat = NULL;
        }*/

        if (this->_Watch != -1) {
                g_source_remove (this->_Watch);
                this->_Watch = -1;
        }

        G_OBJECT_CLASS (ParentClass)->dispose (G_OBJECT (this));
}

static void                    gdv_inspector_finalize (GdvInspector *this)
{
        g_return_if_fail (GDV_IS_INSPECTOR (this));

        GDV_DEBUG_ELEMENT ("Finalizing...", NULL);

        if (this->_Mime != NULL) {
                g_free (this->_Mime);
                this->_Mime = NULL;
        }

        if (this->_Url != NULL) {
                g_free (this->_Url);
                this->_Url = NULL;
        }

        G_OBJECT_CLASS (ParentClass)->finalize (G_OBJECT (this));
}

/* GObject init */
static void                    gdv_inspector_init (GdvInspector *this)
{
        GDV_DEBUG_ELEMENT ("Initializing fresh GdvInspector object", NULL);

        this->_Mime = NULL;
        this->_Url = NULL;
        this->_Error = NULL;
        this->_HasVideo = FALSE;
        this->_HasAudio = FALSE;
        this->_VideoFormat = NULL;
        this->_AudioFormat = NULL;
        this->_Length = GDV_ZEROTIME;
        this->_Tags = gst_tag_list_new ();
        this->_Watch = -1;
        this->_Executed = FALSE;
        this->_Finished = FALSE;

        GDV_DEBUG_ELEMENT ("Creating all the elements", NULL);
        this->_Filesrc = gst_element_factory_make ("filesrc", NULL);
        g_assert (this->_Filesrc != NULL);
        g_object_set (G_OBJECT (this->_Filesrc), "blocksize", 1000000, NULL);

        this->_Decodebin = gst_element_factory_make ("decodebin", NULL);
        g_assert (this->_Decodebin != NULL);

        GDV_DEBUG_ELEMENT ("Connecting signals", NULL);

        gulong sigid1 = g_signal_connect (G_OBJECT(this->_Decodebin), "new-decoded-pad",
                                          G_CALLBACK(new_pad), this);

        gulong sigid2 = g_signal_connect (G_OBJECT(this->_Decodebin), "no-more-pads",
                                          G_CALLBACK(no_more_pads), this);

        g_assert (sigid1 != 0 && sigid2 != 0);

        GDV_DEBUG_ELEMENT ("Adding & linking", NULL);
        gst_bin_add_many ((GstBin *) this, this->_Filesrc, this->_Decodebin,
                          NULL);
        gboolean l1 = gst_element_link (this->_Filesrc, this->_Decodebin);
        g_assert (l1 == TRUE);

        // Typefinder
        GstElement *Typefind = gst_bin_get_by_name ((GstBin *) this->_Decodebin, "typefind");
        g_assert (Typefind != NULL);

        gulong sigid3 = g_signal_connect (G_OBJECT (Typefind), "have-type",
                                          G_CALLBACK(have_type), this);
        g_assert (sigid3 != 0);

        gulong sigid4 = g_signal_connect (G_OBJECT (this->_Decodebin), "unknown-type",
                                          G_CALLBACK (unknown_type), this);
        g_assert (sigid4 != 0);

}

/* GObject class init */
static void                    gdv_inspector_class_init (GdvInspectorClass *klass)
{
        GObjectClass *gobjectclass = (GObjectClass *) klass;

        gobjectclass->get_property = (gpointer) gdv_inspector_get_property;

        // Properties
        g_object_class_install_property (gobjectclass, ARG_URL,
					 g_param_spec_string
					 ("url", "Url",
					  "Url of the file",
					  NULL, G_PARAM_READABLE));

        g_object_class_install_property (gobjectclass, ARG_MIME,
					 g_param_spec_string
					 ("mime", "Mime",
					  "Mime type",
					  NULL, G_PARAM_READABLE));

        g_object_class_install_property (gobjectclass, ARG_HASAUDIO,
                                         g_param_spec_boolean
                                         ("hasaudio", "HasAudio",
                                          "If this source has audio",
                                          FALSE, G_PARAM_READABLE));

        g_object_class_install_property (gobjectclass, ARG_HASVIDEO,
                                         g_param_spec_boolean
                                         ("hasvideo", "HasVideo",
                                          "If this source has video",
                                          FALSE, G_PARAM_READABLE));

        g_object_class_install_property (gobjectclass, ARG_VIDEOFORMAT,
                                         g_param_spec_object
                                         ("videoformat", "VideoFormat",
                                          "VideoFormat object of this source",
                                          GDV_TYPE_VIDEOFORMAT,
                                          G_PARAM_READABLE));

        g_object_class_install_property (gobjectclass, ARG_AUDIOFORMAT,
                                         g_param_spec_object
                                         ("audioformat", "AudioFormat",
                                          "AudioFormat object of this source",
                                          GDV_TYPE_AUDIOFORMAT,
                                          G_PARAM_READABLE));

        g_object_class_install_property (gobjectclass, ARG_LENGTH,
                                         g_param_spec_uint64
                                         ("length", "Length",
                                          "Length of the source in nanoseconds",
                                          0, G_MAXUINT64, 0, G_PARAM_READABLE));

        g_object_class_install_property (gobjectclass, ARG_ERROR,
                                         g_param_spec_pointer
                                         ("error", "Error", "The GError that happened",
                                          G_PARAM_READABLE));

        ParentClass = g_type_class_ref (GST_TYPE_PIPELINE);
        gobjectclass->dispose = (gpointer) (gdv_inspector_dispose);
        gobjectclass->finalize = (gpointer) (gdv_inspector_finalize);
}

/* No more pads will be decoded. Called during preroll */
static void                    no_more_pads (GstElement *element, GdvInspector *this)
{
        GDV_DEBUG_ELEMENT ("No more pads", NULL);

        // if (check_if_done (this) == TRUE) {
        //        GDV_DEBUG_ELEMENT ("All resolved. Stopping inspecting", NULL);
        //        g_idle_add ((GSourceFunc) stop_inspecting, this);
        // }
}

static gboolean                bus_callback (GstBus *bus, GstMessage *message,
                                             GdvInspector *this)
{
        GDV_DEBUG_ELEMENT ("Bus callback for %s message %s", GST_OBJECT_NAME (this),
                           gst_message_type_get_name (GST_MESSAGE_TYPE (message)));

        switch (GST_MESSAGE_TYPE (message)) {

                case GST_MESSAGE_ERROR: {
                        GError *err;
                        gchar *debug;
                        gst_message_parse_error (message, &err, &debug);
                        this->_Error = err;
                        this->_Executed = TRUE;
                        GDV_DEBUG_ELEMENT ("Error: %s (%s)", this->_Error->message, debug);

                        // Call the callback if we have it
                        if (this->_ErrorFunc != NULL)
                                g_idle_add ((GSourceFunc) this->_ErrorFunc, this);

                        g_source_remove (this->_Watch);
                        this->_Watch = -1;

                        this->_Executed = TRUE;

                }
                break;

                case GST_MESSAGE_EOS:
                GDV_DEBUG_ELEMENT ("EOS reached. Stopping inspecting", NULL);
                g_idle_add ((GSourceFunc) stop_inspecting, this);
                break;

                case GST_MESSAGE_TAG: {
                        GDV_DEBUG_ELEMENT ("Appending new set of tags", NULL);
                        GstTagList *taglist = gst_tag_list_new ();
                        gst_message_parse_tag (message, &taglist);
                        this->_Tags = gst_tag_list_merge (this->_Tags, taglist, GST_TAG_MERGE_APPEND);
                }
                break;

                default:
                break;
        }

        return TRUE;
}

/* This is called via gidle_add to prevent race conditions */
static gboolean                stop_inspecting (GdvInspector *this)
{
        GDV_DEBUG_ELEMENT ("Stopping inspecting from idle", NULL);

        if (this->_Finished == TRUE)
                return FALSE;

        this->_Finished = TRUE;
        this->_Executed = TRUE;

        // only pause it if it has content and we recognized it
        // GstState end_state = (this->_HasAudio || this->_HasVideo) ? GST_STATE_PAUSED : GST_STATE_NULL;
        //gst_element_set_state ((GstElement *) this, end_state);
        //gst_element_get_state ((GstElement *) this, NULL, NULL, GST_CLOCK_TIME_NONE);

        // If we didn't managed to get a full info about video/audio,
        // we assume that source has no video/audio (even if we got a pad)
        this->_HasAudio = (this->_AudioFormat != NULL) ? TRUE : FALSE;
        this->_HasVideo = (this->_VideoFormat != NULL) ? TRUE : FALSE;

        // FIXME: Remove watch

        if (check_length (this) == TRUE)
                GDV_DEBUG_ELEMENT ("Length: %lld (%.2fs)", this->_Length, this->_Length / (gfloat) GST_SECOND);

        // So we can later on dispose it...
        gst_element_set_state ((GstElement *) this, GST_STATE_NULL);
        gst_element_get_state ((GstElement *) this, NULL, NULL, GST_CLOCK_TIME_NONE);

        if (this->_HasVideo == FALSE && this->_HasAudio == FALSE) {
                gdv_errors_set_error (GDV_ERROR_NO_VIDEO_NO_AUDIO, &this->_Error);
                if (this->_ErrorFunc != NULL)
                        g_idle_add (this->_ErrorFunc, this);
        } else {
                if (this->_DoneFunc != NULL)
                        g_idle_add (this->_DoneFunc, this);
        }

        return FALSE;
}

/* This is called when pads are fixated on the sink end. This is our main function
 * for learning all the nice stuff about source  */
static void                    caps_notify (GstPad *pad, gpointer param,
                                            GdvInspector *this)
{
        GDV_DEBUG_ELEMENT ("Caps notify function for pad", gst_pad_get_name (pad));
        GstCaps *caps = gst_pad_get_negotiated_caps (pad);

        if (caps == NULL)
                return;

        gchar *capsstring = gst_caps_to_string (caps);

        GDV_DEBUG_ELEMENT ("Caps: %s", capsstring);
        parse_caps (this, caps);

        gst_caps_unref (caps);
        g_free (capsstring);

        // Check if we're done
        if (check_if_done (this) == TRUE) {
                GDV_DEBUG_ELEMENT ("All resolved. Stopping inspecting", NULL);
                g_idle_add ((GSourceFunc) stop_inspecting, this);
        }
}

/* New pad was added */
static void                    new_pad (GstElement *element, GstPad *pad, gboolean b, GdvInspector *this)
{
        if (this->_Executed == TRUE) return; // #FIXME - hotfix for ticket #85

        GDV_DEBUG_ELEMENT ("New pad %s, creating elements", gst_pad_get_name (pad));

        GstElement *Queue = gst_element_factory_make ("queue", NULL);
        g_assert (Queue != NULL);
        GstElement *Fakesink = gst_element_factory_make ("fakesink", NULL);
        g_assert (Fakesink != NULL);

        GDV_DEBUG_ELEMENT ("Adding & linking elements", NULL);
        gst_bin_add_many ((GstBin *) this, Queue, Fakesink, NULL);

        // Check if we might extract some information now
        GstCaps *caps = gst_pad_get_caps (pad);
        parse_caps (this, caps);

        gulong sigid = g_signal_connect (gst_element_get_pad (Queue, "sink"), "notify::caps",
                                         G_CALLBACK (caps_notify), this);
        g_assert (sigid != 0);

        gboolean l1 = gst_element_link (Queue, Fakesink);
        g_assert (l1 == TRUE);

        GstPadLinkReturn l2 = gst_pad_link (pad, gst_element_get_pad (Queue, "sink"));
        g_assert (l2 == GST_PAD_LINK_OK);

        gst_element_set_state (Queue, GST_STATE_PAUSED);
        gst_element_set_state (Fakesink, GST_STATE_PAUSED);
}

/* Returns TRUE if we have all the information. False if we should rather continue inspecting */
static gboolean                check_if_done (GdvInspector *this)
{
        gboolean c1, c2;

        c1 = FALSE;
        if (this->_HasVideo == FALSE)
                c1 = TRUE;
        if (this->_HasVideo == TRUE && this->_VideoFormat != NULL)
                c1 = TRUE;

        c2 = FALSE;
        if (this->_HasAudio == FALSE)
                c2 = TRUE;
        if (this->_HasAudio == TRUE && this->_AudioFormat != NULL)
                c2 = TRUE;

        if (c1 == TRUE && c2 == TRUE)
                return TRUE;
        else
                return FALSE;
}

/* Analyze all the pads of the decodebin to find the length of the source. Return FALSE on failure. */
static gboolean                check_length (GdvInspector *this)
{
        GSList *iterator = (GSList *) GST_ELEMENT_PADS (this->_Decodebin);
        if (g_slist_length (iterator) <= 1)
                return FALSE;

        GDV_DEBUG_ELEMENT ("Checking the length of the source, analyzing %d pads", g_slist_length (iterator));

        while (iterator != NULL)
        {
                GstPad *currentpad = iterator->data;

                if (GST_PAD_DIRECTION (currentpad) == GST_PAD_SINK) {
                        iterator = g_slist_next (iterator);
                        continue;
                }

                // Check length
                GstFormat fmt = GST_FORMAT_TIME;
                gint64 len = 0;
                gst_pad_query_duration (currentpad, &fmt, &len);

                if (fmt == GST_FORMAT_TIME && len != 0) {
                        this->_Length = len;
                        return TRUE;
                }

                iterator = g_slist_next (iterator);
        }

        // If we're here, it means we didn't manage to find it. Our last chance is
        // the element query
        GDV_DEBUG_ELEMENT ("Trying to use the decodebin element for length query", NULL);

        gint64 len = 0;
        GstFormat fmt = GST_FORMAT_TIME;
        gst_element_query_duration (this->_Decodebin, &fmt, &len);
        if (fmt == GST_FORMAT_TIME && len != 0) {
                this->_Length = len;
                return TRUE;
        }

        return FALSE;
}

/* This is fired by the typefinder. We use it to set the mime */
static void                    have_type (GstElement *typefind, gpointer data, GstCaps *caps, GdvInspector  *this)
{
        this->_Mime = gst_caps_to_string (caps);
        GDV_DEBUG_ELEMENT ("Has type: %s", this->_Mime);
}

/* This is fired by the decodebin. Source could not be decoded */
static void                    unknown_type (GstElement *element, GstPad *pad, GstCaps *caps, GdvInspector *this)
{
        GDV_DEBUG_ELEMENT ("Pad %d has unknown type (caps: %s)", gst_pad_get_name (pad), gst_caps_to_string (caps));
}

/* Here we parse caps (either fixed or negotiated) and create all the format info */
static void                    parse_caps (GdvInspector *this, GstCaps *caps)
{
        g_assert (caps != NULL);
        GDV_DEBUG_ELEMENT ("Parsing caps %s", gst_caps_to_string (caps));

        if (gst_caps_is_any (caps) == TRUE) {
                GDV_DEBUG_ELEMENT ("ANY caps, aborting", NULL);
                return;
        }

        GstStructure *str;
        str = gst_caps_get_structure (caps, 0);
        if (str == NULL) {
                GDV_WARNING_ELEMENT ("No structure in caps", NULL);
                return;
        }

        if (g_strrstr (gst_structure_get_name (str), "video")) {
                GDV_DEBUG_ELEMENT ("Got some video info in caps", NULL);
                this->_HasVideo = TRUE;

                if (this->_VideoFormat == NULL && gdv_videoformat_caps_ok (caps))
                        this->_VideoFormat = gdv_videoformat_new (caps);
        }

        if (g_strrstr (gst_structure_get_name (str), "audio")) {
                GDV_DEBUG_ELEMENT ("Got some audio info in caps", NULL);
                this->_HasAudio = TRUE;

                if (this->_AudioFormat == NULL && gdv_audioformat_caps_ok (caps))
                        this->_AudioFormat = gdv_audioformat_new (caps);
        }
}

/* GObject get property */
static void                    gdv_inspector_get_property (GdvInspector *this, guint propid,
                                                           GValue *value, GParamSpec *pspec)
{
        g_return_if_fail (GDV_IS_INSPECTOR (this));
        g_return_if_fail (this->_Executed == TRUE);

        switch (propid) {

	        case ARG_URL:
                g_value_set_string (value, this->_Url);
                break;

                case ARG_MIME:
                g_value_set_string (value, this->_Mime);
                break;

                case ARG_VIDEOFORMAT:
                g_assert (this->_VideoFormat != NULL);
                g_value_set_object (value, this->_VideoFormat);
                break;

                case ARG_AUDIOFORMAT:
                g_assert (this->_AudioFormat != NULL);
                g_value_set_object (value, this->_AudioFormat);
                break;

                case ARG_HASVIDEO:
                g_value_set_boolean (value, this->_HasVideo);
                break;

                case ARG_HASAUDIO:
                g_value_set_boolean (value, this->_HasAudio);
                break;

                case ARG_LENGTH:
                g_value_set_uint64 (value, this->_Length);
                break;

                case ARG_ERROR:
                g_return_if_fail (this->_Error != NULL);
                g_value_set_pointer (value, this->_Error);
                break;

                default:
                G_OBJECT_WARN_INVALID_PROPERTY_ID (G_OBJECT (this), propid, pspec);
                break;
        }
}


text:
package org.synyx.urlaubsverwaltung.calendar;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
interface CompanyCalendarAccessibleRepository extends CrudRepository<CompanyCalendarAccessible, Long> {

    List<CompanyCalendarAccessible> findAll();
}


text:
package org.wso2.carbon.apimgt.hybrid.gateway.usage.publisher.internal;

import org.junit.Test;
import org.mockito.Mockito;
import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService;
import org.wso2.carbon.ntask.core.service.TaskService;
import org.wso2.carbon.user.core.service.RealmService;

/**
 *  ServiceReferenceHolder Test Class
 *
 */
public class ServiceReferenceHolderTest {

    @Test
    public void getInstance() throws Exception {
        ServiceReferenceHolder.getInstance();
    }

    @Test
    public void getRealmService() throws Exception {
        ServiceReferenceHolder.getInstance().getRealmService();
    }

    @Test
    public void getAPIManagerConfigurationService() throws Exception {
        ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService();
    }

    @Test public void setAPIManagerConfigurationService() throws Exception {
        APIManagerConfigurationService apiManagerConfigurationService = Mockito
                .mock(APIManagerConfigurationService.class);
        ServiceReferenceHolder.getInstance().setAPIManagerConfigurationService(apiManagerConfigurationService);
    }

    @Test
    public void setTaskService() throws Exception {
        TaskService taskService = Mockito.mock(TaskService.class);
        ServiceReferenceHolder.getInstance().setTaskService(taskService);
    }

    @Test
    public void getTaskService() throws Exception {
        ServiceReferenceHolder.getInstance().getTaskService();
    }

    @Test
    public void setRealmService() throws Exception {
        RealmService realmService = Mockito.mock(RealmService.class);
        ServiceReferenceHolder.getInstance().setRealmService(realmService);
    }

}


text:
from django.urls import re_path, include
from feedback.views import *

urlpatterns = [
    # '',
    re_path(r'^send', send_feedback),
    # (r'^bookmark', send_bookmark),
]


text:
package ru.org.linux.user

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import ru.org.linux.group.GroupDao
import ru.org.linux.section.SectionService
import ru.org.linux.spring.dao.{DeleteInfoDao, MsgbaseDao}
import ru.org.linux.topic.TopicTagService
import ru.org.linux.util.bbcode.LorCodeService

import scala.collection.JavaConverters._

@Service
class UserEventPrepareService @Autowired() (
  msgbaseDao:MsgbaseDao,
  lorCodeService: LorCodeService,
  userService:UserService,
  deleteInfoDao:DeleteInfoDao,
  sectionService:SectionService,
  groupDao:GroupDao,
  tagService: TopicTagService
) {
  /**
   * @param events      список событий
   * @param readMessage возвращать ли отрендеренное содержимое уведомлений (используется только для RSS)
   * @param secure      является ли текущие соединение https
   */
  def prepare(events:java.util.List[UserEvent], readMessage:Boolean, secure:Boolean):java.util.List[PreparedUserEvent] = {
    val evts = events.asScala

    val userIds = (evts.map(_.getCommentAuthor) ++ evts.map(_.getTopicAuthor)).filter(_ != 0).distinct

    val users = userService.getUsersCached(userIds.map(Integer.valueOf).asJavaCollection).asScala.map { user ⇒
      user.getId -> user
    }.toMap

    val tags = tagService.tagRefs(evts.map(_.getTopicId).distinct).mapValues(_.map(_.name))

    val prepared = evts map { event ⇒
      val msgid = if (event.isComment) event.getCid else event.getTopicId

      val text = if (readMessage) {
        val messageText = msgbaseDao.getMessageText(msgid)

        Some(lorCodeService.prepareTextRSS(messageText.getText, secure, messageText.isLorcode))
      } else {
        None
      }

      val topicAuthor = users(event.getTopicAuthor)

      val commentAuthor = if (event.isComment) {
        users.get(event.getCommentAuthor)
      } else {
        None
      }

      val bonus = (if ("DEL" == event.getType.getType) {
        Option(deleteInfoDao.getDeleteInfo(msgid))
      } else {
        None
      }) map (_.getBonus)

      val group = groupDao.getGroup(event.getGroupId)

      PreparedUserEvent(
        event = event,
        messageText = text,
        topicAuthor = topicAuthor,
        commentAuthor = commentAuthor,
        bonus = bonus,
        section = sectionService.getSection(group.getSectionId),
        group = group,
        tags = tags.getOrElse(event.getTopicId, Seq.empty).take(TopicTagService.MaxTagsInTitle)
      )
    }

    prepared.asJava
  }
}


text:
import csv
from HTMLParser import HTMLParser
from optparse import make_option
import StringIO
from zipfile import ZipFile, ZipInfo

from django.core.management.base import BaseCommand, CommandError

from moocng.courses.models import Course
from moocng.courses.marks import calculate_course_mark

class Command(BaseCommand):

    help = ("create a zip bundle with csv files with students (firt_name, "
            "last_name, email)")

    option_list = BaseCommand.option_list + (
        make_option('-c', '--course',
                    action='append',
                    dest='courses',
                    default=[],
                    help='Only list this courses (can repeat this param)'),
        make_option('-f', '--filename',
                    action='store',
                    dest='filename',
                    default="",
                    help="Filename.zip to save the csv files"),
        make_option('-l', '--limit',
                    action='store',
                    dest='limit',
                    default="10000",
                    help="Limit of the users that will be processed"),
    )

    def error(self, message):
        self.stderr.write("%s\n" % message.encode("ascii", "replace"))

    def message(self, message):
        self.stdout.write("%s\n" % message.encode("ascii", "replace"))

    def handle(self, *args, **options):

        if not options["filename"]:
            raise CommandError("-f filename.zip is required")

        limit = options["limit"]

        if options["courses"]:
            courses = options["courses"]
            courses = Course.objects.filter(slug__in=options["courses"])
        else:
            courses = Course.objects.all()

        if not courses:
            raise CommandError("Courses not found")

        if options["filename"].endswith(".zip"):
            self.filename = options["filename"]
        else:
            self.filename = "%s.zip" % options["filename"]

        h = HTMLParser()

        zip = ZipFile(self.filename, mode="w")

        for course in courses:
            self.message("Adding course file %s.csv" % course.slug)

            course_file = StringIO.StringIO()

            course_csv = csv.writer(course_file, quoting=csv.QUOTE_ALL)
            headers = ["first_name", "last_name", "email", "mark"]

            course_csv.writerow(headers)

            students = course.students.all()[:limit]
            headers = ["first_name", "last_name", "email"]

            for student in students:
                row = []
                for field in headers:
                    fieldvalue = getattr(student, field)
                    row.append(h.unescape(fieldvalue).encode("ascii", "ignore"))
                mark, mark_info = calculate_course_mark(course, student)
                row.append(mark)
                course_csv.writerow(row)

            course_fileinfo = ZipInfo("%s.csv" % course.slug)

            course_file.seek(0)

            zip.writestr(course_fileinfo, course_file.read())

            course_file.close()

        zip.close()

        self.message("Created %s file" % self.filename)


text:
cd "${0%/*}"  # Change to script directory.

if ! command -v sphinx-build &> /dev/null
then
    echo "sphinx could not be found. Please install with 'pip3 install sphinx sphinx_rtd_theme recommonmark.'"
    exit
fi

cleanup() {
  rm -rf single.py* _build __pycache__
  exit
}
trap cleanup ERR INT TERM

echo 'Paste the docstring to check including the """ (end with ctrl+D).'
cat > single.py

sphinx-build -b singlehtml -q -T . _build
cleanup


text:
/* eslint-disable func-names, space-before-function-paren, prefer-arrow-callback, quotes, no-var, vars-on-top, max-len */
(function() {
  $(function() {
    $("body").on("click", ".js-details-target", function() {
      var container;
      container = $(this).closest(".js-details-container");
      return container.toggleClass("open");
    });
    // Show details content. Hides link after click.
    //
    // %div
    //   %a.js-details-expand
    //   %div.js-details-content
    //
    return $("body").on("click", ".js-details-expand", function(e) {
      $(this).next('.js-details-content').removeClass("hide");
      $(this).hide();

      var truncatedItem = $(this).siblings('.js-details-short');
      if (truncatedItem.length) {
        truncatedItem.addClass("hide");
      }
      return e.preventDefault();
    });
  });
}).call(window);


text:
package javax.el;

import java.beans.FeatureDescriptor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import junit.framework.TestCase;
import javax.el.TestContext;

public class CompositeELResolverTest extends TestCase {
	ELContext context = new TestContext();

	Map<Integer,Integer> sampleMap() {
		Map<Integer,Integer> map = new HashMap<Integer, Integer>();
		for (int i = 0; i < 3; i++) {
			map.put(i, i+1);
		}
		return map;
	}

	public void testGetCommonPropertyType() {
		CompositeELResolver resolver = new CompositeELResolver();
		assertNull(resolver.getCommonPropertyType(context, null));
		assertNull(resolver.getCommonPropertyType(context, "foo"));

		resolver.add(new ArrayELResolver());
		assertNull(resolver.getCommonPropertyType(context, null));
		assertNull(resolver.getCommonPropertyType(context, "foo"));
		assertSame(Integer.class, resolver.getCommonPropertyType(context, new int[0]));

		resolver.add(new ListELResolver());
		assertNull(resolver.getCommonPropertyType(context, null));
		assertNull(resolver.getCommonPropertyType(context, "foo"));
		assertSame(Integer.class, resolver.getCommonPropertyType(context, new ArrayList<String>()));

		resolver.add(new MapELResolver());
		assertNull(resolver.getCommonPropertyType(context, null));
		assertNull(resolver.getCommonPropertyType(context, "foo"));
		assertSame(Object.class, resolver.getCommonPropertyType(context, new HashMap<String,String>()));
	}

	private int count(Iterator<FeatureDescriptor> iterator) {
		int count = 0;
		while (iterator.hasNext()) {
			iterator.next();
			count++;
		}
		return count;
	}

	public void testGetFeatureDescriptors() {
		CompositeELResolver resolver = new CompositeELResolver();
		assertFalse(resolver.getFeatureDescriptors(context, null).hasNext());
		assertFalse(resolver.getFeatureDescriptors(context, "foo").hasNext());
		assertFalse(resolver.getFeatureDescriptors(context, sampleMap()).hasNext());

		resolver.add(new MapELResolver());
		assertEquals(3, count(resolver.getFeatureDescriptors(context, sampleMap()))); // 0, 1, 2

		resolver.add(new ArrayELResolver());
		resolver.add(new BeanELResolver());
		resolver.add(new ListELResolver());
		assertEquals(5, count(resolver.getFeatureDescriptors(context, sampleMap()))); // 0, 1, 2, class, empty
	}

	public void testGetType() {
		CompositeELResolver resolver = new CompositeELResolver();
		assertNull(resolver.getType(context, null, "foo"));
		assertNull(resolver.getType(context, "foo", "class"));

		resolver.add(new MapELResolver());
		assertNull(resolver.getType(context, null, "foo"));
		assertNull(resolver.getType(context, "foo", "class"));
		assertEquals(Object.class, resolver.getType(context, sampleMap(), "foo"));
		assertEquals(Object.class, resolver.getType(context, sampleMap(), 0));

		resolver.add(new BeanELResolver());
		assertNull(resolver.getType(context, null, "foo"));
		assertEquals(Class.class, resolver.getType(context, "foo", "class"));
		assertEquals(Object.class, resolver.getType(context, sampleMap(), "foo"));
		assertEquals(Object.class, resolver.getType(context, sampleMap(), 0));
	}

	public void testGetValue() {
		CompositeELResolver resolver = new CompositeELResolver();
		assertNull(resolver.getValue(context, null, "foo"));
		assertNull(resolver.getValue(context, "foo", "class"));

		resolver.add(new MapELResolver());
		assertNull(resolver.getValue(context, null, "foo"));
		assertNull(resolver.getValue(context, "foo", "class"));
		assertNull(resolver.getValue(context, sampleMap(), "foo"));
		assertEquals(1, resolver.getValue(context, sampleMap(), 0));

		resolver.add(new BeanELResolver());
		assertNull(resolver.getValue(context, null, "foo"));
		assertEquals(String.class, resolver.getValue(context, "foo", "class"));
		assertNull(resolver.getValue(context, sampleMap(), "foo"));
		assertEquals(1, resolver.getValue(context, sampleMap(), 0));
	}

	public void testIsReadOnly() {
		CompositeELResolver resolver = new CompositeELResolver();
		assertFalse(resolver.isReadOnly(context, null, "foo"));
		assertFalse(resolver.isReadOnly(context, "foo", "class"));

		resolver.add(new MapELResolver());
		assertFalse(resolver.isReadOnly(context, null, "foo"));
		assertFalse(resolver.isReadOnly(context, "foo", "class"));
		assertFalse(resolver.isReadOnly(context, sampleMap(), "foo"));
		assertFalse(resolver.isReadOnly(context, sampleMap(), 0));

		resolver.add(new BeanELResolver());
		assertFalse(resolver.isReadOnly(context, null, "foo"));
		assertTrue(resolver.isReadOnly(context, "foo", "class"));
		assertFalse(resolver.isReadOnly(context, sampleMap(), "foo"));
		assertFalse(resolver.isReadOnly(context, sampleMap(), 0));
	}

	public void testSetValue() {
		CompositeELResolver resolver = new CompositeELResolver();
		resolver.setValue(context, null, "foo", "bar");
		resolver.setValue(context, "foo", "class", Integer.class);

		resolver.add(new MapELResolver());
		resolver.setValue(context, null, "foo", "bar");
		resolver.setValue(context, "foo", "class", Integer.class);
		Map<?,?> map = sampleMap();
		resolver.setValue(context, map, "foo", "bar");
		assertEquals("bar", map.get("foo"));
		resolver.setValue(context, map, 0, 999);
		assertEquals(999, map.get(0));

		resolver.add(new BeanELResolver());
		resolver.setValue(context, null, "foo", "bar");
		try {
			resolver.setValue(context, "foo", "class", Integer.class);
			fail();
		} catch (PropertyNotWritableException e) {
			// fine
		}
		map = sampleMap();
		resolver.setValue(context, map, "foo", "bar");
		assertEquals("bar", map.get("foo"));
		resolver.setValue(context, map, 0, 999);
		assertEquals(999, map.get(0));
	}

}


text:
using System;
using System.Collections.Generic;

namespace Eshunna.Lib.PLY
{
    public class PlyFileHeader
    {
        #region Static

        public static PlyFileHeader GetDefault()
        {
            var header = new PlyFileHeader
            {
                FileFormatVersion = PlyFile.GetDefaultVersion(),
                FileDataFormat = PlyFileDataFormat.ASCII
            };
            return header;
        }

        #endregion

        public PlyFileDataFormat FileDataFormat { get; set; }
        public Version FileFormatVersion { get; set; }
        public List<string> Comments { get; }
        public List<PlyElementDescriptor> Elements { get; }

        public PlyFileHeader()
        {
            this.Comments = new List<string>();
            this.Elements = new List<PlyElementDescriptor>();
        }
    }
}


text:
if [ "$TRAVIS_PULL_REQUEST" == "false" ] && [ "$TRAVIS_TAG" != "" ]; then
    docker build -t netflixoss/vector .
    docker tag netflixoss/vector:latest netflixoss/vector:$TRAVIS_TAG
    docker images
    docker login -u=${dockerhubUsername} -p=${dockerhubPassword}
    docker push netflixoss/vector
fi


text:
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class User extends CI_Controller {

    public function purchases() {
        $this->load->view('users/index');
        echo "yes";
    }
}


text:
package com.wrmsr;

public class App
{
    public static void main(String[] args)
    {
        System.out.println("Hello World!");
    }
}


text:
/*
 * main.cpp
 *
 *  Created on: ${date}
 *      Author: ${author}
 */

#include <stdio.h>
#include <unistd.h>

#include "MyServer.h"

using namespace gwc;
using namespace std;
using namespace gwc::server;

int main(int argc, char **argv) {
	string serverConf = "server.properties";
	int ch;
	opterr = 0;
	while ((ch = getopt(argc, argv, "f:")) != -1) {
		switch (ch) {
		case 'f':
			serverConf = optarg;
			break;
		default:
			printf("other option :%c\n", ch);
		}
	}

	MyServer server;
	if (0 != server.Run(serverConf)) {
		printf("Server::Run failed, %s\n", server.GetLastErr());
		return -1;
	}

	return 0;
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework.Input;
using NUnit.Framework;
using SdlDotNet.Input;

namespace Tests.Microsoft.Xna.Framework.Input
{
    [TestFixture]
    public class GamePadDPadTests
    {
        [Test]
        public void ValidateToGamePadDPadFromJoystickHatStates()
        {
            GamePadDPad o = new GamePadDPad();
            GamePadDPad.ToGamePadDPad(ref o, JoystickHatStates.None);
            Assert.AreEqual(ButtonState.Released, o.Up, "For JoystickHatStates.None, o.Up = ButtonState.Released");
            Assert.AreEqual(ButtonState.Released, o.Right, "For JoystickHatStates.None, o.Right = ButtonState.Released");
            Assert.AreEqual(ButtonState.Released, o.Down, "For JoystickHatStates.None, o.Down = ButtonState.Released");
            Assert.AreEqual(ButtonState.Released, o.Left, "For JoystickHatStates.None, o.Left = ButtonState.Released");

            GamePadDPad.ToGamePadDPad(ref o, JoystickHatStates.Up);
            Assert.AreEqual(ButtonState.Pressed, o.Up, "For JoystickHatStates.Up, o.Up = ButtonState.Pressed");
            Assert.AreEqual(ButtonState.Released, o.Right, "For JoystickHatStates.Up, o.Right = ButtonState.Released");
            Assert.AreEqual(ButtonState.Released, o.Down, "For JoystickHatStates.Up, o.Down = ButtonState.Released");
            Assert.AreEqual(ButtonState.Released, o.Left, "For JoystickHatStates.Up, o.Left = ButtonState.Released");

            GamePadDPad.ToGamePadDPad(ref o, JoystickHatStates.RightUp);
            Assert.AreEqual(ButtonState.Pressed, o.Up, "For JoystickHatStates.RightUp, o.Up = ButtonState.Pressed");
            Assert.AreEqual(ButtonState.Pressed, o.Right, "For JoystickHatStates.RightUp, o.Right = ButtonState.Pressed");
            Assert.AreEqual(ButtonState.Released, o.Down, "For JoystickHatStates.RightUp, o.Down = ButtonState.Released");
            Assert.AreEqual(ButtonState.Released, o.Left, "For JoystickHatStates.RightUp, o.Left = ButtonState.Released");

            GamePadDPad.ToGamePadDPad(ref o, JoystickHatStates.Right);
            Assert.AreEqual(ButtonState.Released, o.Up, "For JoystickHatStates.Right, o.Up = ButtonState.Released");
            Assert.AreEqual(ButtonState.Pressed, o.Right, "For JoystickHatStates.Right, o.Right = ButtonState.Pressed");
            Assert.AreEqual(ButtonState.Released, o.Down, "For JoystickHatStates.Right, o.Down = ButtonState.Released");
            Assert.AreEqual(ButtonState.Released, o.Left, "For JoystickHatStates.Right, o.Left = ButtonState.Released");

            GamePadDPad.ToGamePadDPad(ref o, JoystickHatStates.RightDown);
            Assert.AreEqual(ButtonState.Released, o.Up, "For JoystickHatStates.RightDown, o.Up = ButtonState.Released");
            Assert.AreEqual(ButtonState.Pressed, o.Right, "For JoystickHatStates.RightDown, o.Right = ButtonState.Pressed");
            Assert.AreEqual(ButtonState.Pressed, o.Down, "For JoystickHatStates.RightDown, o.Down = ButtonState.Pressed");
            Assert.AreEqual(ButtonState.Released, o.Left, "For JoystickHatStates.RightDown, o.Left = ButtonState.Released");

            GamePadDPad.ToGamePadDPad(ref o, JoystickHatStates.Down);
            Assert.AreEqual(ButtonState.Released, o.Up, "For JoystickHatStates.Down, o.Up = ButtonState.Released");
            Assert.AreEqual(ButtonState.Released, o.Right, "For JoystickHatStates.Down, o.Right = ButtonState.Released");
            Assert.AreEqual(ButtonState.Pressed, o.Down, "For JoystickHatStates.Down, o.Down = ButtonState.Pressed");
            Assert.AreEqual(ButtonState.Released, o.Left, "For JoystickHatStates.Down, o.Left = ButtonState.Released");

            GamePadDPad.ToGamePadDPad(ref o, JoystickHatStates.LeftDown);
            Assert.AreEqual(ButtonState.Released, o.Up, "For JoystickHatStates.LeftDown, o.Up = ButtonState.Released");
            Assert.AreEqual(ButtonState.Released, o.Right, "For JoystickHatStates.LeftDown, o.Right = ButtonState.Released");
            Assert.AreEqual(ButtonState.Pressed, o.Down, "For JoystickHatStates.LeftDown, o.Down = ButtonState.Pressed");
            Assert.AreEqual(ButtonState.Pressed, o.Left, "For JoystickHatStates.LeftDown, o.Left = ButtonState.Pressed");

            GamePadDPad.ToGamePadDPad(ref o, JoystickHatStates.Left);
            Assert.AreEqual(ButtonState.Released, o.Up, "For JoystickHatStates.Left, o.Up = ButtonState.Released");
            Assert.AreEqual(ButtonState.Released, o.Right, "For JoystickHatStates.Left, o.Right = ButtonState.Released");
            Assert.AreEqual(ButtonState.Released, o.Down, "For JoystickHatStates.Left, o.Down = ButtonState.Released");
            Assert.AreEqual(ButtonState.Pressed, o.Left, "For JoystickHatStates.Left, o.Left = ButtonState.Pressed");

            GamePadDPad.ToGamePadDPad(ref o, JoystickHatStates.LeftUp);
            Assert.AreEqual(ButtonState.Pressed, o.Up, "For JoystickHatStates.LeftUp, o.Up = ButtonState.Pressed");
            Assert.AreEqual(ButtonState.Released, o.Right, "For JoystickHatStates.LeftUp, o.Right = ButtonState.Released");
            Assert.AreEqual(ButtonState.Released, o.Down, "For JoystickHatStates.LeftUp, o.Down = ButtonState.Released");
            Assert.AreEqual(ButtonState.Pressed, o.Left, "For JoystickHatStates.LeftUp, o.Left = ButtonState.Pressed");

        }
    }
}
#endif


text:
package com.advancedpwr.samples;

public class ObjectHolder
{
	protected Object fieldObject;

	public Object getObject()
	{
		return fieldObject;
	}

	public void setObject( Object object )
	{
		fieldObject = object;
	}
}


text:
namespace Yt
{
	/// Vertex attribute type.
	enum class VA
	{
		f,  ///< Single float.
		f2, ///< Vector of 2 floats.
		f3, ///< Vector of 3 floats.
		f4, ///< Vector of 4 floats.
	};

	class MeshData
	{
	public:
		std::vector<VA> _vertex_format;
		Buffer _vertex_data;
		std::vector<uint32_t> _indices;

		bool make_uint16_indices(Buffer&) const;
	};
}


text:
package main // <<<<< godoc,1,1,1,1,pass

import "fmt"

func main() {
	Exported()
}

func Exported() {
	fmt.Println("Hello, Go")
}

type Shaper interface {
}

type Rectangle struct {
}

type square struct {
}

type circle interface {
}

type Oval struct {
}

func A() { }; func B() { }; func c() { }; func D() { }

type alpha struct { }; type Beta struct { }


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>statsmodels.tsa.statespace.varmax.VARMAXResults.plot_diagnostics — statsmodels 0.8.0 documentation</title>

    <link rel="stylesheet" href="../_static/nature.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="shortcut icon" href="../_static/statsmodels_hybi_favico.ico"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="statsmodels.tsa.statespace.varmax.VARMAXResults.predict" href="statsmodels.tsa.statespace.varmax.VARMAXResults.predict.html" />
    <link rel="prev" title="statsmodels.tsa.statespace.varmax.VARMAXResults.normalized_cov_params" href="statsmodels.tsa.statespace.varmax.VARMAXResults.normalized_cov_params.html" />
<link rel="stylesheet" href="../_static/examples.css" type="text/css" />
<link rel="stylesheet" href="../_static/facebox.css" type="text/css" />

Navigation

          index

          modules |

          next |

          previous |

Install
  |

Support
  |

Bugs
  |

Develop
  |

Examples
  |

FAQ
  |

Time Series Analysis by State Space Methods statespace |

statsmodels.tsa.statespace.varmax.VARMAXResults |

statsmodels.tsa.statespace.varmax.VARMAXResults.plot_diagnostics¶

VARMAXResults.plot_diagnostics(variable=0, lags=10, fig=None, figsize=None)¶

Diagnostic plots for standardized residuals of one endogenous variable

<col class="field-name" />
<col class="field-body" />

Parameters:
variable : integer, optional

Index of the endogenous variable for which the diagnostic plots
should be created. Default is 0.

lags : integer, optional

Number of lags to include in the correlogram. Default is 10.

fig : Matplotlib Figure instance, optional

If given, subplots are created in this figure instead of in a new
figure. Note that the 2x2 grid will be created in the provided
figure using fig.add_subplot().

figsize : tuple, optional

If a figure is created, this argument allows specifying a size.
The tuple is (width, height).

See also

statsmodels.graphics.gofplots.qqplot, statsmodels.graphics.tsaplots.plot_acf

Notes

Produces a 2x2 plot grid with the following plots (ordered clockwise
from top left):

Standardized residuals over time

Histogram plus estimated density of standardized residulas, along
with a Normal(0,1) density plotted for reference.

Normal Q-Q plot, with Normal reference line.

Correlogram

Previous topic

statsmodels.tsa.statespace.varmax.VARMAXResults.normalized_cov_params

Next topic

statsmodels.tsa.statespace.varmax.VARMAXResults.predict

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">

<input type="text" name="q" />

<input type="submit" value="Go" />

      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

        © Copyright 2009-2017, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
      Created using Sphinx 1.5.3.


text:
// Copyright 2020 Google LLC

// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd

package glob

import (
	"context"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"reflect"
	"runtime"
	"sort"
	"strings"
	"testing"

	"github.com/google/go-cmp/cmp"
	"github.com/google/go-cmp/cmp/cmpopts"
)

// contains reports whether vector contains the string s.
func contains(vector []string, s string) bool {
	for _, elem := range vector {
		if elem == s {
			return true
		}
	}
	return false
}

func cmpStrings(x, y string) bool {
	return x < y
}

var sortStringSlices = cmpopts.SortSlices(cmpStrings)

func TestGlob(t *testing.T) {
	if err := os.Chdir("testdata"); err != nil {
		t.Fatal(err)
	}
	defer os.Chdir("..")

	for _, tt := range []struct {
		pattern string
		results []string
	}{
		{"match", []string{"match"}},
		{"mat?h", []string{"match"}},
		{"../*/match", []string{"../testdata/match"}},
		{"*", []string{"a", "b", "match", "other"}},
		{"*/*", []string{"a/a", "a/b", "a/c", "b/a"}},
		{"no-existo/*", []string{}},
	} {
		pattern := tt.pattern
		results := tt.results
		if runtime.GOOS == "windows" {
			pattern = filepath.Clean(pattern)
			var cleaned []string
			for _, r := range results {
				cleaned = append(cleaned, r)
			}
			results = cleaned
		}
		matches, err := Glob(context.Background(), pattern)
		if err != nil {
			t.Errorf("Glob error for %q: %s", pattern, err)
			continue
		}
		if diff := cmp.Diff(results, matches, sortStringSlices); diff != "" {
			t.Errorf("Bad results from Glob(%#q), -want +got: %v", pattern, diff)
		}
	}

	for _, pattern := range []string{"no_match", "../*/no_match"} {
		matches, err := Glob(context.Background(), pattern)
		if err != nil {
			t.Errorf("Glob error for %q: %s", pattern, err)
			continue
		}
		if len(matches) != 0 {
			t.Errorf("Glob(%#q) = %#v want []", pattern, matches)
		}
	}
}

func TestGlobError(t *testing.T) {
	_, err := Glob(context.Background(), "[]")
	if err == nil {
		t.Error("expected error for bad pattern; got none")
	}
}

func TestGlobUNC(t *testing.T) {
	// Just make sure this runs without crashing for now.
	// See issue 15879.
	Glob(context.Background(), `\\?\C:\*`)
}

var globSymlinkTests = []struct {
	path, dest string
	brokenLink bool
}{
	{"test1", "link1", false},
	{"test2", "link2", true},
}

func TestGlobSymlink(t *testing.T) {
	if runtime.GOOS == "windows" {
		t.Skipf("skipping symlink test on Windows")
	}

	tmpDir, err := ioutil.TempDir("", "globsymlink")
	if err != nil {
		t.Fatal("creating temp dir:", err)
	}
	defer os.RemoveAll(tmpDir)

	for _, tt := range globSymlinkTests {
		path := filepath.Join(tmpDir, tt.path)
		dest := filepath.Join(tmpDir, tt.dest)
		f, err := os.Create(path)
		if err != nil {
			t.Fatal(err)
		}
		if err := f.Close(); err != nil {
			t.Fatal(err)
		}
		err = os.Symlink(path, dest)
		if err != nil {
			t.Fatal(err)
		}
		if tt.brokenLink {
			// Break the symlink.
			os.Remove(path)
		}
		matches, err := Glob(context.Background(), dest)
		if err != nil {
			t.Errorf("GlobSymlink error for %q: %s", dest, err)
		}
		if !contains(matches, dest) {
			t.Errorf("Glob(%#q) = %#v want %v", dest, matches, dest)
		}
	}
}

type globTest struct {
	pattern string
	matches []string
}

func (test *globTest) buildWant(root string) []string {
	want := make([]string, 0)
	for _, m := range test.matches {
		want = append(want, root+filepath.FromSlash(m))
	}
	sort.Strings(want)
	return want
}

func (test *globTest) globAbs(root, rootPattern string) error {
	p := filepath.FromSlash(rootPattern + `\` + test.pattern)
	have, err := Glob(context.Background(), p)
	if err != nil {
		return err
	}
	sort.Strings(have)
	want := test.buildWant(root + `\`)
	if strings.Join(want, "_") == strings.Join(have, "_") {
		return nil
	}
	return fmt.Errorf("Glob(%q) returns %q, but %q expected", p, have, want)
}

func (test *globTest) globRel(root string) error {
	p := root + filepath.FromSlash(test.pattern)
	have, err := Glob(context.Background(), p)
	if err != nil {
		return err
	}
	sort.Strings(have)
	want := test.buildWant(root)
	if strings.Join(want, "_") == strings.Join(have, "_") {
		return nil
	}
	// try also matching version without root prefix
	wantWithNoRoot := test.buildWant("")
	if strings.Join(wantWithNoRoot, "_") == strings.Join(have, "_") {
		return nil
	}
	return fmt.Errorf("Glob(%q) returns %q, but %q expected", p, have, want)
}

func TestWindowsGlob(t *testing.T) {
	if runtime.GOOS != "windows" {
		t.Skipf("skipping windows specific test")
	}

	tmpDir, err := ioutil.TempDir("", "TestWindowsGlob")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(tmpDir)

	// /tmp may itself be a symlink
	tmpDir, err = filepath.EvalSymlinks(tmpDir)
	if err != nil {
		t.Fatal("eval symlink for tmp dir:", err)
	}

	if len(tmpDir) < 3 {
		t.Fatalf("tmpDir path %q is too short", tmpDir)
	}
	if tmpDir[1] != ':' {
		t.Fatalf("tmpDir path %q must have drive letter in it", tmpDir)
	}

	dirs := []string{
		"a",
		"b",
		"dir/d/bin",
	}
	files := []string{
		"dir/d/bin/git.exe",
	}
	for _, dir := range dirs {
		err := os.MkdirAll(filepath.Join(tmpDir, dir), 0777)
		if err != nil {
			t.Fatal(err)
		}
	}
	for _, file := range files {
		err := ioutil.WriteFile(filepath.Join(tmpDir, file), nil, 0666)
		if err != nil {
			t.Fatal(err)
		}
	}

	tests := []globTest{
		{"a", []string{"a"}},
		{"b", []string{"b"}},
		{"c", []string{}},
		{"*", []string{"a", "b", "dir"}},
		{"d*", []string{"dir"}},
		{"*i*", []string{"dir"}},
		{"*r", []string{"dir"}},
		{"?ir", []string{"dir"}},
		{"?r", []string{}},
		{"d*/*/bin/git.exe", []string{"dir/d/bin/git.exe"}},
	}

	// test absolute paths
	for _, test := range tests {
		var p string
		err = test.globAbs(tmpDir, tmpDir)
		if err != nil {
			t.Error(err)
		}
		// test C:\*Documents and Settings\...
		p = tmpDir
		p = strings.Replace(p, `:\`, `:\*`, 1)
		err = test.globAbs(tmpDir, p)
		if err != nil {
			t.Error(err)
		}
		// test C:\Documents and Settings*\...
		p = tmpDir
		p = strings.Replace(p, `:\`, `:`, 1)
		p = strings.Replace(p, `\`, `*\`, 1)
		p = strings.Replace(p, `:`, `:\`, 1)
		err = test.globAbs(tmpDir, p)
		if err != nil {
			t.Error(err)
		}
	}

	// test relative paths
	wd, err := os.Getwd()
	if err != nil {
		t.Fatal(err)
	}
	err = os.Chdir(tmpDir)
	if err != nil {
		t.Fatal(err)
	}
	defer func() {
		err := os.Chdir(wd)
		if err != nil {
			t.Fatal(err)
		}
	}()
	for _, test := range tests {
		err := test.globRel("")
		if err != nil {
			t.Error(err)
		}
		err = test.globRel(`.\`)
		if err != nil {
			t.Error(err)
		}
		err = test.globRel(tmpDir[:2]) // C:
		if err != nil {
			t.Error(err)
		}
	}
}

func TestNonWindowsGlobEscape(t *testing.T) {
	if runtime.GOOS == "windows" {
		t.Skipf("skipping non-windows specific test")
	}
	pattern := `\glob.go`
	want := []string{"glob.go"}
	matches, err := Glob(context.Background(), pattern)
	if err != nil {
		t.Fatalf("Glob error for %q: %s", pattern, err)
	}
	if !reflect.DeepEqual(matches, want) {
		t.Fatalf("Glob(%#q) = %v want %v", pattern, matches, want)
	}
}

func TestPartialGlob(t *testing.T) {
	gr := Stream("testdata/**")

	i := 0
	for i < 3 {
		match, err := gr.Next()
		i++
		if err != nil {
			t.Fatalf("Next() returned unexpected error: %v", err)
		}
		if match == "" {
			t.Fatalf("Next() unexpectedly stopped producing matches (returned \"\") after %d calls", i)
		}
	}

	err := gr.Close()
	if err != nil {
		t.Fatalf("Close() returned unexpected error: %v", err)
	}

	match, err := gr.Next()
	if err != nil {
		t.Errorf("After Close(), Next() returned unexpected error: %v", err)
	}
	if match != "" {
		t.Errorf("After Close(), Next() returned non-empty match %q", match)
	}
}

func TestCloseInvalidPattern(t *testing.T) {
	gr := Stream("[]") // This is an invalid glob pattern.
	err := gr.Close()
	if err != nil {
		t.Errorf("Close() on invalid patterns' result returned unexpected error: %v", err)
	}
}


text:
<?xml version="1.0"?>
<package>
  <name>object_manipulation_msgs</name>
  <version>0.0.0</version>
  <description>
     The object_manipulation_msg package
  </description>

  <maintainer email="jnicho@swri.org">jnicho</maintainer> -->
  <author email="jnicho@swri.org">jnicho</author>

  <license>BSD</license>

  <url type="website">http://ros.org/wiki/object_manipulation_msg</url>
  <buildtool_depend>catkin</buildtool_depend>

  <build_depend>roscpp</build_depend>

  <build_depend>actionlib_msgs</build_depend>
  <build_depend>std_msgs</build_depend>
  <build_depend>geometry_msgs</build_depend>
  <build_depend>sensor_msgs</build_depend>
  <build_depend>trajectory_msgs</build_depend>
  <build_depend>sensor_msgs</build_depend>
  <build_depend>shape_msgs</build_depend>
  <build_depend>manipulation_msgs</build_depend>
  <build_depend>household_objects_database_msgs</build_depend>

  <run_depend>actionlib_msgs</run_depend>
  <run_depend>std_msgs</run_depend>
  <run_depend>geometry_msgs</run_depend>
  <run_depend>sensor_msgs</run_depend>
  <run_depend>trajectory_msgs</run_depend>
  <run_depend>sensor_msgs</run_depend>
  <run_depend>shape_msgs</run_depend>
  <run_depend>manipulation_msgs</run_depend>
  <run_depend>message_runtime</run_depend>
  <run_depend>household_objects_database_msgs</run_depend>

</package>


text:
package com.sedmelluq.lava.player.extras.stream;

import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
import com.sedmelluq.discord.lavaplayer.player.event.AudioEvent;
import com.sedmelluq.discord.lavaplayer.player.event.AudioEventAdapter;
import com.sedmelluq.discord.lavaplayer.player.event.TrackEndEvent;
import com.sedmelluq.discord.lavaplayer.player.event.TrackStuckEvent;
import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
import com.sedmelluq.discord.lavaplayer.track.playback.AudioFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;

public class StreamInstance {
  private static final Logger log = LoggerFactory.getLogger(StreamInstance.class);

  private final AudioTrack track;
  private final AudioPlayer trackPlayer;
  private final int maximumFrameCount;
  private final AudioFrame[] ringBuffer;
  private final Set<Cursor> cursors;
  private boolean initialized;
  private boolean destroyed;
  private int absoluteOffset;
  private int frameCount;

  public StreamInstance(AudioTrack track, AudioPlayer trackPlayer, int maximumFrameCount) {
    this.track = track;
    this.trackPlayer = trackPlayer;
    this.maximumFrameCount = maximumFrameCount;
    this.ringBuffer = new AudioFrame[maximumFrameCount];
    this.cursors = new HashSet<>();
  }

  public AudioTrack getTrack() {
    return track;
  }

  public synchronized Cursor createCursor(Consumer<Cursor> detachListener) {
    if (destroyed) {
      return null;
    }

    initialize();

    Cursor cursor = new Cursor(getFreshOffset(), detachListener);
    cursors.add(cursor);
    return cursor;
  }

  public synchronized void shutdown() {
    destroy();
  }

  private void destroy() {
    if (!destroyed) {
      destroyed = true;

      for (Cursor cursor : new ArrayList<>(cursors)) {
        cursor.detach();
        cursor.close();
      }

      if (initialized) {
        log.debug("Shutting down centralized stream for {}.", track.getInfo());
        trackPlayer.destroy();
      }
    }
  }

  private void initialize() {
    if (!initialized) {
      initialized = true;

      log.debug("Initializing centralized stream for {}.", track.getInfo());

      trackPlayer.addListener(new Listener());
      trackPlayer.playTrack(track);
    }
  }

  private synchronized AudioFrame getFrame(Cursor cursor) {
    if (destroyed) {
      return null;
    }

    if (cursor.absoluteOffset < 0 || cursor.absoluteOffset < absoluteOffset) {
      cursor.absoluteOffset = getFreshOffset();
    }

    if (cursor.absoluteOffset >= absoluteOffset + frameCount) {
      AudioFrame newFrame = trackPlayer.provide();

      if (newFrame == null) {
        return null;
      }

      absoluteOffset++;
      frameCount = Math.min(frameCount + 1, ringBuffer.length);

      int framePosition = getRelativeOffset(absoluteOffset + frameCount - 1);
      ringBuffer[framePosition] = newFrame;

      cursor.absoluteOffset++;
      return newFrame;
    } else {
      int framePosition = getRelativeOffset(cursor.absoluteOffset);
      cursor.absoluteOffset++;
      return ringBuffer[framePosition];
    }
  }

  private synchronized void releaseCursor(Cursor cursor) {
    if (cursors.remove(cursor) && cursors.isEmpty()) {
      destroy();
    }
  }

  private long getFreshOffset() {
    return absoluteOffset + Math.max(0, frameCount - 1);
  }

  private int getRelativeOffset(long absoluteOffset) {
    return (int) (absoluteOffset % maximumFrameCount);
  }

  public class Cursor {
    private final Consumer<Cursor> detachListener;
    private final AtomicBoolean detached = new AtomicBoolean();
    private long absoluteOffset;

    private Cursor(long absoluteOffset, Consumer<Cursor> detachListener) {
      this.detachListener = detachListener;
      this.absoluteOffset = absoluteOffset;
    }

    public AudioTrack getTrack() {
      return track;
    }

    public void close() {
      detach();
      releaseCursor(this);
    }

    public AudioFrame provide() {
      return StreamInstance.this.getFrame(this);
    }

    private void detach() {
      if (detached.compareAndSet(false, true)) {
        detachListener.accept(this);
      }
    }
  }

  private class Listener extends AudioEventAdapter {
    @Override
    public void onEvent(AudioEvent event) {
      if (event instanceof TrackEndEvent || event instanceof TrackStuckEvent) {
        destroy();
      }
    }
  }
}