text:
<?php

/* SonataDoctrineORMAdminBundle:CRUD:edit_orm_many_to_one.html.twig */
class __TwigTemplate_e464f14a55910816d073ecea50be00278fdab9f0ba881240b9cc1b5ab1bab113 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 11
        echo "
";
        // line 12
        if ( !$this->getAttribute($this->getAttribute((isset($context["sonata_admin"]) ? $context["sonata_admin"] : null), "field_description", array()), "hasassociationadmin", array())) {
            // line 13
            echo "    ";
            echo twig_escape_filter($this->env, $this->env->getExtension('sonata_admin')->renderRelationElement((isset($context["value"]) ? $context["value"] : null), $this->getAttribute((isset($context["sonata_admin"]) ? $context["sonata_admin"] : null), "field_description", array())), "html", null, true);
            echo "
";
        } elseif (($this->getAttribute(        // line 14
(isset($context["sonata_admin"]) ? $context["sonata_admin"] : null), "edit", array()) == "inline")) {
            // line 15
            echo "    ";
            $context['_parent'] = (array) $context;
            $context['_seq'] = twig_ensure_traversable($this->getAttribute($this->getAttribute($this->getAttribute((isset($context["sonata_admin"]) ? $context["sonata_admin"] : null), "field_description", array()), "associationadmin", array()), "formfielddescriptions", array()));
            foreach ($context['_seq'] as $context["_key"] => $context["field_description"]) {
                // line 16
                echo "        ";
                echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), $this->getAttribute($context["field_description"], "name", array()), array(), "array"), 'row');
                echo "
    ";
            }
            $_parent = $context['_parent'];
            unset($context['_seq'], $context['_iterated'], $context['_key'], $context['field_description'], $context['_parent'], $context['loop']);
            $context = array_intersect_key($context, $_parent) + $_parent;
        } else {
            // line 19
            echo "
env, (isset($context["id"]) ? $context["id"] : null), "html", null, true);
            echo "\" class=\"field-container\">
        ";
            // line 20
            if (($this->getAttribute((isset($context["sonata_admin"]) ? $context["sonata_admin"] : null), "edit", array()) == "list")) {
                // line 21
                echo "            env, (isset($context["id"]) ? $context["id"] : null), "html", null, true);
                echo "\" class=\"field-short-description\">
                ";
                // line 22
                if ($this->getAttribute($this->getAttribute((isset($context["sonata_admin"]) ? $context["sonata_admin"] : null), "admin", array()), "id", array(0 => $this->getAttribute((isset($context["sonata_admin"]) ? $context["sonata_admin"] : null), "value", array())), "method")) {
                    // line 23
                    echo "                    ";
                    echo $this->env->getExtension('actions')->renderUri($this->env->getExtension('routing')->getUrl("sonata_admin_short_object_information", array("code" => $this->getAttribute($this->getAttribute($this->getAttribute(                    // line 24
(isset($context["sonata_admin"]) ? $context["sonata_admin"] : null), "field_description", array()), "associationadmin", array()), "code", array()), "objectId" => $this->getAttribute($this->getAttribute($this->getAttribute(                    // line 25
(isset($context["sonata_admin"]) ? $context["sonata_admin"] : null), "field_description", array()), "associationadmin", array()), "id", array(0 => $this->getAttribute((isset($context["sonata_admin"]) ? $context["sonata_admin"] : null), "value", array())), "method"), "uniqid" => $this->getAttribute($this->getAttribute($this->getAttribute(                    // line 26
(isset($context["sonata_admin"]) ? $context["sonata_admin"] : null), "field_description", array()), "associationadmin", array()), "uniqid", array()), "linkParameters" => $this->getAttribute($this->getAttribute($this->getAttribute(                    // line 27
(isset($context["sonata_admin"]) ? $context["sonata_admin"] : null), "field_description", array()), "options", array()), "link_parameters", array()))), array());
                    // line 29
                    echo "                ";
                } elseif (($this->getAttribute($this->getAttribute($this->getAttribute((isset($context["sonata_admin"]) ? $context["sonata_admin"] : null), "field_description", array(), "any", false, true), "options", array(), "any", false, true), "placeholder", array(), "any", true, true) && $this->getAttribute($this->getAttribute($this->getAttribute((isset($context["sonata_admin"]) ? $context["sonata_admin"] : null), "field_description", array()), "options", array()), "placeholder", array()))) {
                    // line 30
                    echo "
                        ";
                    // line 31
                    echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans($this->getAttribute($this->getAttribute($this->getAttribute((isset($context["sonata_admin"]) ? $context["sonata_admin"] : null), "field_description", array()), "options", array()), "placeholder", array()), array(), "SonataAdminBundle"), "html", null, true);
                    echo "

                ";
                }
                // line 34
                echo "

                ";
                // line 36
                echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : null), 'widget');
                echo "

        ";
            } else {
                // line 39
                echo "            env, (isset($context["id"]) ? $context["id"] : null), "html", null, true);
                echo "\" >
                ";
                // line 40
                echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : null), 'widget');
                echo "

        ";
            }
            // line 43
            echo "
        env, (isset($context["id"]) ? $context["id"] : null), "html", null, true);
            echo "\" class=\"field-actions\">

                ";
            // line 46
            if ((((($this->getAttribute((isset($context["sonata_admin"]) ? $context["sonata_admin"] : null), "edit", array()) == "list") && $this->getAttribute($this->getAttribute($this->getAttribute((isset($context["sonata_admin"]) ? $context["sonata_admin"] : null), "field_description", array()), "associationadmin", array()), "hasRoute", array(0 => "list"), "method")) && $this->getAttribute($this->getAttribute($this->getAttribute((isset($context["sonata_admin"]) ? $context["sonata_admin"] : null), "field_description", array()), "associationadmin", array()), "isGranted", array(0 => "LIST"), "method")) && (isset($context["btn_list"]) ? $context["btn_list"] : null))) {
                // line 47
                echo "                    env, $this->getAttribute($this->getAttribute($this->getAttribute((isset($context["sonata_admin"]) ? $context["sonata_admin"] : null), "field_description", array()), "associationadmin", array()), "generateUrl", array(0 => "list", 1 => $this->getAttribute($this->getAttribute((isset($context["sonata_admin"]) ? $context["sonata_admin"] : null), "field_description", array()), "getOption", array(0 => "link_parameters", 1 => array()), "method")), "method"), "html", null, true);
                echo "\"
                        onclick=\"return start_field_dialog_form_list_";
                // line 48
                echo twig_escape_filter($this->env, (isset($context["id"]) ? $context["id"] : null), "html", null, true);
                echo "(this);\"
                        class=\"btn btn-info btn-sm btn-outline sonata-ba-action\"
                        title=\"";
                // line 50
                echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans((isset($context["btn_list"]) ? $context["btn_list"] : null), array(), (isset($context["btn_catalogue"]) ? $context["btn_catalogue"] : null)), "html", null, true);
                echo "\"
                        >

                        ";
                // line 53
                echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans((isset($context["btn_list"]) ? $context["btn_list"] : null), array(), (isset($context["btn_catalogue"]) ? $context["btn_catalogue"] : null)), "html", null, true);
                echo "

                ";
            }
            // line 56
            echo "
                ";
            // line 57
            if ((((($this->getAttribute((isset($context["sonata_admin"]) ? $context["sonata_admin"] : null), "edit", array()) != "admin") && $this->getAttribute($this->getAttribute($this->getAttribute((isset($context["sonata_admin"]) ? $context["sonata_admin"] : null), "field_description", array()), "associationadmin", array()), "hasRoute", array(0 => "create"), "method")) && $this->getAttribute($this->getAttribute($this->getAttribute((isset($context["sonata_admin"]) ? $context["sonata_admin"] : null), "field_description", array()), "associationadmin", array()), "isGranted", array(0 => "CREATE"), "method")) && (isset($context["btn_add"]) ? $context["btn_add"] : null))) {
                // line 58
                echo "                    env, $this->getAttribute($this->getAttribute($this->getAttribute((isset($context["sonata_admin"]) ? $context["sonata_admin"] : null), "field_description", array()), "associationadmin", array()), "generateUrl", array(0 => "create", 1 => $this->getAttribute($this->getAttribute((isset($context["sonata_admin"]) ? $context["sonata_admin"] : null), "field_description", array()), "getOption", array(0 => "link_parameters", 1 => array()), "method")), "method"), "html", null, true);
                echo "\"
                        onclick=\"return start_field_dialog_form_add_";
                // line 59
                echo twig_escape_filter($this->env, (isset($context["id"]) ? $context["id"] : null), "html", null, true);
                echo "(this);\"
                        class=\"btn btn-success btn-sm btn-outline sonata-ba-action\"
                        title=\"";
                // line 61
                echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans((isset($context["btn_add"]) ? $context["btn_add"] : null), array(), (isset($context["btn_catalogue"]) ? $context["btn_catalogue"] : null)), "html", null, true);
                echo "\"
                        >

                        ";
                // line 64
                echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans((isset($context["btn_add"]) ? $context["btn_add"] : null), array(), (isset($context["btn_catalogue"]) ? $context["btn_catalogue"] : null)), "html", null, true);
                echo "

                ";
            }
            // line 67
            echo "

                ";
            // line 70
            if ((((($this->getAttribute((isset($context["sonata_admin"]) ? $context["sonata_admin"] : null), "edit", array()) == "list") && $this->getAttribute($this->getAttribute($this->getAttribute((isset($context["sonata_admin"]) ? $context["sonata_admin"] : null), "field_description", array()), "associationadmin", array()), "hasRoute", array(0 => "delete"), "method")) && $this->getAttribute($this->getAttribute($this->getAttribute((isset($context["sonata_admin"]) ? $context["sonata_admin"] : null), "field_description", array()), "associationadmin", array()), "isGranted", array(0 => "DELETE"), "method")) && (isset($context["btn_delete"]) ? $context["btn_delete"] : null))) {
                // line 71
                echo "                    env, (isset($context["id"]) ? $context["id"] : null), "html", null, true);
                echo "(this);\"
                        class=\"btn btn-danger btn-sm btn-outline sonata-ba-action\"
                        title=\"";
                // line 74
                echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans((isset($context["btn_delete"]) ? $context["btn_delete"] : null), array(), (isset($context["btn_catalogue"]) ? $context["btn_catalogue"] : null)), "html", null, true);
                echo "\"
                        >

                        ";
                // line 77
                echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans((isset($context["btn_delete"]) ? $context["btn_delete"] : null), array(), (isset($context["btn_catalogue"]) ? $context["btn_catalogue"] : null)), "html", null, true);
                echo "

                ";
            }
            // line 80
            echo "

        ";
            // line 83
            $this->env->loadTemplate("SonataDoctrineORMAdminBundle:CRUD:edit_modal.html.twig")->display($context);
            // line 84
            echo "

    ";
            // line 86
            $this->env->loadTemplate("SonataDoctrineORMAdminBundle:CRUD:edit_orm_many_association_script.html.twig")->display($context);
        }
    }

    public function getTemplateName()
    {
        return "SonataDoctrineORMAdminBundle:CRUD:edit_orm_many_to_one.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  197 => 86,  193 => 84,  191 => 83,  186 => 80,  180 => 77,  174 => 74,  169 => 72,  166 => 71,  164 => 70,  159 => 67,  153 => 64,  147 => 61,  142 => 59,  137 => 58,  135 => 57,  132 => 56,  126 => 53,  120 => 50,  115 => 48,  110 => 47,  108 => 46,  103 => 44,  100 => 43,  94 => 40,  89 => 39,  83 => 36,  79 => 34,  73 => 31,  70 => 30,  67 => 29,  65 => 27,  64 => 26,  63 => 25,  62 => 24,  60 => 23,  58 => 22,  53 => 21,  51 => 20,  46 => 19,  36 => 16,  31 => 15,  29 => 14,  24 => 13,  22 => 12,  19 => 11,);
    }
}


