text:
<?php

/**
 * Unit test class for the SwitchDeclaration sniff.
 *
 * A sniff unit test checks a .inc file for expected violations of a single
 * coding standard. Expected errors and warnings are stored in this class.
 *
 * @category  PHP
 * @package   PHP_CodeSniffer
 * @author    Greg Sherwood <gsherwood@squiz.net>
 * @author    Marc McIntyre <mmcintyre@squiz.net>
 * @copyright 2006 Squiz Pty Ltd (ABN 77 084 670 600)
 * @license   http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
 * @version   Release: @package_version@
 * @link      http://pear.php.net/package/PHP_CodeSniffer
 */
class Squiz_Tests_ControlStructures_SwitchDeclarationUnitTest extends AbstractSniffUnitTest
{

    /**
     * Returns the lines where errors should occur.
     *
     * The key of the array should represent the line number and the value
     * should represent the number of errors that should occur on that line.
     *
     * @param string $testFile The name of the file being tested.
     *
     * @return array(int => int)
     */
    public function getErrorList($testFile='SwitchDeclarationUnitTest.inc')
    {
        return array(
                27  => 1,
                29  => 1,
                34  => 1,
                36  => 1,
                44  => 1,
                48  => 1,
                52  => 1,
                54  => 1,
                55  => 1,
                56  => 1,
                58  => 1,
                59  => 1,
                61  => 1,
                62  => 1,
                79  => 1,
                85  => 2,
                88  => 2,
                89  => 2,
                92  => 1,
                95  => 3,
                99  => 1,
                116 => 1,
                122 => 1,
                127 => 2,
                134 => 2,
                135 => 1,
                138 => 1,
                143 => 1,
                147 => 1,
                165 => 1,
                172 => 1,
                224 => 1,
               );

    }//end getErrorList()

    /**
     * Returns the lines where warnings should occur.
     *
     * The key of the array should represent the line number and the value
     * should represent the number of warnings that should occur on that line.
     *
     * @return array(int => int)
     */
    public function getWarningList()
    {
        return array();

    }//end getWarningList()

}//end class

?>


text:
package com.frojas.francisco.pojo;

import java.util.Date;

/**
 * Created by Francisco on 24/03/2015.
 */
public class Movie {

    private long id;
    private String title;
    private Date releaseDateTheater;
    private int audienceScore;
    private String synopsis;
    private String urlThumbnail;
    private String urlSelf;
    private String urlCast;
    private String urlReviews;
    private String urlSimilar;

    public Movie(){

    }

