text:
package com.appspot.nfcsmarttag;

import com.appspot.nfcsmarttag.url.InvalidInputException;
import com.appspot.nfcsmarttag.url.SimpleKeyStore;
import com.appspot.nfcsmarttag.url.SmartTagKeyStoreInterface;
import com.appspot.nfcsmarttag.url.Url4Tag;

import java.io.IOException;
import javax.servlet.http.*;

@SuppressWarnings("serial")
public class NfcSmartTagServlet extends HttpServlet {

  private static final String PAGE_HEADER =
      "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"
      + ""
      + "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">"
      + "<title>NFC Smart Tag Test Server</title>"
      + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.4, user-scalable=yes\">"
      + "";

  private static final String PAGE_FOOTER = "";

  SmartTagKeyStoreInterface keyStore;

  public NfcSmartTagServlet() {
    keyStore = new SimpleKeyStore();
  }

  private static String hexString(byte[] byteArray) {
    StringBuilder stringBuilder = new StringBuilder();
    for (byte b : byteArray) {
      stringBuilder.append(String.format("%02x", b));
    }
    return stringBuilder.toString();
  }

  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    resp.setContentType("text/html");
    String nv = req.getParameter("nv");
    resp.getWriter().println(PAGE_HEADER);

    if (nv != null && !nv.isEmpty()) {
      Url4Tag url4tag;
      try {
        url4tag = Url4Tag.fromEncodedValue(keyStore, nv);
        resp.getWriter().println("
");
        resp.getWriter().println("Tag Id:" + hexString(url4tag.getTagId()));
        resp.getWriter().println("SmartTagInfo:\n" + url4tag.getNfcSmartTagInfo());
        resp.getWriter().println("
");
      } catch (InvalidInputException e) {
        resp.getWriter().println("Decoding error");
      }
    } else {
      resp.getWriter().println("nv parameter is missing");
    }
    resp.getWriter().println(PAGE_FOOTER);
  }
}


text:
package com.netflix.conductor.rest.controllers;

import java.util.Map;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.netflix.conductor.core.events.queue.DefaultEventQueueProcessor;
import com.netflix.conductor.model.TaskModel.Status;

import io.swagger.v3.oas.annotations.Operation;

import static com.netflix.conductor.rest.config.RequestMappingConstants.QUEUE;

@RestController
@RequestMapping(QUEUE)
public class QueueAdminResource {

    private final DefaultEventQueueProcessor defaultEventQueueProcessor;

    public QueueAdminResource(DefaultEventQueueProcessor defaultEventQueueProcessor) {
        this.defaultEventQueueProcessor = defaultEventQueueProcessor;
    }

    @Operation(summary = "Get the queue length")
    @GetMapping(value = "/size")
    public Map<String, Long> size() {
        return defaultEventQueueProcessor.size();
    }

    @Operation(summary = "Get Queue Names")
    @GetMapping(value = "/")
    public Map<Status, String> names() {
        return defaultEventQueueProcessor.queues();
    }

    @Operation(summary = "Publish a message in queue to mark a wait task as completed.")
    @PostMapping(value = "/update/{workflowId}/{taskRefName}/{status}")
    public void update(
            @PathVariable("workflowId") String workflowId,
            @PathVariable("taskRefName") String taskRefName,
            @PathVariable("status") Status status,
            @RequestBody Map<String, Object> output)
            throws Exception {
        defaultEventQueueProcessor.updateByTaskRefName(workflowId, taskRefName, output, status);
    }

    @Operation(summary = "Publish a message in queue to mark a wait task (by taskId) as completed.")
    @PostMapping("/update/{workflowId}/task/{taskId}/{status}")
    public void updateByTaskId(
            @PathVariable("workflowId") String workflowId,
            @PathVariable("taskId") String taskId,
            @PathVariable("status") Status status,
            @RequestBody Map<String, Object> output)
            throws Exception {
        defaultEventQueueProcessor.updateByTaskId(workflowId, taskId, output, status);
    }
}

redpajama_set_name: RedPajamaGithub


text:
iperflexer.infrastructure.index_builder.create_toctree
======================================================

.. currentmodule:: iperflexer.infrastructure.index_builder

.. autofunction:: create_toctree


text:
package org.camunda.bpm.engine.rest.dto.authorization;

import org.camunda.bpm.engine.rest.util.ResourceUtil;

/**
 * @author Daniel Meyer
 *
 */
public class AuthorizationCheckResultDto {

  protected String permissionName;
  protected String resourceName;
  protected String resourceId;

  protected Boolean isAuthorized;

  public AuthorizationCheckResultDto() {
  }

  public AuthorizationCheckResultDto(boolean userAuthorized, String permissionName, ResourceUtil resource, String resourceId) {
    isAuthorized = userAuthorized;
    this.permissionName = permissionName;
    resourceName = resource.resourceName();
    this.resourceId = resourceId;
  }

  public String getPermissionName() {
    return permissionName;
  }
  public void setPermissionName(String permissionName) {
    this.permissionName = permissionName;
  }

  public Boolean isAuthorized() {
    return isAuthorized;
  }

  public void setAuthorized(Boolean isAuthorized) {
    this.isAuthorized = isAuthorized;
  }

  public String getResourceName() {
    return resourceName;
  }
  public void setResourceName(String resourceName) {
    this.resourceName = resourceName;
  }

  public String getResourceId() {
    return resourceId;
  }

