text:
package org.jetbrains.plugins.scala
package format

import org.jetbrains.plugins.scala.base.ScalaLightCodeInsightFixtureTestCase
import org.jetbrains.plugins.scala.extensions.{IteratorExt, PsiElementExt}
import org.jetbrains.plugins.scala.lang.psi.api.ScalaFile
import org.jetbrains.plugins.scala.lang.psi.api.expr.ScExpression
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.templates.ScTemplateBody
import org.jetbrains.plugins.scala.lang.psi.impl.ScalaPsiElementFactory
import org.jetbrains.plugins.scala.project.ScalaFeatures
import org.junit.Assert._

class StringConcatenationFormatterTest extends ScalaLightCodeInsightFixtureTestCase {
  def testEmpty(): Unit = {
    assertEquals("\"\"", format())
  }

  def testText(): Unit = {
    assertEquals(""""foo"""", format(Text("foo")))
  }

  def testText_SiblingsShouldBeMerged(): Unit = {
    assertEquals(""""aabb"""", format(Text("aa"), Text("bb")))
    assertEquals(""""aabbccc"""", format(Text("aa"), Text("bb"), Text("ccc")))
    assertEquals(""""aabbccc"""", format(Text("aa"), Text("bb"), Text("ccc")))
  }

  def testTextLike_SiblingsShouldBeMerged(): Unit = {
    assertEquals(""""% text %"""",
      format(SpecialFormatEscape.PercentChar, Text(" text "), SpecialFormatEscape.PercentChar))
    assertEquals(""""\n text \n"""",
      format(SpecialFormatEscape.LineSeparator, Text(" text "), SpecialFormatEscape.LineSeparator))
    assertEquals(""""% text \n"""",
      format(SpecialFormatEscape.PercentChar, Text(" text "), SpecialFormatEscape.LineSeparator))
    assertEquals(""""\n text %"""",
      format(SpecialFormatEscape.LineSeparator, Text(" text "), SpecialFormatEscape.PercentChar))
  }

  def testTextLike_SiblingsShouldBeMerged_1(): Unit = {
    assertEquals(s""""%% text %"""", format(
      SpecialFormatEscape.PercentChar,
      SpecialFormatEscape.PercentChar,
      Text(" text "),
      SpecialFormatEscape.PercentChar,
    ))

    assertEquals(s""""%% text %" + int""", format(
      SpecialFormatEscape.PercentChar,
      SpecialFormatEscape.PercentChar,
      Text(" text "),
      SpecialFormatEscape.PercentChar,
      Injection(exp("int"), None),
    ))

    assertEquals(s"""int.toString + "%% text %"""", format(
      Injection(exp("int"), None),
      SpecialFormatEscape.PercentChar,
      SpecialFormatEscape.PercentChar,
      Text(" text "),
      SpecialFormatEscape.PercentChar,
    ))

    assertEquals(s"""int.toString + "%%" + str + " text %"""", format(
      Injection(exp("int"), None),
      SpecialFormatEscape.PercentChar,
      SpecialFormatEscape.PercentChar,
      Injection(exp("str"), None),
      Text(" text "),
      SpecialFormatEscape.PercentChar,
    ))
  }

  def testEscapeChar(): Unit = {
    assertEquals(""""\n"""", format(Text("\n")))
    assertEquals(""""\t\r\n"""", format(Text("\t\r\n")))
  }

  def testEscapeChar_WithUnicodeCandidate(): Unit = {
    assertEquals("\"\\\\u0025\"", format(Text("\\u0025")))
  }

  def testSlash(): Unit = {
    assertEquals(""""\\"""", format(Text("\\")))
    assertEquals(""""\\\\"""", format(Text("\\\\")))
    assertEquals(""""\\ \\"""", format(Text("\\ \\")))
    assertEquals("""" \\ \\\\ \\\\ """", format(Text(" \\ \\\\ \\\\ ")))
  }

  def testPlainExpression_String(): Unit = {
    assertEquals("""str""", format(Injection(exp("""str"""), None)))
  }

  def testPlainExpression_Numeric(): Unit = {
    assertEquals("""int.toString""", format(Injection(exp("int"), None)))
    assertEquals("""long.toString""", format(Injection(exp("long"), None)))
    assertEquals("""bool.toString""", format(Injection(exp("bool"), None)))
  }

  def testExpressionWithDispensableFormat(): Unit = {
    assertEquals("""str""", format(Injection(exp("str"), Some(Specifier(null, "%s")))))
    assertEquals("""int.toString""", format(Injection(exp("int"), Some(Specifier(null, "%d")))))
  }

  def testExpressionWithMandatoryFormat(): Unit = {
    assertEquals("""int.formatted("%2d")""", format(Injection(exp("int"), Some(Specifier(null, "%2d")))))
  }

  def testPlainLiteral_Numeric(): Unit = {
    assertEquals("""123.toString""", format(Injection(exp("123"), None)))
    assertEquals("""123L.toString""", format(Injection(exp("123L"), None)))
    assertEquals("""true.toString""", format(Injection(exp("true"), None)))
  }

  def testPlainLiteral_String(): Unit = {
    assertEquals(""""text"""", format(Injection(exp(""""text""""), None)))
    assertEquals("""s"text"""", format(Injection(exp("""s"text""""), None)))
    assertEquals("""f"text"""", format(Injection(exp("""f"text""""), None)))
  }

  //noinspection RedundantBlock
  def testPlainLiteral_MultilineString(): Unit = {
    val qqq = "\"\"\""
    assertEquals(s"""${qqq}text${qqq}""", format(Injection(exp(s"""${qqq}text${qqq}"""), None)))
    assertEquals(s"""s${qqq}text${qqq}""", format(Injection(exp(s"""s${qqq}text${qqq}"""), None)))
    assertEquals(s"""f${qqq}text${qqq}""", format(Injection(exp(s"""f${qqq}text${qqq}"""), None)))
  }

  def testMultipleLiterals_Mixed(): Unit = {
    assertEquals(""""text" + 123""", format(Injection(exp(""""text""""), None), Injection(exp("123"), None)))
    assertEquals("""123.toString + "text"""", format(Injection(exp("123"), None), Injection(exp(""""text""""), None)))

    assertEquals(""""text1" + "text2"""", format(Injection(exp(""""text1""""), None), Injection(exp(""""text2""""), None)))
    assertEquals("""123.toString + 456L""", format(Injection(exp("123"), None), Injection(exp("456L"), None)))
  }

  def testMultipleExpressions_Mixed(): Unit = {
    assertEquals("""str + int""", format(Injection(exp("str"), None), Injection(exp("int"), None)))
    assertEquals("""123.toString + str""", format(Injection(exp("123"), None), Injection(exp("str"), None)))

    assertEquals("""str + str""", format(Injection(exp("str"), None), Injection(exp("str"), None)))
    assertEquals("""int.toString + long""", format(Injection(exp("int"), None), Injection(exp("long"), None)))

    assertEquals(""""foo " + str + " bar"""", format(Text("foo "), Injection(exp("str"), None), Text(" bar")))
    assertEquals(""""foo " + int + " bar"""", format(Text("foo "), Injection(exp("int"), None), Text(" bar")))
  }

  def testLiteralWithDispensableFormat(): Unit = {
    assertEquals("""123.toString""", format(Injection(exp("123"), Some(Specifier(null, "%d")))))
  }

  def testLiteralWithMandatoryFormat(): Unit = {
    assertEquals("123.formatted(\"%2d\")", format(Injection(exp("123"), Some(Specifier(null, "%2d")))))
  }

  def testPlainComplexExpression(): Unit = {
    assertEquals("obj.str", format(Injection(exp("obj.str"), None)))
  }

  def testComplexExpressionWithDispensableFormat(): Unit = {
    assertEquals("obj.str", format(Injection(exp("obj.str"), Some(Specifier(null, "%d")))))
  }

  def testComplexExpressionWithMandatoryFormat(): Unit = {
    assertEquals("obj.str.formatted(\"%2d\")", format(Injection(exp("obj.str"), Some(Specifier(null, "%2d")))))
  }

  def testPlainBlockExpression(): Unit = {
    assertEquals("obj.str", format(Injection(exp("{obj.str}"), None)))
  }
  def testPlainBlockExpression_1(): Unit = {
    assertEquals("obj.strCall()", format(Injection(exp("{obj.strCall()}"), None)))
  }
  def testReference(): Unit = {
    assertEquals("obj.str", format(Injection(exp("obj.str"), None)))
  }
  def testMethodCall(): Unit = {
    assertEquals("obj.strCall()", format(Injection(exp("obj.strCall()"), None)))
  }

  def testBlockExpressionWithDispensableFormat(): Unit = {
    assertEquals("obj.str", format(Injection(exp("{obj.str}"), Some(Specifier(null, "%d")))))
  }

  def testBlockExpressionWithMandatoryFormat(): Unit = {
    assertEquals("obj.str.formatted(\"%2d\")", format(Injection(exp("{obj.str}"), Some(Specifier(null, "%2d")))))
  }

  def testPlainComplexBlockExpression(): Unit = {
    assertEquals("{null; obj.str}", format(Injection(exp("{null; obj.str}"), None)))
  }

  def testComplexBlockExpressionWithDispensableFormat(): Unit = {
    assertEquals("{null; obj.str}", format(Injection(exp("{null; obj.str}"), Some(Specifier(null, "%d")))))
  }

  def testComplexBlockExpressionWithMandatoryFormat(): Unit = {
    assertEquals("{null; obj.str}.formatted(\"%2d\")", format(Injection(exp("{null; obj.str}"), Some(Specifier(null, "%2d")))))
  }

  def testOther(): Unit = {
    assertEquals("", format(UnboundExpression(exp("foo"))))
  }

  private def format(parts: StringPart*): String = {
    StringConcatenationFormatter.format(parts)
  }

  private lazy val contextFile: ScalaFile = ScalaPsiElementFactory.createScalaFileFromText(
    """class A {
      |  def obj: A        = new A
      |  def str: String   = "text"
      |  def strCall(): String   = "text"
      |  def int: Int      = 42
      |  def long: Long    = 23L
      |  def bool: Boolean = true
      |}
      |""".stripMargin,
    ScalaFeatures.onlyByVersion(version)
  )(getProject)

  private def exp(s: String): ScExpression = {
    val context = contextFile.depthFirst().findByType[ScTemplateBody].get
    ScalaPsiElementFactory.createExpressionWithContextFromText(s, context)
  }
}


text:
package org.vitrivr.cineast.core.data.query.containers;

public class IdQueryTermContainer extends AbstractQueryTermContainer {

  public IdQueryTermContainer(String id) {
    setId(id);
  }

}

redpajama_set_name: RedPajamaGithub


text:
module.exports = function(grunt) {
    grunt.initConfig({
        sshconfig: {
            'server': {
                host: process.env.SSH_HOST,
                username: process.env.SSH_USER,
                password: process.env.SSH_PASSWORD,
                port: process.env.SSH_PORT
            }
        },
        sshexec: {
            deploy: {
                command: [
                    'cd /var/www/riplive_instagram',
                    'git pull origin master',
                    'npm install --dev',
                    'forever restartall',
                    'forever list'
                ].join(' && '),
                options: {
                    config: 'server'
                }
            }
        }
    });

    grunt.loadNpmTasks('grunt-ssh');

    grunt.registerTask('deploy', [
        'sshexec:deploy'
    ]);
};


text:
extern "C" {
#endif

extern word_t *comma(context_t *ctx, word_t num);
extern void literal(context_t *ctx, int n);
extern void compile(context_t *ctx, int n, ...);
extern context_t *load(context_t *ctx, char *filename, char *buf);

#ifdef __cplusplus
}
#endif

#endif


text:
package com.example.android.sunshine.app.widget;

import android.annotation.TargetApi;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.AdapterView;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.example.android.sunshine.app.R;
import com.example.android.sunshine.app.Utility;
import com.example.android.sunshine.app.data.WeatherContract;

import java.util.concurrent.ExecutionException;

/**
 * Created by debashispaul on 27/01/2016.
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class DetailWidgetRemoteViewsService extends RemoteViewsService {
    private final static String LOG_TAG = DetailWidgetRemoteViewsService.class.getSimpleName();
    private static final String[] FORECAST_COLUMNS = {
            // In this case the id needs to be fully qualified with a table name, since
            // the content provider joins the location & weather tables in the background
            // (both have an _id column)
            // On the one hand, that's annoying.  On the other, you can search the weather table
            // using the location set by the user, which is only in the Location table.
            // So the convenience is worth it.
            WeatherContract.WeatherEntry.TABLE_NAME + "." + WeatherContract.WeatherEntry._ID,
            WeatherContract.WeatherEntry.COLUMN_WEATHER_ID,
            WeatherContract.WeatherEntry.COLUMN_SHORT_DESC,
            WeatherContract.WeatherEntry.COLUMN_MAX_TEMP,
            WeatherContract.WeatherEntry.COLUMN_MIN_TEMP,
            WeatherContract.LocationEntry.COLUMN_CITY_NAME,
            WeatherContract.WeatherEntry.COLUMN_DATE,

    };
    // These indices are tied to FORECAST_COLUMNS.  If FORECAST_COLUMNS changes, these
    // must change.
    static final int COL_WEATHER_ID = 0;
    static final int COL_WEATHER_COND_ID = 1;
    static final int COL_WEATHER_DESC = 2;
    static final int COL_WEATHER_MAX_TEMP = 3;
    static final int COL_WEATHER_MIN_TEMP = 4;
    static final int COL_CITY_NAME = 5;
    static final int COL_WEATHER_DATE = 6;

    private static final String SORT_ORDER = WeatherContract.WeatherEntry.COLUMN_DATE + " ASC";

    @Override
    public RemoteViewsFactory onGetViewFactory(Intent intent) {
        return new DetailWidgetRemoteViewsFactory(this.getApplicationContext(), intent);
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    class DetailWidgetRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory {
        private Context mContext;
        private int mAppWidgetId;
        Cursor mCursor = null;

        public DetailWidgetRemoteViewsFactory(Context context, Intent intent) {
            mContext = context;
            mAppWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
        }

        @Override
        public void onCreate() {
            // In onCreate() you setup any connections / cursors to your data source. Heavy lifting,
            // for example downloading or creating content etc, should be deferred to onDataSetChanged()
            // or getViewAt(). Taking more than 20 seconds in this call will result in an ANR.
        }

        @Override
        public void onDataSetChanged() {
            // This is triggered when you call AppWidgetManager notifyAppWidgetViewDataChanged
            // on the collection view corresponding to this factory. You can do heaving lifting in
            // here, synchronously. For example, if you need to process an image, fetch something
            // from the network, etc., it is ok to do it here, synchronously. The widget will remain
            // in its current state while work is being done here, so you don't need to worry about
            // locking up the widget.
            if (mCursor != null) {
                mCursor.close();
            }
            //Get today's weather data from the database
            final long identityToken = Binder.clearCallingIdentity();
            String locationSettings = Utility.getPreferredLocation(mContext);
            Uri weatherForLocationUri = WeatherContract.WeatherEntry.buildWeatherLocationWithStartDate(locationSettings,
                    System.currentTimeMillis());
            mCursor = getApplicationContext().getContentResolver().query(
                    weatherForLocationUri,
                    FORECAST_COLUMNS,
                    null,
                    null,
                    SORT_ORDER
            );
            Binder.restoreCallingIdentity(identityToken);

            if (mCursor == null) {
                Log.v(LOG_TAG, "Cursor is null!!");
                return;
            }
            if (!mCursor.moveToFirst()) {
                Log.v(LOG_TAG, "Cursor is empty!!");
                mCursor.close();
                return;
            }
            Log.v(LOG_TAG, "Total record in the cursor:" + mCursor.getCount());
        }

        @Override
        public void onDestroy() {
            // In onDestroy() you should tear down anything that was setup for your data source,
            // eg. cursors, connections, etc.
            if (mCursor != null) {
                mCursor.close();
                mCursor = null;
            }
        }

        @Override
        public int getCount() {
            return mCursor == null ? 0 : mCursor.getCount();
        }

        @Override
        public RemoteViews getViewAt(int position) {
            // position will always range from 0 to getCount() - 1.

            //Position the cursor to right row
            if (position == AdapterView.INVALID_POSITION ||
                    mCursor == null || !mCursor.moveToPosition(position)) {
                return null;
            }

            // Extract the weather data from the Cursor
            int weatherId = mCursor.getInt(COL_WEATHER_COND_ID);
            int weatherArtResourceId = Utility.getArtResourceForWeatherCondition(weatherId);
            Bitmap weatherArtImage = null;
            if (!Utility.usingLocalGraphics(DetailWidgetRemoteViewsService.this)) {
                String weatherArtResourceUrl = Utility.getArtUrlForWeatherCondition(
                        DetailWidgetRemoteViewsService.this, weatherId);
                try {
                    weatherArtImage = Glide.with(DetailWidgetRemoteViewsService.this)
                            .load(weatherArtResourceUrl)
                            .asBitmap()
                            .error(weatherArtResourceId)
                            .into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL).get();
                } catch (InterruptedException | ExecutionException e) {
                    Log.e(LOG_TAG, "Error retrieving large icon from " + weatherArtResourceUrl, e);
                }
            }

            double maxTemp = mCursor.getDouble(COL_WEATHER_MAX_TEMP);
            String formattedMaxTemperature = Utility.formatTemperature(mContext, maxTemp, Utility.isMetric(mContext));
            double minTemp = mCursor.getDouble(COL_WEATHER_MIN_TEMP);
            String formattedMinTemperature = Utility.formatTemperature(mContext, minTemp, Utility.isMetric(mContext));
            String weatherDesc = mCursor.getString(COL_WEATHER_DESC);
            String cityName = mCursor.getString(COL_CITY_NAME);
            long weatherDate = mCursor.getLong(COL_WEATHER_DATE);
            String weatherDateText = Utility.getFriendlyDayString(mContext, weatherDate);
            long dateInMillis = mCursor.getLong(COL_WEATHER_DATE);

            // We construct a remote views item based on our widget item xml file, and set the
            // text based on the position.
            RemoteViews rv = new RemoteViews(mContext.getPackageName(), R.layout.widget_detail_item);

            // Add the data to the RemoteViews
            if (weatherArtImage != null) {
                rv.setImageViewBitmap(R.id.widget_list_item_icon, weatherArtImage);
            } else {
                rv.setImageViewResource(R.id.widget_list_item_icon, weatherArtResourceId);
            }
            // Content Descriptions for RemoteViews were only added in ICS MR1
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
                setRemoteContentDescription(rv, weatherDesc);
            }
            rv.setTextViewText(R.id.widget_list_item_high_textview, formattedMaxTemperature);
            rv.setTextViewText(R.id.widget_list_item_low_textview, formattedMinTemperature);
            rv.setTextViewText(R.id.widget_list_item_forecast_textview, weatherDesc);
            if (position == 0) {
                //Display the Day as "Today" for first item of tablet
                rv.setTextViewText(R.id.widget_list_item_date_textview, "Today");
            } else {
                //Display the Data as friendly date for rest
                rv.setTextViewText(R.id.widget_list_item_date_textview, weatherDateText);
            }

            // Next, we set a fill-intent which will be used to fill-in the pending intent template
            // which is set on the collection view in StackWidgetProvider.
            final Intent fillInIntent = new Intent();
            String locationSetting = Utility.getPreferredLocation(DetailWidgetRemoteViewsService.this);
            Uri weatherUri = WeatherContract.WeatherEntry.buildWeatherLocationWithDate(locationSetting, dateInMillis);
            fillInIntent.setData(weatherUri);
            rv.setOnClickFillInIntent(R.id.widget_list_item, fillInIntent);
            // You can do heaving lifting in here, synchronously. For example, if you need to
            // process an image, fetch something from the network, etc., it is ok to do it here,
            // synchronously. A loading view will show up in lieu of the actual contents in the
            // interim.
            try {
                System.out.println("Loading view " + position);
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // Return the remote views object.
            return rv;
        }

        @Override
        public RemoteViews getLoadingView() {
            // You can create a custom loading view (for instance when getViewAt() is slow.) If you
            // return null here, you will get the default loading view.
            return new RemoteViews(getPackageName(), R.layout.widget_detail_item);
        }

        @Override
        public int getViewTypeCount() {
            return 1;
        }

        @Override
        public long getItemId(int position) {
            if (mCursor.moveToPosition(position))
                return mCursor.getLong(COL_WEATHER_ID);
            return position;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }
    }

    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
    private void setRemoteContentDescription(RemoteViews views, String description) {
        views.setContentDescription(R.id.widget_icon, description);
    }
}


text:
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>Vorlon.js desktop</title>
    <link href="./fonts/roboto/roboto.css" rel="stylesheet" type="text/css" />
    <link href="./fonts/oswald/oswald.css" rel="stylesheet" type="text/css" />
    <link href="./stylesheets/app.css" rel="stylesheet" type="text/css" />
</head>
<body class="messageWindow">
    <div class="message error">
        ERROR loading dashboard. Check that Vorlon is running and try re-openning dashboard window.
    </div>
</body>
</html>


text:
<?php
// src/Pcd/UserBundle/PcdUserBundle.php

namespace Pcd\UserBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class PcdUserBundle extends Bundle
{
    public function getParent()
    {
        return 'FOSUserBundle';
    }
}


text:
package org.spongepowered.test.myhomes.data.home;

import org.spongepowered.api.data.manipulator.DataManipulator;
import org.spongepowered.api.data.value.mutable.MapValue;
import org.spongepowered.api.data.value.mutable.Value;

public interface HomeData extends DataManipulator<HomeData, ImmutableHomeData> {

    Value<Home> defaultHome();

    MapValue<String, Home> homes();

}


text:
require File.expand_path(File.join(File.dirname(__FILE__), 'spec_helper'))

describe "verify", :shared => true do
  it do
    lambda{  @context.verify{ true }  }.should_not raise_error
  end
  it do
    lambda{  @context.verify{ false }  }.should raise_error(Util::VerifyFailed)
  end
  it "should return the block results" do
    obj = Object.new
    @context.verify{ obj }.should == obj
  end
end

describe "Util.verify" do
  before(:each) do
    @context = Util
  end
  it_should_behave_like "verify"
end

describe "Util#verify" do
  before(:each) do
    @context = Class.new{include Util}.new
  end
  it_should_behave_like "verify"
end


text:
Rails.application.routes.draw do
  get 'password_resets/new'

  get 'password_resets/edit'

  root             'static_pages#home'
  get 'help'    => 'static_pages#help'
  get 'about'   => 'static_pages#about'
  get 'contact' => 'static_pages#contact'
  get 'signup' => 'users#new'
  get    'login'   => 'sessions#new'
  post   'login'   => 'sessions#create'
  delete 'logout'  => 'sessions#destroy'
  resources :users do
    member do
      get :following, :followers
    end
  end
  resources :account_activations, only: [:edit]
  resources :password_resets,     only: [:new, :create, :edit, :update]
  resources :microposts,          only: [:create, :destroy]
  resources :relationships,       only: [:create, :destroy]
end


text:
<?php

namespace Database\Factories\Quiz;

use App\Models\Quiz\QuizQuestion;
use App\Models\Quiz\QuizTemplate;
use Cache;
use Database\Factories\Factory;
use GuzzleHttp\Client;

class QuizQuestionFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = QuizQuestion::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'quiz_id' => QuizTemplate::factory()
        ];
    }

    /**
     * Indicates that the question is multiple choice.
     *
     * @return $this
     */
    public function multipleChoice()
    {
        return $this->state(function(array $attributes) {
            return [
                'type' => 'multiple_choice',
                'points_available' => 1
            ];
        });
    }

    /**
     * Indicates that the question is multiple choice.
     *
     * @return $this
     */
    public function trueFalse()
    {
        return $this->state(function(array $attributes) {
            return [
                'type' => 'true_false',
                'points_available' => 1
            ];
        });
    }

    /**
     * Configures this model factory.
     *
     * @return $this
     */
    public function configure()
    {
        return $this->afterMaking(function(QuizQuestion $question) {
            $this->generatePrompt($question);
        });
    }

    /**
     * Generates the prompt for the specified question.
     *
     * @param  \App\Models\Quiz\QuizQuestion  $question
     *
     * @return $this
     */
    protected function generatePrompt(QuizQuestion $question)
    {
        // If a prompt was provided, leave it alone
        if(!is_null($question->prompt)) {
            return $this;
        }

        // If the type isn't generateable, leave it alone
        if(!in_array($question->type, ['multiple_choice', 'true_false'])) {
            return $this;
        }

        // Generate a random prompt
        $prompt = $this->randomPrompt([
            'type' => $question->type == 'multiple_choice' ? 'multiple' : 'boolean',
            'category' => $question->category,
            'difficulty' => $question->difficulty
        ]);

        unset($question['category']);
        unset($question['difficulty']);

        // Assign the prompt
        $question->prompt = array_filter([
            'question' => $prompt->question,
            'incorrect' => $question->type == 'multiple_choice' ? $prompt->incorrect_answers : null
        ]);

        // Assign the answer key
        $question->answer_key = [
            'exact' => $prompt->correct_answer
        ];

        // Allow chaining
        return $this;
    }

    /**
     * Returns a random prompt based on the specified parameters.
     *
     * @param  array  $parameters
     *
     * @return \stdClass
     */
    protected function randomPrompt(array $parameters)
    {
        // We'll be using an api to generate our questions. To minimize
        // the number of api calls, we're going to cache results and
        // pull larger samples. This will save us time later on.

        // Determine the cache store
        $cache = Cache::store('array');

        // Convert the parameters to a base cache key
        $key = json_encode($parameters);

        // Request a random set of questions
        $questions = $cache->remember("{$key}.response", 0, function() use ($parameters) {

            // Determine the response
            $client = new Client;
            $response = $client->request('GET', 'https://opentdb.com/api.php?amount=10&' . http_build_query($parameters));

            // Decode the results
            return json_decode($response->getBody()->getContents())->results;

        });

        // Determine the current index
        $index = $cache->get("{$key}.index") ?? 0;

        // If the next pull won't have new questions, bust the cache
        if($index >= 9) {

            // Forget the response
            $cache->forget("{$key}.response");

            // Forget the index
            $cache->forget("{$key}.index");

        }

        // Otherwise, increment the index
        else {
            $cache->put("{$key}.index", $index + 1);
        }

        // Return the current question
        return $questions[$index];
    }
}


text:
package com.oneponygames.frozen.base.ashley.system;

import com.badlogic.ashley.core.Entity;
import com.badlogic.ashley.core.Family;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.oneponygames.frozen.base.eventsystem.subscriber.OrthoCameraController;
import com.oneponygames.frozen.base.gfx.Drawable;
import com.oneponygames.frozen.base.ashley.component.DrawableComponent;
import com.oneponygames.frozen.base.ashley.component.PositionComponent;
import com.oneponygames.frozen.utils.BaseMappers;

/**
 * Created by Icewind on 23.01.2017.
 */
public class EntityRenderer extends HookedIteratingSystem {

    private final SpriteBatch batch;
    private final OrthoCameraController camera;
    private final float pixelScaling;

    public EntityRenderer(SpriteBatch batch, OrthoCameraController camera) {
        this(batch, camera, 1);
    }

    public EntityRenderer(SpriteBatch batch, OrthoCameraController camera, float pixelScaling) {
        super(Family.all(DrawableComponent.class, PositionComponent.class).get());
        this.batch = batch;
        this.camera = camera;
        this.pixelScaling = pixelScaling;
    }

    @Override
    protected void afterUpdate() {
        batch.end();
    }

    @Override
    protected void beforeUpdate(float delta) {
        batch.begin();
        batch.setProjectionMatrix(camera.getCombined());
    }

    @Override
    protected void processEntity(Entity entity, float delta) {
        PositionComponent pos = BaseMappers.positionMap.get(entity);
        DrawableComponent draw = BaseMappers.drawableMap.get(entity);

        for(Drawable d : draw.getDrawables()) {
            if(d.doDraw()) {
                batch.setColor(1, 1, 1, d.getAlpha());
                float width = d.getWidth();
                float height = d.getHeight();
                float x = pos.getX() + d.getXOffset();
                float y = pos.getY() + d.getYOffset();
                float dx = x - width / 2f;
                float dy = y - height / 2f;
                float originX = -d.getXOffset() + width/2;
                float originY = -d.getYOffset() + height/2;
                float rotation = pos.getRotation() + d.getRotationOffset();
                TextureRegion tr = d.getTexture();

                batch.draw(tr, dx * pixelScaling, dy * pixelScaling, originX * pixelScaling, originY * pixelScaling, width * pixelScaling, height * pixelScaling, pos.getOrientation(), 1, rotation);
            }
        }
    }
}


text:
set -euf
if [ "${BASH_VERSINFO[0]}" -ge 3 ]; then
  set -o pipefail
fi
IFS=$'\n\t'
###
# use command debugging
#set -x

# Ask for the administrator password upfront
sudo -v
# Keep-alive: update existing `sudo` time stamp until function has finished
while true; do
  sudo -n true
  sleep 60
  kill -0 "$$" || exit
done 2>/dev/null &

base_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)

curl -s "https://get.sdkman.io" | bash

echo "Install Java versions next"
echo "Run 'sdk list java' and select the version to install, e.g."
echo "'sdk install java 11.0.16-amzn'"


text:
class ChangeCommentToTextInPosts < ActiveRecord::Migration
  def change
    change_column :news_posts, :comment, :text
  end
end


text:
'use strict';

require('chai').should();

var path = require('path');

var utils = require('../../app/src/utils');

describe('gulp-angular generator utils', function () {
  describe('normalizePath', function () {
    var realSep;

    before(function() {
      realSep = path.sep;
    });

    after(function() {
      path.sep = realSep;
    });

    it('should return simplest form of given relative path to cwd', function () {
      path.sep = '/';
      utils.normalizePath('path' + path.sep + path.sep + 'to' + path.sep + 'folder' + path.sep).should.be.equal('path/to/folder');
      utils.normalizePath('..' + path.sep).should.be.equal('..');
      path.sep = '\\';
      utils.normalizePath('path\\to\\folder\\').should.be.equal('path/to/folder');
    });
  });

  describe('isAbsolutePath', function () {
    it('should return true for absolute path', function () {
      utils.isAbsolutePath(path.sep + 'some' + path.sep + 'folder').should.be.equal(true);
    });

    it('should return false for relative path', function () {
      utils.isAbsolutePath(['some', 'relative', 'folder'].join(path.sep)).should.be.equal(false);
    });
  });

  describe('replacePrefix', function () {
    var folderPairs = {
      'src/path': 'some/dest/path',
      'some/folder': 'a',
      'some/folder/longer': 'b'
    };

    it('should replace source folder with dest folder from given path', function () {
      utils.replacePrefix('src/path/to/file.txt', folderPairs).should.be.equal('some/dest/path/to/file.txt');
    });

    it('should not replace anything if no source folder found as prefix', function () {
      utils.replacePrefix('pre/src/path/file.txt', folderPairs).should.be.equal('pre/src/path/file.txt');
      utils.replacePrefix('no/match/file.txt', folderPairs).should.be.equal('no/match/file.txt');
    });

    it('should choose longer match for ambiguous case', function () {
      utils.replacePrefix('some/folder/longer/some/file.txt', folderPairs).should.be.equal('b/some/file.txt');
    });
  });
});


text:
package org.jbpm.workbench.common.client.filters.active;

import org.jboss.errai.common.client.api.elemental2.IsElement;
import org.uberfire.mvp.Command;
import org.uberfire.mvp.ParameterizedCommand;

public interface ActiveFiltersView extends IsElement {

    <T extends Object> void addActiveFilter(ActiveFilterItem<T> filter);

    <T extends Object> void removeActiveFilter(ActiveFilterItem<T> filter);

    void removeAllActiveFilters(Boolean useCallback);

    void setSaveFilterCallback(ParameterizedCommand<String> callback);

    void setRemoveAllFilterCallback(Command callback);

    void closeSaveFilter();

    void setSaveFilterErrorMessage(String message);
}


text:
using UnityEngine;
using System.Collections;

public class MiniGame1Controller : MiniGameController
{
	private Player player;
	// Use this for initialization
	void Start()
	{
		player		= GameObject.FindGameObjectWithTag("Player").GetComponent<Player>();
		player.ChangeAnimationState(Player.STATE_KNOCK);
	}

	// Update is called once per frame
	void Update()
	{
        if (!Started) return;
//
//        if (Input.GetMouseButtonDown(0))
//        {
//			SceneEnd();
//        }
	}

	public void SceneEnd(){
	    if (OnGameDone != null)
	        OnGameDone(0f);
	    Destroy(gameObject);

	}
}


text:
title: Kramdown
category: Markup
---

### Configuration

 * `parse_block_html` - process kramdown syntax inside blocks
 * `parse_span_html` - process kramdown syntax inside inlines
 * `html_to_native` - convert html elements to native elements

    {::options parse_block_html="true" /}

For the GFM parser:

 * `hard_wrap`

http://kramdown.gettalong.org/parser/gfm.html

### For jekyll (gh-pages)

    # _config.yml
    markdown: kramdown
    kramdown:
      input: GFM

### Footnotes (Kramdown)

    This is some text.[^1]. Other text.[^footnote].

    [^1]: Some *crazy* footnote definition.

### Abbreviations (Kramdown)

    This is some text not written in HTML but in another language!

    *[another language]: It's called Markdown
    *[HTML]: HyperTextMarkupLanguage

### Classes and IDs (Kramdown)

    A simple paragraph with an ID attribute.
    {: #para-one}

    > A blockquote with a title
    {:title="The blockquote title"}
    {: #myid}

    * {:.cls} This item has the class "cls"

    {:.ruby}
        Some code here

### References

 * http://kramdown.gettalong.org/syntax.html
 * http://kramdown.gettalong.org/parser/kramdown.html


text:
function GetSelectedText() {
    var txt = '';
    if (window.getSelection) {
        txt = window.getSelection().toString();
    }
    else if (document.getSelection) {
        txt = document.getSelection().toString();
    }
    else if (document.selection) {
        txt = document.selection.createRange().text;
    }
    else return;
    return txt;
}
/* Usage: var idInteger = Base62Decode('AbsjdDd') */
function Base62Decode(a, b, c, d) { for (b = c = 0; d = a.charCodeAt(c++); b = b * 62 + d - [, 48, 29, 87][d >> 5]); return b; }

/* Usage: var queryStringValue = Q('UserId',0); - returns UserId from query string, or 0 for default.  This is case sensitive. */
function Q(key, default_) {
    if (default_ == null) default_ = "";
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
    var qs = regex.exec(window.location.href);
    if (qs == null)
        return default_;
    else
        return qs[1];
}
function Query() {
    var ix = window.location.href.indexOf('?');
    if (ix < 1) return '';
    return window.location.href.substring(ix + 1);
}

//Converts value from a model to a date obj
function asDate(value) {
    return new Date(parseInt(value.substring(6, value.length - 2)));
}

//For use with number formatting
function addCommas(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

function HideViewsNear(toView) {
    $(toView).parent().find(".view").not(toView).hide();
}
function SwitchView(toView, dontAddToBackQue) {
    if (!dontAddToBackQue) AddBack(toView);
    HideViewsNear(toView);
    $(toView).find('.commandButtons').show();
    $(toView).find('.loading').hide();
    $(toView).fadeIn('slow');
}
function DeleteSelectedItems(container, vm) {
    var $container = $(container);
    for (var ix = 0; ix < vm.Items.length; ix++) {
        if (vm.Items[ix]._IsSelected) {
            vm.Items[ix]._IsSelected = false;
            vm.Items[ix]._IsDeleted = true;
            if (ix == vm.Items.length - 1) $container.find("HR:visible").last().fadeOut('fast');
        }
    }
    //If current item is last, remove last hr
    if (vm.CurrentIndex == vm.Items.length - 1 && vm.CurrentItem._IsDeleted == true) {
        $container.find("HR:visible").last().fadeOut('fast');
    }
    vm.Items[vm.CurrentIndex]._IsSelected = false;
    vm.Items[vm.CurrentIndex]._IsDeleted = true;
    vm.setCurrentIndex(-1);

    var floatingActions = $container.find(".floating-actions");
    floatingActions.hide();
    floatingActions.detach();
    floatingActions.appendTo($container);

    var selected = $container.find(".selected");
    selected.removeClass(".selected").slideUp('fast')
    selected.next("HR").fadeOut('fast');

}
function HideIf(test, obj) { if (test) return null; return $(obj); }
function SelectItem(rowObj, vm, index, multiSelect, toggle) {
    var rowContainer = $(rowObj).parent();
    var permissionCheck = eval(rowContainer.attr("data-permissions"));
    var floatingActions = rowContainer.find(".floating-actions");
    floatingActions.hide();
    floatingActions.detach();

    var isSelected = $(rowObj).hasClass("selected");
    if (!multiSelect) {
        rowContainer.children(".selectable").removeClass("selected");
        for (var ix = 0; ix < vm.Items.length; ix++) {
            vm.Items[ix]._IsSelected = false;
        }
    }

    if (isSelected && toggle) {
        floatingActions.appendTo(rowContainer);
        floatingActions.hide();

        vm.setCurrentIndex(-1);
        vm.Items[index]._IsSelected = false;

        $(rowObj).removeClass("selected");
    } else {
        $(rowObj).addClass("selected");

        $(rowObj).after(floatingActions);

        floatingActions.show();
        vm.Items[index]._IsSelected = true;
        vm.setCurrentIndex(index);

        //Check permissions?
        if (typeof permissionCheck == 'function') {
            floatingActions.find(".btn").hide();
            permissionCheck(vm, vm.Items[index]);
        }

        if (floatingActions.not(":hidden").length == 0) floatingActions.hide();
        else floatingActions.show();
    }
}

function UnselectAllInView(view, dontChangeIndex) {
    var rowContainer = view.viewRender.find(".listWrap");
    if (rowContainer.length == 0) rowContainer = view.viewRender;
    var floatingActions = rowContainer.find(".floating-actions");
    var vm = view.viewModel;

    floatingActions.hide();
    floatingActions.detach();
    floatingActions.appendTo(rowContainer);
    floatingActions.hide();

    rowContainer.children(".selectable").removeClass("selected");
    for (var ix = 0; ix < vm.Items.length; ix++) {
        vm.Items[ix]._IsSelected = false;
    }

    if (!dontChangeIndex) vm.setCurrentIndex(-1);
}
function ShowButtons(buttonIds) {
    $(buttonIds).fadeIn('fast');
}
function HideButtons(buttonIds) {
    $(buttonIds).fadeOut('fast');
}

function StartLoading(container) {
    if (container === undefined) container = $(document);
    $(container).find('.commandButtons').hide();
    $(container).find('.loading').fadeIn('fast');
    $(container).find('.largeLoading').fadeIn('fast');
}
function FinishLoading(container) {
    if (container === undefined) container = $(document);
    $(container).find('.commandButtons').fadeIn('fast');
    $(container).find('.loading').fadeOut('fast');
    $(container).find('.largeLoading').fadeOut('fast');
}

var backActions = [];
var backIndex = -1;

function NavBack() {
    GoBack(window.backIndex - 1);
}
function GoBack(index) {
    window.backIndex = index;
    var view = window.backActions[window.backIndex];

    $(view).find('.commandButtons').show();
    $(view).find('.loading').hide();

    SwitchView(view, true);
    UpdateBreadcrum();
    if (window.backIndex <= 0) $('#NavBackButton').fadeOut();
}
function AddBack(view) {
    if (window.backActions[backIndex] != view) {
        window.backActions[backIndex + 1] = view;
        window.backIndex++;
        if (window.backIndex >= 1) $('#NavBackButton').fadeIn();
        UpdateBreadcrum();
    }
}
function ClearBack() {
    window.backIndex = -1;
    window.backActions = [];
    $('#NavBackButton').fadeOut();
    UpdateBreadcrum();
}
function UpdateBreadcrum() {
    var crumDiv = $('.breadcrum');

    window.crumList = [];
    window.crumList[0] = { "title": crumDiv.attr('title'), "index": 0 };
    window.crumIndex = 0;

    window.crumIndex = 1;
    var i = 0;
    while (i <= window.backIndex) {
        var viewNames = window.backActions[i];

        window.crumTitle = '';

        $(viewNames).each(function () {
            var title = $(this).attr('title');
            if (title) {
                if (window.crumTitle != '') window.crumTitle += " / ";
                window.crumTitle += title;
            }
        });
        if (window.crumTitle != '') {

            window.crumList[window.crumIndex] =
                {
                    "title": window.crumTitle,
                    "index": i
                };
            window.crumIndex++;
        }
        i++;
    }

    i = 0;
    var html = '
';
    while (i < window.crumIndex) {
        var crum = window.crumList[i];
        var active = '';
        if (i == window.crumIndex - 1) active = ' class="active"'
        html +=
            '
' + crum.title + '
';
        i++;
    }
    html += '
';
    crumDiv.html(html);
}
function ListClear(list) {
    $(list).find("OPTION").remove();
}
function ListAdd(list, text, value, selected) {
    var item = $('<option/>').val(value).html(text);
    if (selected) item.attr('selected', 'selected');
    $(list).append(item);
    return item;
}

function ListBind(list, items, textField, valueField, overwrite) {
    $(list).each(function () {
        if (overwrite) ListClear($(this));
        var selectedValue = $(this).attr('autoselect');
        for (var i = 0; i < items.length; i++) {
            var item = items[i];
            var text = item[textField];
            var value = item[valueField];
            var listItem = ListAdd($(this), text, value, ((selectedValue || '').toString() == (value || '').toString()));
        }
    });
}

$(document).ready(OnViewBound);

function OnViewBound() {
    //Run these methods after a view is bound.
    $("[validation-decimal]").forceDecimal();
    $("[validation-integer]").forceInteger();
}

// forceDecimal() plug-in implementation
jQuery.fn.forceDecimal = function () {

    return this.each(function () {
        $(this).keydown(function (e) {
            var key = e.which || e.keyCode;

            if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
            // numbers
                         key >= 48 && key <= 57 ||
            // Numeric keypad
                         key >= 96 && key <= 105 ||
            // comma, period and minus, . on keypad
                        key == 190 || key == 188 || key == 109 || key == 110 ||
            // Backspace and Tab and Enter
                        key == 8 || key == 9 || key == 13 ||
            // Home and End
                        key == 35 || key == 36 ||
            // left and right arrows
                        key == 37 || key == 39 ||
            // Del and Ins
                        key == 46 || key == 45)
                return true;

            return false;
        });
    });
}
// forceInteger() plug-in implementation
jQuery.fn.forceInteger = function () {

    return this.each(function () {
        $(this).keydown(function (e) {
            var key = e.which || e.keyCode;

            if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
            // numbers
                         key >= 48 && key <= 57 ||
            // Numeric keypad
                         key >= 96 && key <= 105 ||
            // comma, period and minus, . on keypad
                        key == 190 || key == 188 || key == 109 || key == 110 ||
            // Backspace and Tab and Enter
                        key == 8 || key == 9 || key == 13 ||
            // Home and End
                        key == 35 || key == 36 ||
            // left and right arrows
                        key == 37 || key == 39 ||
            // Del and Ins
                        key == 46 || key == 45)
                return true;

            return false;
        });
    });
}


text:
package com.spring.redis;

import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class RedisConfiguration {

	@Value("${redis.hostname}")
	String hostname;
	@Value("${redis.password}")
	String password;
	@Value("${redis.port}")
	int port;

	@Value("${redis.pool.maxTotal}")
	int maxTotal;
	@Value("${redis.pool.maxIdle}")
	int maxIdle;
	@Value("${redis.pool.maxWait}")
	int maxWait;

	@Value("${redis.sentinel.master}")
	String master;
	@Value("${redis.sentinel.nodes}")
	String nodes;
	@Value("${morning.is_product}")
	boolean isProduct;

	@Bean
	public JedisConnectionFactory redisConnectionFactory() {

		if (isProduct) {
			Set<String> sentinels = new HashSet<String>();
			sentinels = this.stringConvertToSet(nodes);
			RedisSentinelConfiguration sentinelConfig = new RedisSentinelConfiguration()
					.master(master);
			for (String sentinel : sentinels) {
				String[] array = sentinel.split(":");
				sentinelConfig.sentinel(array[0], Integer.valueOf(array[1]));
			}

			return new JedisConnectionFactory(sentinelConfig);
		} else {
			JedisPoolConfig poolConfig = new JedisPoolConfig();
			poolConfig.setMaxIdle(maxIdle);
			poolConfig.setMaxWaitMillis(maxWait);
			poolConfig.setMaxTotal(maxTotal);

			JedisConnectionFactory jcf = new JedisConnectionFactory(poolConfig);
			jcf.setHostName(hostname);
			jcf.setPort(port);
			jcf.setPassword(password);
			jcf.setPoolConfig(poolConfig);

			return jcf;
		}
	}

	@Bean
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public RedisTemplate redisTemplate() {

		RedisTemplate redisTemplate = new RedisTemplate();
		redisTemplate.setConnectionFactory(redisConnectionFactory());

		StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
		RedisSerializer jdkSerializer = new JdkSerializationRedisSerializer();

		redisTemplate.setKeySerializer(stringRedisSerializer);
		redisTemplate.setValueSerializer(jdkSerializer);

		return redisTemplate;
	}

	public Set<String> stringConvertToSet(String source) {
		Set<String> target = new HashSet<String>();
		StringTokenizer st = new StringTokenizer(source, ",");
		while (st.hasMoreElements()) {
			target.add(st.nextElement().toString());
		}
		return target;
	}

}


text:
import UserTable from "./UserTable";
import FiltersBar from "./FiltersBar";

export {
    UserTable,
    FiltersBar
};


text:
[![Gem Version](https://badge.fury.io/rb/money.svg)](https://rubygems.org/gems/money)
[![Build Status](https://travis-ci.org/RubyMoney/money.svg?branch=master)](https://travis-ci.org/RubyMoney/money)
[![Code Climate](https://codeclimate.com/github/RubyMoney/money.svg)](https://codeclimate.com/github/RubyMoney/money)
[![Inline docs](https://inch-ci.org/github/RubyMoney/money.svg)](https://inch-ci.org/github/RubyMoney/money)
[![License](https://img.shields.io/github/license/RubyMoney/money.svg)](https://opensource.org/licenses/MIT)

:warning: Please read the [migration notes](#migration-notes) before upgrading to a new major version.

If you miss String parsing, check out the new [monetize gem](https://github.com/RubyMoney/monetize).

## Contributing

See the [Contribution Guidelines](https://github.com/RubyMoney/money/blob/master/CONTRIBUTING.md)

## Introduction

A Ruby Library for dealing with money and currency conversion.

### Features

- Provides a `Money` class which encapsulates all information about a certain
  amount of money, such as its value and its currency.
- Provides a `Money::Currency` class which encapsulates all information about
  a monetary unit.
- Represents monetary values as integers, in cents. This avoids floating point
  rounding errors.
- Represents currency as `Money::Currency` instances providing a high level of
  flexibility.
- Provides APIs for exchanging money from one currency to another.

### Resources

- [Website](https://rubymoney.github.io/money/)
- [API Documentation](http://www.rubydoc.info/gems/money/frames)
- [Git Repository](https://github.com/RubyMoney/money)

### Notes

- Your app must use UTF-8 to function with this library. There are a
  number of non-ASCII currency attributes.
- This app requires JSON. If you're using JRuby < 1.7.0
  you'll need to add `gem "json"` to your Gemfile or similar.

## Downloading

Install stable releases with the following command:

    gem install money

The development version (hosted on Github) can be installed with:

    git clone git://github.com/RubyMoney/money.git
    cd money
    rake install

## Usage

``` ruby
require 'money'

# 10.00 USD
money = Money.new(1000, "USD")
money.cents     #=> 1000
money.currency  #=> Currency.new("USD")

# Comparisons
Money.new(1000, "USD") == Money.new(1000, "USD")   #=> true
Money.new(1000, "USD") == Money.new(100, "USD")    #=> false
Money.new(1000, "USD") == Money.new(1000, "EUR")   #=> false
Money.new(1000, "USD") != Money.new(1000, "EUR")   #=> true

# Arithmetic
Money.new(1000, "USD") + Money.new(500, "USD") == Money.new(1500, "USD")
Money.new(1000, "USD") - Money.new(200, "USD") == Money.new(800, "USD")
Money.new(1000, "USD") / 5                     == Money.new(200, "USD")
Money.new(1000, "USD") * 5                     == Money.new(5000, "USD")

# Unit to subunit conversions
Money.from_amount(5, "USD") == Money.new(500, "USD")  # 5 USD
Money.from_amount(5, "JPY") == Money.new(5, "JPY")    # 5 JPY
Money.from_amount(5, "TND") == Money.new(5000, "TND") # 5 TND

# Currency conversions
some_code_to_setup_exchange_rates
Money.new(1000, "USD").exchange_to("EUR") == Money.new(some_value, "EUR")

# Swap currency
Money.new(1000, "USD").with_currency("EUR") == Money.new(1000, "EUR")

# Formatting (see Formatting section for more options)
Money.new(100, "USD").format #=> "$1.00"
Money.new(100, "GBP").format #=> "£1.00"
Money.new(100, "EUR").format #=> "€1.00"
```

## Currency

Currencies are consistently represented as instances of `Money::Currency`.
The most part of `Money` APIs allows you to supply either a `String` or a
`Money::Currency`.

``` ruby
Money.new(1000, "USD") == Money.new(1000, Money::Currency.new("USD"))
Money.new(1000, "EUR").currency == Money::Currency.new("EUR")
```

A `Money::Currency` instance holds all the information about the currency,
including the currency symbol, name and much more.

``` ruby
currency = Money.new(1000, "USD").currency
currency.iso_code #=> "USD"
currency.name     #=> "United States Dollar"
```

To define a new `Money::Currency` use `Money::Currency.register` as shown
below.

``` ruby
curr = {
  priority:            1,
  iso_code:            "USD",
  iso_numeric:         "840",
  name:                "United States Dollar",
  symbol:              "$",
  subunit:             "Cent",
  subunit_to_unit:     100,
  decimal_mark:        ".",
  thousands_separator: ","
}

Money::Currency.register(curr)
```

The pre-defined set of attributes includes:

- `:priority` a numerical value you can use to sort/group the currency list
- `:iso_code` the international 3-letter code as defined by the ISO 4217 standard
- `:iso_numeric` the international 3-digit code as defined by the ISO 4217 standard
- `:name` the currency name
- `:symbol` the currency symbol (UTF-8 encoded)
- `:subunit` the name of the fractional monetary unit
- `:subunit_to_unit` the proportion between the unit and the subunit
- `:decimal_mark` character between the whole and fraction amounts
- `:thousands_separator` character between each thousands place

All attributes except `:iso_code` are optional. Some attributes, such as
`:symbol`, are used by the Money class to print out a representation of the
object. Other attributes, such as `:name` or `:priority`, exist to provide a
basic API you can take advantage of to build your application.

### :priority

The priority attribute is an arbitrary numerical value you can assign to the
`Money::Currency` and use in sorting/grouping operation.

For instance, let's assume your Rails application needs to render a currency
selector like the one available
[here](https://finance.yahoo.com/currency-converter/). You can create a couple of
custom methods to return the list of major currencies and all currencies as
follows:

``` ruby
# Returns an array of currency id where
# priority < 10
def major_currencies(hash)
  hash.inject([]) do |array, (id, attributes)|
    priority = attributes[:priority]
    if priority && priority < 10
      array[priority] ||= []
      array[priority] << id
    end
    array
  end.compact.flatten
end

# Returns an array of all currency id
def all_currencies(hash)
  hash.keys
end

major_currencies(Money::Currency.table)
# => [:usd, :eur, :gbp, :aud, :cad, :jpy]

all_currencies(Money::Currency.table)
# => [:aed, :afn, :all, ...]
```

### Default Currency

By default `Money` defaults to USD as its currency. This can be overwritten
using:

``` ruby
Money.default_currency = Money::Currency.new("CAD")
```

If you use [Rails](https://github.com/RubyMoney/money/tree/master#ruby-on-rails), then `config/initializers/money.rb` is a very good place to put this.

### Currency Exponent

The exponent of a money value is the number of digits after the decimal
separator (which separates the major unit from the minor unit). See e.g.
[ISO 4217](https://www.currency-iso.org/en/shared/amendments/iso-4217-amendment.html) for more
information. You can find the exponent (as an `Integer`) by

``` ruby
Money::Currency.new("USD").exponent  # => 2
Money::Currency.new("JPY").exponent  # => 0
Money::Currency.new("MGA").exponent  # => 1
```

### Currency Lookup

To find a given currency by ISO 4217 numeric code (three digits) you can do

``` ruby
Money::Currency.find_by_iso_numeric(978) #=> Money::Currency.new(:eur)
```

## Currency Exchange

Exchanging money is performed through an exchange bank object. The default
exchange bank object requires one to manually specify the exchange rate. Here's
an example of how it works:

``` ruby
Money.add_rate("USD", "CAD", 1.24515)
Money.add_rate("CAD", "USD", 0.803115)

Money.us_dollar(100).exchange_to("CAD")  # => Money.new(124, "CAD")
Money.ca_dollar(100).exchange_to("USD")  # => Money.new(80, "USD")
```

Comparison and arithmetic operations work as expected:

``` ruby
Money.new(1000, "USD") <=> Money.new(900, "USD")   # => 1; 9.00 USD is smaller
Money.new(1000, "EUR") + Money.new(10, "EUR") == Money.new(1010, "EUR")

Money.add_rate("USD", "EUR", 0.5)
Money.new(1000, "EUR") + Money.new(1000, "USD") == Money.new(1500, "EUR")
```

### Exchange rate stores

The default bank is initialized with an in-memory store for exchange rates.

```ruby
Money.default_bank = Money::Bank::VariableExchange.new(Money::RatesStore::Memory.new)
```

You can pass your own store implementation, i.e. for storing and retrieving rates off a database, file, cache, etc.

```ruby
Money.default_bank = Money::Bank::VariableExchange.new(MyCustomStore.new)
```

Stores must implement the following interface:

```ruby
# Add new exchange rate.
# @param [String] iso_from Currency ISO code. ex. 'USD'
# @param [String] iso_to Currency ISO code. ex. 'CAD'
# @param [Numeric] rate Exchange rate. ex. 0.0016
#
# @return [Numeric] rate.
def add_rate(iso_from, iso_to, rate); end

# Get rate. Must be idempotent. i.e. adding the same rate must not produce duplicates.
# @param [String] iso_from Currency ISO code. ex. 'USD'
# @param [String] iso_to Currency ISO code. ex. 'CAD'
#
# @return [Numeric] rate.
def get_rate(iso_from, iso_to); end

# Iterate over rate tuples (iso_from, iso_to, rate)
#
# @yieldparam iso_from [String] Currency ISO string.
# @yieldparam iso_to [String] Currency ISO string.
# @yieldparam rate [Numeric] Exchange rate.
#
# @return [Enumerator]
#
# @example
#   store.each_rate do |iso_from, iso_to, rate|
#     puts [iso_from, iso_to, rate].join
#   end
def each_rate(&block); end

# Wrap store operations in a thread-safe transaction
# (or IO or Database transaction, depending on your implementation)
#
# @yield [n] Block that will be wrapped in transaction.
#
# @example
#   store.transaction do
#     store.add_rate('USD', 'CAD', 0.9)
#     store.add_rate('USD', 'CLP', 0.0016)
#   end
def transaction(&block); end

# Serialize store and its content to make Marshal.dump work.
#
# Returns an array with store class and any arguments needed to initialize the store in the current state.

# @return [Array] [class, arg1, arg2]
def marshal_dump; end
```

The following example implements an `ActiveRecord` store to save exchange rates to a database.

```ruby
# rails g model exchange_rate from:string to:string rate:float

class ExchangeRate < ApplicationRecord
  def self.get_rate(from_iso_code, to_iso_code)
    rate = find_by(from: from_iso_code, to: to_iso_code)
    rate&.rate
  end

  def self.add_rate(from_iso_code, to_iso_code, rate)
    exrate = find_or_initialize_by(from: from_iso_code, to: to_iso_code)
    exrate.rate = rate
    exrate.save!
  end

  def self.each_rate
    return find_each unless block_given?

    find_each do |rate|
      yield rate.from, rate.to, rate.rate
    end
  end
end
```

Now you can use it with the default bank.

```ruby
# For Rails 6 pass model name as a string to make it compatible with zeitwerk
# Money.default_bank = Money::Bank::VariableExchange.new("ExchangeRate")
Money.default_bank = Money::Bank::VariableExchange.new(ExchangeRate)

# Add to the underlying store
Money.default_bank.add_rate('USD', 'CAD', 0.9)
# Retrieve from the underlying store
Money.default_bank.get_rate('USD', 'CAD') # => 0.9
# Exchanging amounts just works.
Money.new(1000, 'USD').exchange_to('CAD') #=> #<Money fractional:900 currency:CAD>
```

There is nothing stopping you from creating store objects which scrapes
[XE](http://www.xe.com) for the current rates or just returns `rand(2)`:

``` ruby
Money.default_bank = Money::Bank::VariableExchange.new(StoreWhichScrapesXeDotCom.new)
```

You can also implement your own Bank to calculate exchanges differently.
Different banks can share Stores.

```ruby
Money.default_bank = MyCustomBank.new(Money::RatesStore::Memory.new)
```

If you wish to disable automatic currency conversion to prevent arithmetic when
currencies don't match:

``` ruby
Money.disallow_currency_conversion!
```

### Implementations

The following is a list of Money.gem compatible currency exchange rate
implementations.

- [eu_central_bank](https://github.com/RubyMoney/eu_central_bank)
- [google_currency](https://github.com/RubyMoney/google_currency)
- [currencylayer](https://github.com/askuratovsky/currencylayer)
- [nordea](https://github.com/matiaskorhonen/nordea)
- [nbrb_currency](https://github.com/slbug/nbrb_currency)
- [money-currencylayer-bank](https://github.com/phlegx/money-currencylayer-bank)
- [money-open-exchange-rates](https://github.com/spk/money-open-exchange-rates)
- [money-historical-bank](https://github.com/atwam/money-historical-bank)
- [russian_central_bank](https://github.com/rmustafin/russian_central_bank)
- [money-uphold-bank](https://github.com/subvisual/money-uphold-bank)

## Formatting

There are several formatting rules for when `Money#format` is called. For more information, check out the [formatting module source](https://github.com/RubyMoney/money/blob/master/lib/money/money/formatter.rb), or read the latest release's [rdoc version](http://www.rubydoc.info/gems/money/Money/Formatter).

If you wish to format money according to the EU's [Rules for expressing monetary units](http://publications.europa.eu/code/en/en-370303.htm#position) in either English, Irish, Latvian or Maltese:

```ruby
m = Money.new('123', :gbp) # => #<Money fractional:123 currency:GBP>
m.format(symbol: m.currency.to_s + ' ') # => "GBP 1.23"
```

## Rounding

By default, `Money` objects are rounded to the nearest cent and the additional precision is not preserved:

```ruby
Money.from_amount(2.34567).format #=> "$2.35"
```

To retain the additional precision, you will also need to set `infinite_precision` to `true`.

```ruby
Money.default_infinite_precision = true
Money.from_amount(2.34567).format #=> "$2.34567"
```

To round to the nearest cent (or anything more precise), you can use the `round` method. However, note that the `round` method on a `Money` object does not work the same way as a normal Ruby `Float` object. Money's `round` method accepts different arguments. The first argument to the round method is the rounding mode, while the second argument is the level of precision relative to the cent.

```
# Float
2.34567.round     #=> 2
2.34567.round(2)  #=> 2.35

# Money
Money.default_infinite_precision = true
Money.new(2.34567).format       #=> "$0.0234567"
Money.new(2.34567).round.format #=> "$0.02"
Money.new(2.34567).round(BigDecimal::ROUND_HALF_UP, 2).format #=> "$0.0235"
```

You can set the default rounding mode by passing one of the `BigDecimal` mode enumerables like so:
```ruby
Money.rounding_mode = BigDecimal::ROUND_HALF_EVEN
```
See [BigDecimal::ROUND_MODE](https://ruby-doc.org/stdlib-2.5.1/libdoc/bigdecimal/rdoc/BigDecimal.html#ROUND_MODE) for more information

## Ruby on Rails

To integrate money in a Rails application use [money-rails](https://github.com/RubyMoney/money-rails).

For deprecated methods of integrating with Rails, check [the wiki](https://github.com/RubyMoney/money/wiki).

## Localization

In order to localize formatting you can use `I18n` gem:

```ruby
Money.locale_backend = :i18n
```

With this enabled a thousands seperator and a decimal mark will get looked up in your `I18n` translation files. In a Rails application this may look like:

```yml
# config/locale/en.yml
en:
  number:
    currency:
      format:
        delimiter: ","
        separator: "."
  # falling back to
  number:
    format:
      delimiter: ","
      separator: "."
```

For this example `Money.new(123456789, "SEK").format` will return `1,234,567.89
kr` which otherwise would have returned `1 234 567,89 kr`.

This will work seamlessly with [rails-i18n](https://github.com/svenfuchs/rails-i18n) gem that already has a lot of locales defined.

If you wish to disable this feature and use defaults instead:

``` ruby
Money.locale_backend = nil
```

### Deprecation

The current default behaviour always checks the I18n locale first, falling back to "per currency"
localization. This is now deprecated and will be removed in favour of explicitly defined behaviour
in the next major release.

If you would like to use I18n localization (formatting depends on the locale):

```ruby
Money.locale_backend = :i18n

# example (using default localization from rails-i18n):
I18n.locale = :en
Money.new(10_000_00, 'USD').format # => $10,000.00
Money.new(10_000_00, 'EUR').format # => €10,000.00

I18n.locale = :es
Money.new(10_000_00, 'USD').format # => $10.000,00
Money.new(10_000_00, 'EUR').format # => €10.000,00
```

If you need to localize the position of the currency symbol, you
have to pass it manually. *Note: this will become the default formatting
behavior in the next version.*

```ruby
I18n.locale = :fr
format = I18n.t :format, scope: 'number.currency.format'
Money.new(10_00, 'EUR').format(format: format) # => 10,00 €
```

For the legacy behaviour of "per currency" localization (formatting depends only on currency):

```ruby
Money.locale_backend = :currency

# example:
Money.new(10_000_00, 'USD').format # => $10,000.00
Money.new(10_000_00, 'EUR').format # => €10.000,00
```

In case you don't need localization and would like to use default values (can be redefined using
`Money.default_formatting_rules`):

```ruby
Money.locale_backend = nil

# example:
Money.new(10_000_00, 'USD').format # => $10000.00
Money.new(10_000_00, 'EUR').format # => €10000.00
```

## Collection

In case you're working with collections of `Money` instances, have a look at [money-collection](https://github.com/RubyMoney/money-collection)
for improved performance and accuracy.

### Troubleshooting

If you don't have some locale and don't want to get a runtime error such as:

    I18n::InvalidLocale: :en is not a valid locale

Set the following:
``` ruby
I18n.enforce_available_locales = false
```

## Heuristics

Prior to v6.9.0 heuristic analysis of string input was part of this gem. Since then it was extracted in to [money-heuristics gem](https://github.com/RubyMoney/money-heuristics).

## Migration Notes

#### Version 6.0.0

- The `Money#dollars` and `Money#amount` methods now return instances of
  `BigDecimal` rather than `Float`. We should avoid representing monetary
  values with floating point types so to avoid a whole class of errors relating
  to lack of precision. There are two migration options for this change:
  * The first is to test your application and where applicable update the
    application to accept a `BigDecimal` return value. This is the recommended
    path.
  * The second is to migrate from the `#amount` and `#dollars` methods to use
    the `#to_f` method instead. This option should only be used where `Float`
    is the desired type and nothing else will do for your application's
    requirements.


text:
require 'helper'

class TestLoremRU < Test::Unit::TestCase
  include DeterministicHelper

  SENTENCE_MATCHER = /\A[а-яА-ЯёЁ\-\s\.\!\?,]+\z/.freeze
  WORDS_MATCHER    = /\A[А-Яа-яёЁ\-\s]+\z/.freeze
  WORD_MATCHER     = /\A[А-Яа-яёЁ\-]+\z/.freeze

  assert_methods_are_deterministic(
    FFaker::LoremRU,
    :paragraph, :sentence, :words, :word
  )

  def setup
    @tester = FFaker::LoremRU
  end

  def test_word
    assert_match(WORD_MATCHER, @tester.word)
  end

  def test_words
    @tester.words(10).each do |word|
      assert_match(WORD_MATCHER, word)
    end
    assert_match(WORDS_MATCHER, @tester.words.join(' '))
  end

  def test_sentence
    assert_match(SENTENCE_MATCHER, @tester.sentence(20))
    assert_match(SENTENCE_MATCHER, @tester.sentence(4))
  end

  def test_sentences
    @tester.sentences(10).each do |sentence|
      assert_match(SENTENCE_MATCHER, sentence)
    end
  end

  def test_paragraph
    assert_match(SENTENCE_MATCHER, @tester.paragraph)
  end

  def test_paragraphs
    @tester.paragraphs.each do |paragraph|
      assert_match(SENTENCE_MATCHER, paragraph)
    end
  end
end


text:
{% extends "base.html" %}

{% block title %}Codez | Sign up{% endblock %}

{% block content %}
<form class="form-signin" method="post" action="" class="wide">
  {% csrf_token %}

Create a Codez Account

  {% if form.errors %}

Please correct the errors below: {{ form.non_field_errors }}

  {% endif %}

    Username:
    {% if form.username.errors %}

{{ form.username.errors.as_text }}

  {% endif %}
  {{ form.username }}

    Email address:
    {% if form.email.errors %}

{{ form.email.errors.as_text }}

  {% endif %}
  {{ form.email }}

    Password:
    {% if form.password1.errors %}

{{ form.password1.errors.as_text }}

  {% endif %}
  {{ form.password1 }}

    Confirm Password:
    {% if form.password2.errors %}

{{ form.password2.errors.as_text }}

  {% endif %}
  {{ form.password2 }}

<input class="btn btn-large btn-primary" type="submit" value="Register">

</form>

{% endblock %}


text:
<?php

class utf8 extends utf8_Core {

	/**
	 * Transliterate UTF8 text to lowercase 7bit ASCII, 0-9a-z
	 *
	 * @param   string  $str
	 * @return  string
	 */
	public static function clean($str) {
		$str = mb_strtolower(text::strip_ascii_ctrl($str));
		if (!text::is_ascii($str)) {
			$str = strtolower(text::transliterate_to_ascii($str));
		}
		if (!text::is_ascii($str)) {
			$str = text::strip_non_ascii($str);
		}

		return $str;
		// return strtolower(iconv(Kohana::CHARSET, 'ASCII//TRANSLIT//IGNORE', $str));
	}

	/**
	 * Makes a UTF-8 string lowercase.
	 *
	 * @param   string   mixed case string
	 * @return  string
	 */
	public static function strtolower($str) {
		return mb_strtolower($str);
	}

	/**
	 * Makes a UTF-8 string uppercase.
	 *
	 * @param   string   mixed case string
	 * @return  string
	 */
	public static function strtoupper($str) {
		return mb_strtoupper($str);
	}

	/**
	 * UTF-8 substring
	 *
	 * @param   string   $str
	 * @param   integer  $offset
	 * @param   integer  $length
	 * @return  string
	 */
	public static function substr($str, $offset, $length = NULL) {
		return ($length === NULL) ? mb_substr($str, $offset) : mb_substr($str, $offset, $length);
	}

}


text:
        <form class="input-typeahead-form">
            <input [(ngModel)]="input"
                   [ngModelOptions]="{standalone: true}"
                   placeholder="Enter Text"
                   class="form-control"
                   type="text"
                   (click)="dropdownOpen = true"
                   (keydown)="typeaheadKeyService.handleKey($event, typeahead)"
                   (keydown.escape)="dropdownOpen = false"
                   (blur)="dropdownOpen = false">

            <ux-typeahead #typeahead
                          class="typeahead-example"
                          [(open)]="dropdownOpen"
                          [filter]="input"
                          [options]="loadOptionsFn"
                          [openOnFilterChange]="true"
                          [pageSize]="40"
                          [selectOnEnter]="selectOnEnter"
                          [selectFirst]="selectFirst"
                          [dropDirection]="dropDirection"
                          (optionSelected)="input = $event.option"
                          [(recentOptions)]="recentOptions"
                          [recentOptionsMaxCount]="recentOptionsMaxCount"
                          [ariaLabel]="ariaLabel">
            </ux-typeahead>
        </form>


text:
package twitter4j;

import javax.annotation.Generated;

/**
 * @author Yusuke Yamamoto - yusuke at mac.com
 * @see oEmded
 * @since Twitter4J 3.0.2
 */
@Generated(
        value = "generate-lazy-objects.sh",
        comments = "This is Tool Generated Code. DO NOT EDIT",
        date = "2012-11-29"
)
final class LazyOEmbed implements twitter4j.OEmbed {
    private final HttpResponse res;
    private final ObjectFactory factory;
    private OEmbed target = null;

    LazyOEmbed(HttpResponse res, ObjectFactory factory) {
        this.res = res;
        this.factory = factory;
    }

    private OEmbed getTarget() {
        if (target == null) {
            try {
                target = factory.createOEmbed(res);
            } catch (TwitterException e) {
                throw new TwitterRuntimeException(e);
            }
        }
        return target;
    }

    /**
     * The HTML required to display the resource. The HTML should have no padding or margins. Consumers may wish to load the HTML in an off-domain iframe to avoid XSS vulnerabilities. The markup should be valid XHTML 1.0 Basic.
     *
     * @return The HTML required to display the resource.
     */
    public String getHtml() {
        return getTarget().getHtml();
    }

    /**
     * The name of the author/owner of the resource.
     *
     * @return The name of the author/owner of the resource.
     */
    public String getAuthorName() {
        return getTarget().getAuthorName();
    }

    /**
     * The url of the resource provider.

     * The source URL of the image. Consumers should be able to insert this URL into an <img> element. Only HTTP and HTTPS URLs are valid.
     *
     * @return The url of the resource provider.
     */
    public String getURL() {
        return getTarget().getURL();
    }

    /**
     * The oEmbed version number.
     *
     * @return The oEmbed version number.
     */
    public String getVersion() {
        return getTarget().getVersion();
    }

    /**
     * The suggested cache lifetime for this resource, in seconds. Consumers may choose to use this value or not.
     *
     * @return The suggested cache lifetime for this resource, in seconds. Consumers may choose to use this value or not.
     */
    public long getCacheAge() {
        return getTarget().getCacheAge();
    }

    /**
     * A URL for the author/owner of the resource.
     *
     * @return A URL for the author/owner of the resource.
     */
    public String getAuthorURL() {
        return getTarget().getAuthorURL();
    }

    /**
     * The width in pixels of the image specified in the url parameter.
     *
     * @return The width in pixels of the image specified in the url parameter.
     */
    public int getWidth() {
        return getTarget().getWidth();
    }

    public RateLimitStatus getRateLimitStatus() {
        return getTarget().getRateLimitStatus();
    }

    public int getAccessLevel() {
        return getTarget().getAccessLevel();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof OEmbed)) return false;
        return getTarget().equals(o);
    }

    @Override
    public int hashCode() {
        return getTarget().hashCode();
    }

    @Override
    public String toString() {
        return "LazyOEmbed{" +
                "target=" + getTarget() +
                "}";
    }
}


text:
require "spec_helper"

describe SongPolicy do
  let(:my_user) { FactoryGirl.create(:user)}
  let(:my_song) { FactoryGirl.create(:song, user: my_user) }

  subject { described_class }

  permissions :update? do
    let(:music_end_date) { 2.weeks.from_now }
    let(:config) { FactoryGirl.create(:event_configuration, music_submission_end_date: music_end_date) }
    let(:user) { my_user }
    let(:reg_closed?) { false }
    let(:authorized_laptop?) { false }
    let(:user_context) { UserContext.new(user, config, reg_closed?, authorized_laptop?) }

    it "can update my own song" do
      expect(subject).to permit(user_context, my_song)
    end

    it "cannot update another person's song" do
      other_song = FactoryGirl.create(:song)
      expect(subject).not_to permit(user_context, other_song)
    end

    describe "when the music_submission_date has passed" do
      let(:music_end_date) { 1.week.ago }

      it "cannot update music" do
        expect(subject).not_to permit(user_context, my_song)
      end

      describe "as a super admin" do
        let(:user) { FactoryGirl.create(:super_admin_user) }

        it "can update music" do
          expect(subject).to permit(user_context, my_song)
        end
      end
    end
  end
end


text:
using System;
using SpotifySDK;
using UIKit;
using Foundation;

namespace Spookify
{

	public class MySPTAuthViewDelegate : SPTAuthViewDelegate {
		UIViewController viewController = null;
		public MySPTAuthViewDelegate(UIViewController vc)  {
			this.viewController = vc;
		}

		public PlayerViewController PlayerViewController { get { return this.viewController as PlayerViewController; } }

		public override void AuthenticationViewControllerDidCancelLogin (SPTAuthViewController authenticationViewController)
		{
			BeginInvokeOnMainThread (() => {
				new UIAlertView("Anmeldung","Die Anmeldung wurde abgerochen.",null,"OK").Show();
			});
		}
		public override void AuthenticationViewControllerFail (SPTAuthViewController authenticationViewController, NSError error)
		{
			BeginInvokeOnMainThread (() => {
				new UIAlertView("Fehler",error.LocalizedDescription + error.Description,null,"OK").Show();
			});
		}

		public override void AuthenticationViewControllerLogin (SPTAuthViewController authenticationViewController, SPTSession session)
		{
			// wir erlauben prinzipiell wieder das Anmelden am Player...
			CurrentPlayer.Current.SessionDisabled = false;

			if (this.viewController != null) {
				if (this.viewController is PlayerViewController) {
					var playerViewController = this.PlayerViewController;
					playerViewController.CompleteAuthentication ();
				} else {
					new UIAlertView("Anmeldung","Login erfolgreich",null,"OK").Show();
				}
			}
		}
	}
}


text:
from neutron_lib.api.definitions import logging_resource
from neutron_lib.tests.unit.api.definitions import base

class LoggingResourceDefinitionTestCase(base.DefinitionBaseTestCase):
    extension_module = logging_resource
    extension_resources = (logging_resource.COLLECTION_NAME,)
    extension_subresources = (logging_resource.FIREWALL_LOGS,)
    extension_attributes = (logging_resource.ENABLED,
                            logging_resource.FIREWALL_LOGS,
                            logging_resource.LOGGING_RESOURCE_ID,
                            logging_resource.FW_EVENT,
                            logging_resource.FIREWALL_ID,)


text:
require 'grape-swagger'

class API < Grape::API
  # Mount RubyRPG API
  mount Rpg::V1::BaseApi => '/rpg/v1'

  # Mount the swagger docs
  add_swagger_documentation(
    base_path: "/api",
    hide_documentation_path: false,
    hide_format: false
  )
end