text:
#include <Carbon/Carbon.h>
#include "SkImageDecoder.h"
#include "SkImageEncoder.h"
#include "SkMovie.h"
#include "SkStream.h"
#include "SkTemplates.h"
#include "SkCGUtils.h"

static void malloc_release_proc(void* info, const void* data, size_t size) {
    sk_free(info);
}

static CGDataProviderRef SkStreamToDataProvider(SkStream* stream) {
    // TODO: use callbacks, so we don't have to load all the data into RAM
    size_t len = stream->getLength();
    void* data = sk_malloc_throw(len);
    stream->read(data, len);

    return CGDataProviderCreateWithData(data, data, len, malloc_release_proc);
}

static CGImageSourceRef SkStreamToCGImageSource(SkStream* stream) {
    CGDataProviderRef data = SkStreamToDataProvider(stream);
    CGImageSourceRef imageSrc = CGImageSourceCreateWithDataProvider(data, 0);
    CGDataProviderRelease(data);
    return imageSrc;
}

class SkImageDecoder_CG : public SkImageDecoder {
protected:
    virtual bool onDecode(SkStream* stream, SkBitmap* bm, Mode);
};

#define BITMAP_INFO (kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast)

bool SkImageDecoder_CG::onDecode(SkStream* stream, SkBitmap* bm, Mode mode) {
    CGImageSourceRef imageSrc = SkStreamToCGImageSource(stream);

    if (NULL == imageSrc) {
        return false;
    }
    SkAutoTCallVProc<const void, CFRelease> arsrc(imageSrc);

    CGImageRef image = CGImageSourceCreateImageAtIndex(imageSrc, 0, NULL);
    if (NULL == image) {
        return false;
    }
    SkAutoTCallVProc<CGImage, CGImageRelease> arimage(image);

    const int width = CGImageGetWidth(image);
    const int height = CGImageGetHeight(image);
    bm->setConfig(SkBitmap::kARGB_8888_Config, width, height);
    if (SkImageDecoder::kDecodeBounds_Mode == mode) {
        return true;
    }

    if (!this->allocPixelRef(bm, NULL)) {
        return false;
    }

    bm->lockPixels();
    bm->eraseColor(0);

    CGColorSpaceRef cs = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
    CGContextRef cg = CGBitmapContextCreate(bm->getPixels(), width, height,
                                            8, bm->rowBytes(), cs, BITMAP_INFO);
    CGContextDrawImage(cg, CGRectMake(0, 0, width, height), image);
    CGContextRelease(cg);
    CGColorSpaceRelease(cs);

    bm->unlockPixels();
    return true;
}

///////////////////////////////////////////////////////////////////////////////

SkImageDecoder* SkImageDecoder::Factory(SkStream* stream) {
    return SkNEW(SkImageDecoder_CG);
}

/////////////////////////////////////////////////////////////////////////

SkMovie* SkMovie::DecodeStream(SkStream* stream) {
    return NULL;
}

/////////////////////////////////////////////////////////////////////////

static size_t consumer_put(void* info, const void* buffer, size_t count) {
    SkWStream* stream = reinterpret_cast<SkWStream*>(info);
    return stream->write(buffer, count) ? count : 0;
}

static void consumer_release(void* info) {
    // we do nothing, since by design we don't "own" the stream (i.e. info)
}

static CGDataConsumerRef SkStreamToCGDataConsumer(SkWStream* stream) {
    CGDataConsumerCallbacks procs;
    procs.putBytes = consumer_put;
    procs.releaseConsumer = consumer_release;
    // we don't own/reference the stream, so it our consumer must not live
    // longer that our caller's ownership of the stream
    return CGDataConsumerCreate(stream, &procs);
}

static CGImageDestinationRef SkStreamToImageDestination(SkWStream* stream,
                                                        CFStringRef type) {
    CGDataConsumerRef consumer = SkStreamToCGDataConsumer(stream);
    if (NULL == consumer) {
        return NULL;
    }
    SkAutoTCallVProc<const void, CFRelease> arconsumer(consumer);

    return CGImageDestinationCreateWithDataConsumer(consumer, type, 1, NULL);
}

class SkImageEncoder_CG : public SkImageEncoder {
public:
    SkImageEncoder_CG(Type t) : fType(t) {}

protected:
    virtual bool onEncode(SkWStream* stream, const SkBitmap& bm, int quality);

private:
    Type fType;
};

/*  Encode bitmaps via CGImageDestination. We setup a DataConsumer which writes
    to our SkWStream. Since we don't reference/own the SkWStream, our consumer
    must only live for the duration of the onEncode() method.
 */
bool SkImageEncoder_CG::onEncode(SkWStream* stream, const SkBitmap& bm,
                                 int quality) {
    CFStringRef type;
    switch (fType) {
        case kJPEG_Type:
            type = kUTTypeJPEG;
            break;
        case kPNG_Type:
            type = kUTTypePNG;
            break;
        default:
            return false;
    }

    CGImageDestinationRef dst = SkStreamToImageDestination(stream, type);
    if (NULL == dst) {
        return false;
    }
    SkAutoTCallVProc<const void, CFRelease> ardst(dst);

    CGImageRef image = SkCreateCGImageRef(bm);
    if (NULL == image) {
        return false;
    }
    SkAutoTCallVProc<CGImage, CGImageRelease> agimage(image);

	CGImageDestinationAddImage(dst, image, NULL);
	CGImageDestinationFinalize(dst);
    return true;
}

SkImageEncoder* SkImageEncoder::Create(Type t) {
    switch (t) {
        case kJPEG_Type:
        case kPNG_Type:
            break;
        default:
            return NULL;
    }
    return SkNEW_ARGS(SkImageEncoder_CG, (t));
}

redpajama_set_name: RedPajamaGithub


text:
module('system/props/events_test');

test('listener should receive event - removing should remove', function() {
  var obj = {}, count = 0;
  var F = function() { count++; };

  Ember.addListener(obj, 'event!', F);
  equal(count, 0, 'nothing yet');

  Ember.sendEvent(obj, 'event!');
  equal(count, 1, 'received event');

  Ember.removeListener(obj, 'event!', F);

  count = 0;
  Ember.sendEvent(obj, 'event!');
  equal(count, 0, 'received event');
});

test('listeners should be inherited', function() {
  var obj = {}, count = 0;
  var F = function() { count++; };

  Ember.addListener(obj, 'event!', F);

  var obj2 = Ember.create(obj);

  equal(count, 0, 'nothing yet');

  Ember.sendEvent(obj2, 'event!');
  equal(count, 1, 'received event');

  Ember.removeListener(obj2, 'event!', F);

  count = 0;
  Ember.sendEvent(obj2, 'event!');
  equal(count, 0, 'did not receive event');

  Ember.sendEvent(obj, 'event!');
  equal(count, 1, 'should still invoke on parent');

});

test('adding a listener more than once should only invoke once', function() {

  var obj = {}, count = 0;
  var F = function() { count++; };
  Ember.addListener(obj, 'event!', F);
  Ember.addListener(obj, 'event!', F);

  Ember.sendEvent(obj, 'event!');
  equal(count, 1, 'should only invoke once');
});

test('adding a listener with a target should invoke with target', function() {
  var obj = {}, target;

  target = {
    count: 0,
    method: function() { this.count++; }
  };

  Ember.addListener(obj, 'event!', target, target.method);
  Ember.sendEvent(obj, 'event!');
  equal(target.count, 1, 'should invoke');
});

test('suspending a listener should not invoke during callback', function() {
  var obj = {}, target, otherTarget;

  target = {
    count: 0,
    method: function() { this.count++; }
  };

  otherTarget = {
    count: 0,
    method: function() { this.count++; }
  };

  Ember.addListener(obj, 'event!', target, target.method);
  Ember.addListener(obj, 'event!', otherTarget, otherTarget.method);

  function callback() {
      equal(this, target);

      Ember.sendEvent(obj, 'event!');

      return 'result';
  }

  Ember.sendEvent(obj, 'event!');

  equal(Ember._suspendListener(obj, 'event!', target, target.method, callback), 'result');

  Ember.sendEvent(obj, 'event!');

  equal(target.count, 2, 'should invoke');
  equal(otherTarget.count, 3, 'should invoke');
});

test('adding a listener with string method should lookup method on event delivery', function() {
  var obj = {}, target;

  target = {
    count: 0,
    method: function() {}
  };

  Ember.addListener(obj, 'event!', target, 'method');
  Ember.sendEvent(obj, 'event!');
  equal(target.count, 0, 'should invoke but do nothing');

  target.method = function() { this.count++; };
  Ember.sendEvent(obj, 'event!');
  equal(target.count, 1, 'should invoke now');
});

test('calling sendEvent with extra params should be passed to listeners', function() {

  var obj = {}, params = null;
  Ember.addListener(obj, 'event!', function() {
    params = Array.prototype.slice.call(arguments);
  });

  Ember.sendEvent(obj, 'event!', ['foo', 'bar']);
  deepEqual(params, ['foo', 'bar'], 'params should be saved');
});

test('implementing sendEvent on object should invoke', function() {
  var obj = {
    sendEvent: function(eventName, params) {
      equal(eventName, 'event!', 'eventName');
      deepEqual(params, ['foo', 'bar']);
      this.count++;
    },

    count: 0
  };

  Ember.addListener(obj, 'event!', obj, function() { this.count++; });

  Ember.sendEvent(obj, 'event!', ['foo', 'bar']);
  equal(obj.count, 2, 'should have invoked method & listener');
});

test('hasListeners tells you if there are listeners for a given event', function() {

  var obj = {}, F = function() {}, F2 = function() {};

  equal(Ember.hasListeners(obj, 'event!'), false, 'no listeners at first');

  Ember.addListener(obj, 'event!', F);
  Ember.addListener(obj, 'event!', F2);

  equal(Ember.hasListeners(obj, 'event!'), true, 'has listeners');

  Ember.removeListener(obj, 'event!', F);
  equal(Ember.hasListeners(obj, 'event!'), true, 'has listeners');

  Ember.removeListener(obj, 'event!', F2);
  equal(Ember.hasListeners(obj, 'event!'), false, 'has no more listeners');

  Ember.addListener(obj, 'event!', F);
  equal(Ember.hasListeners(obj, 'event!'), true, 'has listeners');
});

test('calling removeListener without method should remove all listeners', function() {
  var obj = {}, F = function() {}, F2 = function() {};

  equal(Ember.hasListeners(obj, 'event!'), false, 'no listeners at first');

  Ember.addListener(obj, 'event!', F);
  Ember.addListener(obj, 'event!', F2);

  equal(Ember.hasListeners(obj, 'event!'), true, 'has listeners');

  Ember.removeListener(obj, 'event!');

  equal(Ember.hasListeners(obj, 'event!'), false, 'has no more listeners');
});

test('while suspended, it should not be possible to add a duplicate listener', function() {
  var obj = {}, target;

  target = {
    count: 0,
    method: function() { this.count++; }
  };

  Ember.addListener(obj, 'event!', target, target.method);

  function callback() {
    Ember.addListener(obj, 'event!', target, target.method);
  }

  Ember.sendEvent(obj, 'event!');

  Ember._suspendListener(obj, 'event!', target, target.method, callback);

  equal(target.count, 1, 'should invoke');
  equal(Ember.meta(obj).listeners['event!'].length, 1, "a duplicate listener wasn't added");

  // now test _suspendListeners...

  Ember.sendEvent(obj, 'event!');

  Ember._suspendListeners(obj, ['event!'], target, target.method, callback);

  equal(target.count, 2, 'should have invoked again');
  equal(Ember.meta(obj).listeners['event!'].length, 1, "a duplicate listener wasn't added");
});