  public void setResourceId(String resourceId) {
    this.resourceId = resourceId;
  }
}


text:
* [Installation and Administration Guide](installation_administration.md)

* [User and Programmer's Guide](user_programmers.md)

---------------------------------------------------------------------------------------------------------
This project is part of FIWARE.
[https://www.fiware.org/](https://www.fiware.org/)

FIWARE catalogue: [2D-UI GE](http://catalogue.fiware.org/enablers/2d-ui)


text:
package com.facebook.stetho.inspector.elements.android;

import android.app.Activity;
import android.app.Application;

import com.facebook.stetho.common.Accumulator;
import com.facebook.stetho.inspector.elements.AbstractChainedDescriptor;
import com.facebook.stetho.inspector.elements.NodeType;

import java.lang.ref.WeakReference;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;

final class ApplicationDescriptor extends AbstractChainedDescriptor<Application> {
  private final Map<Application, ElementContext> mElementToContextMap =
      Collections.synchronizedMap(new IdentityHashMap<Application, ElementContext>());

  private final ActivityTracker mActivityTracker = ActivityTracker.get();

  private ElementContext getContext(Application element) {
    return mElementToContextMap.get(element);
  }

  @Override
  protected void onHook(Application element) {
    ElementContext context = new ElementContext();
    context.hook(element);
    mElementToContextMap.put(element, context);
  }

  @Override
  protected void onUnhook(Application element) {
    ElementContext context = mElementToContextMap.remove(element);
    context.unhook();
  }

  @Override
  protected NodeType onGetNodeType(Application element) {
    return NodeType.ELEMENT_NODE;
  }

  @Override
  protected void onGetChildren(Application element, Accumulator<Object> children) {
    ElementContext context = getContext(element);
    List<WeakReference<Activity>> activities = context.getActivitiesList();
    // We report these in reverse order so that the newer ones show up on top
    for (int i = activities.size() - 1; i >= 0; --i) {
      Activity activity = activities.get(i).get();
      if (activity != null) {
        children.store(activity);
      }
    }
  }

  private class ElementContext {
    private Application mElement;

    public ElementContext() {
    }

    public void hook(Application element) {
      mElement = element;
      mActivityTracker.registerListener(mListener);
    }

    public void unhook() {
      mActivityTracker.unregisterListener(mListener);
      mElement = null;
    }

    public List<WeakReference<Activity>> getActivitiesList() {
      return mActivityTracker.getActivitiesView();
    }

    private final ActivityTracker.Listener mListener = new ActivityTracker.Listener() {
      @Override
      public void onActivityAdded(Activity activity) {
        // TODO: once we have the ability to report fine-grained updates, do that here
      }

      @Override
      public void onActivityRemoved(Activity activity) {
        // TODO: once we have the ability to report fine-grained updates, do that here
      }
    };
  }
}


text:
from django.contrib import admin

"""
This demo admin class shows you how to add TinyMCE to a textarea and use language-aware
inlines:

from django import forms
from feincms import translations

from models import Demo, DemoTranslation

class TinyMCEAdminForm(forms.ModelForm):
    # Use this form class if you want to add TinyMCE to a text input.
    class Meta:
        widgets = {
            'text': forms.widgets.Textarea(attrs={'class':'vLargeTextField tinymce'}),
        }

class DemoAdmin(admin.ModelAdmin):
    # Add the TinyMCE Form class for TinyMCE support:
    form = TinyMCEAdminForm
    list_display = ('name', )
    # For multi-language apps add language-aware inlines.
    # raw_id foreign key to page opens a nice tree view and lets you select a page.
    inlines=[translations.admin_translationinline(DemoTranslation, raw_id_fields = ('page',),
                                                   form=TinyMCEAdminForm)]

    class Media:
        # add the TinyMCE Java scripts
        js = (
            'https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js',
            'tinymce/tiny_mce.js',
            'tinymce_admin/init.js',
        )

admin.site.register(Demo, DemoTranslation)
"""


text:
package org.onosproject.store.service;

/**
 * Transactional Set data structure.
 * <p>
 * A TransactionalSet is implemented with the help of TransactionalMap data structure.
 * All operations performed on this set within a transaction boundary are invisible externally
 * until the point when the transaction commits. A commit usually succeeds in the absence of conflicts.
 *
 * @param <E> type of element.
 */
public interface TransactionalSet<E> {

    /**
     * Adds the specified element to this set if it is not already present
     * (optional operation).  More formally, adds the specified element
     * <tt>e</tt> to this set if the set contains no element <tt>e2</tt>
     * such that
     * <tt>(e==null ? e2==null : e.equals(e2))</tt>.
     * If this set already contains the element, the call leaves the set
     * unchanged and returns <tt>false</tt>.  In combination with the
     * restriction on constructors, this ensures that sets never contain
     * duplicate elements.
     *
     * @param e element to be added to this set
     * @return <tt>true</tt> if this set did not already contain the specified
     *         element
     */
    boolean add(E e);

    /**
     * Removes the specified element from this set if it is present
     * (optional operation).  More formally, removes an element <tt>e</tt>
     * such that
     * <tt>(o==null ? e==null : o.equals(e))</tt>, if
     * this set contains such an element.  Returns <tt>true</tt> if this set
     * contained the element (or equivalently, if this set changed as a
     * result of the call).  (This set will not contain the element once the
     * call returns.)
     *
     * @param e element to be removed to this set
     * @return <tt>true</tt> if this set contained the specified element
     */
    boolean remove(E e);

    /**
     * Returns <tt>true</tt> if this set contains the specified element.
     * More formally, returns <tt>true</tt> if and only if this set
     * contains an element <tt>e</tt> such that
     * <tt>(o==null ? e==null : o.equals(e))</tt>.
     *
     * @param e element whose presence in this set is to be tested
     * @return <tt>true</tt> if this set contains the specified element
     * @throws ClassCastException if the type of the specified element
     *         is incompatible with this set
     * @throws NullPointerException if the specified element is null and this
     *         set does not permit null elements
     */
    boolean contains(E e);
}


text:
package org.apache.camel.spring.scan;

import java.io.File;
import java.io.FileInputStream;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.jar.JarFile;

import org.apache.camel.core.xml.scan.PatternBasedPackageScanFilter;
import org.apache.camel.util.CollectionHelper;

public class PatternBasedPackageScanFilterTest extends org.apache.camel.spring.scan.ScanTestSupport {

    private Set<Class<?>> allClasses;

    public void setUp() throws Exception {
        // use classes that are pretty much constants
        allClasses = new HashSet<Class<?>>();
        allClasses.add(List.class);
        allClasses.add(ArrayList.class);
        allClasses.add(LinkedList.class);
        allClasses.add(File.class);
        allClasses.add(FileInputStream.class);
        allClasses.add(RandomAccessFile.class);
        // contains file pattern but in util pkg not io
        allClasses.add(JarFile.class);
        super.setUp();
    }

    public void testNoPattersIncludeAllClasses() {
        validateMatchingSetContains(allClasses);
    }

    public void testIncludePatterns() {
        addIncludePatterns("*");
        validateMatchingSetContains(allClasses);

        filter = new PatternBasedPackageScanFilter();
        addIncludePatterns("java*");
        validateMatchingSetContains(allClasses);

        filter = new PatternBasedPackageScanFilter();
        addIncludePatterns("java.io.*");
        validateMatchingSetContains(File.class, FileInputStream.class, RandomAccessFile.class);

        filter = new PatternBasedPackageScanFilter();
        addIncludePatterns("java.util.**");
        validateMatchingSetContains(List.class, ArrayList.class, LinkedList.class, JarFile.class);

        filter = new PatternBasedPackageScanFilter();
        addIncludePatterns("java.io.*", "java.util.*");
        validateMatchingSetContains(allClasses);

        filter = new PatternBasedPackageScanFilter();
        addIncludePatterns("java.io.File");
        validateMatchingSetContains(File.class);

        filter = new PatternBasedPackageScanFilter();
        addIncludePatterns("java.io.File*");
        validateMatchingSetContains(File.class, FileInputStream.class);

        filter = new PatternBasedPackageScanFilter();
        addIncludePatterns("java.io.*File*");
        validateMatchingSetContains(File.class, FileInputStream.class, RandomAccessFile.class);

        filter = new PatternBasedPackageScanFilter();
        addIncludePatterns("java.**.*File*");
        validateMatchingSetContains(File.class, FileInputStream.class, RandomAccessFile.class, JarFile.class);

        filter = new PatternBasedPackageScanFilter();
        addIncludePatterns("java.util.*List");
        validateMatchingSetContains(List.class, ArrayList.class, LinkedList.class);

        filter = new PatternBasedPackageScanFilter();
        addIncludePatterns("java.lang", "java.lang.*");
        validateMatchingSetContains();

        filter = new PatternBasedPackageScanFilter();
        addIncludePatterns("java.lang", "java.lang.*");
        validateMatchingSetContains();
    }

    public void testExcludePatterns() {
        addExcludePatterns("*");
        validateMatchingSetContains();

        filter = new PatternBasedPackageScanFilter();
        addExcludePatterns("java*");
        validateMatchingSetContains();

        filter = new PatternBasedPackageScanFilter();
        addExcludePatterns("java.io.*");
        validateMatchingSetContains(List.class, ArrayList.class, LinkedList.class, JarFile.class);

        filter = new PatternBasedPackageScanFilter();
        addExcludePatterns("java.util.**");
        validateMatchingSetContains(File.class, FileInputStream.class, RandomAccessFile.class);

        filter = new PatternBasedPackageScanFilter();
        addExcludePatterns("java.io.*", "java.util.*");
        validateMatchingSetContains();

        filter = new PatternBasedPackageScanFilter();
        addExcludePatterns("java.io.File");
        validateMatchingSetContains(List.class, ArrayList.class, LinkedList.class, JarFile.class, FileInputStream.class, RandomAccessFile.class);

        filter = new PatternBasedPackageScanFilter();
        addExcludePatterns("java.io.File*");
        validateMatchingSetContains(List.class, ArrayList.class, LinkedList.class, JarFile.class, RandomAccessFile.class);

        filter = new PatternBasedPackageScanFilter();
        addExcludePatterns("java.io.*File*");
        validateMatchingSetContains(List.class, ArrayList.class, LinkedList.class, JarFile.class);

        filter = new PatternBasedPackageScanFilter();
        addExcludePatterns("java.**.*File*");
        validateMatchingSetContains(List.class, ArrayList.class, LinkedList.class);

        filter = new PatternBasedPackageScanFilter();
        addExcludePatterns("java.util.*List");
        validateMatchingSetContains(File.class, FileInputStream.class, RandomAccessFile.class, JarFile.class);

        filter = new PatternBasedPackageScanFilter();
        addExcludePatterns("java.lang", "java.lang.*");
        validateMatchingSetContains(allClasses);

        filter = new PatternBasedPackageScanFilter();
        addExcludePatterns("java.lang", "java.lang.*");
        validateMatchingSetContains(allClasses);
    }

    public void testExcludeHasPrecedenceOverInclude() {
        // include any classes from the util pkg but exclude those in jar
        addIncludePatterns("java.util.*");
        addExcludePatterns("java.util.jar.*");
        validateMatchingSetContains(List.class, ArrayList.class, LinkedList.class);
    }

    public void testBulkIncludeAdd() {
        // include any classes from the util pkg but exclude those in jar
        Set<String> includes = CollectionHelper.createSetContaining("java.io.*", "java.util.*");
        filter.addIncludePatterns(includes);
        validateMatchingSetContains(allClasses);
    }

    public void testBulkExcludeAdd() {
        // include any classes from the util pkg but exclude those in jar
        Set<String> excludes = CollectionHelper.createSetContaining("java.io.*", "java.util.*");
        filter.addExcludePatterns(excludes);
        validateMatchingSetContains();
    }

    protected void validateMatchingSetContains(Class<?>... matchingClasses) {
        super.validateMatchingSetContains(allClasses, matchingClasses);
    }

    protected void validateMatchingSetContains(Set<Class<?>> matchingClasses) {
        super.validateMatchingSetContains(allClasses, matchingClasses);
    }
}


text:
package com.sky.hsf1002.practicedraw1.practice;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

import com.sky.hsf1002.practicedraw1.R;

/**
 * Created by hsf1002 on 2017/10/3.
 */

public class PracticeDrawPathView extends View {
    Paint paint = new Paint();
    Path path = new Path();

    public PracticeDrawPathView(Context context) {
        super(context);
    }

    public PracticeDrawPathView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public PracticeDrawPathView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public PracticeDrawPathView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        paint.setColor(Color.RED);
        paint.setAntiAlias(true);

        path.addArc(100, 100, 200, 200, -225, 225);
        path.arcTo(200, 100, 300, 200, -180, 225, false);
        path.lineTo(200, 272);
        canvas.drawPath(path, paint);

        //path.addCircle(100, 100, 80, Path.Direction.CW);
        //path.addCircle(150, 150, 80, Path.Direction.CW);

        //path.addCircle(300, 100, 80, Path.Direction.CCW);
        //path.addCircle(350, 150, 80, Path.Direction.CCW);

        path.addCircle(500, 100, 80, Path.Direction.CW);
        path.addCircle(550, 150, 80, Path.Direction.CCW);
        canvas.drawPath(path, paint);

        paint.setStyle(Paint.Style.STROKE);
        path.moveTo(0, 0);
        path.lineTo(10, 400);
        path.rLineTo(200, 40);
        path.close();
        path.moveTo(550, 400);
        path.lineTo(300, 500);
        path.arcTo(400, 400, 500, 500, 0, 90, false/*forceMoveTo*/);
        canvas.drawPath(path, paint);

        path.quadTo(300, 100, 500, 400);
        canvas.drawPath(path, paint);

        path.cubicTo(300, 100, 500, 400, 700, 600);
        canvas.drawPath(path, paint);

        //drawBitmap(Bitmap bitmap, Rect src, RectF dst, Paint paint)
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.sample_arc);
        canvas.drawBitmap(bitmap, 500, 500, paint);
        canvas.drawPath(path, paint);

        String text = "Hello World";
        paint.setTextSize(10);
        canvas.drawText(text, 200, 300, paint);
        paint.setTextSize(16);
        canvas.drawText(text, 200, 330, paint);
        paint.setTextSize(24);
        canvas.drawText(text, 200, 360, paint);
    }
}


text:
void SDMDaodanWriteDump(struct SDMSTLibrary *libTable);

#endif


text:
module picCapt {

	"use strict";

	export class Picture {
		// Nom de l'image
		public name: string;
		// Chemin de l'image
		public path: string;
		// Dimensions
		public width: number;
		public height: number;
		// Service Defer
		public $q: ng.IQService;

		constructor ($q: ng.IQService,
			name: string,
			path: string) {
			this.$q = $q;
			this.name = name;
			this.path = path;
		}

		// Chargement d'une image
		public load(containerWidth: number): ng.IPromise<Kinetic.Image> {
			// creation promise
			let deferred = this.$q.defer();
			// calcul largeur
			this.width = containerWidth - 50;
			// nouvelle image
			let img = new Image();
			img.onload = () => {
				//calcul du ratio
				let ratio: number = img.width / img.height;
				// calul des hauteurs
				this.height = this.width / ratio;
				// creation de l'image
				let kImage = new Kinetic.Image({
					x: 0,
					y: 0,
					image: img,
					width: this.width,
					height: this.height
				});
				deferred.resolve(kImage);
			};
			img.src = this.path;
			return deferred.promise;
		}

	}
}


text:
Imports System.Data
Imports System.Drawing.Printing

Partial Class fEtiquetas_fCompras
    Inherits vis1Controles.frmBase

''' <summary>
''' Almacena la estructura simplificada de una imagen monocromática de mapa de bits.
''' </summary>
''' <remarks></remarks>
	Private Structure strImagen

		Dim lnAncho		As Integer
		Dim lnAlto		As Integer
		Dim laBytes()	As Byte

	''' <summary>
	''' Devuelve una representación de cadena de la imagen.
	''' </summary>
	''' <returns></returns>
	''' <remarks></remarks>
		Overrides Function ToString() As String

			If	laBytes IsNot Nothing	AndAlso _
				laBytes.Length > 0		Then
				Return Encoding.GetEncoding(1252).GetString(laBytes)
			Else
				Return ""
			End If

		End Function

	End Structure

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim loComandoSeleccionar As New StringBuilder()

		loComandoSeleccionar.AppendLine("SELECT		Renglones_Compras.Cod_Art		AS Cod_Art,")
		loComandoSeleccionar.AppendLine("			Renglones_Compras.Can_Art1		AS Can_Art1,")
		loComandoSeleccionar.AppendLine("			Articulos.Nom_Art				AS Nom_Art,")
		loComandoSeleccionar.AppendLine("			Articulos.Modelo				AS Modelo")
		loComandoSeleccionar.AppendLine("FROM		Compras")
		loComandoSeleccionar.AppendLine("	JOIN	Renglones_Compras ON Renglones_Compras.Documento = Compras.Documento")
		loComandoSeleccionar.AppendLine("	JOIN	Articulos ON Articulos.Cod_Art = Renglones_Compras.Cod_Art")
		loComandoSeleccionar.AppendLine("WHERE		")
		loComandoSeleccionar.AppendLine(			cusAplicacion.goFormatos.pcCondicionPrincipal)
		loComandoSeleccionar.AppendLine("ORDER BY	Renglones_Compras.Cod_Art")

        Try

            Dim loServicios As New cusDatos.goDatos
            Dim laDatosReporte As DataSet = loServicios.mObtenerTodos(loComandoSeleccionar.ToString(), "curReportes")

		'Carga la imagen en un objeto strImagen
			Dim lcArchivoImagen As String = Strings.Trim(goOpciones.mObtener("ARCLOGMONP","")) '"Logo_Guarida_BN.bmp"
			lcArchivoImagen = "~/Administrativo/Complementos/" & goCliente.pcCodigo & "/" & goEmpresa.pcCodigo & "/" & lcArchivoImagen
			lcArchivoImagen = Me.Server.MapPath(lcArchivoImagen)
			Dim loImagen As strImagen = Me.mGenerarImagen(lcArchivoImagen)

		'Prepara los textos para imprimir
			Dim loCadena As New StringBuilder()
			Dim lcImpresora As String = "\\rjg\LP2824Plus"

			For Each loRenglon As DataRow In laDatosReporte.Tables(0).Rows

				Dim lcCodigo As String =  CStr(loRenglon.Item("cod_art")).Trim()
				Dim lcNombre As String =  Strings.Left(CStr(loRenglon.Item("nom_art")).Trim(), 18)
				Dim lcModelo As String =  Strings.Left(CStr(loRenglon.Item("modelo")).Trim(), 18)
				'lcModelo = "PRM-01"
				Dim lnIzq1	As Integer = (448 - lcCodigo.Length * 1.7*8)/2		'Centrado
				Dim lnIzq2	As Integer = (448 - lcNombre.Length * 1.7*8) - 32	'Alineado a la izquierda
				Dim lnIzq3	As Integer = (448 - lcModelo.Length * 1.7*8) - 32	'Alineado a la izquierda
				Dim lnCantidad	As Integer = Math.Ceiling(CDec(loRenglon.Item("Can_Art1")))

				If (lnIzq1 < 5) Then lnIzq1 = 5
				If (lnIzq2 < 5) Then lnIzq2 = 5
				If (lnIzq3 < 5) Then lnIzq3 = 5

				loCadena.AppendLine("N")
				loCadena.AppendLine(Me.mImprimirBarra(10, 10, 0, "1", 2, 8, 50, False, lcCodigo))
				loCadena.AppendLine(Me.mImprimirImagen(10, 80, loImagen))
				loCadena.AppendLine(Me.mImprimirTexto(lnIzq1, 65,	0, "3", 1, 1, False, lcCodigo))
				loCadena.AppendLine(Me.mImprimirTexto(lnIzq2, 120,	0, "3", 1, 1, False, lcNombre))
				loCadena.AppendLine(Me.mImprimirTexto(lnIzq3, 90,	0, "4", 1, 1, False, lcModelo))
				'loCadena.AppendLine("P1")
				loCadena.AppendLine("P" & lnCantidad.ToString())

				'Exit For

			Next loRenglon

			loCadena.AppendLine("N")

			Dim lcArchivo As String = "~/Administrativo/Temporales/" & System.Guid.NewGuid().ToString("D") & ".txt"
			lcArchivo = Me.Server.MapPath(lcArchivo)

			System.IO.File.WriteAllText(lcArchivo, loCadena.ToString(), System.Text.Encoding.Default)
			shell("PRINT " & lcArchivo & " /D:" & lcImpresora)

			ScriptManager.RegisterClientScriptBlock(Me, Me.GetType(), "CerrarPagina", "window.top.close();", True)

        Catch loExcepcion As Exception

            Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _
                          "No se pudo Completar el Proceso: " & loExcepcion.Message, _
                           vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _
                           "auto", _
                           "auto")

        End Try

    End Sub

	Private Function mImprimirBarra(ByVal lnTop As Integer, ByVal lnLeft As Integer, ByVal lnRotacion As Integer, ByVal lcTipoCodigo As String, _
									ByVal lnAncho1 As Integer, ByVal lnAncho2 As Integer, ByVal lnAlto As Integer, _
									ByVal llImprimirTexto As Boolean, ByVal lcCodigo As String) As String

		Dim loComando As New StringBuilder()

		loComando.Append("B")
		loComando.Append(lnTop.ToString())
		loComando.Append(",")
		loComando.Append(lnLeft.ToString())
		loComando.Append(",")
		loComando.Append(lnRotacion.ToString())
		loComando.Append(",")
		loComando.Append(lcTipoCodigo.ToString())
		loComando.Append(",")
		loComando.Append(lnAncho1.ToString())
		loComando.Append(",")
		loComando.Append(lnAncho2.ToString())
		loComando.Append(",")
		loComando.Append(lnAlto.ToString())
		loComando.Append(",")
		loComando.Append(IIf(llImprimirTexto, "B", "N"))
		loComando.Append(",")
		loComando.Append("""" & lcCodigo.Replace("\", "\\").Replace("""", "\""") & """")

		Return loComando.ToString()

	End Function

	Private Function mImprimirTexto(ByVal lnLeft As Integer, ByVal lnTop As Integer, ByVal lnRotacion As Integer, ByVal lcFuente As String, _
									ByVal lnEscalaHorizontal As Integer, ByVal lnEscalaVertical As Integer, _
									ByVal llInvertirImagen As Boolean, ByVal lcTexto As String) As String

		Dim loComando As New StringBuilder()

		loComando.Append("A")
		loComando.Append(lnLeft.ToString())
		loComando.Append(",")
		loComando.Append(lnTop.ToString())
		loComando.Append(",")
		loComando.Append(lnRotacion.ToString())
		loComando.Append(",")
		loComando.Append(lcFuente.ToString())
		loComando.Append(",")
		loComando.Append(lnEscalaHorizontal.ToString())
		loComando.Append(",")
		loComando.Append(lnEscalaVertical.ToString())
		loComando.Append(",")
		loComando.Append(IIf(llInvertirImagen, "R", "N"))
		loComando.Append(",")
		loComando.Append("""" & lcTexto.Replace("\", "\\").Replace("""", "\""") & """")

		Return loComando.ToString()

	End Function

''' <summary>
''' Devuelve la cadena de comando para imprimir la imagen indicada.
''' </summary>
''' <param name="lnLeft">Distancia, en puntos, desde el borde izquierdo del papel.</param>
''' <param name="lnTop">Distancia, en puntos, desde el borde superior del papel.</param>
''' <param name="loImagen">Objeto strImagen con los bytes y el tamaño de la imagen a imprimir.</param>
''' <returns></returns>
''' <remarks></remarks>
	Private Function mImprimirImagen(lnLeft AS Integer, lnTop As Integer, loImagen As strImagen) As String

		Return String.Format("GW{0},{1},{2},{3},{4}" & vbLf, lnLeft.ToString(), lnTop.ToString(), _
			loImagen.lnAncho.ToString(), _
			loImagen.lnAlto.ToString(), _
			Encoding.GetEncoding(1252).GetString(loImagen.laBytes))

	End Function

''' <summary>
''' Devuelve un objeto strImagen para ser usado por mImprimirImagen.
''' </summary>
''' <param name="lcArchivo">ruta completa al archivo de imagen a cargar.</param>
''' <returns></returns>
''' <remarks></remarks>
	Private Function mGenerarImagen(lcArchivo As String) As strImagen

		Dim loBitMap As Bitmap   = Drawing.Image.FromFile(lcArchivo)
		Dim loConversor As New Drawing.ImageConverter()

		Dim laBits As Imaging.BitmapData = loBitMap.LockBits(New Rectangle(0, 0, loBitMap.Width, loBitMap.Height), Imaging.ImageLockMode.[ReadOnly], loBitMap.PixelFormat)

		Dim imageBytes As Byte() = New Byte(laBits.Height * laBits.Stride - 1) {}
		System.Runtime.InteropServices.Marshal.Copy(laBits.Scan0, imageBytes, 0, laBits.Stride * laBits.Height)

		'Dim realWidth As Integer = laBits.Width / 8
		''only works for fixed size 1bpp images where width % 8 == 0
		'If realWidth <> laBits.Stride Then
		'	Dim bytesToClear As Integer = laBits.Stride - realWidth
		'	For i As Integer = 0 To laBits.Height - 1
		'		Dim pos As Integer = realWidth + laBits.Stride * i
		'		Dim counter As Integer = 0
		'		While counter < bytesToClear
		'			imageBytes(pos) = 255
		'			counter += 1
		'			pos += 1
		'		End While
		'	Next
		'End If

		'Dim realWidth As Integer = laBits.Width / 8
		If laBits.Width <> laBits.Stride * 8 Then
			Dim bitsToClear As Integer = laBits.Stride*8 - laBits.Width
			For i As Integer = 0 To laBits.Height - 1
				Dim counter As Integer = bitsToClear
				Dim pos As Integer = (laBits.Width / 8) + laBits.Stride * i
				While (counter > 0)
					If (counter>=8)
						imageBytes(pos) = 255
					Else
						imageBytes(pos) = ( imageBytes(pos) Or (CInt(Math.Pow(2, counter))-1) )
					End If

					counter -= 8
					pos -= 1
				End While
			Next
		End If

		Dim loImagen As strImagen

		loImagen.lnAncho = laBits.Stride
		loImagen.lnAlto = laBits.Height
		loImagen.laBytes = imageBytes
		loBitMap.UnlockBits(laBits)

		Return loImagen

	End Function

End Class
'-------------------------------------------------------------------------------------------'
' Fin del codigo
'-------------------------------------------------------------------------------------------'
' RJG: 18/04/2011: Programacion inicial.
'-------------------------------------------------------------------------------------------'


text:
package io.debezium.examples.saga.customer.facade;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;

import org.apache.kafka.common.header.Header;
import org.apache.kafka.common.header.Headers;
import org.eclipse.microprofile.reactive.messaging.Incoming;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.debezium.examples.saga.customer.model.CreditLimitEvent;
import io.opentracing.Scope;
import io.opentracing.Tracer;
import io.opentracing.contrib.kafka.TracingKafkaUtils;
import io.smallrye.reactive.messaging.kafka.KafkaRecord;

@ApplicationScoped
public class KafkaEventConsumer {

    private static final Logger LOG = LoggerFactory.getLogger(KafkaEventConsumer.class);

    @Inject
    CreditEventHandler creditEventHandler;

    @Inject
    Tracer tracer;

    @Incoming("credit")
    public CompletionStage<Void> onMessage(KafkaRecord<String, CreditLimitEvent> message) throws IOException {
        return CompletableFuture.runAsync(() -> {
            try (final Scope span = tracer.scopeManager().activate(getOrdersSpanBuilder(message.getHeaders()).start())) {
                LOG.debug("Kafka message with key = {} arrived", message.getKey());

                String eventId = getHeaderAsString(message, "id");

                creditEventHandler.onCreditEvent(
                        UUID.fromString(eventId),
                        UUID.fromString(message.getKey()),
                        message.getPayload()
                );
            }
        }).thenRun(() -> message.ack());
    }

    private Tracer.SpanBuilder getOrdersSpanBuilder(Headers headers) {
        return tracer.buildSpan("orders").asChildOf(TracingKafkaUtils.extractSpanContext(headers, tracer));
    }

    private String getHeaderAsString(KafkaRecord<?, ?> record, String name) {
        Header header = record.getHeaders().lastHeader(name);
        if (header == null) {
            throw new IllegalArgumentException("Expected record header '" + name + "' not present");
        }

        return new String(header.value(), StandardCharsets.UTF_8);
    }
}


text:
@implementation PKTFile

#pragma mark - PKTModel

+ (NSDictionary *)dictionaryKeyPathsForPropertyNames {
  return @{
           @"fileID" : @"file_id",
           @"mimeType" : @"mimetype",
           @"hostedBy" : @"hosted_by",
           @"link" : @"link",
           @"thumbnailLink" : @"thumbnail_link",
           @"createdOn" : @"created_on",
           @"fileDescription" : @"description"
           };
}

+ (NSValueTransformer *)linkValueTransformer {
  return [NSValueTransformer pkt_URLTransformer];
}

+ (NSValueTransformer *)thumbnailLinkValueTransformer {
  return [NSValueTransformer pkt_URLTransformer];
}

+ (NSValueTransformer *)createdOnValueTransformer {
  return [NSValueTransformer pkt_dateValueTransformer];
}

#pragma mrk - API

+ (PKTAsyncTask *)uploadWithData:(NSData *)data fileName:(NSString *)fileName {
  PKTRequest *request = [PKTFilesAPI requestToUploadFileWithData:data fileName:fileName];
  PKTAsyncTask *requestTask = [[PKTClient currentClient] performRequest:request];

  Class klass = [self class];

  PKTAsyncTask *task = [requestTask map:^id(PKTResponse *response) {
    return [[klass alloc] initWithDictionary:response.body];
  }];

  return task;
}

+ (PKTAsyncTask *)uploadWithPath:(NSString *)filePath fileName:(NSString *)fileName {
  PKTRequest *request = [PKTFilesAPI requestToUploadFileWithPath:filePath fileName:fileName];
  PKTAsyncTask *requestTask = [[PKTClient currentClient] performRequest:request];

  Class klass = [self class];

  PKTAsyncTask *task = [requestTask map:^id(PKTResponse *response) {
    return [[klass alloc] initWithDictionary:response.body];
  }];

  return task;
}

- (PKTAsyncTask *)attachWithReferenceID:(NSUInteger)referenceID referenceType:(PKTReferenceType)referenceType {
  PKTRequest *request = [PKTFilesAPI requestToAttachFileWithID:self.fileID referenceID:referenceID referenceType:referenceType];
  PKTAsyncTask *task = [[PKTClient currentClient] performRequest:request];

  return task;
}

+ (PKTAsyncTask *)downloadFileWithURL:(NSURL *)fileURL {
  NSParameterAssert(fileURL);

  PKTRequest *request = [PKTFilesAPI requestToDownloadFileWithURL:fileURL];
  PKTAsyncTask *requestTask = [[PKTClient currentClient] performRequest:request];

  PKTAsyncTask *task = [requestTask map:^id(PKTResponse *response) {
    return response.body;
  }];

  return task;
}

+ (PKTAsyncTask *)downloadFileWithURL:(NSURL *)fileURL toFileWithPath:(NSString *)filePath {
  NSParameterAssert(fileURL);

  PKTRequest *request = [PKTFilesAPI requestToDownloadFileWithURL:fileURL toLocalFileWithPath:filePath];
  PKTAsyncTask *task = [[PKTClient currentClient] performRequest:request];

  return task;
}

- (PKTAsyncTask *)download {
  return [[self class] downloadFileWithURL:self.link];
}

- (PKTAsyncTask *)downloadToFileWithPath:(NSString *)filePath {
  return [[self class] downloadFileWithURL:self.link toFileWithPath:filePath];
}

- (NSURL *)downloadURLForImageSize:(PKTImageSize)imageSize {
  NSParameterAssert(self.link);

  return [self.link pkt_imageURLForSize:imageSize];
}

@end


text:
<?php

class Attachment implements JsonSerializable {
    private $id;
    private $title;
    private $required;
    private $needSign;

    public function jsonSerialize() {
        $data = [];
        foreach ($this as $key=>$val){
            if ($val !== null) $data[$key] = $val;
        }
        return $data;
    }

    /**
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param mixed $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * @return mixed
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * @param mixed $title
     */
    public function setTitle($title)
    {
        $this->title = $title;
    }

    /**
     * @return mixed
     */
    public function getRequired()
    {
        return $this->required;
    }

    /**
     * @param mixed $required
     */
    public function setRequired($required)
    {
        $this->required = $required;
    }

    /**
     * @return mixed
     */
    public function getNeedSign()
    {
        return $this->needSign;
    }

    /**
     * @param mixed $needSign
     */
    public function setNeedSign($needSign)
    {
        $this->needSign = $needSign;
    }

}


text:
<BroadcastMonitor>
  <updated>2015-08-05T19:45:00</updated>
  <stationName>Radio 6</stationName>
  <Current>
    <startTime>2015-08-05T19:45:00</startTime>
    <itemId>1000080544:1241457</itemId>
    <titleId>216107767</titleId>
    <itemCode>07320</itemCode>
    <itemReference></itemReference>
    <titleName>Attila</titleName>
    <artistName>Jungle By Night</artistName>
    <albumName></albumName>
    <CategoryCode>737</CategoryCode>
    <CategoryName>JAZZ</CategoryName>
    <itemDuration>231</itemDuration>
    <MultiMedia1></MultiMedia1>
    <MultiMedia2></MultiMedia2>
    <MultiMedia3></MultiMedia3>
    <MultiMedia4></MultiMedia4>
  </Current>
  <Next>
    <startTime>2015-08-05T19:48:52</startTime>
    <itemId>1000080544:1241456</itemId>
    <titleId>216122175</titleId>
    <itemCode>09456</itemCode>
    <itemReference></itemReference>
    <titleName>I Don't Know What It Is But It Sure Is Funky</titleName>
    <artistName>Ripple</artistName>
    <albumName></albumName>
    <CategoryCode>736</CategoryCode>
    <CategoryName>SOUL</CategoryName>
    <itemDuration>199</itemDuration>
    <MultiMedia1></MultiMedia1>
    <MultiMedia2></MultiMedia2>
    <MultiMedia3></MultiMedia3>
    <MultiMedia4></MultiMedia4>
  </Next>
</BroadcastMonitor>


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

    <package name="ognl" extends="struts-default">

        <action name="ognl" class="www.hwh.ognl.OgnlAction">
            <result>/ognl.jsp</result>
        </action>
        <action name="test" class="www.hwh.ognl.TestAction">
            <result type="chain">ognl</result>
        </action>

    </package>
</struts>


text:
using System;
using RethinkDb.Test.Integration;
using NUnit.Framework;

namespace RethinkDb.Test.Integration.Documentation
{
    // C# implementation of queries documented in http://www.rethinkdb.com/docs/guide/python/
    [TestFixture]
    public class TenMinuteGuide : TestBase
    {
        [Test]
        public void QuerySequence()
        {
            {
                var res = connection.Run(Query.DbCreate("test"));
                Assert.That(res.DbsCreated, Is.EqualTo(1));
            }

            // Create a new table
            {
                var res = connection.Run(Query.Db("test").TableCreate("authors"));
                Assert.That(res.TablesCreated, Is.EqualTo(1));
            }

            var table = Query.Db("test").Table<Author>("authors");
            string pk1;

            // Insert data
            {
                var res =  connection.Run(table.Insert(
                    new Author[] {
                        new Author {
                            Name = "William Adama",
                            TVShow = "Battlestar Galactica",
                            Posts = new Post[] {
                                new Post { Title = "Decommissioning speech", Content = "The Cylon War is long over..." },
                                new Post { Title = "We are at war", Content = "Moments ago, this ship received..." },
                                new Post { Title = "The new Earth", Content = "The discoveries of the past few days..." }
                            }
                        },
                        new Author {
                            Name = "Laura Roslin",
                            TVShow = "Battlestar Galactica",
                            Posts = new Post[] {
                                new Post { Title = "The oath of office", Content = "I, Laura Roslin, ..." },
                                new Post { Title = "They look like us", Content = "The Cylons have the ability..." },
                            }
                        },
                        new Author {
                            Name = "Jean-Luc Picard",
                            TVShow = "Star Trek TNG",
                            Posts = new Post[] {
                                new Post { Title = "Civil rights", Content = "There are some words I've known since..." },
                            }
                        },
                    }
                ));
                Assert.That(res.Inserted, Is.EqualTo(3));
                Assert.That(res.GeneratedKeys, Has.Length.EqualTo(3));
                pk1 = res.GeneratedKeys[0];
            }

            // All documents in a table
            {
                int count = 0;
                foreach (var rec in connection.Run(table))
                    ++count;
                Assert.That(count, Is.EqualTo(3));
            }

            // Filter documents based on a condition
            {
                int count = 0;
                foreach (var rec in connection.Run(table.Filter(r => r.Name == "William Adama")))
                {
                    Assert.That(rec.Name, Is.EqualTo("William Adama"));
                    ++count;
                }
                Assert.That(count, Is.EqualTo(1));

                count = 0;
                foreach (var rec in connection.Run(table.Filter(r => r.Posts.Length > 2)))
                {
                    Assert.That(rec.Name, Is.EqualTo("William Adama"));
                    ++count;
                }
                Assert.That(count, Is.EqualTo(1));
            }

            // Retrieve documents by primary key
            {
                var rec = connection.Run(table.Get(pk1));
                Assert.That(rec, Is.Not.Null);
            }

            // Update documents
            {
                var res = connection.Run(table.Update(r => new Author() { Type = "fictional" }));
                Assert.That(res.Replaced, Is.EqualTo(3));

                res = connection.Run(
                    table.Filter(r => r.Name == "William Adama").Update(r => new Author() { Rank = "Admiral" }));
                Assert.That(res.Replaced, Is.EqualTo(1));

                // Issue #108
                res = connection.Run(
                    table
                    .Filter(r => r.Name == "Jean-Luc Picard")
                    .Update(r => new Author() {
                        Posts = r.Posts.Append(new Post { Title = "Shakespear", Content = "What a piece of work is man..." })
                    })
                );
                Assert.That(res.Replaced, Is.EqualTo(1));
            }

            // Delete documents
            {
                var res = connection.Run(table.Filter(r => r.Posts.Length < 3).Delete());
                Assert.That(res.Deleted, Is.EqualTo(2));
            }
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/white"
    android:gravity="center"
    android:orientation="vertical" >

    <ProgressBar
        android:id="@+id/pb"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="80dp"
        android:layout_height="80dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:text="求解中...."
        android:textColor="@android:color/black"
        android:textSize="16sp" />

</LinearLayout>


text:
.column {
  -webkit-column-count: 2; /* Chrome, Safari, Opera */
  -moz-column-count: 2; /* Firefox */
  column-count: 2;
}

/* Center Heading */

p span{
  display:block;
}

#biggest {
  font: 50px;
}

/*
h3 {
  display: block;
  font-weight:bold;
}
*/

html {
  background-color: #ffffff;
}

p {
   color: #000080;
}

a:link {
  color: #800080;
}

a:visited {
  color:#ff0000;
}

/*
li {
  column-count: 2;
}
*/

body:first-child{
  line-break:auto;
}

/* Center Geico image */
img {
  align:center;
}

/* Create Horizontal line */
.hline {
  width=100%; height:1px; background-color: black;
}
/*
(1)What is important to know when linking an external file (like a stylesheet) to an HTML file?

It would be important to know:
  a) where the stylesheet is saved and where to link to it
  b) whether the selectors you need for your HTML elements are saved to the .css file.
  c) the branching of elements relative to selectors, classes, id's etc. that will be linked to.

(2)What tricks did you use to help you with positioning? How hard was it to get the site as you wanted it?

I found I could use 2 different methods:
  a) hmtl syntax: <element align="value">
  b) css syntax: display: value
It depends on the amount of code being used on particular elements.  If using the above simple syntax, fine.  However, the more elements, the more selectors...well, it can get confusing and things might counteract each other.

(3)What CSS did you use to modify the element style (like size, color, etc.)
  a) display
  b) font-weight
  c) background-color
  d) column-count
  e) align

(4)Did you modify the HTML to include classes or ids? If so, which did you chose and why?

I included a class in order to create the 2 columns:

  CSS:
    .column {
      -webkit-column-count: 2;
      -moz-column-count: 2;
      column-count: 2;
      }
  HTML:

And another for creating a horizontal line:

  CSS:
    .hline {
      width=100%; height:1px; background-color: black;
    }

  HTML:

(5)When you compared your site to the actual code base, which do you think had cleaner code that followed best practices and why?

I don't think I'm far enough along to say , however, I wondered if their code was older.   It certainly was busy and hard to read in places.  And for that last sentence alone, I do not think it followed best practices.  It's indentations were definetely lacking.

*/


text:
"""Tests for cleverhans.experimental.certification.dual_formulation."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import unittest
import numpy as np
import tensorflow as tf

from cleverhans.experimental.certification import dual_formulation
from cleverhans.experimental.certification import neural_net_params

class DualFormulationTest(unittest.TestCase):

  def test_init(self):
    # Function to test initialization of dual formulation class.
    net_weights = [[[2, 2], [3, 3], [4, 4]], [[1, 1, 1], [-1, -1, -1]]]
    net_biases = [np.transpose(np.matrix([0, 0, 0])),
                  np.transpose(np.matrix([0, 0]))]
    net_layer_types = ['ff_relu', 'ff']
    nn_params1 = neural_net_params.NeuralNetParams(net_weights, net_biases,
                                                   net_layer_types)

    test_input = np.transpose(np.matrix([0, 0]))
    true_class = 0
    adv_class = 1
    input_minval = 0
    input_maxval = 0
    epsilon = 0.1
    three_dim_tensor = tf.random_uniform(shape=(3, 1), dtype=tf.float32)
    two_dim_tensor = tf.random_uniform(shape=(2, 1), dtype=tf.float32)
    scalar = tf.random_uniform(shape=(1, 1), dtype=tf.float32)
    lambda_pos = [two_dim_tensor, three_dim_tensor]
    lambda_neg = lambda_pos
    lambda_quad = lambda_pos
    lambda_lu = lambda_pos
    nu = scalar
    dual_var = {'lambda_pos': lambda_pos, 'lambda_neg': lambda_neg,
                'lambda_quad': lambda_quad, 'lambda_lu': lambda_lu, 'nu': nu}
    dual_formulation_object = dual_formulation.DualFormulation(dual_var,
                                                               nn_params1,
                                                               test_input,
                                                               true_class,
                                                               adv_class,
                                                               input_minval,
                                                               input_maxval,
                                                               epsilon)
    self.assertIsNotNone(dual_formulation_object)

  def test_set_differentiable_objective(self):
    # Function to test the function that sets the differentiable objective.
    net_weights = [[[2, 2], [3, 3], [4, 4]], [[1, 1, 1], [-1, -1, -1]]]
    net_biases = [np.transpose(np.matrix([0, 0, 0])),
                  np.transpose(np.matrix([0, 0]))]
    net_layer_types = ['ff_relu', 'ff']
    nn_params1 = neural_net_params.NeuralNetParams(net_weights, net_biases,
                                                   net_layer_types)

    test_input = np.transpose(np.matrix([0, 0]))
    true_class = 0
    adv_class = 1
    input_minval = 0
    input_maxval = 0
    epsilon = 0.1
    three_dim_tensor = tf.random_uniform(shape=(3, 1), dtype=tf.float32)
    two_dim_tensor = tf.random_uniform(shape=(2, 1), dtype=tf.float32)
    scalar = tf.random_uniform(shape=(1, 1), dtype=tf.float32)
    lambda_pos = [two_dim_tensor, three_dim_tensor]
    lambda_neg = lambda_pos
    lambda_quad = lambda_pos
    lambda_lu = lambda_pos
    nu = scalar
    dual_var = {'lambda_pos': lambda_pos, 'lambda_neg': lambda_neg,
                'lambda_quad': lambda_quad, 'lambda_lu': lambda_lu, 'nu': nu}
    dual_formulation_object = dual_formulation.DualFormulation(dual_var,
                                                               nn_params1,
                                                               test_input,
                                                               true_class,
                                                               adv_class,
                                                               input_minval,
                                                               input_maxval,
                                                               epsilon)
    dual_formulation_object.set_differentiable_objective()
    self.assertEqual(dual_formulation_object.scalar_f.shape.as_list(), [1])
    self.assertEqual(
        dual_formulation_object.unconstrained_objective.shape.as_list(), [1, 1])
    self.assertEqual(dual_formulation_object.vector_g.shape.as_list(), [5, 1])

  def test_get_full_psd_matrix(self):
    # Function to test product with PSD matrix.
    net_weights = [[[2, 2], [3, 3], [4, 4]], [[1, 1, 1], [-1, -1, -1]]]
    net_biases = [np.transpose(np.matrix([0, 0, 0])),
                  np.transpose(np.matrix([0, 0]))]
    net_layer_types = ['ff_relu', 'ff']
    nn_params1 = neural_net_params.NeuralNetParams(net_weights, net_biases,
                                                   net_layer_types)

    test_input = np.transpose(np.matrix([0, 0]))
    true_class = 0
    adv_class = 1
    input_minval = 0
    input_maxval = 0
    epsilon = 0.1
    three_dim_tensor = tf.random_uniform(shape=(3, 1), dtype=tf.float32)
    two_dim_tensor = tf.random_uniform(shape=(2, 1), dtype=tf.float32)
    scalar = tf.random_uniform(shape=(1, 1), dtype=tf.float32)
    lambda_pos = [two_dim_tensor, three_dim_tensor]
    lambda_neg = lambda_pos
    lambda_quad = lambda_pos
    lambda_lu = lambda_pos
    nu = scalar
    dual_var = {'lambda_pos': lambda_pos, 'lambda_neg': lambda_neg,
                'lambda_quad': lambda_quad, 'lambda_lu': lambda_lu, 'nu': nu}
    dual_formulation_object = dual_formulation.DualFormulation(dual_var,
                                                               nn_params1,
                                                               test_input,
                                                               true_class,
                                                               adv_class,
                                                               input_minval,
                                                               input_maxval,
                                                               epsilon)
    matrix_h, matrix_m = dual_formulation_object.get_full_psd_matrix()
    self.assertEqual(matrix_h.shape.as_list(), [5, 5])
    self.assertEqual(matrix_m.shape.as_list(), [6, 6])

  def test_get_psd_product(self):
    # Function to test implicit product with PSD matrix.
    net_weights = [[[2, 2], [3, 3], [4, 4]], [[1, 1, 1], [-1, -1, -1]]]
    net_biases = [np.transpose(np.matrix([0, 0, 0])),
                  np.transpose(np.matrix([0, 0]))]
    net_layer_types = ['ff_relu', 'ff']
    nn_params1 = neural_net_params.NeuralNetParams(net_weights, net_biases,
                                                   net_layer_types)

    test_input = np.transpose(np.matrix([0, 0]))
    true_class = 0
    adv_class = 1
    input_minval = 0
    input_maxval = 0
    epsilon = 0.1
    three_dim_tensor = tf.random_uniform(shape=(3, 1), dtype=tf.float32)
    two_dim_tensor = tf.random_uniform(shape=(2, 1), dtype=tf.float32)
    scalar = tf.random_uniform(shape=(1, 1), dtype=tf.float32)
    lambda_pos = [two_dim_tensor, three_dim_tensor]
    lambda_neg = lambda_pos
    lambda_quad = lambda_pos
    lambda_lu = lambda_pos
    nu = scalar
    dual_var = {'lambda_pos': lambda_pos, 'lambda_neg': lambda_neg,
                'lambda_quad': lambda_quad, 'lambda_lu': lambda_lu, 'nu': nu}
    dual_formulation_object = dual_formulation.DualFormulation(dual_var,
                                                               nn_params1,
                                                               test_input,
                                                               true_class,
                                                               adv_class,
                                                               input_minval,
                                                               input_maxval,
                                                               epsilon)
    _, matrix_m = dual_formulation_object.get_full_psd_matrix()

    # Testing if the values match
    six_dim_tensor = tf.random_uniform(shape=(6, 1), dtype=tf.float32)
    implicit_product = dual_formulation_object.get_psd_product(
        six_dim_tensor)
    explicit_product = tf.matmul(matrix_m, six_dim_tensor)
    with tf.Session() as sess:
      [implicit_product_value, explicit_product_value] = sess.run(
          [implicit_product, explicit_product])
      self.assertEqual(np.shape(implicit_product_value),
                       np.shape(explicit_product_value))
      self.assertLess(np.max(np.abs(
          implicit_product_value - explicit_product_value)), 1E-5)

if __name__ == '__main__':
  unittest.main()


text:
Responsive web front-end for accessing certain representative IT services of the City of Helsinki.
Implemented using Javascript, Angular 1 and Bootstrap 3.

#### Building & development

##### Preconditions

* Install node.js: <https://nodejs.org>
* Install bower: `npm i -g bower`
* Install grunt cli: `npm i -g grunt-cli`

##### Configure project

* Clone the repository
* Run `npm install` for installing node modules. Calls also `bower install`.
  * (Optional: Run `bower install` for installing bower components)
* Copy your specific environment settings into following directory. Default configurations are read build-time from `conf/app.env.default.json`. Specific settings for a target env may be overridden in
  * `custom/conf/app.env.dev.json`
  * `custom/conf/app.env.test1.json`
  * `custom/conf/app.env.test2.json`
   * `custom/conf/app.env.test3.json`
  * `custom/conf/app.env.prod.json`

##### Building

* `grunt` for building for default target
* `grunt build:dev|test1|test2|test3|prod` for building for a specific configuration
* `grunt preparedeploy` after building for preparing build output for deployment, if necessary. Calls a postbuild script in `custom/tools`

##### Running on localhost

* `grunt serve` for preview of the development content
* `grunt serve:dist` for preview of the distribution content

##### Testing

* `grunt test` will run the unit tests using karma.

##### Generating documentation

* `grunt build_architecture_graph` Generates dependency diagrams using graphviz. For issues on installing the grap generator tool see https://github.com/carlo-colombo/angular-modules-graph

#### Known issues

* If a local `grunt` is not found in project folder run `npm i grunt` there (`npm i` should have done it)
* If `compass` is not found
  * Install `ruby` <http://rubyinstaller.org/downloads/>, and be sure to check "Add ruby executables to your PATH" !
  * install compass: `gem install compass`
* If on `grunt` run an indirect npm dependency is missing install it, e.g. "npm i serve-static --save-dev", and be sure to commit the `package.json` update
* For `grunt` toolchain issues: on access rights you may have to use node version < 5.7
* Development on Windows environment
  * ruby/compass not installed by default, install separately
  * If using a "git command prompt" check where it installs packages. It's better to do all the package and grunt operations in an "Administrator command prompt".

### Some key files

|File or folder|Description|
|:-------------|:-----|
| `index.html` | HTML file for this Single Page Application (SPA)
| `app.js` | Declaration and initialization of the angular application
| `app.constants.js` | Declarations of constants
| `app.env.js` | Run-time configuration settings generated during build
| `app.env.default.json` | Default values for run-time configuration settings, overwritten by environment-specific configuration files during build
| `app.routes.js` | State definitions and routes
| `custom/` | Folder under which grunt is configured to search for environment-specific configuration files
| `Gruntfile.js` | Build rules and tasks
| `package.json` | Npm module dependencies. See also `npm-shrinkwrap.json` and `bower.json`. Defines also a version number for this application.
| `npm-shrinkwrap.json` | Locks npm dependencies instead of using latest available for `package.json`. Created using `$npm shrinkwrap --dev`. Notice that updating app version number requires also updating `npm-shrinkwrap.json` app version reference!
| `bower.json` |  Bower module dependencies. See also `package.json`. Defines also a version number for this application.


text:
class CustomCheckedException extends Exception {

    CustomCheckedException() {
        throw new UnsupportedOperationException("Delete this statement and write your own implementation.");
    }

    CustomCheckedException(String message) {
        throw new UnsupportedOperationException("Delete this statement and write your own implementation.");
    }

}


text:
from django.views import generic

class IndexView(generic.TemplateView):
    template_name = 'admin/project_monitor/index.html'


text:
<?php
namespace Migrator\Command;

use LogicException;
use Migrator\Console\Application;
use Migrator\Migrator;
use Migrator\Factory\FactoryInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Output\OutputInterface;

class BaseCommand extends Command implements FactoryInterface
{
    /**
     * Get an instance of Migrator for the given database
     * @param string $database
     * @return Migrator
     */
    public function getMigrator($database)
    {
        $app = $this->getApplication();
        if ($app instanceof Application) {
            return $app->getFactory()->getMigrator($database);
        }
        throw new LogicException('Application is expected to be an instance of \\Migrator\\Console\\Application');
    }

    /**
     * @param OutputInterface $output
     * @param string          $name
     * @param int             $lowest
     * @param int             $current
     * @param int             $highest
     */
    protected function printStatus(OutputInterface $output, $name, $lowest, $current, $highest)
    {
        $output->writeln("Database:        <info>$name</info>");
        $output->writeln("At version:      <info>$current</info>");
        $output->writeln("");
        if ($highest > $current) {
            $output->writeln("Upgradable to:   <info>$highest</info>");
        }
        if ($lowest < $current) {
            $output->writeln("Downgradable to: <info>$lowest</info>");
        }
    }
}


text:
package com.github.wesleyegberto.simplecompiler.grammar;

import com.github.wesleyegberto.simplecompiler.grammar.ast.Table;

/**
 * MORE_EXP_BOOL → OP_BOOL EXP_BOOL
 *
 * @author Wesley Egberto on 02/06/16.
 */
public class MoreExpBool extends GrammarRule {
	private OpBool opBool;
	private ExpBool expBool;

	public MoreExpBool(OpBool opBool, ExpBool expBool) {
		this.opBool = opBool;
		this.expBool = expBool;
	}

	@Override
	public String toString() {
		return "MoreExpBool{" +
			"opBool=" + opBool +
			", expBool=" + expBool +
			'}';
	}

	@Override
	public void generateCode(Table memory) {
		opBool.generateCode(memory);
		expBool.generateCode(memory);
	}
}


text:
package com.linkedin.kafka.cruisecontrol.async.progress;

/**
 * Indicating the goal optimization is in progress.
 */
public class OptimizationForGoal implements OperationStep {
  private final String _goalName;
  private volatile boolean completed = false;

  public OptimizationForGoal(String goalName) {
    _goalName = goalName;
  }

  public void done() {
    completed = true;
  }

  @Override
  public String name() {
    return "OPTIMIZING " + _goalName;
  }

  @Override
  public float completionPercentage() {
    return completed ? 1.0f : 0.0f;
  }

  @Override
  public String description() {
    return "Optimizing goal " + _goalName;
  }
}


text:
'use strict';

var gulpconf = require('./gulpconf.js');

module.exports = function (config) {
    config.set({

        basePath: '../' + gulpconf.config.paths.build.development,

        files: [
            {pattern: 'vendor/js/*.js', included: false},
            {pattern: 'components/**/*.js', included: false},
            {pattern: '*.html', included: false},
            {pattern: '**/*.html', included: false},
            {pattern: '**/*.unit.spec.js', included: false},
            {pattern: '**/*.json', included: false},
            './test-config.js'
        ],

        autoWatch: true,

        port: 9001,

        preprocessors: {
            '!(vendor)/**/!(*spec).js': ['coverage']
        },

        frameworks: ['jasmine', 'requirejs'],

        browsers: [
            'PhantomJS'
        ],

        exclude: [
            'config.js',
            'boot.js'
        ],

        plugins: [
            'karma-phantomjs-launcher',
            'karma-jasmine',
            'karma-junit-reporter',
            'karma-requirejs',
            'karma-coverage'
        ],

        reporters: ['progress', 'coverage', 'junit'],

        singleRun: false,

        colors: true,

        logLevel: config.LOG_INFO,

        junitReporter : {
            outputFile: './test-coverage/test-results.xml',
            suite: 'unit'
        },

        coverageReporter: {
            type: 'html',
            dir: './test-coverage/'
        }

    });
};


text:
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

import os
import json
import pytest
from mock import ANY
from ansible.module_utils.network.fortios.fortios import FortiOSHandler

try:
    from ansible.modules.network.fortios import fortios_system_fortimanager
except ImportError:
    pytest.skip("Could not load required modules for testing", allow_module_level=True)

@pytest.fixture(autouse=True)
def connection_mock(mocker):
    connection_class_mock = mocker.patch('ansible.modules.network.fortios.fortios_system_fortimanager.Connection')
    return connection_class_mock

fos_instance = FortiOSHandler(connection_mock)

def test_system_fortimanager_creation(mocker):
    schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema')

    set_method_result = {'status': 'success', 'http_method': 'POST', 'http_status': 200}
    set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result)

    input_data = {
        'username': 'admin',
        'state': 'present',
        'system_fortimanager': {
            'central_management': 'enable',
            'central_mgmt_auto_backup': 'enable',
            'central_mgmt_schedule_config_restore': 'enable',
            'central_mgmt_schedule_script_restore': 'enable',
            'ip': 'test_value_7',
            'ipsec': 'enable',
            'vdom': 'test_value_9'
        },
        'vdom': 'root'}

    is_error, changed, response = fortios_system_fortimanager.fortios_system(input_data, fos_instance)

    expected_data = {
        'central-management': 'enable',
        'central-mgmt-auto-backup': 'enable',
        'central-mgmt-schedule-config-restore': 'enable',
        'central-mgmt-schedule-script-restore': 'enable',
        'ip': 'test_value_7',
        'ipsec': 'enable',
        'vdom': 'test_value_9'
    }

    set_method_mock.assert_called_with('system', 'fortimanager', data=expected_data, vdom='root')
    schema_method_mock.assert_not_called()
    assert not is_error
    assert changed
    assert response['status'] == 'success'
    assert response['http_status'] == 200

def test_system_fortimanager_creation_fails(mocker):
    schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema')

    set_method_result = {'status': 'error', 'http_method': 'POST', 'http_status': 500}
    set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result)

    input_data = {
        'username': 'admin',
        'state': 'present',
        'system_fortimanager': {
            'central_management': 'enable',
            'central_mgmt_auto_backup': 'enable',
            'central_mgmt_schedule_config_restore': 'enable',
            'central_mgmt_schedule_script_restore': 'enable',
            'ip': 'test_value_7',
            'ipsec': 'enable',
            'vdom': 'test_value_9'
        },
        'vdom': 'root'}

    is_error, changed, response = fortios_system_fortimanager.fortios_system(input_data, fos_instance)

    expected_data = {
        'central-management': 'enable',
        'central-mgmt-auto-backup': 'enable',
        'central-mgmt-schedule-config-restore': 'enable',
        'central-mgmt-schedule-script-restore': 'enable',
        'ip': 'test_value_7',
        'ipsec': 'enable',
        'vdom': 'test_value_9'
    }

    set_method_mock.assert_called_with('system', 'fortimanager', data=expected_data, vdom='root')
    schema_method_mock.assert_not_called()
    assert is_error
    assert not changed
    assert response['status'] == 'error'
    assert response['http_status'] == 500

def test_system_fortimanager_idempotent(mocker):
    schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema')

    set_method_result = {'status': 'error', 'http_method': 'DELETE', 'http_status': 404}
    set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result)

    input_data = {
        'username': 'admin',
        'state': 'present',
        'system_fortimanager': {
            'central_management': 'enable',
            'central_mgmt_auto_backup': 'enable',
            'central_mgmt_schedule_config_restore': 'enable',
            'central_mgmt_schedule_script_restore': 'enable',
            'ip': 'test_value_7',
            'ipsec': 'enable',
            'vdom': 'test_value_9'
        },
        'vdom': 'root'}

    is_error, changed, response = fortios_system_fortimanager.fortios_system(input_data, fos_instance)

    expected_data = {
        'central-management': 'enable',
        'central-mgmt-auto-backup': 'enable',
        'central-mgmt-schedule-config-restore': 'enable',
        'central-mgmt-schedule-script-restore': 'enable',
        'ip': 'test_value_7',
        'ipsec': 'enable',
        'vdom': 'test_value_9'
    }

    set_method_mock.assert_called_with('system', 'fortimanager', data=expected_data, vdom='root')
    schema_method_mock.assert_not_called()
    assert not is_error
    assert not changed
    assert response['status'] == 'error'
    assert response['http_status'] == 404

def test_system_fortimanager_filter_foreign_attributes(mocker):
    schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema')

    set_method_result = {'status': 'success', 'http_method': 'POST', 'http_status': 200}
    set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result)

    input_data = {
        'username': 'admin',
        'state': 'present',
        'system_fortimanager': {
            'random_attribute_not_valid': 'tag',
            'central_management': 'enable',
            'central_mgmt_auto_backup': 'enable',
            'central_mgmt_schedule_config_restore': 'enable',
            'central_mgmt_schedule_script_restore': 'enable',
            'ip': 'test_value_7',
            'ipsec': 'enable',
            'vdom': 'test_value_9'
        },
        'vdom': 'root'}

    is_error, changed, response = fortios_system_fortimanager.fortios_system(input_data, fos_instance)

    expected_data = {
        'central-management': 'enable',
        'central-mgmt-auto-backup': 'enable',
        'central-mgmt-schedule-config-restore': 'enable',
        'central-mgmt-schedule-script-restore': 'enable',
        'ip': 'test_value_7',
        'ipsec': 'enable',
        'vdom': 'test_value_9'
    }

    set_method_mock.assert_called_with('system', 'fortimanager', data=expected_data, vdom='root')
    schema_method_mock.assert_not_called()
    assert not is_error
    assert changed
    assert response['status'] == 'success'
    assert response['http_status'] == 200


text:
var Approvers = function(element) {
  this.element = element;

  var thumbsUpCount = 0;
  var usernames     = [];
  var avatarUrls    = [];
  var timestamps    = [];

  this.element.find('.timeline-comment-wrapper.js-comment-container').each(function() {
    var commentWrapper   = $(this);
    var avatarUrl        = commentWrapper.find('img.timeline-comment-avatar').attr('src');
    var commentContainer = commentWrapper.find('.comment.js-comment');
    var username         = commentContainer.find('a.author').text();
    var timestamp        = commentContainer.find('time').length > 0 ? commentContainer.find('time').text() : commentContainer.find('relative-time').text();
    var commentRow       = commentContainer.find('.comment-body.js-comment-body');
    var messageText      = commentRow.text().trim();

    if (messageText === '+1'
    || messageText.toLowerCase() === 'lg2m'
    || messageText.toLowerCase() === 'lgtm'
    || commentRow.find('img[title=":+1:"]').length === 1
    || commentRow.find('img[title=":thumbsup:"]').length === 1
    || commentRow.find('g-emoji[alias="+1"]').length === 1) {
      usernames.push(username);
      avatarUrls.push(avatarUrl);
      timestamps.push(timestamp);
      thumbsUpCount++;
    }
  });

  this.thumbsUpCount = thumbsUpCount;
  this.usernames     = usernames;
  this.avatarUrls    = avatarUrls;
  this.timestamps    = timestamps;
};

Approvers.prototype.size = function() {
  return this.thumbsUpCount;
};

Approvers.prototype.getUsername = function(i) {
  return this.usernames[i];
};

Approvers.prototype.getAvatarUrl = function(i) {
  return this.avatarUrls[i];
};

Approvers.prototype.getTimestamp = function(i) {
  return this.timestamps[i];
};


text:
Set Bet Terms

Set the terms of your bet below!

            <input type="text" placeholder="Bet Name" data-ng-model="cbInstance.betName">

  			<ionic-datepicker
	  		date="cbInstance.currentStartDate"
	  		min="cbInstance.minDate"
	  		max="cbInstance.maxDate"
	  		callback="cbInstance.betStartDate"
	  		data-ng-model="cbInstance.currentStartDate">

            	<button class="button button-calm button-small button-outline">Start Date : {{cbInstance.currentStartDate | date:'MMMM.dd.yy' }}</button>

        </ionic-datepicker>

  			<ionic-datepicker
	        date="cbInstance.currentEndDate"
	        min="cbInstance.currentStartDate"
	        max="cbInstance.maxDate"
	        callback="cbInstance.betEndDate"
	        data-ng-model="cbInstance.currentEndDate">

				<button class="button button-calm button-small button-outline">End Date : {{cbInstance.currentEndDate | date:'MMMM.dd.yy' }}</button>

		</ionic-datepicker>

Wager Amount: {{cbInstance.wagerAmount}}

			<input type="range" name="volume" min="5" max="{{cbInstance.creatorCurrency}}" value="cbInstance.wagerAmount" data-ng-model="cbInstance.wagerAmount">

    		Bet Terms
    		<textarea rows="5" placeholder="Bet Terms"
    		data-ng-model="cbInstance.betTerms"
    		data-ng-blur="cbInstance.saveData()"></textarea>