    public Movie(long id,
                 String title,
                 Date releaseDateTheater,
                 int audienceScore,
                 String synopsis,
                 String urlThumbnail,
                 String urlSelf,
                 String urlCast,
                 String urlReviews,
                 String urlSimilar){
        this.id=id;
        this.title=title;
        this.releaseDateTheater=releaseDateTheater;
        this.audienceScore=audienceScore;
        this.synopsis=synopsis;
        this.urlThumbnail=urlThumbnail;
        this.urlSelf=urlSelf;
        this.urlCast=urlCast;
        this.urlReviews=urlReviews;
        this.urlSimilar=urlSimilar;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Date getReleaseDateTheater() {
        return releaseDateTheater;
    }

    public void setReleaseDateTheater(Date releaseDateTheater) {
        this.releaseDateTheater = releaseDateTheater;
    }

    public int getAudienceScore() {
        return audienceScore;
    }

    public void setAudienceScore(int audienceScore) {
        this.audienceScore = audienceScore;
    }

    public String getSynopsis() {
        return synopsis;
    }

    public void setSynopsis(String synopsis) {
        this.synopsis = synopsis;
    }

    public String getUrlThumbnail() {
        return urlThumbnail;
    }

    public void setUrlThumbnail(String urlThumbnail) {
        this.urlThumbnail = urlThumbnail;
    }

    public String getUrlSelf() {
        return urlSelf;
    }

    public void setUrlSelf(String urlSelf) {
        this.urlSelf = urlSelf;
    }

    public String getUrlCast() {
        return urlCast;
    }

    public void setUrlCast(String urlCast) {
        this.urlCast = urlCast;
    }

    public String getUrlReviews() {
        return urlReviews;
    }

    public void setUrlReviews(String urlReviews) {
        this.urlReviews = urlReviews;
    }

    public String getUrlSimilar() {
        return urlSimilar;
    }

    public void setUrlSimilar(String urlSimilar) {
        this.urlSimilar = urlSimilar;
    }

    @Override
    public String toString() {
        return "ID: "+id+
                "Title "+title+
                "Date "+releaseDateTheater+
                "Synopsis "+synopsis+
                "Score "+audienceScore+
                "urlThumbnail "+urlThumbnail+
                "\n";
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace trntv\glide_tests;
use Symfony\Component\HttpFoundation\Request;

/**
 * @author Eugene Terentev <eugene@terentev.net>
 */
class GlideActionTest extends TestCase
{
    public function testImageFound()
    {
        \Yii::$app->glide->signKey = null;
        ob_start();
        $this->getGlideAction()->run('kayaks.jpg');
        ob_end_clean();
    }

    public function testImageNotFound()
    {
        \Yii::$app->glide->signKey = null;
        $this->setExpectedException('\yii\web\NotFoundHttpException');
        $this->getGlideAction()->run('wrong-image.jpg');
    }

    public function testRequestValidationUglyUrl()
    {
        $rigthSignedUrl = '/index.php?r=glide%2Findex&path=test-img&s=7632784193f00c91a6f06dc87c43090f';
        $wrongSignedUrl = '/index.php?r=glide%2Findex&path=test-img&w=1000000&s=7632784193f00c91a6f06dc87c43090f';
        $this->assertEquals(
            true,
            $this->getGlideAction()->validateRequest(Request::create($rigthSignedUrl))
        );
        $this->assertEquals(
            false,
            $this->getGlideAction()->validateRequest(Request::create($wrongSignedUrl))
        );
    }

    public function testRequestValidationPrettyUrl()
    {
        \Yii::$app->urlManager->enablePrettyUrl = true;
        \Yii::$app->urlManager->showScriptName = false;
        $rigthSignedUrl = '/glide/index?path=test-img&s=d60ed7390b035237c96135e76038b7e4';
        $wrongSignedUrl = '/glide/index?path=test-img&w=10000&s=d60ed7390b035237c96135e76038b7e4';
        $this->assertEquals(
            true,
            $this->getGlideAction()->validateRequest(Request::create($rigthSignedUrl))
        );
        $this->assertEquals(
            false,
            $this->getGlideAction()->validateRequest(Request::create($wrongSignedUrl))
        );
    }
}


text:
using System;
using System.Collections.Generic;
using System.Reflection;
using System.IO;
using System.Text;

namespace FmbLib {
    public delegate TOut SelectFunc<TIn, TOut>(TIn value);
    public static class FmbHelper {

        private readonly static Dictionary<string, Type> CacheTypes = new Dictionary<string, Type>(128);
        private readonly static Dictionary<string, Type> CachePrefoundTypes = new Dictionary<string, Type>(1024);

        static FmbHelper() {
            BlacklistedAssemblies.Add("SDL2-CS");
            BlacklistedAssemblies.Add("System.Drawing");

            ValueTypes.Add("Matrix");
            ValueTypes.Add("Quaternion");
            ValueTypes.Add("Vector2");
            ValueTypes.Add("Vector3");
            ValueTypes.Add("Vector4");
            ValueTypes.Add("Color");
            ValueTypes.Add("BoundingSphere");
        }

        public static List<string> BlacklistedAssemblies = new List<string>();

        /// <summary>
        /// List of types that are value types in XNA but not value types in other frameworks / engines (f.e. UNITY)
        /// </summary>
        public static List<string> ValueTypes = new List<string>();

        public static Type FindType(string name) {
            return FindType_(name, false);
        }

        private static Type FindType_(string name, bool remappedNamespace) {
            Type type_ = null;
            if (CacheTypes.TryGetValue(name, out type_)) {
                return type_;
            }
            if (CachePrefoundTypes.TryGetValue(name, out type_)) {
                CacheTypes[name] = type_;
                return type_;
            }

            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
            List<Assembly> delayedAssemblies = new List<Assembly>();

            foreach (Assembly assembly in assemblies) {
                if (assembly.GetName().Name.EndsWith(".mm") || BlacklistedAssemblies.Contains(assembly.GetName().Name)) {
                    delayedAssemblies.Add(assembly);
                    continue;
                }
                try {
                    Type[] types = assembly.GetTypes();
                    foreach (Type type in types) {
                        if ((type.Name == name && type.FullName.EndsWith("."+name)) || name == type.FullName) {
                            CacheTypes[name] = type;
                            return type;
                        }
                        CachePrefoundTypes[type.FullName] = CachePrefoundTypes[type.Name] = type;
                    }
                } catch (ReflectionTypeLoadException e) {
                    FmbHelper.Log("Failed searching a type in XmlHelper's FindType.");
                    FmbHelper.Log("Assembly: " + assembly.GetName().Name);
                    FmbHelper.Log(e.Message);
                    foreach (Exception le in e.LoaderExceptions) {
                        FmbHelper.Log(le.Message);
                    }
                }
            }

            foreach (Assembly assembly in delayedAssemblies) {
                try {
                    Type[] types = assembly.GetTypes();
                    foreach (Type type in types) {
                        if ((type.Name == name && type.FullName.EndsWith("."+name)) || name == type.FullName) {
                            CacheTypes[name] = type;
                            return type;
                        }
                    }
                } catch (ReflectionTypeLoadException e) {
                    FmbHelper.Log("Failed searching a type in XmlHelper's FindType.");
                    FmbHelper.Log("Assembly: " + assembly.GetName().Name);
                    FmbHelper.Log(e.Message);
                    foreach (Exception le in e.LoaderExceptions) {
                        FmbHelper.Log(le.Message);
                    }
                }
            }

            if (!remappedNamespace) {
                string oldname = name;
                for (int i = 0; i < FmbUtil.NamespaceRemap.Count; i++) {
                    name = name.Replace(FmbUtil.NamespaceRemap[i].Key, FmbUtil.NamespaceRemap[i].Value);
                }
                Type foundType = FindType_(name, true);
                CacheTypes[oldname] = foundType;
                return foundType;
            } else {
                CacheTypes[name] = null;
                return null;
            }
        }

        public static TypeHandler GetGenericTypeHandler(Type typeHandlerType, params Type[] genericArgs) {
            return (TypeHandler) typeHandlerType.MakeGenericType(genericArgs).GetConstructor(new Type[0]).Invoke(new object[0]);
        }

        public static int Read7BitEncodedInt(this BinaryReader reader) {
            int ret = 0;
            int shift = 0;
            int len;
            byte b;

            for (len = 0; len < 5; ++len) {
                b = reader.ReadByte();

                ret = ret | ((b & 0x7f) << shift);
                shift += 7;
                if ((b & 0x80) == 0) {
                    break;
                }
            }

            if (len < 5) {
                return ret;
            } else {
                throw new FormatException("Too many bytes in what should have been a 7 bit encoded Int32.");
            }
        }

        public static bool IsValueType(this Type type) {
            return type.IsValueType || ValueTypes.Contains(type.Name);
        }

        public static List<Type> GetGenericParamTypes(string typeName) {
            typeName = typeName.Substring(typeName.IndexOf("[[") + 1, typeName.Length - typeName.IndexOf("[[") - 2);

            List<string> matches = new List<string>();
            StringBuilder current = new StringBuilder();
            int depth = 0;
            for (int i = 0; i < typeName.Length; i++) {
                char c = typeName[i];
                if (c == '[') {
                    depth++;
                    if (depth != 1) {
                        current.Append(c);
                    }
                } else if (c == ']') {
                    depth--;
                    if (depth != 0) {
                        current.Append(c);
                    }
                } else {
                    current.Append(c);
                }
                if (depth == 0) {
                    if (1 < current.Length) {
                        matches.Add(current.ToString());
                    }
                    current = new StringBuilder();
                }
            }

            List<Type> genericParams = new List<Type>(matches.Count);
            for (int i = 0; i < matches.Count; i++) {
                string paramName = matches[i];
                if (paramName.Contains("Version=")) {
                    if (!paramName.Contains("[[")) {
                        int commaIndex = paramName.LastIndexOf("Version=") - 1;
                        commaIndex = paramName.LastIndexOf(", ", commaIndex - 1);
                        paramName = paramName.Substring(0, commaIndex);
                    } else {
                        paramName = paramName.Substring(0, paramName.LastIndexOf("]]") + 2);
                    }
                } else {
                    paramName = paramName.Substring(0, paramName.LastIndexOf(", "));
                }
                //FmbHelper.Log(i + ": " + paramName + ": " + FmbHelper.FindType(paramName));
                if (!paramName.Contains("[[")) {
                    genericParams.Add(FindType(paramName));
                } else {
                    string paramNameStrip = paramName.Substring(0, paramName.IndexOf("[["));
                    paramNameStrip = paramNameStrip.Substring(paramNameStrip.LastIndexOf('.') + 1);
                    Type type = FindType(paramNameStrip);
                    type = type.MakeGenericType(GetGenericParamTypes(paramName).ToArray());
                    genericParams.Add(type);
                }
            }
            return genericParams;
        }

#if FEZENGINE
        public static HashSet<T> HashSetOrList<T>(T[] arr, IEqualityComparer<T> comp) {
            return new HashSet<T>(arr, comp);
        }

        public static T[] HashSetOrListToArray<T>(HashSet<T> set) {
            T[] arr = new T[set.Count];
            set.CopyTo(arr);
            return arr;
        }
#else
        public static List<T> HashSetOrList<T>(T[] arr, object comp) {
            return new List<T>(arr);
        }

        public static T[] HashSetOrListToArray<T>(List<T> set) {
            return set.ToArray();
        }
#endif

        public static void AppendTo(string str, StringBuilder b1, StringBuilder b2) {
            b1.Append(str);
            b2.Append(str);
        }

        public static void Log(string str) {
            //This is shorter to reach than FmbUtil.Setup.Log
            if (FmbUtil.Setup.Log != null) {
                FmbUtil.Setup.Log(str);
            }
        }

        public static void DefaultLog(string str) {
            Console.WriteLine(str);
            #if UNITY
            UnityEngine.Debug.Log(str);
            #endif
        }

        // Linq

        // Optimized, writing to the same array
        public static T[] Select<T>(T[] a, SelectFunc<T, T> func) {
            for (int i = 0; i < a.Length; i++) {
                a[i] = func(a[i]);
            }
            return a;
        }

        public static TOut[] Select<TIn, TOut>(TIn[] aIn, SelectFunc<TIn, TOut> func) {
            TOut[] aOut = new TOut[aIn.Length];
            for (int i = 0; i < aIn.Length; i++) {
                aOut[i] = func(aIn[i]);
            }
            return aOut;
        }

        // FezMath

        private static readonly double Log2 = Math.Log(2D);
        public static int NextPowerOfTwo(double value) {
            return (int) Math.Pow(2D, Math.Ceiling(Math.Log(value) / Log2));
        }

        #if !UNITY
        public static float GetX(Microsoft.Xna.Framework.Vector2 v) {return v.X;}
        public static float GetX(Microsoft.Xna.Framework.Vector3 v) {return v.X;}
        public static float GetX(Microsoft.Xna.Framework.Vector4 v) {return v.X;}
        public static float GetY(Microsoft.Xna.Framework.Vector2 v) {return v.Y;}
        public static float GetY(Microsoft.Xna.Framework.Vector3 v) {return v.Y;}
        public static float GetY(Microsoft.Xna.Framework.Vector4 v) {return v.Y;}
        public static float GetZ(Microsoft.Xna.Framework.Vector3 v) {return v.Z;}
        public static float GetZ(Microsoft.Xna.Framework.Vector4 v) {return v.Z;}
        public static float GetW(Microsoft.Xna.Framework.Vector4 v) {return v.W;}
        #else
        public static float GetX(UnityEngine.Vector2 v) {return v.x;}
        public static float GetX(UnityEngine.Vector3 v) {return v.x;}
        public static float GetX(UnityEngine.Vector4 v) {return v.x;}
        public static float GetY(UnityEngine.Vector2 v) {return v.y;}
        public static float GetY(UnityEngine.Vector3 v) {return v.y;}
        public static float GetY(UnityEngine.Vector4 v) {return v.y;}
        public static float GetZ(UnityEngine.Vector3 v) {return v.z;}
        public static float GetZ(UnityEngine.Vector4 v) {return v.z;}
        public static float GetW(UnityEngine.Vector4 v) {return v.w;}
        #endif

    }
}


text:
/* @flow */
/*
---
id: getting-started
title: Getting started with Flow
permalink: /docs/getting-started.html
prev: about-flow.html
next: five-simple-examples.html
---
*/

/*
  To demonstrate how to add Flow to a project, let's set up an example npm project.

  First, we'll make an npm package for our example project called "get_started":

  ```bash
  $> mkdir -p get_started
  $> cd get_started
  $> echo '{"name": "get_started", "scripts": {"flow": "flow; [[ $?=0||$?=2 ]]"}}' > package.json
  ```

  Next we'll add Flow to our project:

  ```bash
  $> touch .flowconfig
  $> npm install --save-dev flow-bin
  ```

  And now we can start writing some code!

  **index.js**
*/

// @flow

// $DocIssue
var str = 'hello world!';
console.log(str);

/*
  Note that we've added `// @flow` to the top of our file. This indicates to Flow
  that we want this file to be checked. **If we don't add this flag to the top of
  the file, Flow will assume that the file isn't ready to be checked yet and
  Flow will not attempt to type check the file.**

  Ok, now let's run Flow and see what it has to say about the code we just wrote:

  ```bash
  $> npm run-script flow

  > test@ flow /get_started
  > flow

  No errors!
  ```

  Woohoo! No errors! Ok, now let's add a trivial type error just to see what
  happens:

  **index.js**
*/

// @flow

// $ExpectError
var str: number = 'hello world!';
console.log(str);

/*
  ```bash
  $> npm run-script flow

  > test@ flow /get_started
  > flow 2> /dev/null

  index.js:3
    3: let str: number = 'hello world!';
                         ^^^^^^^^^^^^^^ string. This type is incompatible with
    3: let str: number = 'hello world!';
                ^^^^^^ number

  Found 1 error
  ```

  Cool -- Flow noticed that we're assigning a string to a number and gave an
  error.

  Before we fix this type error, let's add Babel to our project so we can
  try running our code:

  ```bash
  $> npm install -g babel-cli
  $> npm install --save-dev babel-plugin-transform-flow-strip-types
  $> echo '{"plugins": ["transform-flow-strip-types"]}' > .babelrc
  ```

  Now we can try running our code *in spite* of the type error and see what
  happens:

  ```bash
  $> babel-node index.js
  hello world!
  ```

  It works! As you can see Flow does not prevent you from running the code you
  have written even if there are type errors. It is considered best practice to
  never publish your project when it has type errors, but often at development
  time it's useful to try running code even before it fully typechecks (usually
  for debugging or ad-hoc testing). This is one of the benefits of gradual typing
  and Flow is designed to support this and stay out of your way as much as you
  need it to during development.

  Note that we ran our code using `babel-node` rather than just vanilla `node` to
  run index.js. [`babel-node`](https://babeljs.io/docs/usage/cli/#babel-node)
  comes with `babel-cli` and is just a thin wrapper around vanilla `node` that
  first intercepts and transpiles JS code before running it with `node`.

  Check out the [Running Flow Code](/docs/running.html) section for more details
  on how we recommend compiling and publishing Flow code to npm and into
  production.

### Next steps

  Now that we know how to set Flow up, let's take a quick look at
  [a few examples](/five-simple-examples.html) that are
  [included in the Flow repo](https://github.com/facebook/flow/tree/master/examples):

  1. [Hello Flow!](/docs/five-simple-examples.html#1-hello-flow)
  2. [Adding type annotations](/docs/five-simple-examples.html#2-adding-type-annotations)
  3. [Nullable types](/docs/five-simple-examples.html#3-nullable-types)
  4. [Arrays](/docs/five-simple-examples.html#4-arrays)
  5. [Dynamic code](/docs/five-simple-examples.html#5-dynamic-code)
*/


text:
@implementation HWDUser

- (void)setValue:(id)value forKey:(NSString *)key
{
    if ([NSNull null] == value) {
        return;
    }

    if ([key isEqualToString:@"user_id"]) {
        self.userId = value;
    } else if ([key isEqualToString:@"user_name"]) {
        self.userName = value;
    } else if ([key isEqualToString:@"city"]) {
        self.city = value;
    } else if ([key isEqualToString:@"avatar_url"]) {
        self.avatarUrl = value;
    } else if ([key isEqualToString:@"liked_dish_count"]) {
        self.likedDishCount = value;
    } else if ([key isEqualToString:@"upload_dish_count"]) {
        self.uploadDishCount = value;
    }
}

@end


text:
<?php

require_once 'Bootstrap.php';

/**
 *  Edit IM
 */

class UI_ActiveRule_004_Test extends IZI\Selenium\UITestCase
{
  public function testMyTestCase()
  {
    $this->open("?id_dm=TEST");
    $this->click("css=.remove-im");
    $this->click("css=.remove-im");
    $this->click("id=add-im");
    $this->select("css=#add-im-select", "value=SUPP");
    $this->type("css=#add-im-threshold-value", "0.10");
    $this->click("css=input[type=\"submit\"]");
    for ($second = 0; ; $second++) {
        if ($second >= 60) $this->fail("timeout");
        try {
            if ($this->isElementPresent("css=.edit-im")) break;
        } catch (Exception $e) {}
        sleep(1);
    }

    $this->click("css=.edit-im");
    $this->assertEquals("SUPP", $this->getSelectedValue("css=#edit-im-select"));
    $this->assertEquals("0.10", $this->getValue("css=#edit-im-threshold-value"));
    $this->type("css=#edit-im-threshold-value", "0.20");
    $this->click("css=input[type=\"submit\"]");
    $this->assertEquals("0.20", $this->getText("css=#im-supp .threshold"));
  }
}


text:
package com.uwics.uwidiscover.classes.adapters;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.uwics.uwidiscover.R;
import com.uwics.uwidiscover.classes.models.Event;
import com.uwics.uwidiscover.fragments.EventDialogFragment;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by shane on 2/12/16.
 */
public class EventAdapter extends RecyclerView.Adapter<EventAdapter.EventHolder> {

    private List<Event> eventList;
    private Context context;

    public EventAdapter(Context context) {
        this.context = context;
        eventList = new ArrayList<>();
        notifyDataSetChanged();
    }

    @Override
    public EventHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.schedule_item, parent, false);
        return new EventHolder(view);
    }

    @Override
    public void onBindViewHolder(EventHolder holder, int position) {
        final Event event = eventList.get(position);

        holder.linearLayoutContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventDialogFragment eventDialogFragment = new EventDialogFragment();
                Bundle bundle = new Bundle();
                bundle.putString("eventStartTime", event.getStartTime());
                bundle.putString("eventEndTime", event.getEndTime());
                bundle.putString("eventDate", event.getDate());
                bundle.putString("eventDetails", event.getDetails());
                bundle.putString("eventVenue", event.getVenue());
                bundle.putString("eventType", event.getType());

                eventDialogFragment.setArguments(bundle);
                eventDialogFragment.show(((AppCompatActivity) context).getSupportFragmentManager(), "eventDialogFragment");
            }
        });
        holder.details.setText(event.getDetails());
        holder.startTime.setText(event.getStartTime());
        holder.endTime.setText(event.getEndTime());
        holder.venue.setText(event.getVenue());
        holder.type.setText(event.getType());
    }

    @Override
    public int getItemCount() {
        return eventList.size();
    }

    public void setEvents(List<Event> events) {
        eventList = events;
        notifyDataSetChanged();
    }