text:
@interface NSMutableArray (JAHConvenience)
- (id)jah_popFirstObject;
@end

@implementation NSMutableArray (JAHConvenience)

- (id)jah_popFirstObject {
    id firstObject = [self firstObject];
    if (firstObject) {
        [self removeObjectAtIndex:0];
    }
    return firstObject;
}

@end

@implementation JAHConvertSDP

+ (NSDictionary*)dictionaryForSDP:(NSString*)sdp withCreatorRole:(NSString*)creator {
    // Divide the SDP into session and media sections
    NSMutableArray* media = [[sdp componentsSeparatedByString:@"\r\nm="] mutableCopy];
    for (NSUInteger i = 1; i < [media count]; i++) {
        NSMutableString* mediaString = [NSMutableString stringWithFormat:@"m=%@", media[i]];
        if (i != [media count] - 1) {
            [mediaString appendString:@"\r\n"];
        }
        media[i] = mediaString;
    }

    NSMutableDictionary* parsed = [NSMutableDictionary dictionary];

    NSString* session = [NSString stringWithFormat:@"%@%@", [media jah_popFirstObject], @"\r\n"];

    NSMutableArray* contents = [NSMutableArray array];
    for (NSString* m in media) {
        [contents addObject:[[self class] convertSDPMediaToDictionary:m withSession:session withCreatorRole:creator]];
    }
    parsed[@"contents"] = contents;

    NSArray* sessionLines = [[self class] linesForSDP:session];
    NSArray* groupLines = [[self class] linesForPrefix:@"a=group:" mediaLines:nil sessionLines:sessionLines];
    if ([groupLines count]) {
        parsed[@"groups"] = [[self class] groupsForGroupLines:groupLines];
    }

    return parsed;
}

+ (NSDictionary*)convertSDPMediaToDictionary:(NSString *)media withSession:(NSString*)session withCreatorRole:(NSString *)creator {
    NSMutableDictionary* content = [NSMutableDictionary dictionary];
    content[@"creator"] = creator;

    NSArray* mediaLines = [[self class] linesForSDP:media];
    NSArray* sessionLines = [[self class] linesForSDP:session];
    NSDictionary* mLine = [[self class] mLineForLine:[mediaLines firstObject]];

    NSString* name = mLine[@"media"];
    // If we have a mid, use that for the content name instead
    NSString* mid = [[self class] lineForPrefix:@"a=mid:" mediaLines:mediaLines sessionLines:nil];
    if (mid) {
        name = [mid substringFromIndex:6];
    }
    content[@"name"] = name;

    NSString* senders;
    if ([[self class] lineForPrefix:@"a=sendrecv" mediaLines:mediaLines sessionLines:sessionLines]) {
        senders = @"both";
    } else if ([[self class] lineForPrefix:@"a=sendonly" mediaLines:mediaLines sessionLines:sessionLines]) {
        senders = @"initiator";
    } else if ([[self class] lineForPrefix:@"a=recvonly" mediaLines:mediaLines sessionLines:sessionLines]) {
        senders = @"responder";
    } else if ([[self class] lineForPrefix:@"a=inactive" mediaLines:mediaLines sessionLines:sessionLines]) {
        senders = @"none";
    }
    content[@"senders"] = senders;

    NSMutableDictionary* description = [NSMutableDictionary dictionary];

    NSMutableDictionary* transport = [NSMutableDictionary dictionary];
    if ([mLine[@"media"] isEqualToString:@"application"]) {
        description[@"descType"] = @"datachannel";

        NSMutableArray* sctp = [NSMutableArray array];
        transport[@"sctp"] = sctp;
    } else {
        description[@"descType"] = @"rtp";
        description[@"media"] = mLine[@"media"];
        description[@"payloads"] = [NSMutableArray array];
        description[@"encryption"] = [NSMutableArray array];
        description[@"feedback"] = [NSMutableArray array];
        description[@"headerExtensions"] = [NSMutableArray array];

        transport[@"transType"] = @"iceUdp";
        transport[@"candidates"] = [NSMutableArray array];
        transport[@"fingerprints"] = [NSMutableArray array];

        NSString* ssrc = [[self class] lineForPrefix:@"a=ssrc:" mediaLines:mediaLines sessionLines:nil];
        if (ssrc) {
            ssrc = [[[ssrc substringFromIndex:7] componentsSeparatedByString:@" "] firstObject];
            description[@"ssrc"] = ssrc;
        }

        NSArray* rtpMapLines = [[self class] linesForPrefix:@"a=rtpmap:" mediaLines:mediaLines sessionLines:nil];
        for (NSString* line in rtpMapLines) {
            NSMutableDictionary* payload = [[self class] rtpMapForLine:line];
            payload[@"feedback"] = [NSMutableArray array];

            NSArray* fmtpLines = [[self class] linesForPrefix:[NSString stringWithFormat:@"a=fmtp:%@", payload[@"id"]] mediaLines:mediaLines sessionLines:nil];
            for (NSString* line in fmtpLines) {
                payload[@"parameters"] = [[self class] fmtpForLine:line];
            }

            NSArray* fbLines = [[self class] linesForPrefix:[NSString stringWithFormat:@"a=rtcp-fb:%@", payload[@"id"]] mediaLines:mediaLines sessionLines:nil];
            for (NSString* line in fbLines) {
                [payload[@"feedback"] addObject:[[self class] rtcpfbForLine:line]];
            }

            [description[@"payloads"] addObject:payload];
        }

        NSArray* cryptoLines = [[self class] linesForPrefix:@"a=crypto:" mediaLines:mediaLines sessionLines:sessionLines];
        for (NSString* line in cryptoLines) {
            [description[@"encryption"] addObject:[[self class] cryptoForLine:line]];
        }

        if ([[self class] linesForPrefix:@"a=rtcp-mux" mediaLines:mediaLines sessionLines:nil]) {
            description[@"mux"] = @YES;
        }

        NSArray* fbLines = [[self class] linesForPrefix:@"a=rtcp-fb:*" mediaLines:mediaLines sessionLines:nil];
        for (NSString* line in fbLines) {
            [description[@"feedback"] addObject:[[self class] rtcpfbForLine:line]];
        }

        NSArray* extLines = [[self class] linesForPrefix:@"a=extmap:" mediaLines:mediaLines sessionLines:nil];
        for (NSString* line in extLines) {
            NSMutableDictionary* ext = [[self class] extMapForLine:line];

            NSDictionary* senders = @{@"sendonly": @"responder",
                                      @"recvonly": @"initiator",
                                      @"sendrecv": @"both",
                                      @"inactive": @"none"};
            ext[@"senders"] = senders[ext[@"senders"]];

            [description[@"headerExtensions"] addObject:ext];
        }

        NSArray* ssrcGroupLines = [[self class] linesForPrefix:@"a=ssrc-group" mediaLines:mediaLines sessionLines:nil];
        description[@"sourceGroups"] = [[self class] sourceGroupsForGroupLines:ssrcGroupLines];

        NSArray* ssrcLines = [[self class] linesForPrefix:@"a=ssrc:" mediaLines:mediaLines sessionLines:nil];
        description[@"sources"] = [[self class] sourcesForLines:ssrcLines];
    }

    // transport specific attributes
    NSArray* fingerprintLines = [[self class] linesForPrefix:@"a=fingerprint:" mediaLines:mediaLines sessionLines:sessionLines];
    for (NSString* line in fingerprintLines) {
        NSMutableDictionary* fp = [[self class] fingerprintForLine:line];
        NSString* setup = [[self class] lineForPrefix:@"a=setup:" mediaLines:mediaLines sessionLines:sessionLines];
        if (setup) {
            fp[@"setup"] = [setup substringFromIndex:8];
        }
        [transport[@"fingerprints"] addObject:fp];
    }

    NSString* ufragLine = [[self class] lineForPrefix:@"a=ice-ufrag:" mediaLines:mediaLines sessionLines:sessionLines];
    NSString* pwdLine = [[self class] lineForPrefix:@"a=ice-pwd:" mediaLines:mediaLines sessionLines:sessionLines];
    if (ufragLine && pwdLine) {
        transport[@"ufrag"] = [ufragLine substringFromIndex:12];
        transport[@"pwd"] = [pwdLine substringFromIndex:10];
        transport[@"candidates"] = [NSMutableArray array];

        NSArray* candidateLines = [[self class] linesForPrefix:@"a=candidate:" mediaLines:mediaLines sessionLines:sessionLines];
        for (NSString* line in candidateLines) {
            [transport[@"candidates"] addObject:[[self class] candidateForLine:line]];
        }
    }

    if ([description[@"descType"] isEqualToString:@"datachannel"]) {
        NSArray* sctpMapLines = [[self class] linesForPrefix:@"a=sctpmap:" mediaLines:mediaLines sessionLines:nil];
        for (NSString* line in sctpMapLines) {
            [transport[@"sctp"] addObject:[[self class] sctpMapForLine:line]];
        }
    }

    content[@"description"] = description;
    content[@"transport"] = transport;

    return content;
}

+ (NSDictionary*)candidateForLine:(NSString*)line {
    line = [[line componentsSeparatedByString:@"\r\n"] firstObject];

    NSArray* parts = [[line substringFromIndex:12] componentsSeparatedByString:@" "];

    NSMutableDictionary* candidate = [NSMutableDictionary dictionary];
    candidate[@"foundation"] = parts[0];
    candidate[@"component"] = parts[1];
    candidate[@"protocol"] = [parts[2] lowercaseString];
    candidate[@"priority"] = parts[3];
    candidate[@"ip"] = parts[4];
    candidate[@"port"] = parts[5];
    // skip parts[6] == 'typ';
    candidate[@"type"] = parts[7];
    candidate[@"generation"] = @"0";

    for (NSUInteger i = 8; i < [parts count]; i += 2) {
        if ([parts[i] isEqualToString:@"raddr"]) {
            candidate[@"relAddr"] = parts[i + 1];
        } else if ([parts[i] isEqualToString:@"rport"]) {
            candidate[@"relPort"] = parts[i + 1];
        } else if ([parts[i] isEqualToString:@"generation"]) {
            candidate[@"generation"] = parts[i + 1];
        }
    }

    candidate[@"network"] = @"1";

    candidate[@"id"] = [[NSUUID UUID] UUIDString];
    return candidate;
}

#pragma mark - Parsing stuff

+ (NSArray*)linesForSDP:(NSString*)sdp {
    NSArray* lines = [sdp componentsSeparatedByString:@"\r\n"];
    NSPredicate* predicate = [NSPredicate predicateWithFormat:@"length > 0"];
    return [lines filteredArrayUsingPredicate:predicate];
}

+ (NSString*)lineForPrefix:(NSString*)prefix mediaLines:(NSArray*)mediaLines sessionLines:(NSArray*)sessionLines {
    for (NSString* mediaLine in mediaLines) {
        if ([mediaLine hasPrefix:prefix]) {
            return mediaLine;
        }
    }

    for (NSString* sessionLine in sessionLines) {
        if ([sessionLine hasPrefix:prefix]) {
            return sessionLine;
        }
    }
    return nil;
}