//    public Event removeItem(int position) {
//        final Event model = eventList.remove(position);
//        notifyItemRemoved(position);
//        return model;
//    }
//
//    public void addItem(int position, Event model) {
//        eventList.add(position, model);
//        notifyItemInserted(position);
//    }
//
//    public void moveItem(int fromPosition, int toPosition) {
//        final Event model = eventList.remove(fromPosition);
//        eventList.add(toPosition, model);
//        notifyItemMoved(fromPosition, toPosition);
//    }

    public class EventHolder extends RecyclerView.ViewHolder {
        LinearLayout linearLayoutContainer;
        TextView startTime, endTime, type, venue, details;

        public EventHolder(View itemView) {
            super(itemView);
            linearLayoutContainer = (LinearLayout) itemView.findViewById(R.id.schedule_linear_layout_container);
            startTime = (TextView) itemView.findViewById(R.id.event_start_time);
            endTime = (TextView) itemView.findViewById(R.id.event_end_time);
            type = (TextView) itemView.findViewById(R.id.event_type);
            venue = (TextView) itemView.findViewById(R.id.event_venue);
            details = (TextView) itemView.findViewById(R.id.event_details);
        }
    }
}


text:
<[options.title]>

    <[options.column_headers[0]]>
    <[options.column_headers[1]]>
    Addressed specifically?

      Answer Set #<[$index + 1]>

            <angular-html-bind html-data="item">
            </angular-html-bind>

    <[row.frequency]>

      Yes
      No


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using AutoFixture;
using AutoFixture.Kernel;
using Leprechaun.Model;

namespace Leprechaun.Tests.Test.SpecimenBuilders.StandardArchitectorValidator
{
	public class DuplicateTemplateNamesSpec : ITemplateMetadataSpec
	{
		protected List<TemplateCodeGenerationMetadata> Metadatas;
		private bool _init;
		public void Init(IFixture fixture)
		{
			Metadatas = fixture.CreateMany<TemplateCodeGenerationMetadata>(5).ToList();
			Metadatas.Add(Metadatas[0]);

			_init = true;
		}

		public object Create(object request, ISpecimenContext context)
		{
			if (!_init) throw new InvalidOperationException("Init not called");

			if (!(request is ParameterInfo pi)) return new NoSpecimen();

			if (pi.Name == "allTemplates")
				return Metadatas;

			return new NoSpecimen();
		}
	}
}


text:
// $Id: SVGGraph.hh 5748 2014-10-11 19:38:53Z flaterco $

namespace libxtide {

class SVGGraph: public Graph {
public:
  SVGGraph (unsigned xSize, unsigned ySize, GraphStyle style = normal);

  void print (Dstr &text_out);

protected:

  Dstr SVG;

  const unsigned stringWidth (const Dstr &s) const;
  const unsigned fontHeight() const;
  const unsigned oughtHeight() const;
  const unsigned oughtVerticalMargin() const;

  void drawLevels (const SafeVector<double> &val,
		   const SafeVector<double> &y,
		   double yzulu,
		   bool isCurrent
#ifdef blendingTest
		   , const SafeVector<BlendBlob> &blendBlobs
#endif
		   );

  void drawX (double x, double y);
  void drawBoxS (double x1, double x2, double y1, double y2,
		 Colors::Colorchoice c);
  void drawVerticalLineS (double x, double y1, double y2,
			  Colors::Colorchoice c);
  void drawHorizontalLineS (double xlo, double xhi, double y,
			    Colors::Colorchoice c);
  void drawHorizontalLinePxSy (int xlo, int xhi, double y,
			       Colors::Colorchoice c);
  void centerStringSxPy    (double x, int y, const Dstr &s);
  void rightJustifyStringS (double x, double y, const Dstr &s);
};

}


text:
require 'active_record'
require 'active_etl/source'

module ActiveETL
  module Destination

    # Include class methods
    def self.included(base)
      base.extend(ActiveETL::Destination::ClassMethods)
      super
    end

    module ClassMethods

      def inherited(subclass)
        super
        subclass.etl_source_attribute = self.etl_source_attribute
        subclass.etl_sources_array = self.etl_sources
        subclass.etl_destination_dependencies_array= self.etl_destination_dependencies
      end

      def etl_source_attribute
        @source_attribute
      end

      def etl_source_attribute=(source_attribute)
        @source_attribute = source_attribute
      end

      def add_etl_source(source)
        raise Exception, "#{source} is not a #{ActiveETL::Source.name}" unless source.is_a?(ActiveETL::Source)
        etl_sources_array << source
      end

      def etl_sources
        etl_sources_array.clone
      end

      def etl_destination_dependencies
        etl_destination_dependencies_array.clone
      end

      def set_etl_destination_dependencies(dependencies)
        self.etl_destination_dependencies_array=(dependencies)
      end

      def run_etl
        execute_etl
      end

      protected

      def etl_sources_array
        @etl_sources ||= []
      end

      def etl_sources_array=(sources)
        @etl_sources = sources
      end

      def etl_destination_dependencies_array
        @etl_destination_dependencies ||= []
      end

      def etl_destination_dependencies_array=(dependencies)
        @etl_destination_dependencies = dependencies
      end

      def find_by_source_conditions(source)
        conditions = {}

        if etl_source_attribute
          source_class = if source.is_a?(Class)
            source
          else
            source.to_s.class
          end

          raise Exception, "#{source_class} is not a #{ActiveETL::Source.name}" unless source_class.is_a?(ActiveETL::Source)

          conditions[etl_source_attribute.to_sym] = source.source
        end

        conditions
      end

      def execute_etl
        # TODO : Delete destination rows corresponding to deleted source rows

        etl_sources_array.each do |source|
          source.find do |source_rows|
            source_rows.each do |source_row|
              # Update destination rows corresponding to existing source rows
              destination_row = if primary_key_attribute = source.primary_key_destination_attribute
                conditions = find_by_source_conditions(source)
                conditions[primary_key_attribute.destination_attribute.to_sym] = source_row.send(source.primary_key)
                self.find(:first, :conditions => conditions)
              end
              # Create destination rows corresponding to new source rows
              destination_row ||= self.new
              source.destination_attributes.each do |destination_attribute|
                destination_row.send(destination_attribute.destination_attribute, destination_attribute.value(source_row))
              end
              destination_row.save!
            end
          end
        end
      end

    end

  end
end


text:
package com.soothsayer.core.utils;

import com.soothsayer.core.entities.user.UserEntity;
import org.apache.commons.codec.digest.DigestUtils;
import org.joda.time.DateTime;

public class CodecUtil {
    public static String generateSessionToken(UserEntity userEntity) {
        String src = String.format("%s-%s-%s-%s", DateTime.now().getMillis(), userEntity.getUserName(), userEntity.getMobile(), userEntity.getEmail());
        return DigestUtils.sha256Hex(src);
    }
}


text:
module Vagrant
  module Notify
    module Action
      class NotifyProvisioningStatus
        def initialize(app, env)
          @app = app
        end

        def call(env)
          system("notify-send '[#{env[:machine].name}] Provisioning with \"#{env[:provisioner_name]}\"...'")
          @app.call(env)
          system("notify-send '[#{env[:machine].name}] Finished provisioning with \"#{env[:provisioner_name]}\"'")
        end
      end
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GlmSharpGenerator.Tests;