+ (NSArray*)linesForPrefix:(NSString*)prefix mediaLines:(NSArray*)mediaLines sessionLines:(NSArray*)sessionLines {
    NSMutableArray* results = [NSMutableArray array];

    for (NSString* mediaLine in mediaLines) {
        if ([mediaLine hasPrefix:prefix]) {
            [results addObject:mediaLine];
        }
    }

    if ([results count]) {
        return results;
    }

    for (NSString* sessionLine in sessionLines) {
        if ([sessionLine hasPrefix:prefix]) {
            [results addObject:sessionLine];
        }
    }
    return results;
}

+ (NSArray*)groupsForGroupLines:(NSArray*)lines {
    // http://tools.ietf.org/html/rfc5888
    NSMutableArray* parsed = [NSMutableArray array];
    NSMutableArray* parts;
    for (NSString* line in lines) {
        parts = [[[line substringFromIndex:8] componentsSeparatedByString:@" "] mutableCopy];
        NSDictionary* group = @{@"semantics":[parts jah_popFirstObject],
                                @"contents": parts};
        [parsed addObject:[group mutableCopy]];
    }
    return parsed;
}

#pragma mark -

+ (NSDictionary*)mLineForLine:(NSString*)line {
    NSArray* parts = [[line substringFromIndex:2] componentsSeparatedByString:@" "];
    NSDictionary* parsed = @{@"media": parts[0],
                             @"port": parts[1],
                             @"proto": parts[2],
                             @"formats": [NSMutableArray array]};

    for (NSUInteger i = 3; i < [parts count]; i++) {
        if (parts[i]) {
            [parsed[@"format"] addObject:parts[i]];
        }
    }

    return parsed;
}

+ (NSMutableDictionary*)rtpMapForLine:(NSString*)line {
    NSMutableArray* parts = [[[line substringFromIndex:9] componentsSeparatedByString:@" "] mutableCopy];
    NSMutableDictionary* parsed = [NSMutableDictionary dictionary];
    parsed[@"id"] = [parts jah_popFirstObject];

    parts = [[parts[0] componentsSeparatedByString:@"/"] mutableCopy];

    parsed[@"name"] = parts[0];
    parsed[@"clockrate"] = parts[1];
    parsed[@"channels"] = ([parts count] == 3 ? parts[2] : @"1");
    return parsed;
}

+ (NSDictionary*)sctpMapForLine:(NSString*)line {
    // based on -05 draft
    NSArray* parts = [[line substringFromIndex:10] componentsSeparatedByString:@" "];
    NSMutableDictionary* parsed = [NSMutableDictionary dictionary];
    parsed[@"number"] = parts[0];
    parsed[@"protocol"] = parts[1];
    parsed[@"streams"] = parts[2];
    return parsed;
}

+ (NSArray*)fmtpForLine:(NSString*)line {
    NSRange range = [line rangeOfString:@" "];
    NSArray* parts = [[line substringFromIndex:(range.location + 1)] componentsSeparatedByString:@";"];

    NSArray* keyValue;
    NSMutableArray* parsed = [NSMutableArray array];
    for (NSString* part in parts) {
        keyValue = [part componentsSeparatedByString:@"="];
        NSString* key = [keyValue[0] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        NSString* value = keyValue[1];
        if (key && value) {
            [parsed addObject:@{@"key": key, @"value": value}];
        } else if (key) {
            [parsed addObject:@{@"key": @"", @"value": value}];
        }
    }

    return parsed;
}

+ (NSDictionary*)cryptoForLine:(NSString*)line {
    NSArray* parts = [[line substringFromIndex:9] componentsSeparatedByString:@" "];
    NSArray* subarray = [parts subarrayWithRange:NSMakeRange(3, [parts count] - 3)];
    NSDictionary* parsed = @{@"tag": parts[0],
                             @"cipherSuite": parts[1],
                             @"keyParams": parts[2],
                             @"sessionParams": [subarray componentsJoinedByString:@" "]};
    return parsed;
}

+ (NSMutableDictionary*)fingerprintForLine:(NSString*)line {
    NSArray* parts = [[line substringFromIndex:14] componentsSeparatedByString:@" "];
    NSMutableDictionary* parsed = [NSMutableDictionary dictionary];
    parsed[@"hash"] = parts[0];
    parsed[@"value"] = parts[1];
    return parsed;
}

+ (NSMutableDictionary*)extMapForLine:(NSString*)line {
    NSMutableArray* parts = [[[line substringFromIndex:9] componentsSeparatedByString:@" "] mutableCopy];
    NSMutableDictionary* parsed = [NSMutableDictionary dictionary];

    NSString* idPart = [parts jah_popFirstObject];
    NSRange sp = [idPart rangeOfString:@"/"];
    if (sp.location != NSNotFound) {
        parsed[@"id"] = [idPart substringWithRange:NSMakeRange(0, sp.location)];
        parsed[@"senders"] = [idPart substringFromIndex:(sp.location + 1)];
    } else {
        parsed[@"id"] = idPart;
        parsed[@"senders"] = @"sendrecv";
    }

    parsed[@"uri"] = [parts jah_popFirstObject] ?: @"";

    return parsed;
}

+ (NSDictionary*)rtcpfbForLine:(NSString*)line {
    NSMutableArray* parts = [[[line substringFromIndex:10] componentsSeparatedByString:@" "] mutableCopy];
    NSMutableDictionary* parsed = [NSMutableDictionary dictionary];
    parsed[@"id"] = [parts jah_popFirstObject];
    parsed[@"type"] = [parts jah_popFirstObject];
    if ([parsed[@"type"] isEqualToString:@"trr-int"]) {
        parsed[@"value"] = [parts jah_popFirstObject];
    } else {
        NSString* subtype = [parts jah_popFirstObject];
        parsed[@"subtype"] = [subtype length] ? subtype : @"";
    }

    parsed[@"parameters"] = parts;
    return parsed;
}

+ (NSArray*)sourceGroupsForGroupLines:(NSArray*)lines {
    NSMutableArray* parsed = [NSMutableArray array];
    NSMutableArray* parts;
    for (NSString* line in lines) {
        parts = [[[line substringFromIndex:13] componentsSeparatedByString:@" "] mutableCopy];
        [parsed addObject:@{@"semantics": [parts jah_popFirstObject],
                            @"sources": parts}];
    }
    return parsed;
}

+ (NSArray*)sourcesForLines:(NSArray*)lines {
    // http://tools.ietf.org/html/rfc5576
    NSMutableArray* parsed = [NSMutableArray array];
    NSMutableDictionary* sources = [NSMutableDictionary dictionary];

    for (NSString* line in lines) {
        NSMutableArray* parts = [[[line substringFromIndex:7] componentsSeparatedByString:@" "] mutableCopy];
        NSString* ssrc = [parts jah_popFirstObject];

        if (!sources[ssrc]) {
            NSDictionary* source = @{@"ssrc": ssrc, @"parameters": [NSMutableArray array]};
            [parsed addObject:source];

            // Keep an index
            sources[ssrc] = source;
        }

        parts = [[[parts componentsJoinedByString:@" "] componentsSeparatedByString:@":"] mutableCopy];
        NSString* attribute = [parts jah_popFirstObject];
        NSString* value = [parts componentsJoinedByString:@":"] ?: @"";

        [sources[ssrc][@"parameters"] addObject:@{@"key": attribute,
                                                  @"value": value}];
    }

    return parsed;
}

#pragma mark - Objects -> SDP

+ (NSDictionary*)senders {
    return @{@"initiator": @"sendonly",
             @"responder": @"recvonly",
             @"both": @"sendrecv",
             @"none": @"inactive",
             @"sendonly": @"initiator",
             @"recvonly": @"responder",
             @"sendrecv": @"both",
             @"inactive": @"none"};
}

+ (NSString*)SDPForSession:(NSDictionary*)session sid:(NSString*)sid time:(NSString*)time {
    if (!sid) {
        sid = session[@"sid"];
    }
    if (!sid) {
        sid = [NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970] * 10];
    }
    if (!time) {
        time = [NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970] * 10];
    }
    NSString* format = [NSString stringWithFormat:@"o=- %@ %@ IN IP4 0.0.0.0", sid, time];

    NSMutableArray* sdp = [NSMutableArray array];
    [sdp addObject:@"v=0"];
    [sdp addObject:format];
    [sdp addObject:@"s=-"];
    [sdp addObject:@"t=0 0"];

    for (NSDictionary* group in session[@"groups"]) {
        [sdp addObject:[NSString stringWithFormat:@"a=group:%@ %@", group[@"semantics"], [group[@"contents"] componentsJoinedByString:@" "]]];
    }

    for (NSDictionary* content in session[@"contents"]) {
        [sdp addObject:[[self class] mediaSDPForContent:content]];
    }

    return [[sdp componentsJoinedByString:@"\r\n"] stringByAppendingString:@"\r\n"];
}