namespace GlmSharpGenerator.Types
{
    partial class VectorType
    {
        private IEnumerable<string> TestConstructor
        {
            get
            {
                {
                    yield return "{";
                    var vals = BaseType.RandomSmallVals(1);
                    yield return $"var v = {Construct(this, vals)};".Indent();
                    foreach (var field in Fields)
                        yield return string.Format("Assert.AreEqual({1}, v.{0});", field, vals[0]).Indent();
                    yield return "}";
                }
                {
                    yield return "{";
                    var vals = BaseType.RandomSmallVals(Components);
                    yield return $"var v = {Construct(this, vals)};".Indent();
                    var it = vals.GetEnumerator();
                    foreach (var field in Fields)
                        yield return string.Format("Assert.AreEqual({1}, v.{0});", field, it.MoveNext() ? it.Current : ZeroValue).Indent();
                    yield return "}";
                }
                for (var comps = 2; comps <= 4; ++comps)
                {
                    yield return "{";
                    var vals = BaseType.RandomSmallVals(comps);
                    yield return $"var v = {Construct(this, Construct(new VectorType(BaseType, comps), vals))};".Indent();
                    var it = vals.GetEnumerator();
                    foreach (var field in Fields)
                        yield return string.Format("Assert.AreEqual({1}, v.{0});", field, it.MoveNext() ? it.Current : ZeroValue).Indent();
                    yield return "}";
                }
            }
        }

        private IEnumerable<string> TestIndexer
        {
            get
            {
                var vals = BaseType.RandomSmallVals(Components);
                yield return $"var v = {Construct(this, vals)};";

                for (var i = 0; i < vals.Length; ++i)
                    yield return $"Assert.AreEqual({vals[i]}, v[{i}]);";

                yield return "";
                foreach (var index in new[] { int.MinValue, -1, Components, int.MaxValue, 5 })
                {
                    yield return $"Assert.Throws<ArgumentOutOfRangeException>(() => {{ var s = v[{index}]; }} );";
                    yield return $"Assert.Throws<ArgumentOutOfRangeException>(() => {{ v[{index}] = {ZeroValue}; }} );";
                }

                yield return "";
                foreach (var val in BaseType.ValuesSmallVals)
                {
                    var i = Random.Next(Components);
                    yield return $"v[{i}] = {val};";
                    yield return $"Assert.AreEqual({val}, v[{i}]);";
                }
            }
        }

        private IEnumerable<string> TestPropertyValue
        {
            get
            {
                var vals = BaseType.RandomSmallVals(Components);
                yield return $"var v = {Construct(this, vals)};";
                yield return "var vals = v.Values;";
                for (var i = 0; i < vals.Length; ++i)
                    yield return $"Assert.AreEqual({vals[i]}, vals[{i}]);";

                yield return string.Format("Assert.That(vals.SequenceEqual(v.ToArray()));");
            }
        }

        private IEnumerable<string> TestStaticProperties
        {
            get
            {
                foreach (var f in Fields)
                    yield return $"Assert.AreEqual({ZeroValue}, {NameThat}.Zero.{f});";

                if (!string.IsNullOrEmpty(OneValue))
                {
                    yield return "";
                    foreach (var f in Fields)
                        yield return $"Assert.AreEqual({OneValue}, {NameThat}.Ones.{f});";

                    foreach (var uf in Fields)
                    {
                        yield return "";
                        foreach (var f in Fields)
                            yield return $"Assert.AreEqual({(f == uf ? OneValue : ZeroValue)}, {NameThat}.Unit{uf.ToUpper()}.{f});";
                    }
                }

                foreach (var constant in BaseType.TypeConstants)
                {
                    yield return "";
                    foreach (var f in Fields)
                        yield return string.Format("Assert.AreEqual({0}.{2}, {1}.{2}.{3});", BaseTypeName, NameThat, constant, f);
                }
            }
        }

        private IEnumerable<string> TestOperators
        {
            get
            {
                var vals = BaseType.RandomSmallVals(Components);
                while (vals.All(v => v == vals[0]))
                    vals = BaseType.RandomSmallVals(Components);

                yield return $"var v1 = {Construct(this, vals)};";
                yield return $"var v2 = {Construct(this, vals)};";
                yield return $"var v3 = {Construct(this, vals.Reverse())};";
                yield return $"Assert.That(v1 == {Construct(this, "v1")});";
                yield return $"Assert.That(v2 == {Construct(this, "v2")});";
                yield return $"Assert.That(v3 == {Construct(this, "v3")});";
                yield return string.Format("Assert.That(v1 == v2);");
                yield return string.Format("Assert.That(v1 != v3);");
                yield return string.Format("Assert.That(v2 != v3);");
            }
        }

        private IEnumerable<string> TestStringInterop
        {
            get
            {
                var vals = BaseType.RandomSmallVals(Components);
                yield return $"var v = {Construct(this, vals)};";

                yield return "";
                yield return string.Format("var s0 = v.ToString();");
                yield return string.Format("var s1 = v.ToString(\"#\");");

                if (!BaseType.IsComplex && !BaseType.Generic)
                {
                    yield return "";
                    yield return $"var v0 = {Name}.Parse(s0);";
                    yield return $"var v1 = {Name}.Parse(s1, \"#\");";
                    yield return string.Format("Assert.AreEqual(v, v0);");
                    yield return string.Format("Assert.AreEqual(v, v1);");
                    yield return "";
                    yield return $"var b0 = {Name}.TryParse(s0, out v0);";
                    yield return $"var b1 = {Name}.TryParse(s1, \"#\", out v1);";
                    yield return string.Format("Assert.That(b0);");
                    yield return string.Format("Assert.That(b1);");
                    yield return string.Format("Assert.AreEqual(v, v0);");
                    yield return string.Format("Assert.AreEqual(v, v1);");
                    yield return "";
                    yield return $"b0 = {Name}.TryParse(null, out v0);";
                    yield return string.Format("Assert.False(b0);");
                    yield return $"b0 = {Name}.TryParse(\"\", out v0);";
                    yield return string.Format("Assert.False(b0);");
                    yield return $"b0 = {Name}.TryParse(s0 + \", 0\", out v0);";
                    yield return string.Format("Assert.False(b0);");
                    yield return "";
                    yield return $"Assert.Throws<NullReferenceException>(() => {{ {Name}.Parse(null); }});";
                    yield return $"Assert.Throws<FormatException>(() => {{ {Name}.Parse(\"\"); }});";
                    yield return $"Assert.Throws<FormatException>(() => {{ {Name}.Parse(s0 + \", 0\"); }});";
                }

                if (!BaseType.Generic)
                {
                    yield return "";
                    yield return string.Format("var s2 = v.ToString(\";\", CultureInfo.InvariantCulture);");
                    yield return string.Format("Assert.That(s2.Length > 0);");

                    if (BaseType.HasFormatString && !BaseType.IsComplex)
                    {
                        yield return "";
                        yield return string.Format("var s3 = v.ToString(\"; \", \"G\");");
                        yield return string.Format("var s4 = v.ToString(\"; \", \"G\", CultureInfo.InvariantCulture);");
                        yield return $"var v3 = {Name}.Parse(s3, \"; \", NumberStyles.Number);";
                        yield return $"var v4 = {Name}.Parse(s4, \"; \", NumberStyles.Number, CultureInfo.InvariantCulture);";
                        yield return string.Format("Assert.AreEqual(v, v3);");
                        yield return string.Format("Assert.AreEqual(v, v4);");
                        yield return "";
                        yield return $"var b4 = {Name}.TryParse(s4, \"; \", NumberStyles.Number, CultureInfo.InvariantCulture, out v4);";
                        yield return string.Format("Assert.That(b4);");
                        yield return string.Format("Assert.AreEqual(v, v4);");
                    }
                }
            }
        }

        private IEnumerable<string> SerializationJson
        {
            get
            {
                var vals = BaseType.RandomSmallVals(Components);
                yield return $"var v0 = {Construct(this, vals)};";
                yield return string.Format("var s0 = JsonConvert.SerializeObject(v0);");
                yield return "";
                yield return $"var v1 = JsonConvert.DeserializeObject<{NameThat}>(s0);";
                yield return string.Format("var s1 = JsonConvert.SerializeObject(v1);");
                yield return "";
                yield return string.Format("Assert.AreEqual(v0, v1);");

                yield return string.Format("Assert.AreEqual(s0, s1);");
            }
        }

        public override IEnumerable<TestFunc> GenerateTests()
        {
            yield return new TestFunc(this, "Constructors", TestConstructor);
            yield return new TestFunc(this, "Indexer", TestIndexer);
            yield return new TestFunc(this, "PropertyValues", TestPropertyValue);
            yield return new TestFunc(this, "StaticProperties", TestStaticProperties);
            yield return new TestFunc(this, "Operators", TestOperators);
            yield return new TestFunc(this, "StringInterop", TestStringInterop);
            if (!BaseType.IsComplex)
                yield return new TestFunc(this, "SerializationJson", SerializationJson);

            if (BaseType.HasArithmetics)
            {
                yield return new InvariantTestFunc(this, "InvariantId", "$V0 == +$V0");
                yield return new InvariantTestFunc(this, "InvariantDouble", "$V0 + $V0 == 2 * $V0");
                yield return new InvariantTestFunc(this, "InvariantTriple", "$V0 + $V0 + $V0 == 3 * $V0");
                yield return new InvariantTestFunc(this, "InvariantCommutative", "$V0 + $V1 == $V1 + $V0", "$V0 * $V1 == $V1 * $V0");
                yield return new InvariantTestFunc(this, "InvariantAssociative", "$V0 * ($V1 + $V2) == $V0 * $V1 + $V0 * $V2");
                if (BaseType.IsSigned)
                {
                    yield return new InvariantTestFunc(this, "InvariantIdNeg", "$V0 == -(-$V0)");
                    yield return new InvariantTestFunc(this, "InvariantCommutativeNeg", "$V0 - $V1 == -($V1 - $V0)");
                    yield return new InvariantTestFunc(this, "InvariantAssociativeNeg", "$V0 * ($V1 - $V2) == $V0 * $V1 - $V0 * $V2");
                }
                yield return new InvariantTestFunc(this, "TriangleInequality",
                    "$V0.Length + $V1.Length >= ($V0 + $V1).Length",
                    "$V0.LengthSqr + $V1.LengthSqr >= ($V0 + $V1).LengthSqr",
                    "$V0.Norm + $V1.Norm >= ($V0 + $V1).Norm",
                    "$V0.Norm1 + $V1.Norm1 >= ($V0 + $V1).Norm1",
                    "$V0.Norm2 + $V1.Norm2 >= ($V0 + $V1).Norm2",
                    "$V0.NormMax + $V1.NormMax >= ($V0 + $V1).NormMax");
                yield return new InvariantTestFunc(this, "InvariantNorm", "$V0.NormMax <= $V0.Norm");
                if (Components == 3 && !BaseType.IsComplex)
                    yield return new InvariantTestFunc(this, "InvariantCrossDot", "glm.Abs(glm.Dot($V0, glm.Cross($V0, $V1))) < 0.1");
            }

            // Random
            if (BaseType.IsInteger)
            {
                for (var i = 0; i < 5; ++i)
                {
                    var min = Random.Next(-5, 5);
                    if (!BaseType.IsSigned)
                        min = Math.Abs(min);
                    var max = min + Random.Next(1, 5);
                    var range = max - min + 1;
                    yield return new DistributionTestFunc(this, "RandomUniform" + i, "Random" + (i % 2 == 0 ? "" : "Uniform"), min + ", " + (max + 1), (min + max) / 2.0, (range * range - 1) / 12.0);
                }
                for (var i = 0; i < 5; ++i)
                {
                    var lambda = Random.NextDouble() * 3 + 0.5;
                    yield return new DistributionTestFunc(this, "RandomPoisson" + i, "RandomPoisson", lambda.ToString(CultureInfo.InvariantCulture), lambda, lambda);
                }
            }
            else if (BaseType.IsFloatingPoint)
            {
                for (var i = 0; i < 5; ++i)
                {
                    var min = Random.Next(-5, 5);
                    if (!BaseType.IsSigned)
                        min = Math.Abs(min);
                    var max = min + Random.Next(1, 5);
                    var range = max - min;
                    yield return new DistributionTestFunc(this, "RandomUniform" + i, "Random" + (i % 2 == 0 ? "" : "Uniform"), min + ", " + max, (min + max) / 2.0, range * range / 12.0);
                }
                for (var i = 0; i < 5; ++i)
                {
                    var mean = Random.NextDouble() * 4 - 2;
                    var variance = Random.NextDouble() * 10;
                    yield return new DistributionTestFunc(this, "RandomGaussian" + i, "Random" + (i % 2 == 0 ? "Normal" : "Gaussian"), ConstantSuffixFor(mean.ToString(CultureInfo.InvariantCulture)) + ", " + ConstantSuffixFor(variance.ToString(CultureInfo.InvariantCulture)), mean, variance);
                }
                for (var i = 0; i < 5; ++i)
                {
                    yield return new DistributionTestFunc(this, "RandomNormal" + i, "RandomNormal", "", 0.0, 1.0);
                }
            }
        }
    }
}


text:
<?php

App::uses('AppController', 'Controller', 'WordAnnotationType');

class WordAnnotationTypeChoicesController extends AppController {
    public $helpers = array('Html', 'Form');

    public function index($wordAnnotationTypeId) {
        if ($this->Auth->user()['role_id'] != 1) {
            $this->Session->setFlash('This action needs administrative privileges.');
            $this->redirect('/');
        }
        $wordAnnotationTypeModel = ClassRegistry::init('WordAnnotationType');
        $wordAnnotationTypeModel->recursive = 0;
        $wordAnnotationType = $wordAnnotationTypeModel->findById($wordAnnotationTypeId);

        $this->WordAnnotationTypeChoice->recursive = 0;
        $wordAnnotationTypeChoices = $this->WordAnnotationTypeChoice->find('all', array(
                                  'conditions' => array('word_annotation_type_id' => $wordAnnotationTypeId),
                                  'order' =>'position'));
        $this->set('wordAnnotationTypeChoices', $wordAnnotationTypeChoices);
        $this->set('wordAnnotationType', $wordAnnotationType);
    }

    public function add($wordAnnotationTypeId) {
        if ($this->Auth->user()['role_id'] != 1) {
            $this->Session->setFlash('This action needs administrative privileges.');
            $this->redirect('/');
        }
        if ($this->request->is('post')) {
            $this->WordAnnotationTypeChoice->create();
            $data = $this->request->data;
            $maxPosition = $this->WordAnnotationTypeChoice->find('first', array(
                                            'fields' =>  array('max(position) AS max_pos', 'count(*) AS total_count'),
                                            'conditions' => array('word_annotation_type_id' => $wordAnnotationTypeId)
                                        ));
            if ($maxPosition[0]['total_count'] == 0) {
                $data['WordAnnotationTypeChoice']['position'] = 0;
            } else {
                $data['WordAnnotationTypeChoice']['position'] = $maxPosition[0]['max_pos']+1;
            }
            $data['WordAnnotationTypeChoice']['word_annotation_type_id'] = $wordAnnotationTypeId;
            if ($this->WordAnnotationTypeChoice->save($data)) {
                $this->Session->setFlash(__('New word annotation type choice has been saved.'), 'flashes/success');
                return $this->redirect(array('action' => 'index', $wordAnnotationTypeId));
            }
            $this->Session->setFlash(__('Unable to add new word annotation type choice.'));
        }
        $this->set('wordAnnotationTypeId', $wordAnnotationTypeId);
    }

    public function move($wordAnnotationTypeId, $position, $offset) {
        if ($this->Auth->user()['role_id'] != 1) {
            $this->Session->setFlash('This action needs administrative privileges.');
            $this->redirect('/');
        }
        $this->WordAnnotationTypeChoice->recursive = 0;
        $current = $this->WordAnnotationTypeChoice->find('first', array('conditions'=> array('word_annotation_type_id'=>$wordAnnotationTypeId, 'position'=>$position)));
        $neighbour = $this->WordAnnotationTypeChoice->find('first', array('conditions'=> array('word_annotation_type_id'=>$wordAnnotationTypeId,'position'=>$position+$offset)));
        $current['WordAnnotationTypeChoice']['position'] = $position + $offset;
        $neighbour['WordAnnotationTypeChoice']['position'] = $position;
        if ($this->WordAnnotationTypeChoice->save($current) && $this->WordAnnotationTypeChoice->save($neighbour)) {
            $this->Session->setFlash(__('Successfully changed order.'), 'flashes/success');
            return $this->redirect(array('action' => 'index', $wordAnnotationTypeId));
        }
        $this->Session->setFlash(__('Unable to change order.'));

    }