+ (NSString*)mediaSDPForContent:(NSDictionary*)content {
    NSMutableArray* sdp = [NSMutableArray array];

    NSDictionary* desc = content[@"description"];
    NSDictionary* transport = content[@"transport"];

    NSMutableArray* mline = [NSMutableArray array];
    if ([desc[@"descType"] isEqualToString:@"datachannel"]) {
        [mline addObject:@"application"];
        [mline addObject:@"1"];
        [mline addObject:@"DTLS/SCTP"];
        for (NSDictionary* map in transport[@"sctp"]) {
            [mline addObject:map[@"number"]];
        }
    } else {
        [mline addObject:desc[@"media"]];
        [mline addObject:@"1"];
        if (([desc[@"encryption"] count] > 0) || ([transport[@"fingerprints"] count] > 0)) {
            [mline addObject:@"RTP/SAVPF"];
        } else {
            [mline addObject:@"RTP/AVPF"];
        }
        for (NSDictionary* payload in desc[@"payloads"]) {
            [mline addObject:payload[@"id"]];
        }
    }

    [sdp addObject:[NSString stringWithFormat:@"m=%@", [mline componentsJoinedByString:@" "]]];

    [sdp addObject:@"c=IN IP4 0.0.0.0"];

    if ([desc[@"descType"] isEqualToString:@"rtp"]) {
        [sdp addObject:@"a=rtcp:1 IN IP4 0.0.0.0"];
    }

    if (transport) {
        if (transport[@"ufrag"]) {
            [sdp addObject:[NSString stringWithFormat:@"a=ice-ufrag:%@", transport[@"ufrag"]]];
        }
        if (transport[@"pwd"]) {
            [sdp addObject:[NSString stringWithFormat:@"a=ice-pwd:%@", transport[@"pwd"]]];
        }
        if (transport[@"setup"]) {
            [sdp addObject:[NSString stringWithFormat:@"a=setup:%@", transport[@"setup"]]];
        }
        for (NSDictionary* fingerprint in transport[@"fingerprints"]) {
            [sdp addObject:[NSString stringWithFormat:@"a=fingerprint:%@ %@", fingerprint[@"hash"], fingerprint[@"value"]]];
        }
        for (NSDictionary* map in transport[@"sctp"]) {
            [sdp addObject:[NSString stringWithFormat:@"a=sctpmap:%@ %@ %@", map[@"number"], map[@"protocol"], map[@"streams"]]];
        }
    }

    if ([desc[@"descType"] isEqualToString:@"rtp"]) {
        NSString* sender = [[[self class] senders] objectForKey:content[@"senders"]] ?: @"sendrecv";
        [sdp addObject:[NSString stringWithFormat:@"a=%@", sender]];
    }
    [sdp addObject:[NSString stringWithFormat:@"a=mid:%@", content[@"name"]]];

    if (desc[@"mux"]) {
        [sdp addObject:@"a=rtcp-mux"];
    }

    for (NSDictionary* crypto in desc[@"encryption"]) {
        NSString* params = [crypto[@"sessionParams"] length] ? [NSString stringWithFormat:@" %@", crypto[@"sessionsParams"]] : @"";
        [sdp addObject:[NSString stringWithFormat:@"a=crypto:%@ %@ %@%@", crypto[@"tag"], crypto[@"cipherSuite"], crypto[@"keyParams"], params]];
    }

    for (NSDictionary* payload in desc[@"payloads"]) {
        NSString* rtpMap = [NSString stringWithFormat:@"a=rtpmap:%@ %@/%@", payload[@"id"], payload[@"name"], payload[@"clockrate"]];
        if (![payload[@"channels"] isEqualToString:@"1"]) {
            rtpMap = [rtpMap stringByAppendingFormat:@"/%@", payload[@"channels"]];
        }
        [sdp addObject:rtpMap];

        if ([payload[@"parameters"] count]) {
            NSMutableArray* fmtp = [NSMutableArray array];
            [fmtp addObject:[@"a=fmtp:" stringByAppendingString:payload[@"id"]]];
            for (NSDictionary* param in payload[@"parameters"]) {
                NSString* key = param[@"key"] ? [param[@"key"] stringByAppendingString:@"="] : @"";
                [fmtp addObject:[key stringByAppendingString:param[@"value"]]];
            }
            [sdp addObject:[fmtp componentsJoinedByString:@" "]];
        }

        if (payload[@"feedback"]) {
            for (NSDictionary* fb in payload[@"feedback"]) {
                NSMutableString* rtcp = [NSMutableString stringWithFormat:@"a=rtcp-fb:%@", payload[@"id"]];
                if ([fb[@"type"] isEqualToString:@"trr-int"]) {
                    [rtcp appendFormat:@" %@", fb[@"value"] ?: @"0"];
                } else {
                    [rtcp appendFormat:@" %@%@", fb[@"type"], [fb[@"subtype"] length] ? [@" " stringByAppendingString:fb[@"subtype"]] : @""];

                }
                [sdp addObject:rtcp];
            }
        }
    }

    for (id fb in desc[@"feedback"]) {
        NSMutableString* rtcp = [NSMutableString stringWithString:@"a=rtcp-fb:* "];
        if ([fb[@"type"] isEqualToString:@"trr-int"]) {
            [rtcp appendFormat:@"trr-int %@", fb[@"value"] ?: @"0"];
        } else {
            [rtcp appendFormat:@"%@%@", fb[@"type"], [fb[@"subtype"] length] ? [@" " stringByAppendingString:fb[@"subtype"]] : @""];
        }
        [sdp addObject:rtcp];
    }

    for (NSDictionary* hdr in desc[@"headerExtensions"]) {
        NSMutableString* extMap = [NSMutableString stringWithFormat:@"a=extmap:%@%@ %@", hdr[@"id"], hdr[@"senders"] ? [@"/" stringByAppendingString:[[[self class] senders] objectForKey:hdr[@"senders"]]] : @"", hdr[@"uri"]];
        [sdp addObject:extMap];
    }

    for (NSDictionary* ssrcGroup in desc[@"sourceGroups"]) {
        NSMutableString* group = [NSMutableString stringWithFormat:@"a=ssrc-group:%@ %@", ssrcGroup[@"semantics"], [ssrcGroup[@"sources"] componentsJoinedByString:@" "]];
        [sdp addObject:group];
    }

    for (NSDictionary* ssrc in desc[@"sources"]) {
        for (id parameter in ssrc[@"parameters"]) {
            NSMutableString* ssrcString = [NSMutableString stringWithFormat:@"a=ssrc:%@ %@%@", ssrc[@"ssrc"] ?: desc[@"ssrc"], parameter[@"key"], parameter[@"value"] ? [@":" stringByAppendingString:parameter[@"value"]] : @""];
            [sdp addObject:ssrcString];
        }
    }

    for (NSDictionary* candidate in transport[@"candidates"]) {
        [sdp addObject:[[self class] sdpForCandidate:candidate]];
    }

    return [sdp componentsJoinedByString:@"\r\n"];
}

+ (NSString*)sdpForCandidate:(NSDictionary*)candidate {
    NSMutableArray* sdp = [NSMutableArray array];

    [sdp addObject:candidate[@"foundation"]];
    [sdp addObject:candidate[@"component"]];
    [sdp addObject:[candidate[@"protocol"] uppercaseString]];
    [sdp addObject:candidate[@"priority"]];
    [sdp addObject:candidate[@"ip"]];
    [sdp addObject:candidate[@"port"]];

    NSString* type = candidate[@"type"];
    [sdp addObject:@"typ"];
    [sdp addObject:type];
    if ([type isEqualToString:@"srflx"] || [type isEqualToString:@"prflx"] || [type isEqualToString:@"relay"]) {
        if (candidate[@"relAddr"] && candidate[@"relPort"]) {
            [sdp addObject:@"raddr"];
            [sdp addObject:candidate[@"relAddr"]];
            [sdp addObject:@"rport"];
            [sdp addObject:candidate[@"relPort"]];
        }
    }

    [sdp addObject:@"generation"];
    [sdp addObject:candidate[@"generation"] ?: @"0"];

    return [@"a=candidate:" stringByAppendingString:[sdp componentsJoinedByString:@" "]];
}

@end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
ParticleEmitter (Slick Util - LWJGL Utilities extracted from Slick)
</TITLE>

<META NAME="date" CONTENT="2012-08-26">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.newdawn.slick.particles

Interface ParticleEmitter

All Known Implementing Classes:
ConfigurableEmitter, FireEmitter

public interface ParticleEmitter

An emitter is responsible for producing the particles and controlling them during
 their life. An implementation of this interface can be considered a particle
 effect.

Author:

kevin

Method Summary

 boolean
completed()

          Check if this emitter has completed it's cycle

 Image
getImage()

          Get the image to draw for each particle

 boolean
isEnabled()

          Check if the emitter is enabled

 boolean
isOriented()

          Check if the particles produced should maintain orientation

 void
resetState()

          Clear the state of emitter back to default

 void
resume()

          Resumes a particle emitter if it is not completed, after wrapUp() was invoked

 void
setEnabled(boolean enabled)

          Indicate whether the emitter should be enabled

 void
update(ParticleSystem system,
       int delta)

          Update the emitter, produce any particles required by requesting
 them from the particle system provided.

 void
updateParticle(Particle particle,
               int delta)

          Update a single particle that this emitter produced

 boolean
useAdditive()

          Check if this emitter should use additive blending

 boolean
usePoints(ParticleSystem system)

          Check if this emitter should use points based on it's own settings
 and those of the particle system

 void
wrapUp()

          Wrap up the particle emitter.

Method Detail

update

void update(ParticleSystem system,
            int delta)

Update the emitter, produce any particles required by requesting
 them from the particle system provided.

Parameters:
system - The particle system used to create particles
delta - The amount of time in milliseconds since last emitter update

completed

boolean completed()

Check if this emitter has completed it's cycle

Returns:
True if the emitter has completed it's cycle

wrapUp

void wrapUp()

Wrap up the particle emitter. This means the emitter will no longer produce
 particles and will be marked as completed once the particles have expired

resume

void resume()

Resumes a particle emitter if it is not completed, after wrapUp() was invoked

updateParticle

void updateParticle(Particle particle,
                    int delta)

Update a single particle that this emitter produced

Parameters:
particle - The particle to be updated
delta - The amount of time in millisecond since last particle update

isEnabled

boolean isEnabled()

Check if the emitter is enabled

Returns:
True if the emitter is enabled

setEnabled

void setEnabled(boolean enabled)

Indicate whether the emitter should be enabled

Parameters:
enabled - True if the emitter should be enabled

useAdditive

boolean useAdditive()

Check if this emitter should use additive blending

Returns:
True if the emitter should use the right blending

getImage

Image getImage()

Get the image to draw for each particle

Returns:
The image to draw for each particle

isOriented

boolean isOriented()

Check if the particles produced should maintain orientation

Returns:
True if the particles produced should maintain orientation

usePoints

boolean usePoints(ParticleSystem system)

Check if this emitter should use points based on it's own settings
 and those of the particle system

Parameters:
system - The particle system to cross check agianst

Returns:
True if we should use points

resetState

void resetState()

Clear the state of emitter back to default

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 2006 New Dawn Software. All Rights Reserved.


text:
/* eslint-disable max-nested-callbacks */

import * _ from'lodash';
import * as React from 'react/addons';
const rewireUtils = require('beaker/src/test-utils/jasmine/rewire');
const rewireDeps = rewireUtils.rewireDeps;
const resetDeps = rewireUtils.resetDeps;
const createStubComponent = require('beaker/src/test-utils/jasmine/rewire-components'). createStubComponent;
import Detail, {__RewireAPI__ as module} from '../../../src/components/detail';
import {model, view} from './common';

const TestUtils = React.addons.TestUtils;

const renderers = {
    'ObjectRenderer': {}
};

xdescribe('Detail', () => {
    let component, defaultView, deps, getDefaultViewSpy, modelValidationResult, propValidationResult, sandbox,
        validateViewSpy, validateModelSpy, validateValueSpy, value, valueValidationResult;

    beforeEach(() => {
        sandbox = sinon.sandbox.create();

        defaultView = {
            type: 'form',
            version: '1.0',
            rootContainers: [{label: 'Main', container: 'main'}],
            containers: [{id: 'main', rows: []}],
        };

        propValidationResult = {
            valid: true,
            errors: [],
            warnings: [{path: 'foo', message: 'bar'}],
        };

        modelValidationResult = {
            valid: true,
            errors: [],
            warnings: [{path: 'foo', message: 'bar'}],
        };

        valueValidationResult = {
            valid: true,
            errors: [],
            warnings: [],
        };

        getDefaultViewSpy = sandbox.spy(() => defaultView);
        validateViewSpy = sandbox.spy(() => propValidationResult);
        validateModelSpy = sandbox.spy(() => modelValidationResult);
        validateValueSpy = sandbox.spy(() => valueValidationResult);

        deps = {
            'ContainerComponent': createStubComponent('ContainerComponent', {}),
            'ValidationResult': createStubComponent('ValidationResult', {}),
            'getDefaultView': getDefaultViewSpy,
            'validateView': validateViewSpy,
            'validateModel': validateModelSpy,
            'validateValue': validateValueSpy,
        };

        value = {
            name: {
                first: 'Clark',
                last: 'Kent',
            },
            addresses: [
                {
                    street: '5 Hickory Ln.',
                    city: 'Smallville',
                    state: 'KA',
                    zip: '66605',
                },
            ],
        };

        rewireDeps(module, deps);
    });

    afterEach(() => {
        sandbox.restore();
        resetDeps(module, deps);
    });

    describe('with valid model/view/value', () => {
        beforeEach(() => {
            component = TestUtils.renderIntoDocument(
                <Detail
                    model={model}
                    renderers={renderers}
                    value={value}
                    view={view}
                />
            );
        });

        it('renders the root container', () => {
            expect(component.refs.rootContainer).to.be.defined;
        });

        it('passes along value to root container', () => {
            expect(component.refs.rootContainer.props.store.formValue).deep.equal(value);
        });

        it('passes along the view to the root container', () => {
            expect(component.refs.rootContainer.props.store.view).deep.equal(view);
        });

        it('passes along the model to the root container', () => {
            expect(component.refs.rootContainer.props.model).deep.equal(model);
        });

        it('passes along the container view to the root container', () => {
            const container = view.containers[view.rootContainers[0].container];
            expect(component.refs.rootContainer.props.containerConfig).deep.equal(container);
        });

        describe('._getView()', () => {
            let ret;

            describe('when view is present', () => {
                beforeEach(() => {
                    ret = component._getView(view, model);
                });

                it('returns the view as-is', () => {
                    expect(ret).to.be.equal(view);
                });
            });

            describe('when view is missing', () => {
                beforeEach(() => {
                    ret = component._getView(undefined, model);
                });

                it('generates a default view', () => {
                    expect(getDefaultViewSpy).to.be.calledWith(model);
                });

                it('returns the generated view', () => {
                    expect(ret).to.be.equal(defaultView);
                });
            });
        });

        describe('.componentWillReceiveProps()', () => {
            let newModel, newView, newValue, newRenderers;
            beforeEach(() => {
                newModel = {foo: 'bar'};
                newView = {bar: 'baz'};
                newValue = {baz: 'foo'};
                newRenderers = {'FooBar': {}};
                sandbox.stub(component, '_validateProps');
                component.componentWillReceiveProps({
                    view: newView,
                    model: newModel,
                    value: newValue,
                    renderers: newRenderers,
                });
            });

            it('validates the model/view/value', () => {
                expect(component._validateProps).to.be.calledWith(newView, newModel, newValue, newRenderers);
            });
        });

        describe('.componentWillMount()', () => {
            beforeEach(() => {
                sandbox.stub(component, '_validateProps');
                component.componentWillMount();
            });

            it('validates the model/view/value', () => {
                expect(component._validateProps).to.be.calledWith(view, model, value, renderers);
            });
        });

    });

    describe('with invalid model/view', () => {
        beforeEach(() => {
            propValidationResult = {
                valid: false,
                errors: [{path: '', message: 'bad, bad data'}],
                warnings: [{path: 'foo', message: 'bar'}],
            };

            component = TestUtils.renderIntoDocument(
                <Detail
                    model={model}
                    renderers={renderers}
                    view={view}
                />
            );
        });

        it('validates the model', () => {
            expect(validateViewSpy).to.be.calledWith(view, model, _.keys(renderers));
        });

        it('updates its state', () => {
            expect(component.state.propValidationResult).deep.equal(propValidationResult);
        });

        it('renders the validation result', () => {
            expect(component.refs.propValidationResult).to.be.defined;
        });

        it('passes along the result', () => {
            expect(component.refs.propValidationResult.props.result).deep.equal(propValidationResult);
        });
    });
});