    public function delete($wordAnnotationTypeId, $id) {
        if ($this->Auth->user()['role_id'] != 1) {
            $this->Session->setFlash('This action needs administrative privileges.');
            $this->redirect('/');
        }
        if ($this->request->is('get')) {
            throw new MethodNotAllowedException();
        }

        if ($this->WordAnnotationTypeChoice->delete($id)) {
            $this->Session->setFlash(
                __('Word annotation type choice (id: %s) was successfully deleted.', h($id)),
                'flashes/success'
            );
            return $this->redirect(array('action' => 'index', $wordAnnotationTypeId));
        }
    }

    public function edit($wordAnnotationTypeId, $id = null) {
        if ($this->Auth->user()['role_id'] != 1) {
            $this->Session->setFlash('This action needs administrative privileges.');
            $this->redirect('/');
        }
        if (!$id) {
            throw new NotFoundException(__('Invalid word annotation type choice'));
        }

        $wordAnnotationTypeChoice = $this->WordAnnotationTypeChoice->findById($id);
        if (!$wordAnnotationTypeChoice) {
            throw new NotFoundException(__('Invalid word annotation type choice'));
        }

        if ($this->request->is(array('post', 'put'))) {
            $this->WordAnnotationTypeChoice->id = $id;
            if ($this->WordAnnotationTypeChoice->save($this->request->data)) {
                $this->Session->setFlash(__('Your word annotation type choice has been updated.'), 'flashes/success');
                return $this->redirect(array('action' => 'index', $wordAnnotationTypeId));
            }
            $this->Session->setFlash(__('Unable to update your word annotation type choice.'));
        }

        if (!$this->request->data) {
            $this->request->data = $wordAnnotationTypeChoice;
        }
        $this->set('wordAnnotationTypeId', $wordAnnotationTypeId);
    }
}

?>


text:
layout: post
title: 38 Codigo
date: 2017-06-04 dg 01:36
description: Editar código para ser marcado en un lugar del documento
keywords: code
coments: true
---

Teniendo en cuenta estas templates:

```
s 	#+BEGIN_SRC ... #+END_SRC
e 	#+BEGIN_EXAMPLE ... #+END_EXAMPLE
q 	#+BEGIN_QUOTE ... #+END_QUOTE
v 	#+BEGIN_VERSE ... #+END_VERSE
c 	#+BEGIN_CENTER ... #+END_CENTER
l 	#+BEGIN_EXPORT latex ... #+END_EXPORT
L 	#+LATEX:
h 	#+BEGIN_EXPORT html ... #+END_EXPORT
H 	#+HTML:
a 	#+BEGIN_EXPORT ascii ... #+END_EXPORT
A 	#+ASCII:
i 	#+INDEX: line
I 	#+INCLUDE: line
```

Para insertar código `<s <TAB>` o lo que es lo mismo `<s` y pulsar la tecla del tabulador.

Seguiremos la misma lógica para todos los tipos de plantillas.

Obtienes esto:

```
#+BEGIN_SRC

#+END_SRC
```

Escribes el tipo de lenguaje que tieres resaltar así:

```
#+BEGIN_SRC python

#+END_SRC
```

Cuando exportas a html se visualiza el código con el lexer oportuno y sale pintadito según el lenguaje.


text:
package org.jboss.resteasy.spi.interception;

import org.jboss.resteasy.core.ServerResponse;

/**
 * Invoked in order, gives you access to the response before MessageBodyReader and Writers get invoked.
 *
 * @author Bill Burke
 * @version $Revision: 1 $
 *
 * @deprecated The Resteasy interceptor facility introduced in release 2.x
 * is replaced by the JAX-RS 2.0 compliant interceptor facility in release 3.0.x.
 *
 * @see jaxrs-api (https://jcp.org/en/jsr/detail?id=339)
 */
@Deprecated
public interface PostProcessInterceptor
{
   void postProcess(ServerResponse response);
}


text:
<?php defined('PATH_ACCESS') or exit("NO DICE! Don't Play Too Smart.");

/**
|--------------------------------------------------------------------------
| App Registered Email
|--------------------------------------------------------------------------
*/
$config['email_info_email']         = 'info@domain.com';
$config['email_noreply_email']      = 'noreply@domain.com';
$config['email_error_log_email']    = 'error@domain.com';
$config['email_copyright_email']    = 'copyright@domain.com';

/**
|--------------------------------------------------------------------------
| App Email Settings.
| see system/libraries/email.class.php AND system/libraries/phpmailer/ for
| more email configuration of Open Source PHPMailer
|--------------------------------------------------------------------------
*/
if (SITE_ENV == 'production' || SITE_ENV == 'testing') { // PRODUCTION and TESTING Environment
    // PRODUCTION Environment Email Settings
    $config['smtp_echo_error']    = false; // Turn off failure error for production/ mode
    $config['smtp_host']          = 'smtp.domain.com';
    $config['smtp_user']          = 'noreply@domain.com'; //
    $config['smtp_pass']          = 'smtppass';
    $config['smtp_secure']        = '';
    $config['smtp_port']          = 587;
    $config['smtp_auth']          = true;
    // Alternative smtp server, using GMAIL:
    $config['alt_smtp_host']      = 'smtp.gmail.com'; // for GMAIL smtp host
    $config['alt_smtp_user']      = 'username.mail@gmail.com'; //gmail email
    $config['alt_smtp_pass']      = 'gmailpass'; // gmail password
    $config['alt_smtp_secure']    = 'tls'; //'tls' for GMAIl.  Sets connection prefix. Options are "", "ssl" or "tls"
    $config['alt_smtp_port']      = 587; // 587 for GMAIl.
    $config['alt_smtp_auth']      = true; // Authenticate SMTP

} else {
    // DEVELOPMENT Environment Email Settings
    $config['smtp_echo_error']    = true; // Turn on failre error for development mode
    $config['smtp_host']          = '127.0.0.1';
    $config['smtp_user']          = '';
    $config['smtp_pass']          = '';
    $config['smtp_secure']        = '';
    $config['smtp_port']          = 25;
    $config['smtp_auth']          = true; //
     // Alternative smtp server
    $config['alt_smtp_host']      = 'localhost';
    $config['alt_smtp_user']      = '';
    $config['alt_smtp_pass']      = '';
    $config['alt_smtp_secure']    = '';
    $config['alt_smtp_port']      = 25;
    $config['alt_smtp_auth']      = true; //
}

$config['email_from_email']         = $config['email_info_email'];
$config['email_from_name']          = $config['name'];
$config['email_reply_to_email']     = $config['email_info_email'];
$config['email_reply_to_name']      = $config['name'];