text:
import * as React from 'react';
import axios from 'axios';
import Api from './api';

import CommentForm from './_comment_form';
import CommentList from './_comment_list';

class Comments extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      comments: props.post.comments,
    };
  }

  loadComments() {
    let URL = Api.getPost(this.props.post.id);

    axios.get(URL).then(response => {
      this.setState({
        comments: response.data.comments,
      });
    });
  }

  handleCommentSubmit(message) {
    let url = Api.createComment(this.props.post.id);
    let params = { comment: { message: message } };
    axios.post(url, params).then(response => {
      this.loadComments();
    });
  }

  render() {
    return (
      <div>
        <CommentForm
          onCommentSubmit={message => this.handleCommentSubmit(message)}
        />
        <CommentList comments={this.state.comments} />
      </div>
    );
  }
}

export default Comments;


text:
package org.apache.hadoop.hbase.security.access;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hbase.FullyQualifiedTableName;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

/**
 * Represents an authorization for access over the given table, column family
 * plus qualifier, for the given user.
 */
public class UserPermission extends TablePermission {
  private static Log LOG = LogFactory.getLog(UserPermission.class);

  private byte[] user;

  /** Nullary constructor for Writable, do not use */
  public UserPermission() {
    super();
  }

  /**
   * Creates a new instance for the given user.
   * @param user the user
   * @param assigned the list of allowed actions
   */
  public UserPermission(byte[] user, Action... assigned) {
    super(null, null, null, assigned);
    this.user = user;
  }

  /**
   * Creates a new instance for the given user,
   * matching the actions with the given codes.
   * @param user the user
   * @param actionCodes the list of allowed action codes
   */
  public UserPermission(byte[] user, byte[] actionCodes) {
    super(null, null, null, actionCodes);
    this.user = user;
  }

  /**
   * Creates a new instance for the given user, table and column family.
   * @param user the user
   * @param table the table
   * @param family the family, can be null if action is allowed over the entire
   *   table
   * @param assigned the list of allowed actions
   */
  public UserPermission(byte[] user, FullyQualifiedTableName table, byte[] family,
                        Action... assigned) {
    super(table, family, assigned);
    this.user = user;
  }

  /**
   * Creates a new permission for the given user, table, column family and
   * column qualifier.
   * @param user the user
   * @param table the table
   * @param family the family, can be null if action is allowed over the entire
   *   table
   * @param qualifier the column qualifier, can be null if action is allowed
   *   over the entire column family
   * @param assigned the list of allowed actions
   */
  public UserPermission(byte[] user, FullyQualifiedTableName table, byte[] family,
                        byte[] qualifier, Action... assigned) {
    super(table, family, qualifier, assigned);
    this.user = user;
  }

  /**
   * Creates a new instance for the given user, table, column family and
   * qualifier, matching the actions with the given codes.
   * @param user the user
   * @param table the table
   * @param family the family, can be null if action is allowed over the entire
   *   table
   * @param qualifier the column qualifier, can be null if action is allowed
   *   over the entire column family
   * @param actionCodes the list of allowed action codes
   */
  public UserPermission(byte[] user, FullyQualifiedTableName table, byte[] family,
                        byte[] qualifier, byte[] actionCodes) {
    super(table, family, qualifier, actionCodes);
    this.user = user;
  }

  public byte[] getUser() {
    return user;
  }

  /**
   * Returns true if this permission describes a global user permission.
   */
  public boolean isGlobal() {
    FullyQualifiedTableName tableName = getTable();
    return(tableName == null);
  }

  @Override
  public boolean equals(Object obj) {
    if (!(obj instanceof UserPermission)) {
      return false;
    }
    UserPermission other = (UserPermission)obj;

    if ((Bytes.equals(user, other.getUser()) &&
        super.equals(obj))) {
      return true;
    } else {
      return false;
    }
  }

  @Override
  public int hashCode() {
    final int prime = 37;
    int result = super.hashCode();
    if (user != null) {
      result = prime * result + Bytes.hashCode(user);
    }
    return result;
  }

  public String toString() {
    StringBuilder str = new StringBuilder("UserPermission: ")
        .append("user=").append(Bytes.toString(user))
        .append(", ").append(super.toString());
    return str.toString();
  }

  @Override
  public void readFields(DataInput in) throws IOException {
    super.readFields(in);
    user = Bytes.readByteArray(in);
  }

  @Override
  public void write(DataOutput out) throws IOException {
    super.write(out);
    Bytes.writeByteArray(out, user);
  }
}


text:
package net.sourceforge.lame.mp3;

/**
 * Control Parameters set by User. These parameters are here for backwards
 * compatibility with the old, non-shared lib API. Please use the
 * lame_set_variablename() functions below
 *
 * @author Ken
 */
public class LameGlobalFlags {

  public long class_id;

	/* input description */

  /**
   * number of samples. default=-1
   */
  public int num_samples;
  /**
   * scale input by this amount before encoding at least not used for MP3
   * decoding
   */
  public float scale;
  /**
   * scale input of channel 0 (left) by this amount before encoding
   */
  public float scale_left;
  /**
   * scale input of channel 1 (right) by this amount before encoding
   */
  public float scale_right;
  /**
   * collect data for a MP3 frame analyzer?
   */
  public boolean analysis;
  /**
   * add Xing VBR tag?
   */
  public boolean bWriteVbrTag;
  /**
   * use lame/mpglib to convert mp3 to wav
   */
  public boolean decode_only;
  /**
   * force M/S mode. requires mode=1
   */
  public boolean force_ms;
  /**
   * use free format? default=0
   */
  public boolean free_format;
  /**
   * decode on the fly? default=0
   */
  public boolean decode_on_the_fly;
  /**
   * sizeof(wav file)/sizeof(mp3 file)
   */
  public float compression_ratio;
  /**
   * mark as copyright. default=0
   */
  public int copyright;
  /**
   * mark as original. default=1
   */
  public int original;

	/* general control params */
  /**
   * the MP3 'private extension' bit. Meaningless
   */
  public int extension;
  /**
   * Input PCM is emphased PCM (for instance from one of the rarely emphased
   * CDs), it is STRONGLY not recommended to use this, because psycho does not
   * take it into account, and last but not least many decoders don't care
   * about these bits
   */
  public int emphasis;
  /**
   * use 2 bytes per frame for a CRC checksum. default=0
   */
  public boolean error_protection;
  /**
   * enforce ISO spec as much as possible
   */
  public boolean strict_ISO;
  /**
   * use bit reservoir?
   */
  public boolean disable_reservoir;
  /* quantization/noise shaping */
  public int quant_comp;
  public int quant_comp_short;
  public boolean experimentalY;
  public int experimentalZ;
  public int exp_nspsytune;
  public int preset;
  /**
   * Range [0,...,1[
   */
  public float VBR_q_frac;
  public int VBR_mean_bitrate_kbps;
  public int VBR_min_bitrate_kbps;
  public int VBR_max_bitrate_kbps;
  /**
   * strictly enforce VBR_min_bitrate normaly, it will be violated for analog
   * silence
   */
  public int VBR_hard_min;
  /**
   * freq in Hz. 0=lame choses. -1=no filter
   */
  public int lowpassfreq;
  /**
   * freq in Hz. 0=lame choses. -1=no filter
   */
  public int highpassfreq;
  /**
   * freq width of filter, in Hz (default=15%)
   */
  public int lowpasswidth;
  /**
   * freq width of filter, in Hz (default=15%)
   */
  public int highpasswidth;
  public float maskingadjust;
  public float maskingadjust_short;

	/* frame params */
  /**
   * only use ATH
   */
  public boolean ATHonly;
  /**
   * only use ATH for short blocks
   */
  public boolean ATHshort;
  /**
   * disable ATH
   */
  public boolean noATH;
  /**
   * select ATH formula
   */
  public int ATHtype;
  /**
   * change ATH formula 4 shape
   */
  public float ATHcurve;
  /**
   * lower ATH by this many db
   */
  public float ATHlower;
  /**
   * select ATH auto-adjust scheme
   */
  public int athaa_type;
  /**
   * select ATH auto-adjust loudness calc
   */
  public int athaa_loudapprox;
  /**
   * dB, tune active region of auto-level
   */
  public float athaa_sensitivity;
  public ShortBlock short_blocks;
  /**
   * use temporal masking effect
   */
  public Boolean useTemporal;
  public float interChRatio;
  /**
   * Naoki's adjustment of Mid/Side maskings
   */
  public float msfix;
  /**
   * 0 off, 1 on
   */
  public boolean tune;
  /**
   * used to pass values for debugging and stuff
   */
  public float tune_value_a;
  /**
   * number of samples of padding appended to input
   */
  public int encoder_padding;
  /**
   * number of frames encoded
   */
  public int frameNum;
  /**
   * is this struct owned by calling program or lame?
   */
  public int lame_allocated_gfp;
  /**
   * **********************************************************************
   */
  public LameInternalFlags internal_flags;
  /**
   * input number of channels. default=2
   */
  private int inNumChannels;
  /**
   * Input: Sampling rate in Hz (default=44100 - 44.1 kHz)
   */
  private int inSampleRate;
  /**
   * Output: Sampling rate in Hz (default=44100 - 44.1 kHz)
   *

   * Default: LAME picks best value at least not used for MP3 decoding:
   * Remember 44.1 kHz MP3s and AC97
   */
  private int outSampleRate;
  /**
   * quality setting 0=best, 9=worst default=5
   */
  private int quality;
  /**
   * Mono/Stereo mode.
   */
  private MPEGMode mode = MPEGMode.STEREO;