text:
define([
    'jquery',
    'jasmine-jquery',
    'streamhub-sdk/content',
    'streamhub-sdk/content/views/tiled-attachment-list-view',
    'streamhub-sdk/content/views/oembed-view'],
function($, jasmineJquery, Content, TiledAttachmentListView) {
    'use strict';

    describe('TiledAttachmentListView', function () {
        var oembedAttachment = {
            provider_name: "Twimg",
            provider_url: "http://pbs.twimg.com",
            type: "photo",
            url: "http://pbs.twimg.com/media/BQGNgs9CEAEhmEF.jpg"
        };
        var content = new Content({ body: 'what' });

        describe('when constructed', function() {

            describe('with no arguments or options', function() {
                var tiledAttachmentListView = new TiledAttachmentListView();
                it('is instance of TiledAttachmentListView', function() {
                    expect(tiledAttachmentListView).toBeDefined();
                    expect(tiledAttachmentListView instanceof TiledAttachmentListView).toBe(true);
                });
            });

            describe('with opts.content', function() {
                var tiledAttachmentListView = new TiledAttachmentListView({ content: content });
                it('is instance of TiledAttachmentListView', function() {
                    expect(tiledAttachmentListView).toBeDefined();
                    expect(tiledAttachmentListView instanceof TiledAttachmentListView).toBe(true);
                });
            });
        });

        describe('when removing an attachment', function () {

            it('calls .retile', function () {
                var tiledAttachmentListView = new TiledAttachmentListView({ content: content });
                tiledAttachmentListView.add(oembedAttachment);
                spyOn(tiledAttachmentListView, 'retile');
                tiledAttachmentListView.remove(oembedAttachment);
                expect(tiledAttachmentListView.retile).toHaveBeenCalled();
            });
        });

        describe('when adding an attachment', function() {

            it('calls .retile', function () {
                var tiledAttachmentListView = new TiledAttachmentListView({ content: content });
                spyOn(tiledAttachmentListView, 'retile');
                tiledAttachmentListView.add(oembedAttachment);
                expect(tiledAttachmentListView.retile).toHaveBeenCalled();
            });

            describe('with photo attachment', function() {
                var tiledAttachmentListView = new TiledAttachmentListView({ content: content });
                tiledAttachmentListView.setElement($('

'));
                tiledAttachmentListView.render();
                oembedAttachment.type = 'photo';
                tiledAttachmentListView.add(oembedAttachment);

                it('is a tiled attachment (appended to .content-attachments-tiled)', function() {
                    expect(tiledAttachmentListView.$el.find('.content-attachments-tiled')).toContain('.content-attachment');
                });
            });

            describe('with video attachment', function() {
                var tiledAttachmentListView = new TiledAttachmentListView({ content: content });
                tiledAttachmentListView.setElement($('

'));
                tiledAttachmentListView.render();
                oembedAttachment.type = 'video';
                tiledAttachmentListView.add(oembedAttachment);

                it('is a tiled attachment (appended to .content-attachments-tiled)', function() {
                    expect(tiledAttachmentListView.$el.find('.content-attachments-tiled')).toContain('.content-attachment');
                });
            });

            describe('with link attachment', function() {
                var tiledAttachmentListView = new TiledAttachmentListView({ content: content });
                tiledAttachmentListView.setElement($('

'));
                tiledAttachmentListView.render();
                oembedAttachment.type = 'link';
                tiledAttachmentListView.add(oembedAttachment);

                it('is not inserted', function() {
                    expect(tiledAttachmentListView.$el.find('.content-attachments-tiled')).toBeEmpty();
                });
            });

            describe('with rich attachment', function() {
                var tiledAttachmentListView = new TiledAttachmentListView({ content: content });
                tiledAttachmentListView.setElement($('

'));
                tiledAttachmentListView.render();
                oembedAttachment.type = 'rich';
                tiledAttachmentListView.add(oembedAttachment);

                it('is not inserted', function() {
                    expect(tiledAttachmentListView.$el.find('.content-attachments-tiled')).toBeEmpty();
                });
            });
        });

        describe('when rendering', function() {

            describe('with 1 tiled attachment', function() {
                var tiledAttachmentListView = new TiledAttachmentListView({ content: content });
                tiledAttachmentListView.setElement($('

'));
                tiledAttachmentListView.render();
                oembedAttachment.type = 'photo';
                tiledAttachmentListView.add(oembedAttachment);

                it('has .content-attachments-1 class name', function() {
                    expect(tiledAttachmentListView.$el.find('.content-attachments-tiled')).toHaveClass('content-attachments-1');
                    expect(tiledAttachmentListView.$el.find('.content-attachments-tiled .content-attachment')).toHaveClass('content-attachment-square-tile');
                });
            });

            describe('with 2 tiled attachments', function() {
                var tiledAttachmentListView = new TiledAttachmentListView({ content: content });
                tiledAttachmentListView.setElement($('

'));
                tiledAttachmentListView.render();
                oembedAttachment.type = 'photo';
                for (var i=0; i < 2; i++) {
                    tiledAttachmentListView.add(oembedAttachment);
                }

                it('has .content-attachments-2 class name', function() {
                    expect(tiledAttachmentListView.$el.find('.content-attachments-tiled')).toHaveClass('content-attachments-2');
                    expect(tiledAttachmentListView.$el.find('.content-attachments-tiled .content-attachment')).toHaveClass('content-attachment-square-tile');
                });
            });

            describe('with 3 tiled attachments', function() {
                var tiledAttachmentListView = new TiledAttachmentListView({ content: content });
                tiledAttachmentListView.setElement($('

'));
                tiledAttachmentListView.render();
                oembedAttachment.type = 'photo';
                for (var i=0; i < 3; i++) {
                    tiledAttachmentListView.add(oembedAttachment);
                }

                it('has .content-attachments-3 class name', function() {
                    expect(tiledAttachmentListView.$el.find('.content-attachments-tiled')).toHaveClass('content-attachments-3');
                    expect(tiledAttachmentListView.$el.find('.content-attachments-tiled > *:nth-child(1) .content-attachment'))
                        .toHaveClass('content-attachment-horizontal-tile');
                    expect(tiledAttachmentListView.$el.find('.content-attachments-tiled > *:nth-child(2) .content-attachment'))
                        .toHaveClass('content-attachment-square-tile');
                    expect(tiledAttachmentListView.$el.find('.content-attachments-tiled > *:nth-child(3) .content-attachment'))
                        .toHaveClass('content-attachment-square-tile');
                });
            });

            describe('with 4 tiled attachments', function() {
                var tiledAttachmentListView = new TiledAttachmentListView({ content: content });
                tiledAttachmentListView.setElement($('

'));
                tiledAttachmentListView.render();
                oembedAttachment.type = 'photo';
                for (var i=0; i < 4; i++) {
                    tiledAttachmentListView.add(oembedAttachment);
                }

                it('has .content-attachments-4 class name', function() {
                    expect(tiledAttachmentListView.$el.find('.content-attachments-tiled')).toHaveClass('content-attachments-4');
                    expect(tiledAttachmentListView.$el.find('.content-attachments-tiled .content-attachment')).toHaveClass('content-attachment-square-tile');
                });
            });

            describe('with > 4 tiled attachments', function() {
                var tiledAttachmentListView = new TiledAttachmentListView({ content: content });
                tiledAttachmentListView.setElement($('

'));
                tiledAttachmentListView.render();
                oembedAttachment.type = 'photo';
                for (var i=0; i < 9; i++) {
                    tiledAttachmentListView.add(oembedAttachment);
                }

                it('has only .content-attachments-tiled class name', function() {
                    expect(tiledAttachmentListView.$el.find('.content-attachments-tiled')[0].className).toBe('content-attachments-tiled');
                    expect(tiledAttachmentListView.$el.find('.content-attachments-tiled .content-attachment')).toHaveClass('content-attachment-horizontal-tile');
                });
            });
        });

        describe('when clicking an attachment tile', function() {
            var tiledAttachmentListView,
                tiledAttachmentEl,
                tiledAttachmentListViewOpts = { content: content };

            it('emits focusContent.hub event', function() {
                tiledAttachmentListView = new TiledAttachmentListView(tiledAttachmentListViewOpts);
                tiledAttachmentListView.setElement($('

'));
                tiledAttachmentListView.render();
                oembedAttachment.type = 'photo';
                for (var i=0; i < 3; i++) {
                    tiledAttachmentListView.add(oembedAttachment);
                }
                tiledAttachmentEl = tiledAttachmentListView.$el.find('.content-attachment:first');

                var spyFocusAttachmentEvent = spyOnEvent(tiledAttachmentListView.el, 'focusContent.hub');
                var tileClicked = false;
                tiledAttachmentListView.$el.on('focusContent.hub', function() {
                    tileClicked = true;
                });

                tiledAttachmentEl.trigger('click');
                expect(tileClicked).toBe(true);
                expect(spyFocusAttachmentEvent).toHaveBeenTriggered();
            });
        });
    });

});