	/* resampling and filtering */
  /**
   * find the RG value? default=0
   */
  private boolean findReplayGain;
  /**
   * true (default) writes ID3 tags, false not.
   */
  private boolean writeId3tagAutomatic;
  /**
   * bit rate (constant bit rate).
   *

   * Note: set either bit rate>0 or compression ratio>0, LAME will compute the
   * value of the variable not set. Default is compression_ratio = 11.025
   */
  private int bitRate;
  /**
   * VBR control (variable bit rate)
   */
  private VbrMode VBR;

	/*
   * psycho acoustics and other arguments which you should not change unless
	 * you know what you are doing
	 */
  /**
   * Range [0,...,9]
   */
  private int VBRQuality;
  /**
   * MPEG version (0=MPEG-2/2.5 1=MPEG-1).
   */
  private int mpegVersion;
  /**
   * encoder delay.
   */
  private int encoderDelay;
  /**
   * Get frame size.
   */
  private int frameSize;

  /**
   * Input: Get number of channels (default=2)
   *
   * @return input number of channels (default=2)
   */
  public final int getInNumChannels() {
    return inNumChannels;
  }

  /**
   * Input: Set number of channels (default=2)
   *
   * @param inNumChannels input number of channels (default=2)
   */
  public final void setInNumChannels(final int inNumChannels) {
    this.inNumChannels = inNumChannels;
  }

  /**
   * Input: Get sampling rate.
   *
   * @return sampling rate in Hz (default=44100 - 44.1 kHz)
   */
  public final int getInSampleRate() {
    return inSampleRate;
  }

  /**
   * Input: Set sampling rate.
   *
   * @param inSampleRate sampling rate in Hz (default=44100 - 44.1 kHz)
   */
  public final void setInSampleRate(final int inSampleRate) {
    this.inSampleRate = inSampleRate;
  }

  /**
   * Output: Get sampling rate.
   *
   * @return sampling rate in Hz (default=44100 - 44.1 kHz)
   */
  public int getOutSampleRate() {
    return outSampleRate;
  }

  /**
   * Output: Set sampling rate.
   *
   * @param inSampleRate sampling rate in Hz (default=44100 - 44.1 kHz)
   */
  public void setOutSampleRate(int outSampleRate) {
    this.outSampleRate = outSampleRate;
  }

  /**
   * Get quality setting 0=best, 9=worst default=5.
   *
   * @return quality
   */
  public int getQuality() {
    return quality;
  }

  /**
   * Set quality setting 0=best, 9=worst default=5.
   *
   * @param quality quality setting 0=best, 9=worst default=5
   */
  public void setQuality(int quality) {
    this.quality = quality;
  }

  /**
   * Get Mono/Stereo mode.
   *
   * @return mono/Stereo mode.
   */
  public final MPEGMode getMode() {
    return mode;
  }

  /**
   * Set Mono/Stereo mode.
   *
   * @param mode Mono/Stereo mode.
   */
  public final void setMode(final MPEGMode mode) {
    this.mode = mode;
  }

  /**
   * Find the RG value? default=0
   *
   * @return find RG value
   */
  public boolean isFindReplayGain() {
    return findReplayGain;
  }

  /**
   * Set to find the RG value? default=0
   *
   * @param findReplayGain find the RG value
   */
  public void setFindReplayGain(boolean findReplayGain) {
    this.findReplayGain = findReplayGain;
  }

  /**
   * Turn off automatic writing of ID3 tag data into mp3 stream.
   *
   * @return true (default) writes ID3 tags, false not.
   */
  public final boolean isWriteId3tagAutomatic() {
    return writeId3tagAutomatic;
  }

  /************************************************************************/
	/* internal variables, do not set... */
	/* provided because they may be of use to calling application */
  /************************************************************************/

  /**
   * true (default) writes ID3 tags, false not.
   *

   * Turn off automatic writing of ID3 tag data into mp3 stream we have to
   * call it before 'Lame.initParams', because that function would spit out
   * ID3v2 tag data.
   */
  public final void setWriteId3tagAutomatic(final boolean writeId3tagAutomatic) {
    this.writeId3tagAutomatic = writeId3tagAutomatic;
  }

  /**
   * Get bit rate (8-640 kbps constant bit rate).
   *
   * @return bitrate
   */
  public final int getBitRate() {
    return bitRate;
  }

  /**
   * Set bit rate (constant bit rate)
   *
   * @param bitRate
   */
  public final void setBitRate(final int bitRate) {
    this.bitRate = bitRate;
  }

  /**
   * Get VBR control (variable bit rate).
   *
   * @return VBR control
   */
  public final VbrMode getVBR() {
    return VBR;
  }

  /**
   * Set VBR control (variable bit rate).
   *
   * @param VBR control
   */
  public final void setVBR(final VbrMode vBR) {
    VBR = vBR;
  }

  /**
   * Get VBR quality.
   *
   * @return VBR quality
   */
  public final int getVBRQuality() {
    return VBRQuality;
  }

  /**
   * Set VBR quality.
   *
   * @param vBRQuality VBR quality
   */
  public final void setVBRQuality(final int vBRQuality) {
    VBRQuality = vBRQuality;
  }

  /**
   * Get MPEG version (0=MPEG-2/2.5 1=MPEG-1)
   *
   * @return MPEG version (0=MPEG-2/2.5 1=MPEG-1)
   */
  public int getMpegVersion() {
    return mpegVersion;
  }

  /**
   * Set MPEG version (0=MPEG-2/2.5 1=MPEG-1).
   *
   * @param mpegVersion MPEG version (0=MPEG-2/2.5 1=MPEG-1)
   */
  public void setMpegVersion(int mpegVersion) {
    this.mpegVersion = mpegVersion;
  }

  /**
   * Get encoder delay.
   *
   * @return encoder delay
   */
  public int getEncoderDelay() {
    return encoderDelay;
  }

  /**
   * Set encoder delay.
   *
   * @param encoderDelay encoder delay
   */
  public void setEncoderDelay(int encoderDelay) {
    this.encoderDelay = encoderDelay;
  }

  /**
   * Set frame size.
   *
   * @return frame size
   */
  public int getFrameSize() {
    return frameSize;
  }
  /**************************************************************************/
	/* more internal variables are stored in this structure: */

  /**
   * Set frame size.
   *
   * @param frameSize frame size
   */
  public void setFrameSize(int frameSize) {
    this.frameSize = frameSize;
  }

}


text:
package com.joyue.tech.gankio.ui;

import android.content.Context;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONTokener;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;

public class Utils {

    private static final String FILENAME = "userinfo.json"; // 用户保存文件名
    private static final String TAG = "Utils";

    /* 保存用户登录信息列表 */
    public static void saveUserList(Context context, ArrayList<User> users) throws Exception {
        /* 保存 */
        Log.i(TAG, "正在保存");
        Writer writer = null;
        OutputStream out = null;
        JSONArray array = new JSONArray();
        for (User user : users) {
            array.put(user.toJSON());
        }
        try {
            out = context.openFileOutput(FILENAME, Context.MODE_PRIVATE); // 覆盖
            writer = new OutputStreamWriter(out);
            Log.i(TAG, "json的值:" + array.toString());
            writer.write(array.toString());
        } finally {
            if (writer != null)
                writer.close();
        }

    }

    /* 获取用户登录信息列表 */
    public static ArrayList<User> getUserList(Context context) {
		/* 加载 */
        FileInputStream in = null;
        ArrayList<User> users = new ArrayList<User>();
        try {

            in = context.openFileInput(FILENAME);
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder jsonString = new StringBuilder();
            JSONArray jsonArray = new JSONArray();
            String line;
            while ((line = reader.readLine()) != null) {
                jsonString.append(line);
            }
            Log.i(TAG, jsonString.toString());
            jsonArray = (JSONArray) new JSONTokener(jsonString.toString()).nextValue(); // 把字符串转换成JSONArray对象
            for (int i = 0; i < jsonArray.length(); i++) {
                User user = new User(jsonArray.getJSONObject(i));
                users.add(user);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return users;
    }
}


text:
<?php
class Upload extends Database {

	public function add_image($name, $image) {
		$date = date("Y-m-d H:i:s");
		$random_name = $this->_generate_name(10);
		$path_to_file = $_SERVER['DOCUMENT_ROOT']."/cdn/blog/".$random_name.".png";

		while (file_exists($path_to_file)) {
			$random_name = $this->_generate_name(10);
			$path_to_file = $_SERVER['DOCUMENT_ROOT']."/cdn/blog/".$random_name.".png";
		}

		move_uploaded_file($image, $path_to_file);

		$query = "INSERT INTO blog_images (name, path, date) VALUES (?, ?, ?)";
		$stmt = $this->mysqli->prepare($query);
		$stmt->bind_param("sss", $name, $path_to_file, $date);
		$stmt->execute();

		$result = $stmt->get_result();

		if ($result) {
			return true;
		} else {
			return false;
		}
	}

	public function delete_image($id) {
		$query = "SELECT path FROM blog_images WHERE id = ?";
		$stmt = $this->mysqli->prepare($query);
		$stmt->bind_param("i", $id);
		$stmt->execute();

		$result = $stmt->get_result();

		unlink($result);

		$query = "DELETE FROM blog_images WHERE id = ?";
		$stmt = $this->mysqli->prepare($query);
		$stmt->bind_param("i", $id);
		$stmt->execute();

		$result = $stmt->get_result();

		if ($result) {
			return true;
		} else {
			return false;
		}
	}

	public function rename_image($id, $name) {
		$query = "UPDATE blog_images SET name = ? WHERE id = ?";
		$stmt = $this->mysqli->prepare($query);
		$stmt->bind_param("si", $name, $id);
		$stmt->execute();

		$result = $stmt->get_result();

		if ($result) {
			return true;
		} else {
			return false;
		}
	}

	public function return_images() {
		$query = "SELECT * FROM blog_images ORDER BY date DESC";
		$result = $this->mysqli->query($query);
		$row = $result->fetch_all(MYSQLI_ASSOC);

		return $row;
	}

	private function _generate_name($length) {
    	$characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    	$characters_length = strlen($characters);
    	$random_string = "";

		for ($i = 0; $i < $length; $i++) {
        	$random_string .= $characters[rand(0, $characters_length - 1)];
    	}

		return $random_string;
	}
}
?>


text:
Proste forum oparte na php oraz AJAX-ie
Do stworzenia projektu zostaly użyte:
-CodeIgniter 3 https://codeigniter.com/
-Tank Auth https://konyukhov.com/soft/tank_auth/
UWAGA!
Żeby strona działała należy zmienić $config['base_url'] = 'http://localhost/default/'; na $config['base_url'] = 'Link do strony głównej'; w pliku katalogGłówny/application/config/config.php


text:
<resources>
    <string name="app_name">eglibrary-android-dropbox</string>
</resources>


text:
<?php
error_reporting(E_ALL | E_STRICT);

define('ROOT_DIR', dirname(dirname(__FILE__)).'/');
define('APP_DIR', ROOT_DIR.'app/');
require_once ROOT_DIR.'dietcake.php';

// backward compatibility for php 5.5 and low (with phpunit < v.6)
if (!class_exists('\PHPUnit\Framework\TestCase') && class_exists('\PHPUnit_Framework_TestCase')) {
    class_alias('\PHPUnit_Framework_TestCase', '\PHPUnit\Framework\TestCase');
}

if (!class_exists('\PHPUnit_Framework_TestCase') && class_exists('\PHPUnit\Framework\TestCase')) {
    class_alias('\PHPUnit\Framework\TestCase', '\PHPUnit_Framework_TestCase');
}


text:
"use strict";
if (true) {
    function foo() { } // Error to declare function in block scope
    foo(); // This call should be ok
}
foo(); // Error to find name foo


text:
//
//  ProgressViewController.m
//  iOSAnimationDemo
//
//  Created by Mekingo8 on 16/3/16.
//  Copyright © 2016年 Mekingo8. All rights reserved.
//

#import "ProgressViewController.h"
#import "ProgressView.h"

@interface ProgressViewController ()

@end

@implementation ProgressViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    CGFloat x = random() % 194 + 1.0;
    self.view.backgroundColor = [UIColor colorWithRed:x / 255.0 green:255.0 / 255.0 blue:255.0 / 255.0 alpha:1.0];

    //加载进度视图
    ProgressView * progressView = [[ProgressView alloc]initWithFrame: CGRectMake((self.view.bounds.size.width - 200) * 0.5, (self.view.bounds.size.height - 200) * 0.5, 200, 200)];
    //圆角
    progressView.layer.cornerRadius = progressView.frame.size.height / 2;
    progressView.backgroundColor = [UIColor colorWithRed:0.0 green:122/255.0 blue:255/255.0 alpha:1.0];

    [self.view addSubview:progressView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation

 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end


text:
from .core import ReadyForObject, ReadyForConnection, FacebookGraphConnection
from cached_property import cached_property
from . import user
from .errors import ProjectCommentsPageBackersZeroException
from .html_parser import ProjectCommentsPageParser, ProjectPageParser, FaceBookLikeParser
from datetime import datetime, timedelta
import itertools

class Project(ReadyForObject):

    def __init__(self, project_id=None, project_key=None, project_url=None):
        if project_id is None and project_key is None and project_url is None:
            raise ValueError('one of argument must be supplied')
        elif project_key is not None:
            if '/' in project_key:
                raise ValueError("\"project_key\" must be the *ending* of a vanity URL, not the entire URL!")
            self.project_key = project_key
            self.__id = None
            self.project_url = None
        elif project_id is not None:
            self.__id = project_id
            self.project_url = None
            self.project_key = None
        elif project_url is not None:
            self.__id = None
            self.project_url = project_url
            self.project_key = None

    @cached_property
    def __project_identifier(self):
        """
        this method return porject identifier for summary request.
        :return: project_key: if project_key or project_url is exist. project_id: if self.__id is exist.
        """
        if self.project_key is not None:
            return self.project_key
        elif self.__id is not None:
            return self.__id
        elif self.project_url is not None:
            return self.project_url.split('/')[4]

    # ----------------------------------------------
    # related summary
    # ----------------------------------------------
    @cached_property
    def summary(self):
        """
        this method return almost of property of project object
        :return:
        """
        response = ReadyForConnection.call(objects_kind="projects", object_id=self.__project_identifier, param=None, method="GET")
        return ProjectPageParser(response.text).parse()

    @cached_property
    def name(self):
        if self.project_key is not None:
            return self.project_key
        else:
            return self.summary["keyword"]

    @cached_property
    def _id(self):
        if self.__id is None:
            return self.summary["id"]
        else:
            return self.__id

    @cached_property
    def url(self):
        if self.project_url is not None:
            return self.project_url
        else:
            return "{domain}/{object}/{key}".format(domain="https://readyfor.jp", object="projects", key=self.name)

    @cached_property
    def amount(self):
        """
        :return: amount of money
        """
        amount = self.summary["amount"].replace(",", "")
        return int(amount)

    @property
    def anticipative_amount(self):
        """
        It is past goal amount of this project but not appear.
        :return: None
        """
        try:
            anticipative_amount = self.summary["anticipative_amount"].replace(",", "")
            return int(anticipative_amount)
        except:
            return None

    @property
    def is_2nd_stage(self):
        """
        :return: if 2nd stage , true else false
        """
        return self.anticipative_amount is not None

    @property
    def news_update_count(self):
        """
        新着情報の更新回数
        :return: 新着情報の更新回数
        """
        return int(self.summary["news_update_count"]) if self.summary["news_update_count"] is not None else None

    @property
    def achievement_amount(self):
        """
        Goal amount of past it appears when this project is setten 2nd goal.
        readyfor typo this property
        :return: goal amount of past.
        """
        return self.summary["achivement_amount"] if "achivement_amount" in self.summary else None

    @property
    def degree(self):
        """
        :return: end time of project
         :rtype: Datetime
        """
        return self.summary["degree"]

    @property
    def expired_at_year(self):
        """
        this parameter appear of project wes end.
        :return: the year when project end.
        :rtype: string
        """
        return self.summary["expired_at_year"] if "expired_at_year" in self.summary else None

    @property
    def funding_percent(self):
        return self.summary["funded_percent"]

    @property
    def goal_amount(self):
        goal_amount = self.summary["goal_amount"].replace(",", "")
        return int(goal_amount)

    @property
    def image(self):
        return self.summary["image"]

    @property
    def is_accomplish_report_published(self):
        return self.summary["is_accomplish_report_published"]

    @cached_property
    def is_expired(self):
        return True if self.summary["is_expired"] == "終了日" else False

    @property
    def is_matching_complete(self):
        return self.summary["is_matching_complete"]

    @property
    def keep_it_all(self):
        return self.summary["keep_it_all"]

    @property
    def deadline(self):
        if self.summary["deadline"] is not None:
            return datetime.strptime(self.summary["deadline"], "%Y-%m-%d")
        else:
            return datetime.today() + timedelta(days=3)

    @cached_property
    def is_succeed(self):
        return True if self.funding_percent >= 100 else False

    @property
    def label_type(self):
        return self.summary["label_type"]

    @property
    def matching(self):
        return self.summary["matching"]

    @property
    def favorite_count(self):
        return int(self.summary["watchlists_count"]) if self.summary["watchlists_count"] is not None else None

    @property
    def project_type(self):
        """
        :return: project type. e.g. "charity" , "normal"
        """
        return self.summary["project_type"]

    @property
    def tags(self):
        return self.summary["tags"]

    @cached_property
    def author(self):
        return user.User(user_url=self.summary["user_profile_url"], name=self.summary["user"]["name"])

    @property
    def comments_count(self):
        return int(self.summary["comments_count"]) if self.summary["comments_count"] is not None else None

    @property
    def project_text(self):
        return self.summary["project_text"]

    @property
    def project_images(self):
        return self.summary["project_images"]

    @property
    def num_project_images(self):
        return len(self.project_images)

    @cached_property
    def category(self):
        for tag in self.tags:
            if tag["tag_type"] == "category":
                return tag["name"]

    @cached_property
    def comments_summary(self):
        """
        :return: Backers which back to this project
        :rtype: user.User
        """
        comments_summary = {"backers": []}
        for page in itertools.count(start=1, step=1):
            try:
                response = ReadyForConnection.call(objects_kind="projects", object_id=self.__project_identifier,
                                                   sub_object_kind="comments", page=page)
                comments_summary["backers"].extend(ProjectCommentsPageParser(response.text).parse()["backers"])
            except ProjectCommentsPageBackersZeroException as e:
                break

        return [
            user.User(
                user_id=backer["backer_id"],
                backed_at=backer["backed_at"],
                name=backer["backer_name"]
            )
            for backer in comments_summary["backers"]
        ]

    @cached_property
    def backers(self):
        return self.comments_summary

    # ----------------------------------------
    # related facebook
    # ----------------------------------------
    @cached_property
    def __facebook_graph(self):
        """
        :return: Facebook_Like
        """
        domain = "https://readyfor.jp"
        object_id = "{domain}/{object}/{name}".format(domain=domain, object="projects", name=self.name)
        return FaceBookLikeParser(FacebookGraphConnection.call(object_id=object_id, v="v2.10").text).parse()

    @property
    def facebook_reaction_count(self):
        return self.__facebook_graph["engagement"]["reaction_count"]

    @property
    def facebook_share_count(self):
        return self.__facebook_graph["engagement"]["share_count"]

    @property
    def facebook_comment_count(self):
        return self.__facebook_graph["share"]["comment_count"]


text:
/**
 * @dgService PropertyNodeMatcher
 * @description Returns code name from node
 */
module.exports = function PropertyNodeMatcherFactory (codeNameService) {
  /**
   * @param {Node} node AST node to process
   * @returns {String|Null} code name from node
   */
  return function PropertyNodeMatcher (node) {
    return codeNameService.find(node.value) || codeNameService.find(node.key);
  }
};


text:
<?php
defined('BASEPATH')or exit('No direct script access allowed');

class cEditarProy extends CI_controller{
	public function editar(){
	 		$archivo=$this->input->post('archivo');
	 		//print_r($_POST);
			$ar=fopen("Proyectos/Redactados/".$archivo,"w+") or
			die("Problemas en la creacion");
			fputs($ar,$_REQUEST['descripcion']);
			fclose($ar);
			echo "<script>alert('Se guardo el registro con exito...')</script>";
			$this->db->where('nombre',$archivo);
			$this->db->update('proyectos',array('estado'=>2));
			$this->load->view('header2');
		  	$this->load->view('proyectista/vMenuproy');
			$this->load->view('proyectista/vexpeds',$archivo);
			$this->load->view('footer');

		}
		public function editarm(){
	 		$expediente=$this->input->post('expediente');
	 		$archivo=$this->input->post('archivo');
			$ar=fopen("Proyectos/".$expediente."/".$archivo,"w+") or
			die("Problemas en la creacion");
			fputs($ar,$_REQUEST['descripcion']);
			fclose($ar);
			echo "<script>alert('Se guardo el registro con exito...')</script>";
			$this->load->view('header2');
		    $this->load->view('body/voficial');
			$this->load->view('magistrado/vMagistrado');
			$this->load->view('footer');

		}
	}
?>


text:
package org.eclipse.jdt.internal.ui.filters;

import org.eclipse.jdt.internal.ui.viewsupport.MemberFilter;

/**
 * Statics filter.
 *
 * @since 3.0
 */
public class StaticsFilter extends MemberFilter {
	public StaticsFilter() {
		addFilter(MemberFilter.FILTER_STATIC);
	}
}


text:
package com.google.errorprone.bugpatterns;

import com.google.errorprone.CompilationTestHelper;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * @author Bill Pugh (bill.pugh@gmail.com)
 */
@RunWith(JUnit4.class)
public class BadShiftAmountTest {

  private CompilationTestHelper compilationHelper;

  @Before
  public void setUp() {
    compilationHelper = CompilationTestHelper.newInstance(new BadShiftAmount());
  }

  @Test
  public void testPositiveCase() throws Exception {
    compilationHelper.assertCompileFailsWithMessages(compilationHelper.fileManager()
        .sources(getClass(), "BadShiftAmountPositiveCases.java"));
  }

  @Test
  public void testNegativeCase() throws Exception {
    compilationHelper.assertCompileSucceeds(compilationHelper.fileManager()
        .sources(getClass(), "BadShiftAmountNegativeCases.java"));
  }

}


text:
package org.apache.shardingsphere.example.core.api.entity;

import java.io.Serializable;

public class Address implements Serializable {

    private static final long serialVersionUID = 661434701950670670L;

    private Long addressId;

    private String addressName;

    public Long getAddressId() {
        return addressId;
    }

    public void setAddressId(final Long addressId) {
        this.addressId = addressId;
    }

    public String getAddressName() {
        return addressName;
    }

    public void setAddressName(final String addressName) {
        this.addressName = addressName;
    }
}


text:
package edu.uw.zookeeper.common;

public interface Generator<E> {
    E next();
}