text:
/*
 * � 2001-2009, Progress Software Corporation and/or its subsidiaries or affiliates.  All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.

Sample Application

Writing a Basic JMS Application using
    - Publish and Subscribe
    - Transacted Sessions
    - Multiple Sessions

Run this program to publish and subscribe to the specified topic.
Messages are buffered and sent when a specific string is seen ("COMMIT").
Messages buffered can be discarded by entering a specified string ("CANCEL").

Usage:
  java TransactedChat -b <broker:port> -u <username> -p <password>
      -b broker:port points to your message broker
                     Default: tcp://localhost:61616
      -u username    must be unique (but is not checked)
      -p password    password for user (not checked)

Suggested demonstration:
  - In a console window with the environment set, start this
    application. In other console windows start other sessions
    under different user names. For example:
       java TransactedChat -u ADMINISTRATION
       java TransactedChat -u FACILITIES
  - Type some text and then press Enter.
  - Repeat to create a batch of messages.
  - Send the batched messages by entering the text "COMMIT"
  - Discard the batched messages by entering the text "CANCEL"

*/
import org.apache.activemq.*;

public class TransactedChat
    implements javax.jms.MessageListener
{
    private static final String APP_TOPIC = "jms.samples.chat";
    private static final String DEFAULT_BROKER_NAME = "tcp://localhost:61616";
    private static final String DEFAULT_PASSWORD = "password";

    private javax.jms.Connection connect = null;
    private javax.jms.Session publishSession = null;
    private javax.jms.Session subscribeSession = null;
    private javax.jms.MessageProducer publisher = null;

    /** Create JMS client for publishing and subscribing to messages. */
    private void chatter( String broker, String username, String password)
    {
        // Create a connection.
        try
        {
            javax.jms.ConnectionFactory factory;
            factory = new ActiveMQConnectionFactory(username, password, broker);
            connect = factory.createConnection (username, password);
            // We want to be able up commit/rollback messages published,
            // but not affect messages consumed. Therefore, we need two sessions.
            publishSession = connect.createSession(true, javax.jms.Session.AUTO_ACKNOWLEDGE);
            subscribeSession = connect.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
        }
        catch (javax.jms.JMSException jmse)
        {
            System.err.println("error: Cannot connect to Broker - " + broker);
            jmse.printStackTrace();
            System.exit(1);
        }

        // Create Publisher and Subscriber to 'chat' topics
        try
        {
            javax.jms.Topic topic = subscribeSession.createTopic (APP_TOPIC);
            javax.jms.MessageConsumer subscriber = subscribeSession.createConsumer(topic);
            subscriber.setMessageListener(this);
            publisher = publishSession.createProducer(topic);
            // Now start the Connection
            connect.start();
        }
        catch (javax.jms.JMSException jmse)
        {
            jmse.printStackTrace();
        }

        try
        {
            // Read all standard input and send it as a message.
            java.io.BufferedReader stdin =
                new java.io.BufferedReader( new java.io.InputStreamReader( System.in ) );
            boolean showMessage = true;
            while ( true )
            {
                if (showMessage)
                {
                    System.out.println ("TransactedChat application:");
	                System.out.println ("===========================" );
                    System.out.println ("The application user " + username + " connects to the broker at " + DEFAULT_BROKER_NAME + ".");
					System.out.println ("The application will stage messages to the " + APP_TOPIC + " topic until you either commit them or roll them back.");
				    System.out.println ("The application also subscribes to that topic to consume any committed messages published there.\n");
                    System.out.println ("1. Enter text to publish and then press Enter to stage the message.");
                    System.out.println ("2. Add a few messages to the transaction batch.");
                    System.out.println ("3. Then, either:");
                    System.out.println ("     o Enter the text 'COMMIT', and press Enter to publish all the staged messages.");
                    System.out.println ("     o Enter the text 'CANCEL', and press Enter to drop the staged messages waiting to be sent.");
                    showMessage = false;
                }
                String s = stdin.readLine();

                if ( s == null )
                    exit();
                else if (s.trim().equals("CANCEL"))
                {
                    // Rollback the messages. A new transaction is implicitly
                    // started for following messages.
                    System.out.println ("Cancelling messages...");
                    publishSession.rollback();
                    System.out.println ("Staged messages have been cleared.");
                    showMessage = false; // don't show the help message again.
                }
                else if ( s.length() > 0 )
                // See if we should send the messages
                  if (s.trim().equals("COMMIT"))
                  {
                        // Commit (send) the messages. A new transaction is
                        // implicitly  started for following messages.
                        System.out.println ("Committing messages... ");
                        publishSession.commit();
                        System.out.println ("Staged messages have all been sent.");
                        showMessage = false; // dont't show the help message again.
                  }
                  else
                   {
                    javax.jms.TextMessage msg = publishSession.createTextMessage();
                    msg.setText( username + ": " + s );
                    // Publish the message persistently
                    publisher.send( msg );
                   }
            }
        }
        catch ( java.io.IOException ioe )
        {
            ioe.printStackTrace();
        }
        catch ( javax.jms.JMSException jmse )
        {
            jmse.printStackTrace();
        }
    }

    /**
     * Handle the message
     * (as specified in the javax.jms.MessageListener interface).
     */
    public void onMessage( javax.jms.Message aMessage)
    {
        try
        {
            // Cast the message as a text message.
            javax.jms.TextMessage textMessage = (javax.jms.TextMessage) aMessage;

            // This handler reads a single String from the
            // message and prints it to the standard output.
            try
            {
                String string = textMessage.getText();
                System.out.println( string );
            }
            catch (javax.jms.JMSException jmse)
            {
                jmse.printStackTrace();
            }
        }
        catch (java.lang.RuntimeException rte)
        {
            rte.printStackTrace();
        }
    }

    /** Cleanup resources cleanly and exit. */
    private void exit()
    {
        try
        {
            publishSession.rollback(); // Rollback any uncommitted messages.
            connect.close();
        }
        catch (javax.jms.JMSException jmse)
        {
            jmse.printStackTrace();
        }

        System.exit(0);
    }

    //
    // NOTE: the remainder of this sample deals with reading arguments
    // and does not utilize any JMS classes or code.
    //

    /** Main program entry point. */
    public static void main(String argv[]) {

        // Is there anything to do?
        if (argv.length == 0) {
            printUsage();
            System.exit(1);
        }

        // Values to be read from parameters
        String broker    = DEFAULT_BROKER_NAME;
        String username  = null;
        String password  = DEFAULT_PASSWORD;

        // Check parameters
        for (int i = 0; i < argv.length; i++) {
            String arg = argv[i];

            if (arg.equals("-b")) {
                if (i == argv.length - 1 || argv[i+1].startsWith("-")) {
                    System.err.println("error: missing broker name:port");
                    System.exit(1);
                }
                broker = argv[++i];
                continue;
            }

            if (arg.equals("-u")) {
                if (i == argv.length - 1 || argv[i+1].startsWith("-")) {
                    System.err.println("error: missing user name");
                    System.exit(1);
                }
                username = argv[++i];
                continue;
            }

            if (arg.equals("-p")) {
                if (i == argv.length - 1 || argv[i+1].startsWith("-")) {
                    System.err.println("error: missing password");
                    System.exit(1);
                }
                password = argv[++i];
                continue;
            }

            if (arg.equals("-h")) {
                printUsage();
                System.exit(1);
            }

            // Invalid argument
            System.err.println ("error: unexpected argument: "+arg);
            printUsage();
            System.exit(1);
        }

        // Check values read in.
        if (username == null) {
            System.err.println ("error: user name must be supplied");
            printUsage();
        }

        // Start the JMS client for the "chat".
        TransactedChat chat = new TransactedChat();
        chat.chatter (broker, username, password);

    }

    /** Prints the usage. */
    private static void printUsage() {

        StringBuffer use = new StringBuffer();
        use.append("usage: java TransactedChat (options) ...\n\n");
        use.append("options:\n");
        use.append("  -b name:port Specify name:port of broker.\n");
        use.append("               Default broker: "+DEFAULT_BROKER_NAME+"\n");
        use.append("  -u name      Specify unique user name. (Required)\n");
        use.append("  -p password  Specify password for user.\n");
        use.append("               Default password: "+DEFAULT_PASSWORD+"\n");
        use.append("  -h           This help screen.\n");
        System.err.println (use);
    }
}


text:
module Kant
  class AllAccess
    attr_reader :user

    def initialize(user = nil)
      @user = user
    end

    def can?(action, object)
      true
    end

    def accessible(action, scope, *rest)
      scope.all
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package com.gemstone.gemfire.cache;

/**
 *
A listener that can be implemented to handle transaction related
 * events.  The methods on TransactionListener are
 * invoked synchronously after the operation, commit or rollback,
 * completes.  The transaction that causes the listener to be called
 * will no longer exist at the time the listener code executes.  The
 * thread that performed the transaction operation will not see that
 * operation complete until the listener method completes its
 * execution.
 *
 *
Multiple transactions, on the same cache, can cause concurrent
 * invocation of TransactionListener methods.  Any
 * exceptions thrown by the listener are caught and logged.
 *
 *
Rollback and failed commit operations are local.
 *
 * @author Darrel Schneider
 *
 * @see CacheTransactionManager#setListener
 * @see CacheTransactionManager#getListener
 * @since 4.0
 */

public interface TransactionListener extends CacheCallback {

  /** Called after a successful commit of a transaction.
   *
   * @param event the TransactionEvent
   * @see CacheTransactionManager#commit
   */
  public void afterCommit(TransactionEvent event);

  /** Called after an unsuccessful commit operation.
   *
   * @param event the TransactionEvent
   * @see CacheTransactionManager#commit
   */
  public void afterFailedCommit(TransactionEvent event);

  /** Called after an explicit rollback of a transaction.
   *
   * @param event the TransactionEvent
   * @see CacheTransactionManager#rollback
   * @see CacheTransactionManager#commit
   */
  public void afterRollback(TransactionEvent event);
}


text:
AccountsTemplates.configure({
  defaultLayout: 'masterLayout',
  defaultLayoutRegions: {
    nav: 'nav',
    footer: 'footer',
  },
  defaultContentRegion: 'main',
  showForgotPasswordLink: true,
  overrideLoginErrors: true,
  enablePasswordChange: true,

  // sendVerificationEmail: true,
  // enforceEmailVerification: true,
  //confirmPassword: true,
  //continuousValidation: false,
  //displayFormLabels: true,
  //forbidClientAccountCreation: true,
  //formValidationFeedback: true,
  //homeRoutePath: '/',
  //showAddRemoveServices: false,
  //showPlaceholders: true,

  negativeValidation: true,
  positiveValidation: true,
  negativeFeedback: false,
  positiveFeedback: true,

  // Privacy Policy and Terms of Use
  //privacyUrl: 'privacy',
  //termsUrl: 'terms-of-use',
});


text:
<?php
$pageTitle = 'User Login';

$check = (!empty($_POST['login']) && ($_POST['login'] === 'Log in')) ? 'login' : 'show_form';

switch($check) {
	case 'login':
		require('session.php');
		require('user.php');

		$user = new User();
		$username = $_POST['username'];
		$password = $_POST['password'];

		if ($user->authenticate($username, $password)) {
			header('location: user-profile.php');
			exit;
		} else {
			$error = '
<button type="button" class="close" data-dismiss="alert">×</button>Warning! All fields require!
';
	break;
	}
	case 'show_form':
	default:
		$error = NULL;
	}
?>

<?php include('header.php');?>

	<form id="login" action="user-login.php" method="post" accept-charset="UTF-8">

	<?php if(isset($error)): ?>

<?php echo $error; ?>

	<?php endif ?>

Username

<input class="textbox" tabindex="1" type="text" name="username" autocomplete="off"/>

Password

<input class="textbox" tabindex="2" type="password" name="password"/>

<input class="btn_submit" name="login" tabindex="3" type="submit" value="Log in" />

	</form>

	<?php include('footer.php');?>

	<?php include('/js/scripts.js');?>


text:
#ifndef __SDS_H
#define __SDS_H

#define SDS_MAX_PREALLOC (1024*1024)

#include <sys/types.h>
#include <stdarg.h>

typedef char *sds;

struct sdshdr {
    int len;
    int free;
    char buf[];
};

static inline size_t sdslen(const sds s) {
    struct sdshdr *sh = (struct sdshdr *)(s-sizeof *sh);
    return sh->len;
}

static inline size_t sdsavail(const sds s) {
    struct sdshdr *sh = (struct sdshdr *)(s-sizeof *sh);
    return sh->free;
}

sds sdsnewlen(const void *init, size_t initlen);
sds sdsnew(const char *init);
sds sdsempty(void);
size_t sdslen(const sds s);
sds sdsdup(const sds s);
void sdsfree(sds s);
size_t sdsavail(const sds s);
sds sdsgrowzero(sds s, size_t len);
sds sdscatlen(sds s, const void *t, size_t len);
sds sdscat(sds s, const char *t);
sds sdscatsds(sds s, const sds t);
sds sdscpylen(sds s, const char *t, size_t len);
sds sdscpy(sds s, const char *t);

sds sdscatvprintf(sds s, const char *fmt, va_list ap);
#ifdef __GNUC__
sds sdscatprintf(sds s, const char *fmt, ...)
    __attribute__((format(printf, 2, 3)));
#else
sds sdscatprintf(sds s, const char *fmt, ...);
#endif

sds sdscatfmt(sds s, char const *fmt, ...);
void sdstrim(sds s, const char *cset);
void sdsrange(sds s, int start, int end);
void sdsupdatelen(sds s);
void sdsclear(sds s);
int sdscmp(const sds s1, const sds s2);
sds *sdssplitlen(const char *s, int len, const char *sep, int seplen, int *count);
void sdsfreesplitres(sds *tokens, int count);
void sdstolower(sds s);
void sdstoupper(sds s);
sds sdsfromlonglong(long long value);
sds sdscatrepr(sds s, const char *p, size_t len);
sds *sdssplitargs(const char *line, int *argc);
sds sdsmapchars(sds s, const char *from, const char *to, size_t setlen);
sds sdsjoin(char **argv, int argc, char *sep, size_t seplen);
sds sdsjoinsds(sds *argv, int argc, const char *sep, size_t seplen);

/* Low level functions exposed to the user API */
sds sdsMakeRoomFor(sds s, size_t addlen);
void sdsIncrLen(sds s, int incr);
sds sdsRemoveFreeSpace(sds s);
size_t sdsAllocSize(sds s);

#endif


text:
using System.Security.Principal;

namespace Kuno.Security
{
    /// <summary>
    /// Represents an anonymous identity.  Intended to implement the null object pattern.
    /// </summary>
    /// <seealso href="http://bit.ly/29e2gRR">Wikipedia: Null Object pattern</seealso>
    /// <seealso cref="System.Security.Principal.GenericIdentity" />
    public class AnonymousIdentity : GenericIdentity
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="AnonymousIdentity" /> class.
        /// </summary>
        public AnonymousIdentity()
            : base("")
        {
        }

        /// <summary>
        /// Gets a value indicating whether the user has been authenticated.
        /// </summary>
        /// <value><c>true</c> if this instance is authenticated; otherwise, <c>false</c>.</value>
        public override bool IsAuthenticated => false;

        /// <summary>
        /// Gets the user's name.
        /// </summary>
        /// <value>The name.</value>
        public override string Name => null;
    }
}


text:
package myrasec

import (
	"fmt"
	"strconv"
	"sync"

	"github.com/GoogleCloudPlatform/terraformer/terraformutils"
	mgo "github.com/Myra-Security-GmbH/myrasec-go/v2"
)

//
// MaintenanceGenerator
//
type MaintenanceGenerator struct {
	MyrasecService
}

//
// createMaintenanceResources
//
func (g *MaintenanceGenerator) createMaintenanceResources(api *mgo.API, domainId int, vhost mgo.VHost, wg *sync.WaitGroup) error {
	defer wg.Done()

	page := 1
	pageSize := 250
	params := map[string]string{
		"page":     strconv.Itoa(page),
		"pageSize": strconv.Itoa(pageSize),
	}

	for {
		params["page"] = strconv.Itoa(page)

		maintenance, err := api.ListMaintenances(domainId, vhost.Label, params)
		if err != nil {
			return err
		}

		for _, m := range maintenance {
			r := terraformutils.NewResource(
				strconv.Itoa(m.ID),
				fmt.Sprintf("%s_%d", vhost.Label, m.ID),
				"myrasec_maintenance",
				"myrasec",
				map[string]string{
					"subdomain_name": vhost.Label,
				},
				[]string{},
				map[string]interface{}{},
			)
			g.Resources = append(g.Resources, r)
		}
		if len(maintenance) < pageSize {
			break
		}
		page++
	}
	return nil
}

//
// InitResources
//
func (g *MaintenanceGenerator) InitResources() error {
	wg := sync.WaitGroup{}

	api, err := g.initializeAPI()
	if err != nil {
		return err
	}

	funcs := []func(*mgo.API, int, mgo.VHost, *sync.WaitGroup) error{
		g.createMaintenanceResources,
	}

	err = createResourcesPerSubDomain(api, funcs, &wg, false)
	if err != nil {
		return err
	}

	wg.Wait()

	return nil
}


text:
<?php

class Magestore_Magenotification_Model_Mysql4_Magenotification_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract
{
    public function _construct()
    {
        parent::_construct();
        $this->_init('magenotification/magenotification');
    }
}


text: python crontest.py


text:
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Encog.Parse.Expression.Common;
using Encog.ML.Prg;

namespace Encog.ML.Prg.Train.Crossover
{
    [TestClass]
    public class TestSubtreeCrossover
    {
        [TestMethod]
        public void TestCrossoverOperation()
        {
            RenderCommonExpression render = new RenderCommonExpression();
            EncogProgram prg = new EncogProgram("1+2");
            EncogProgram prg2 = new EncogProgram("4+5");
            ProgramNode node = prg.FindNode(2);
            prg.ReplaceNode(node, prg2.RootNode);
            Assert.AreEqual("(1+(4+5))", render.Render(prg));
        }
    }
}


text:
package org.apache.camel.component.telegram.service;

import java.io.ByteArrayInputStream;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
import org.apache.camel.component.telegram.TelegramService;
import org.apache.camel.component.telegram.model.EditMessageLiveLocationMessage;
import org.apache.camel.component.telegram.model.MessageResult;
import org.apache.camel.component.telegram.model.OutgoingAudioMessage;
import org.apache.camel.component.telegram.model.OutgoingDocumentMessage;
import org.apache.camel.component.telegram.model.OutgoingMessage;
import org.apache.camel.component.telegram.model.OutgoingPhotoMessage;
import org.apache.camel.component.telegram.model.OutgoingTextMessage;
import org.apache.camel.component.telegram.model.OutgoingVideoMessage;
import org.apache.camel.component.telegram.model.SendLocationMessage;
import org.apache.camel.component.telegram.model.SendVenueMessage;
import org.apache.camel.component.telegram.model.StopMessageLiveLocationMessage;
import org.apache.camel.component.telegram.model.UpdateResult;
import org.apache.cxf.jaxrs.client.JAXRSClientFactory;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.cxf.jaxrs.ext.multipart.Attachment;
import org.apache.cxf.jaxrs.ext.multipart.ContentDisposition;

/**
 * Adapts the {@code RestBotAPI} to the {@code TelegramService} interface.
 */
public class TelegramServiceRestBotAPIAdapter implements TelegramService {

    private RestBotAPI api;

    public TelegramServiceRestBotAPIAdapter() {
        this.api = JAXRSClientFactory.create(RestBotAPI.BOT_API_DEFAULT_URL, RestBotAPI.class, Collections.singletonList(providerByCustomObjectMapper()));
        WebClient.getConfig(this.api).getHttpConduit().getClient().setAllowChunking(false);
    }

    public TelegramServiceRestBotAPIAdapter(RestBotAPI api) {
        this.api = api;
    }

    @Override
    public UpdateResult getUpdates(String authorizationToken, Long offset, Integer limit, Integer timeoutSeconds) {
        return api.getUpdates(authorizationToken, offset, limit, timeoutSeconds);
    }

    @Override
    public Object sendMessage(String authorizationToken, OutgoingMessage message) {
        Object resultMessage;

        if (message instanceof OutgoingTextMessage) {
            resultMessage = this.sendMessage(authorizationToken, (OutgoingTextMessage) message);
        } else if (message instanceof OutgoingPhotoMessage) {
            resultMessage = this.sendMessage(authorizationToken, (OutgoingPhotoMessage) message);
        } else if (message instanceof OutgoingAudioMessage) {
            resultMessage = this.sendMessage(authorizationToken, (OutgoingAudioMessage) message);
        } else if (message instanceof OutgoingVideoMessage) {
            resultMessage = this.sendMessage(authorizationToken, (OutgoingVideoMessage) message);
        } else if (message instanceof OutgoingDocumentMessage) {
            resultMessage = this.sendMessage(authorizationToken, (OutgoingDocumentMessage) message);
        } else if (message instanceof SendLocationMessage) {
            resultMessage = api.sendLocation(authorizationToken, (SendLocationMessage) message);
        } else if (message instanceof EditMessageLiveLocationMessage) {
            resultMessage = api.editMessageLiveLocation(authorizationToken, (EditMessageLiveLocationMessage) message);
        } else if (message instanceof StopMessageLiveLocationMessage) {
            resultMessage = api.stopMessageLiveLocation(authorizationToken, (StopMessageLiveLocationMessage) message);
        } else if (message instanceof SendVenueMessage) {
            resultMessage = api.sendVenue(authorizationToken, (SendVenueMessage) message);
        } else {
            throw new IllegalArgumentException("Unsupported message type " + (message != null ? message.getClass().getName() : null));
        }

        return resultMessage;
    }

    private MessageResult sendMessage(String authorizationToken, OutgoingTextMessage message) {
        return api.sendMessage(authorizationToken, message);
    }

    private MessageResult sendMessage(String authorizationToken, OutgoingPhotoMessage message) {
        List<Attachment> parts = new LinkedList<>();

        fillCommonMediaParts(parts, message);

        parts.add(buildMediaPart("photo", message.getFilenameWithExtension(), message.getPhoto()));
        if (message.getCaption() != null) {
            parts.add(buildTextPart("caption", message.getCaption()));
        }

        return api.sendPhoto(authorizationToken, parts);
    }

    private MessageResult sendMessage(String authorizationToken, OutgoingAudioMessage message) {
        List<Attachment> parts = new LinkedList<>();

        fillCommonMediaParts(parts, message);

        parts.add(buildMediaPart("audio", message.getFilenameWithExtension(), message.getAudio()));
        if (message.getTitle() != null) {
            parts.add(buildTextPart("title", message.getTitle()));
        }
        if (message.getDurationSeconds() != null) {
            parts.add(buildTextPart("duration", String.valueOf(message.getDurationSeconds())));
        }
        if (message.getPerformer() != null) {
            parts.add(buildTextPart("performer", message.getPerformer()));
        }

        return api.sendAudio(authorizationToken, parts);
    }

    private MessageResult sendMessage(String authorizationToken, OutgoingVideoMessage message) {
        List<Attachment> parts = new LinkedList<>();

        fillCommonMediaParts(parts, message);

        parts.add(buildMediaPart("video", message.getFilenameWithExtension(), message.getVideo()));
        if (message.getCaption() != null) {
            parts.add(buildTextPart("caption", message.getCaption()));
        }
        if (message.getDurationSeconds() != null) {
            parts.add(buildTextPart("duration", String.valueOf(message.getDurationSeconds())));
        }
        if (message.getWidth() != null) {
            parts.add(buildTextPart("width", String.valueOf(message.getWidth())));
        }
        if (message.getHeight() != null) {
            parts.add(buildTextPart("height", String.valueOf(message.getHeight())));
        }

        return api.sendVideo(authorizationToken, parts);
    }

    private MessageResult sendMessage(String authorizationToken, OutgoingDocumentMessage message) {
        List<Attachment> parts = new LinkedList<>();

        fillCommonMediaParts(parts, message);

        parts.add(buildMediaPart("document", message.getFilenameWithExtension(), message.getDocument()));
        if (message.getCaption() != null) {
            parts.add(buildTextPart("caption", message.getCaption()));
        }

        return api.sendDocument(authorizationToken, parts);
    }

    private void fillCommonMediaParts(List<Attachment> parts, OutgoingMessage message) {
        parts.add(buildTextPart("chat_id", message.getChatId()));

        if (message.getReplyToMessageId() != null) {
            parts.add(buildTextPart("reply_to_message_id", String.valueOf(message.getReplyToMessageId())));
        }
        if (message.getDisableNotification() != null) {
            parts.add(buildTextPart("disable_notification", String.valueOf(message.getDisableNotification())));
        }
    }

    private Attachment buildTextPart(String name, String value) {
        MultivaluedMap m = new MultivaluedHashMap<>();
        m.putSingle("Content-Type", "text/plain");
        m.putSingle("Content-Disposition", "form-data; name=\"" + escapeMimeName(name) + "\"");

        Attachment a = new Attachment(m, value);
        return a;
    }

    private Attachment buildMediaPart(String name, String fileNameWithExtension, byte[] value) {
        Attachment a = new Attachment(name, new ByteArrayInputStream(value),
                new ContentDisposition("form-data; name=\"" + escapeMimeName(name) + "\"; filename=\"" + escapeMimeName(fileNameWithExtension) + "\""));
        return a;
    }

    private String escapeMimeName(String name) {
        return name.replace("\"", "");
    }

    private JacksonJsonProvider providerByCustomObjectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_NULL);
        return new JacksonJsonProvider(mapper);
    }
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Type Traits by Category</title>
<link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../index.html" title="Chapter 1. Boost.TypeTraits">
<link rel="up" href="../index.html" title="Chapter 1. Boost.TypeTraits">
<link rel="prev" href="background.html" title="Background and Tutorial">
<link rel="next" href="category/value_traits.html" title="Type Traits that Describe the Properties of a Type">

Home
Libraries
People
FAQ
More

Type Traits by Category

Type Traits that
      Describe the Properties of a Type

Categorizing
        a Type

General
        Type Properties

Relationships
        Between Two Types

Operator
        Type Traits

Type Traits that
      Transform One Type to Another

Synthesizing Types
      with Specific Alignments

Decomposing Function
      Types

Copyright © 2000, 2011 Adobe Systems Inc, David Abrahams,
      Frederic Bron, Steve Cleary, Beman Dawes, Glen Fernandes, Aleksey Gurtovoy,
      Howard Hinnant, Jesse Jones, Mat Marcus, Itay Maman, John Maddock, Alexander
      Nasonov, Thorsten Ottosen, Roman Perepelitsa, Robert Ramey, Jeremy Siek, Robert
      Stewart and Steven Watanabe

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
Operating Systems
Ubuntu
Relational Databases
MySQL


text:
using HearthStone.Database.Repositories;
using HearthStone.Library;
using MySql.Data.MySqlClient;
using System.Collections.Generic;

namespace HearthStone.Database.MySQL.Repositories
{
    class MySQL_DeckCardRepository : DeckCardRepository
    {
        public override bool Create(int deckID, int cardID)
        {
            string sqlString = @"INSERT INTO DeckCardCollection
                    (DeckID, CardID) VALUES (@deckID, @cardID) ;";
            lock (DatabaseService.ConnectionList.PlayerDataConnection)
            {
                using (MySqlCommand command = new MySqlCommand(sqlString, DatabaseService.ConnectionList.PlayerDataConnection.Connection as MySqlConnection))
                {
                    command.Parameters.AddWithValue("deckID", deckID);
                    command.Parameters.AddWithValue("cardID", cardID);
                    if (command.ExecuteNonQuery() == 1)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
        }

        public override bool Delete(int deckID, int cardID)
        {
            string sqlString = @"DELETE FROM DeckCardCollection
                WHERE DeckID = @deckID AND CardID = @cardID LIMIT 1;";
            lock (DatabaseService.ConnectionList.PlayerDataConnection)
                using (MySqlCommand command = new MySqlCommand(sqlString, DatabaseService.ConnectionList.PlayerDataConnection.Connection as MySqlConnection))
                {
                    command.Parameters.AddWithValue("deckID", deckID);
                    command.Parameters.AddWithValue("cardID", cardID);
                    return command.ExecuteNonQuery() > 0;
                }
        }

        public override List<Card> ListOfDeck(int deckID)
        {
            List<Card> cards = new List<Card>();
            string sqlString = @"SELECT CardID from DeckCardCollection
                WHERE DeckID = @deckID;";
            lock (DatabaseService.ConnectionList.PlayerDataConnection)
                using (MySqlCommand command = new MySqlCommand(sqlString, DatabaseService.ConnectionList.PlayerDataConnection.Connection as MySqlConnection))
                {
                    command.Parameters.AddWithValue("deckID", deckID);
                    using (MySqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            int cardID = reader.GetInt32(0);
                            Card card;
                            if(CardManager.Instance.FindCard(cardID, out card))
                            {
                                cards.Add(card);
                            }
                        }
                    }
                }
            return cards;
        }
    }
}


text:
// ==========================================================================
//                 SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2015, Knut Reinert, FU Berlin
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of Knut Reinert or the FU Berlin nor the names of
//       its contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ==========================================================================
// Author: Manuel Holtgrewe <manuel.holtgrewe@fu-berlin.de>
// ==========================================================================
// Metaprogramming control structures.
//
// This header defines metaprogramming control structure such as conditionals
// and loops.
// ==========================================================================

#ifndef SEQAN_INCLUDE_SEQAN_BASIC_METAPROGRAMMING_CONTROL_H_
#define SEQAN_INCLUDE_SEQAN_BASIC_METAPROGRAMMING_CONTROL_H_

namespace seqan {

// ============================================================================
// Forwards
// ============================================================================

// ============================================================================
// Tags, Classes, Enums
// ============================================================================

// ============================================================================
// Metafunctions
// ============================================================================

// ----------------------------------------------------------------------------
// Metafunction Switch;  Supporting Tags Case, NilCase.
// ----------------------------------------------------------------------------

/*!
 * @defgroup MetafunctionSwitch Switch Metafunction Types
 * @brief Tags for the metafunction Switch and the metafunction itself.
 *
 * @section Example
 *
 * The following shows a complete example of using the Switch statement.
 *
 * @snippet demos/basic/metaprogramming_switch.cpp switch demo
 */

// TODO(holtgrew): Use Tag<>?
/*!
 * @tag MetafunctionSwitch#NilCase
 * @brief Tag for terminating the case in Switch statement.
 *
 * @signature struct NilCase {};
 */

/*!
 * @mfn MetafunctionSwitch#Case
 * @brief Tag for one case.
 *
 * @signature template <int TAG, typename TResult, typename TNext>
 *            struct Case;
 *
 * @tparam TAG     The <tt>int</tt> tag number to use.
 * @tparam TResult The type to return in <tt>Case<...>::Type</tt> if matches.
 * @tparam TNext   The next <tt>Case</tt>.
 */

/*!
 * @mfn MetafunctionSwitch#Switch
 * @brief Switch statement for metaprogramming.
 *
 * @signature Switch<TAG, TCase>::Type
 *
 * @tparam TAG   <tt>int</tt> with the current value.
 * @tparam TCase First <tt>Case</tt> statement.
 *
 * @return Type The selected type.
 */

const int DEFAULT_ = ~(~0u >> 1); // initialize with the smallest int

struct NilCase {};

template <int TAG, typename Type_, typename Next_ = NilCase>
struct Case
{
    enum { TAG_ = TAG };
    typedef Type_ Type;
    typedef Next_ Next;
};

template <int TAG, typename Case_>
struct Switch
{
    typedef typename Case_::Next NextCase_;
    enum
    {
        CASE_TAG_ = Case_::TAG_,
        FOUND_    = (CASE_TAG_ == TAG || CASE_TAG_ == DEFAULT_)
    };

    typedef typename IfC<FOUND_,
                         typename Case_::Type,
                         typename Switch<TAG, NextCase_>::Type
                         >::Type Type;
};

template <int TAG>
struct Switch<TAG, NilCase>
{
    typedef NilCase Type;
};

// ----------------------------------------------------------------------------
// Metafunction Loop
// ----------------------------------------------------------------------------

/*!
 * @class Loop
 * @headerfile <seqan/basic.h>
 * @brief Helper for loops.
 *
 * @signature template <typename TWorker, unsigned COUNT>
 *            struct Loop;
 *
 * @tparam TWorker A struct with a static inline void function called <tt>body</tt>.  <tt>body</tt> should have two
 *                 parameters, one for passing in values and state from the outside and the second is an int.  The
 *                 function will be called <tt>COUNT</tt> times with the same reference for the first one and the values
 *                 <tt>COUNT</tt>, <tt>COUNT - 1</tt>, ..., <tt>1</tt> for the second parameter.
 * @tparam COUNT   An <tt>int</tt> constant.
 *
 * @section Example
 *
 * We define the following worker to print an integer.  The first argument is of <tt>Nothing</tt> as a dummy.  Note that
 * the parameter is not const.
 *
 * @snippet demos/basic/metaprogramming_control.cpp print worker
 *
 * The following shows an example calling <tt>PrintWorker::body()</tt> through Loop.  We have to create a local variable
 * since the first parameter is not const.  The reason for this is that the parameter can also be used for a mutable
 * object that holds some state.
 *
 * @snippet demos/basic/metaprogramming_control.cpp print worker call loop reverse
 *
 * @see LoopReverse
 *
 * @fn Loop::run
 * @brief Run the loop body.
 *
 * @signature Loop::run(arg, i);
 *
 * @param[in,out] arg The argument to pass to the worker's <tt>body()</tt> function.
 * @param[in]     i   The <tt>int</tt> passed to the <tt>body()</tt> function.
 */

// Example of a loop Worker class.  Could be removed, serves no
// purpose.
struct WorkerNothing
{
    template <typename Arg>
    static inline void body(Arg & /*arg*/, int /*I*/)
    {}
};

template <typename Worker, int I>
class Loop {
public:
    template <typename Arg>
    static inline void run(Arg & arg)
    {
        Loop<Worker, I - 1>::run(arg);
        Worker::body(arg, I);
    }
};

template <typename Worker>
class Loop<Worker, 0>
{
public:
    // end of loop
    template <typename Arg>
    static inline void run(Arg &)
    {}
};

// ----------------------------------------------------------------------------
// Metafunction LoopReverse
// ----------------------------------------------------------------------------

/*!
 * @class LoopReverse
 * @brief Helper for reverse loops.
 *
 * @headerfile <seqan/basic.h>
 *
 * @signature template <typename TWorker, unsigned COUNT>
 *            struct LoopReverse;
 *
 * @tparam TWorker A struct with a static inline void function called <tt>body</tt>.  <tt>body</tt> should have two
 *                 parameters, one for passing in values and state from the outside and the second is an int.  The
 *                 function will be called <tt>COUNT</tt> times with the same reference for the first one and the values
 *                 <tt>COUNT</tt>, <tt>COUNT - 1</tt>, ..., <tt>1</tt> for the second parameter.
 * @tparam COUNT   An <tt>int</tt> constant.
 *
 * @section Example
 *
 * We define the following worker to print an integer.  The first argument is of <tt>Nothing</tt> as a dummy.  Note that
 * the parameter is not const.
 *
 * @snippet demos/basic/metaprogramming_control.cpp print worker
 *
 * The following shows an example calling <tt>PrintWorker::body()</tt> through LoopReverse.  We have to create a local
 * variable since the first parameter is not const.  The reason for this is that the parameter can also be used for a
 * mutable object that holds some state.
 *
 * @snippet demos/basic/metaprogramming_control.cpp print worker call loop
 *
 * @see Loop
 *
 * @fn LoopReverse::run
 * @brief Run the loop body.
 *
 * @signature LoopReverse::run(arg, i);
 *
 * @param[in,out] arg The argument to pass to the worker's <tt>body()</tt> function.
 * @param[in]     i   The <tt>int</tt> passed to the <tt>body()</tt> function.
 */

template <typename Worker, int I>
class LoopReverse
{
public:
    template <typename Arg>
    static inline void run(Arg & arg)
    {
        Worker::body(arg, I);
        LoopReverse<Worker, I - 1>::run(arg);
    }
};

template <typename Worker>
class LoopReverse<Worker, 0>
{
  public:
    // end of loop
    template <typename Arg>
    static inline void run(Arg &) {}
};

// ============================================================================
// Functions
// ============================================================================

}  // namespace seqan

#endif  // #ifndef SEQAN_INCLUDE_SEQAN_BASIC_METAPROGRAMMING_CONTROL_H_


text:
export * from './wp-auth.decorator';
export * from './wp-collection.decorator';
export * from './wp-model.decorator';
export * from './wp-error.dectorator';


text:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;

using Khronos;

// ReSharper disable CheckNamespace
// ReSharper disable InconsistentNaming
// ReSharper disable JoinDeclarationAndInitializer

namespace OpenGL
{
	public partial class Gl
	{
		/// <summary>
		/// [GL] Value of GL_SUBSAMPLE_DISTANCE_AMD symbol.
		/// </summary>
		[RequiredByFeature("GL_AMD_framebuffer_sample_positions")]
		[RequiredByFeature("GL_AMD_sample_positions")]
		public const int SUBSAMPLE_DISTANCE_AMD = 0x883F;

		/// <summary>
		/// [GL] glSetMultisamplefvAMD: Binding for glSetMultisamplefvAMD.
		/// </summary>
		/// <param name="pname">
		/// A <see cref="T:int"/>.
		/// </param>
		/// <param name="index">
		/// A <see cref="T:uint"/>.
		/// </param>
		/// <param name="val">
		/// A <see cref="T:float[]"/>.
		/// </param>
		[RequiredByFeature("GL_AMD_sample_positions")]
		public static void SetMultisampleAMD(int pname, uint index, float[] val)
		{
			Debug.Assert(val.Length >= 2);
			unsafe {
				fixed (float* p_val = val)
				{
					Debug.Assert(Delegates.pglSetMultisamplefvAMD != null, "pglSetMultisamplefvAMD not implemented");
					Delegates.pglSetMultisamplefvAMD(pname, index, p_val);
					LogCommand("glSetMultisamplefvAMD", null, pname, index, val					);
				}
			}
			DebugCheckErrors(null);
		}

		internal static unsafe partial class Delegates
		{
			[RequiredByFeature("GL_AMD_sample_positions")]
			[SuppressUnmanagedCodeSecurity]
			internal delegate void glSetMultisamplefvAMD(int pname, uint index, float* val);

			[RequiredByFeature("GL_AMD_sample_positions")]
			[ThreadStatic]
			internal static glSetMultisamplefvAMD pglSetMultisamplefvAMD;

		}
	}

}


text:
import { Subscription } from './subscription';

export interface IMessage {
    subscribe(callback: (payload?: any) => void): number;
    unsubscribe(id: number): void;
    notify(payload?: any): void;
}

export class Message implements IMessage {

    private _subscriptions: Subscription[];
    private _nextId: number;

    constructor(public message: string) {
        this._subscriptions = [];
        this._nextId = 0;
    }

    public subscribe(callback: (payload?: any) => void) {
        var subscription = new Subscription(this._nextId++, callback);
        this._subscriptions[subscription.id] = subscription;

        return subscription.id;
    }

    public unsubscribe(id: number) {
        this._subscriptions[id] = undefined;
    }

    public notify(payload?: any) {
        for (var index: number = 0; index < this._subscriptions.length; index++) {
            if (this._subscriptions[index]) {
                this._subscriptions[index].callback(payload);
            }
        }
    }
}


text:
@interface GLLiveBodyView ()
@property (weak, nonatomic) IBOutlet UIImageView *coverImageView;
@property (weak, nonatomic) IBOutlet UIImageView *up_faceImageView;
@property (weak, nonatomic) IBOutlet UILabel *upLabel;
@property (weak, nonatomic) IBOutlet UILabel *onlineLabel;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;

@end

@implementation GLLiveBodyView

+ (instancetype)GLLiveBodyViewFromNib
{
    return [[[NSBundle mainBundle] loadNibNamed:@"GLLiveBodyView" owner:self options:nil] lastObject];
}

- (void)setBody:(NSDictionary *)body
{
    _body = body;

    NSNumber *onlineText =body[@"online"];

    [self.up_faceImageView sd_setImageWithURL:[NSURL URLWithString:body[@"up_face"]] placeholderImage:[UIImage imageNamed:@"placeholderImage1"]];
    [self.coverImageView sd_setImageWithURL:[NSURL URLWithString:body[@"cover"]] placeholderImage:[UIImage imageNamed:@"placeholderImage1"]];
    self.titleLabel.text = body[@"title"];
    self.onlineLabel.text = onlineText.stringValue;
    self.upLabel.text = body[@"up"];
}

@end


text:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

namespace SiteGroupCms.ajaxhandler
{
    public partial class loadright1 : SiteGroupCms.Ui.AdminCenter
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            SiteGroupCms.Entity.Admin _admin = (SiteGroupCms.Entity.Admin)Session["admin"];
            Response.Write(_admin.Rights);
        }
    }
}


text:
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;

/* @var $this yii\web\View */
/* @var $form yii\bootstrap\ActiveForm */
/* @var $model \frontend\models\ResetPasswordForm */

$this->title = 'Сброс пароля';
$this->params['breadcrumbs'][] = $this->title;
?>
<?= $this->render('_catalog', ['categories' => $categories]) ?>

<?= Html::encode($this->title) ?>

Введите новый пароль.

            <?php $form = ActiveForm::begin(['id' => 'reset-password-form']); ?>
                <?= $form->field($model, 'password')->passwordInput() ?>

                    <?= Html::submitButton('Сохранить', ['class' => 'btn btn-primary']) ?>

            <?php ActiveForm::end(); ?>

<?= $this->render('_footer',['page' => $post, 'type' => 'post']) ?>


text:
$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'svengali_gem'
require 'spec'
require 'spec/autorun'

Spec::Runner.configure do |config|

end


text:
package cgeo.geocaching.search;

import cgeo.geocaching.Intents;
import cgeo.geocaching.enumerations.CacheType;

import androidx.annotation.NonNull;

public class GeocacheSearchSuggestionCursor extends BaseSearchSuggestionCursor {

    public void addCache(@NonNull final String geocode, @NonNull final String name, final String type) {
        final int icon = CacheType.getById(type).markerId;
        addRow(new String[] {
            String.valueOf(rowId),
            name,
            geocode,
            Intents.ACTION_GEOCACHE,
            geocode,
            String.valueOf(icon)
        });
        rowId++;
    }

}


text:
import Immutable from 'immutable';
import uuid from 'node-uuid';
import * as date from '../utils/date';
import localforage from 'localforage';
import { addMessage } from './messages';

/*ACTION TYPES*/
export const ADD_NOTE = 'ADD_NOTE';
export const SELECT_NOTE = 'SELECT_NOTE';
export const UPDATE_NOTE = 'UPDATE_NOTE';
export const CLOSE_NOTE = 'CLOSE_NOTE';
export const DELETE_NOTE = 'DELETE_NOTE';
export const FETCHING_NOTES = 'FETCHING_NOTES';
export const LOADED_NOTES = 'LOADED_NOTES';
export const SAVE_ALL = 'SAVE_ALL';
export const LOCK_NOTES = 'LOCK_NOTES';
export const UNLOCKED_NOTES = 'UNLOCKED_NOTES';

/*ACTION CREATORS*/
export const fetchingNotes = () => {
  return {type: FETCHING_NOTES}
}
export const fetchNotes = (username, key) => {
  return dispatch => {
    dispatch(fetchingNotes())
    let notes = Immutable.List();
    let decrypted = Immutable.Map();

    const store = localforage.createInstance({
      name: username
    })

    store.length((err, number) => {
      if (!number) {
        return dispatch({type: LOADED_NOTES, store, notes})
      }
    })

    store.iterate((content, id, i) => {
      notes = notes.push(
        Immutable.Map({saved: true, id, content, decrypted}));
    })
    .then(() => {
      if (!key.ring) {
        return dispatch({type: LOADED_NOTES, store, notes})
      }
      else {
        Promise.all(
          notes.map(note => {return decrypt(note, key)})
        ).then(notes => {
          let decryptedNotes = Immutable.List(notes);
          return dispatch({type: LOADED_NOTES, notes: decryptedNotes, store})
        })
      }
    })
  }
}

export const addNote = () => {
  const now = date.now();
  const note = Immutable.Map({
    id: uuid.v4(),
    saved: true,
    content: '',
    decrypted: Immutable.Map({
      title: 'Untitled',
      body: '',
      created: now,
      updated: now
    })
  })

  return { type: ADD_NOTE, note };
}

export const selectNote = (id) => {
  return (dispatch, getState) => {
    const { notes } = getState();
    const note = notes.find(note => note.get('id') === id);
    return dispatch({type: SELECT_NOTE, note});
  }
}

export const closeNote = () => {
  return {type: CLOSE_NOTE}
}

export const renameNote = (id) => {
  return dispatch => {
    const message = {
      title: 'Rename Note',
      body: '',
      type: 'message',
      action: {
        type: 'prompt',
        after: (title) => dispatch(updateNote(id, {title}, () => dispatch(saveNote(id)))),
        label: 'Rename'
      }
    }
    dispatch(addMessage(message))
  }
}

export const updateNote = (id, {title, body, saved, content, updated}, cb) => {
  return (dispatch, getState) => {
    let {notes} = getState();
    const index = notes.findIndex(note => note.get('id') === id);
    const note = notes.get(index);
    saved = saved || false;
    updated = updated || date.now();

    const changes = Immutable.Map({
      content: content,
      saved: saved,
      decrypted: Immutable.Map({
        title: title,
        body: body,
        updated: updated
      })
    })

    const update = note.mergeDeepWith((prev, next) => {
      if (typeof next === 'undefined') {
        return prev;
      }
      return next;
    }, changes);

    if (cb) {
      cb();
    }

    return dispatch({ type: UPDATE_NOTE, index, update });
  }
}

export const saveAll = (lock = false) => {
  return (dispatch, getState) => {
    let { notes } = getState();

    if (lock) {
      notes.forEach(note => {dispatch(saveAndLockNote(note.get('id')))})
    }
    else {
      notes.filter(note => !note.get('saved'))
           .forEach(note => {dispatch(saveNote(note.get('id')))})
    }

    console.log('Saved all the unsaved notes');
  }
}

export const saveNote = (id) => {
  return (dispatch, getState) => {
    const {key, notes, notesStore} = getState();
    const note = notes.find(note => note.get('id') === id);

    const title = note.getIn(['decrypted', 'title']);
    const body = note.getIn(['decrypted', 'body']);
    const created = note.getIn(['decrypted', 'created']);
    const updated = date.now();

    key.encrypt({title, body, created, updated})
      .then(content => {
        notesStore.setItem(id, content).then(() => {
          console.log('Successfully Saved Note');
          dispatch(updateNote(id, {saved: true, content, updated}));
        })
      })
      .catch(err => console.error(err))
  }
}

export const saveAndLockNote = (id) => {
  return (dispatch, getState) => {
    const {key, notes, notesStore} = getState();
    const index = notes.findIndex(note => note.get('id') === id);
    const note = notes.get(index);

    if (note.saved) {
      let update = Immutable.Map({
        saved: true,
        decrypted: Immutable.Map(),
        content: note.get('content'),
        id
      })
      return dispatch({ type: UPDATE_NOTE, index, update });
    }

    const title = note.getIn(['decrypted', 'title']);
    const body = note.getIn(['decrypted', 'body']);
    const created = note.getIn(['decrypted', 'created']);
    const updated = date.now();

    key.encrypt({title, body, created, updated})
      .then(content => {
        notesStore.setItem(id, content).then(() => {
          console.log('Successfully Saved Note');
          let update = Immutable.Map({
            saved: true, decrypted: Immutable.Map(), id, content
          })
          dispatch({ type: UPDATE_NOTE, index, update });
        })
      })
      .catch(err => console.error(err))
  }
}

export const lockNotes = () => {
  return (dispatch, getState) => {
    let { notes } = getState();
    notes = notes.map(n => n.set('saved', true).set('decrypted', Immutable.Map()))
    console.log('Locked Notes')
    dispatch({type: LOCK_NOTES, notes})
  }
}

const decrypt = (note, key) => {
  return new Promise((resolve, reject) => {
    let {id, content} = note.toJS();
    key.decrypt(content)
      .then(decrypted => {
        let decryptedNote = Immutable.Map({
          decrypted: Immutable.Map(decrypted)
        })
        return resolve(note.merge(decryptedNote))
      })
  })
}

export const unlockNotes = () => {
  return (dispatch, getState) => {
    let {key, notes} = getState();

    let decryptedNotes = Promise.all(
      notes.map(note => {return decrypt(note, key)})
    ).then(notes => {
      let decryptedNotes = Immutable.List(notes);
      return dispatch({type: UNLOCKED_NOTES, notes: decryptedNotes})
    })

  }
}

export const deleteNote = (id) => {
  return (dispatch, getState) => {
    const {notes, notesStore} = getState();
    const index = notes.findIndex(note => note.get('id') === id);
    const message = {
      title: 'Are you sure?',
      body: 'Delete this note?',
      action: {
        type: 'confirm',
        after: () => { return {type: DELETE_NOTE, index, id}},
        label: 'Delete'
      }
    }
    notesStore.removeItem(id, (err) => {
      if (err) {
        console.error(err)
        return dispatch(addMessage({
          title: 'Uh Oh. Something went wrong',
          body: 'There was an error deleting this note.'
        }))
      }
      return dispatch(addMessage(message));
    })
  }
}


text:
package io.github.htools.io.struct;

import io.github.htools.io.Datafile;
import io.github.htools.io.buffer.BufferReaderWriter;
import io.github.htools.lib.Log;
import io.github.htools.search.ByteSearch;
import io.github.htools.search.ByteSearchSection;
import io.github.htools.search.ByteSection;

import java.util.ArrayList;

/**
 * Structures data in a tab-delimited file for processing with Pig.
 * <p>
 * @author jeroen
 */
public abstract class StructuredTextPig extends StructuredTextCSV {

    public static Log log = new Log(StructuredTextPig.class);
    private static final ByteSearch open = ByteSearch.create("");
    private static final ByteSearch close = ByteSearch.create("\t");
    private static final ByteSearch closecomma = ByteSearch.create(",\\s*");
    private static final ByteSearch empty = ByteSearch.create("");
    private static final ByteSearch braceopen = ByteSearch.create("\\{");
    private static final ByteSearch braceclose = ByteSearch.create("\\}\\s*");
    private static final ByteSearch brackopen = ByteSearch.create("\\,?\\s*\\(");
    private static final ByteSearch brackclose = ByteSearch.create("\\)");
    private static final ByteSection brace = braceopen.toSection(braceclose);
    private static final ByteSection brack = brackopen.toSection(brackclose);
    private static final ByteSearch closeline = ByteSearch.create("($|\n)");

    public StructuredTextPig(BufferReaderWriter reader) {
        super(reader);
    }

    public StructuredTextPig(Datafile writer) {
        super(writer);
    }

    @Override
    public FolderNode createRoot() {
        return addNode(null, "root", ByteSearch.create(""), ByteSearch.create("($|\n)"), "", "\n");
    }

    /**
     * Before first use, the last node in each (nested) folder is modified and
     * the separators within bags are changed to , instead of \t
     */
    @Override
    public void rebuildBeforeFirstUse() {
        setTerminators(getRoot());
    }

    private void setTerminators(FolderNode root) {
        Node last = root.orderedfields.get(root.orderedfields.size() - 1);
        for (Node n : root.orderedfields) {
            if (n instanceof FolderNode) {
                setTerminators((FolderNode) n);
                if (n != last) {
                    n.closelabel = "}\t";
                }
            } else if (n != last) {
                if (root == getRoot()) {
                    n.setOpenClose(open, close);
                    n.closelabel = "\t";
                } else {
                    n.setOpenClose(open, closecomma);
                    n.closelabel = ",";
                }
            }
        }
    }

    public class Bag extends FolderNode {

        protected Bag(FolderNode parent, String label) {
            super(parent, label, braceopen, braceclose, "{", "}");
        }

        @Override
        protected ByteSearchSection readNode(ByteSearchSection section) {
            for (ByteSearchSection s : section.findAllSections(brack)) {
                this.addAnother();
                for (Node f : orderedfields) {
                    ByteSearchSection pos = findSection(s, f.section);
                    if (pos.found()) {
                        pos = f.readNode(pos);
                        s.movePast(pos);
                    }
                }
            }
            return section;
        }

        @Override
        protected void write(ArrayList list) {
            if (list != null && list.size() > 0) {
                if (openlabel.length() > 0) {
                    datafile.printf("%s", openlabel);
                }
                boolean firsttuple = true;
                for (NodeValue v : (ArrayList<NodeValue>) list) {
                    if (v.size() > 0) {
                        if (firsttuple) {
                            firsttuple = false;
                        } else {
                            datafile.printf(",");
                        }
                        datafile.printf("(");
                        boolean firstfield = true;
                        for (Node f : orderedfields) {
                            if (firstfield) {
                                firstfield = false;
                            } else {
                                datafile.printf(",");
                            }
                            ArrayList subvalues = v.get(f.label);
                            if (subvalues != null) {
                                f.write(subvalues);
                            } else {
                                log.fatal("Attempted to write an OrderedNode with value %s unset", f.label);
                            }
                        }
                        datafile.printf(")");
                    }
                }
                if (closelabel.length() > 0) {
                    datafile.printf("%s", closelabel);
                }
            }
        }
    }

    public IntField addInt(FolderNode parent, String label) {
        return addInt(parent, label, open, empty, "", "");
    }

    public BoolField addBoolean(FolderNode parent, String label) {
        return addBoolean(parent, label, open, empty, "", "");
    }

    public LongField addLong(FolderNode parent, String label) {
        return addLong(parent, label, open, empty, "", "");
    }

    public DoubleField addDouble(FolderNode parent, String label) {
        return addDouble(parent, label, open, empty, "", "");
    }

    public StringField addString(FolderNode parent, String label) {
        return addString(parent, label, open, empty, "", "");
    }

    public IntField addInt(String label) {
        return addInt(getRoot(), label);
    }

    public LongField addLong(String label) {
        return addLong(getRoot(), label);
    }

    public DoubleField addDouble(String label) {
        return addDouble(getRoot(), label);
    }

    public StringField addString(String label) {
        return addString(getRoot(), label);
    }

    public BoolField addBoolean(String label) {
        return addBoolean(getRoot(), label);
    }

    public Bag addBag(String label) {
        return addBag(getRoot(), label);
    }

    public Bag addBag(FolderNode folder, String label) {
        Bag bag = new Bag(folder, label);
        return bag;
    }

    public void write(StructuredTextPigTuple t) {
        t.write(this);
    }
}


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

<meta charset="utf-8" />
<meta name="generator" content="skuro.tk/0.1 | jekyll/2.0.3" />
<meta name="description" content="Personal Blog of Carlo Sciolla (skuro)" />
<meta name="keywords" content="skuro, carlo sciolla, clojure, backbase, biography, architecture" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />

<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://skuro.tk/img/avatar.jpg">
<meta name="twitter:title" content="About me">
<meta name="twitter:description" content="Personal Blog of Carlo Sciolla (skuro)">
<meta name="twitter:creator" content="@skuro">

<meta property="og:locale" content="en_US">
<meta property="og:type" content="article">
<meta property="og:title" content="About me">
<meta property="og:description" content="Personal Blog of Carlo Sciolla (skuro)">
<meta property="og:url" content="http://skuro.tk/about/">
<meta property="og:site_name" content="SKURO! -- Shading lights">

<link rel="stylesheet" href="/stylesheets/bootstrap.min.css" type="text/css" />

<link rel="stylesheet" href="/stylesheets/skuro.css" type="text/css" />

<title>About me @ SKURO! -- Shading lights</title>

                SKURO!

Archive

Categories

About me

                            <button type="button" class="btn btn-default"></button>
                            <button type="button" class="btn btn-default"></button>
                            <button type="button" class="btn btn-default"></button>
                            <button type="button" class="btn btn-default"></button>

      Spring Environment is for initialization code only

    About me

    November 20, 2011

Patrias est mellus a ddas tenni prus de una

Joice Lussu

This little piece of blogosphere is owned by skuro, a.k.a. Carlo
Sciolla. I'm an IT professional by day and Clojurian,
meetup organizer, open source developer, biker and, well, blogger by
night.

Work stuff

I grew up from fiddling with embedded linux systems, to mobile
development, to mainstream Java™ backend development. I got
certified as an Alfresco Recognized Developer on 2011.

I currently work at Backbase, where I act
as the Technical Managerfor the server components of the Backbase CXP product.

Clojure

This awesome functional programming language is the current sink of most of my spare time. Besides coding, I try to contribute to its already great community by organizing the Amsterdam Clojurians Meetup.

Open Source

There simply isn't any other way of doing software (said the guy that
works for a closed source software company). I contribute at different
levels to the following open source projects:

plan-maven-plugin -- Unravel your maven build

lambdalf -- Clojure bridge for Alfresco

spring-webscripts-clojure-plugin -- The name tells it all

maven-alfresco-archetypes -- Properly build your Alfresco projects

Please enable JavaScript to view the comments powered by Disqus.
blog comments powered by Disqus

              SKURO! blog by

                Carlo Sciolla

              All text licensed under CC BY 3.0

              All code licensed under MIT unless otherwise specified


text:
//
//  CreatePlaylistTableTableViewController.m
//  Soundrocket
//
//  Created by Sebastian Boldt on 03.01.15.
//  Copyright (c) 2015 sebastianboldt. All rights reserved.
//

#import "CreatePlaylistTableTableViewController.h"
#import <MBProgressHUD.h>
#import "SoundtraceClient.h"
#import <SVProgressHUD.h>
#import "CredentialStore.h"
@interface CreatePlaylistTableTableViewController ()
@property(nonatomic,strong) CredentialStore * store;
@end

@implementation CreatePlaylistTableTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.store = [[CredentialStore alloc]init];

    if (self.playlist) {
        self.nameOfPlaylistTextField.text = self.playlist.title;
        if ([self.playlist.sharing isEqualToString:@"public"]) {
            [self.sharingSwitch setOn:YES];
        } else {
            [self.sharingSwitch setOn:NO];
        }
        [self.createPlaylistButton setTitle:@"Update Playlist" forState:UIControlStateNormal];
    } else {
        UIBarButtonItem * cancelIcon = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(close:)];
        self.navigationItem.leftBarButtonItem = cancelIcon;
        [self.createPlaylistButton setTitle:@"Create Playlist" forState:UIControlStateNormal];
    }
}

-(void)close:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

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

/**
 *  Creates a completly new Playlist
 *
 *  @param name   name of Playlist
 *  @param public public or private ?
 */
-(void)createPlaylistWithName:(NSString*)name  andSharingoption:(BOOL)public{

    [[UIApplication sharedApplication] beginIgnoringInteractionEvents];
    [self.nameOfPlaylistTextField resignFirstResponder];
    [SVProgressHUD showWithStatus:@"Creating playlist"];
    NSMutableDictionary * paramters = [[NSMutableDictionary alloc]init];
    [paramters setObject:self.store.authToken forKey:@"oauth_token"];

    NSMutableDictionary * playlist = [[NSMutableDictionary alloc]init];
    [playlist setObject:name forKey:@"title"];

    if (public) {
        [playlist setObject:@"public" forKey:@"sharing"];
    } else {
        [playlist setObject:@"private" forKey:@"sharing"];

    }

    [paramters setObject:playlist forKey:@"playlist"];
    [[SoundtraceClient sharedClient] POST:@"/playlists" parameters:paramters

     success: ^(NSURLSessionDataTask *task, id responseObject)
     {
         [[UIApplication sharedApplication] endIgnoringInteractionEvents];
         [self dismissViewControllerAnimated:YES completion:^(){
             [self.createPlaylistDelegate playlistCreated];
             [SVProgressHUD showSuccessWithStatus:@"Created Playlist"];

         }];
     }

        failure: ^(NSURLSessionDataTask *task, NSError *error)
     {
         // Fehlerbehandlung
         [[UIApplication sharedApplication] endIgnoringInteractionEvents];
         [SVProgressHUD showErrorWithStatus:@"Something went wrong, please try again"];

     }];
}
/**
 *  Updates a Playlist
 *
 *  @param name   name of Playlist
 *  @param public public or private
 */
-(void)updatePlaylistWithName:(NSString*)name  andSharingoption:(BOOL)public{
    [[UIApplication sharedApplication] beginIgnoringInteractionEvents];

    [self.nameOfPlaylistTextField resignFirstResponder];
    [SVProgressHUD showWithStatus:@"Updating playlist"];
    NSMutableDictionary * paramters = [[NSMutableDictionary alloc]init];
    [paramters setObject:self.store.authToken forKey:@"oauth_token"];

    NSMutableDictionary * playlist = [[NSMutableDictionary alloc]init];
    [playlist setObject:name forKey:@"title"];

    if (public) {
        [playlist setObject:@"public" forKey:@"sharing"];
    } else {
        [playlist setObject:@"private" forKey:@"sharing"];

    }

    [paramters setObject:playlist forKey:@"playlist"];
    [[SoundtraceClient sharedClient] PUT:[NSString stringWithFormat:@"/playlists/%@",self.playlist.id] parameters:paramters

     success: ^(NSURLSessionDataTask *task, id responseObject)
     {
         [[UIApplication sharedApplication] endIgnoringInteractionEvents];
         [self.navigationController popViewControllerAnimated:YES];
         [SVProgressHUD showSuccessWithStatus:@"Updated Playlist"];
     }

    failure: ^(NSURLSessionDataTask *task, NSError *error)
     {
         // Fehlerbehandlung
         [SVProgressHUD showErrorWithStatus:@"Something went wrong, please try again"];
         [[UIApplication sharedApplication] endIgnoringInteractionEvents];

     }];
}

- (IBAction)createPlaylistButtonPressed:(id)sender {
    if (self.playlist) {
        [self updatePlaylistWithName:self.nameOfPlaylistTextField.text andSharingoption:self.sharingSwitch.on];
    } else {
        [self createPlaylistWithName:self.nameOfPlaylistTextField.text andSharingoption:self.sharingSwitch.on];
    }
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (self.playlist) {
        return @"Update Playlist";
    } else {
        return @"Create Playlist";
    }
}
@end


text:
#include "StdH.h"
#include "Shader.h"
#include "Game.h"

#include <GL/glew.h>

using namespace Scratch;

#define OGL_CHECK_ERROR() { \
		GLenum err = glGetError(); \
		if(err != GL_NO_ERROR) { \
			printf("OGL Error on line %d: %d (%s)\n", __LINE__, err, glewGetErrorString(err)); \
		} \
	}

MRAGPP_NAMESPACE_BEGIN;

CShader::CShader()
{
	sha_bReady = false;

	sha_iProgram = 0;
	sha_iShaderVertex = 0;
	sha_iShaderFragment = 0;
	sha_iPosAttrib = -1;
	sha_iTexCoordAttrib = -1;

	sha_strFragDataLocation = "s_colOut";
	sha_strInPosName = "in_vPos";
	sha_strInTexCoordName = "in_vTexCoord";
}

CShader::~CShader()
{
	Clear();
}

void CShader::Clear()
{
	if(sha_iProgram > 0) {
		glDeleteProgram(sha_iProgram);
		sha_iProgram = 0;
	}
	if(sha_iShaderVertex > 0) {
		glDeleteShader(sha_iShaderVertex);
		sha_iShaderVertex = 0;
	}
	if(sha_iShaderFragment > 0) {
		glDeleteShader(sha_iShaderFragment);
		sha_iShaderFragment = 0;
	}
	sha_bReady = false;
}

bool CShader::LoadShader(const Filename &fnm, int type)
{
	// load the code from file
	String strCode;
	FileStream fs;
	fs.Open(fnm, "r");
	while(!fs.AtEOF()) {
		strCode += fs.ReadLine() + "\n";
	}
	fs.Close();

	// create the program if we don't have one yet
	if(sha_iProgram == 0) {
		sha_iProgram = glCreateProgram();
	}

	// compile the shader and attach to the program it if it succeeded
	bool bSuccess = false;
	GLuint iShader = CompileShader(strCode, type, bSuccess);
	if(bSuccess) {
		glAttachShader(sha_iProgram, iShader);
		if(type == GL_VERTEX_SHADER) {
			sha_iShaderVertex = iShader;
		} else if(type == GL_FRAGMENT_SHADER) {
			sha_iShaderFragment = iShader;
		}
	}
	return bSuccess;
}

unsigned int CShader::CompileShader(const char* str, int type, bool &bSuccess)
{
	// create a new shader
	GLuint iShader = glCreateShader(type);
	const GLchar* aSourceVertex[] = { str };
	glShaderSource(iShader, 1, aSourceVertex, NULL);
	glCompileShader(iShader);

	// check if compiling went okay
	GLint bShaderCompiled = GL_FALSE;
	glGetShaderiv(iShader, GL_COMPILE_STATUS, &bShaderCompiled);
	if(bShaderCompiled != GL_TRUE) {
		// it did not.
		printf("Error compiling %sshader:\n", (type == GL_VERTEX_SHADER ? "vertex " : ""));
		int iLogLength = 0;
		int iMaxLength = 0;
		glGetShaderiv(iShader, GL_INFO_LOG_LENGTH, &iMaxLength);
		char* buffer = new char[iMaxLength];
		glGetShaderInfoLog(iShader, iMaxLength, &iLogLength, buffer);
		if(iLogLength > 0) {
			printf("%s\n", buffer);
		}
		delete[] buffer;

		// report it back
		bSuccess = false;
		// and delete the shader
		glDeleteShader(iShader);
	} else {
		// it worked!
		bSuccess = true;
	}

	// return shader
	return iShader;
}

bool CShader::LinkProgram(CGame* pGame)
{
	sha_pGame = pGame;

	// explicitly define what the fragment data location is
	glBindFragDataLocation(sha_iProgram, 0, sha_strFragDataLocation);

	// link the program
	glLinkProgram(sha_iProgram);

	// check if program linking went okay
	GLint bProgramLinked = GL_FALSE;
	glGetProgramiv(sha_iProgram, GL_LINK_STATUS, &bProgramLinked);
	if(bProgramLinked != GL_TRUE) {
		// it did not.
		printf("Error linking shader program:\n");
		int iLogLength = 0;
		int iMaxLength = 0;
		glGetProgramiv(sha_iProgram, GL_INFO_LOG_LENGTH, &iMaxLength);
		char* buffer = new char[iMaxLength];
		glGetProgramInfoLog(sha_iProgram, iMaxLength, &iLogLength, buffer);
		if(iLogLength > 0) {
			printf("%s\n", buffer);
		}
		delete[] buffer;
		return false;
	}

	// get input attribute for vertex shader position
	sha_iPosAttrib = glGetAttribLocation(sha_iProgram, sha_strInPosName);
	if(sha_iPosAttrib == -1) {
		printf("Couldn't find position attribute\n");
	}

	// get input attribute for vertex shader texcoord
	sha_iTexCoordAttrib = glGetAttribLocation(sha_iProgram, sha_strInTexCoordName);
	if(sha_iTexCoordAttrib == -1) {
		// don't report, because this is most likely intentional
		//printf("Couldn't find texcoord attribute\n");
	}

	sha_bReady = true;
	return true;
}

bool CShader::LoadVertexShader(const Filename &fnmVertex)
{
	return LoadShader(fnmVertex, GL_VERTEX_SHADER);
}

bool CShader::LoadFragmentShader(const Filename &fnmFragment)
{
	return LoadShader(fnmFragment, GL_FRAGMENT_SHADER);
}

int CShader::GetUniform(const char* szUniform)
{
	return glGetUniformLocation(sha_iProgram, szUniform);
}

void CShader::SetUniform1i(int iUniform, int iValue)
{
	ASSERT(iUniform != -1);
	glUniform1i(iUniform, iValue);
}

void CShader::SetUniform1i(const char* szUniform, int iValue)
{
	SetUniform1i(GetUniform(szUniform), iValue);
}

void CShader::SetUniform1f(int iUniform, float fValue)
{
	ASSERT(iUniform != -1);
	glUniform1f(iUniform, fValue);
}

void CShader::SetUniform1f(const char* szUniform, float fValue)
{
	SetUniform1f(GetUniform(szUniform), fValue);
}

void CShader::SetUniform2f(int iUniform, const Vector2f &v)
{
	ASSERT(iUniform != -1);
	glUniform2f(iUniform, v(1), v(2));
}

void CShader::SetUniform2f(const char* szUniform, const Vector2f &v)
{
	SetUniform2f(GetUniform(szUniform), v);
}

void CShader::SetUniform3f(int iUniform, const Vector3f &v)
{
	ASSERT(iUniform != -1);
	glUniform3f(iUniform, v(1), v(2), v(3));
}

void CShader::SetUniform3f(const char* szUniform, const Vector3f &v)
{
	SetUniform3f(GetUniform(szUniform), v);
}

void CShader::SetUniform3f(int iUniform, COLOR col)
{
	ASSERT(iUniform != -1);
	COLOR_VALUE r, g, b;
	MRAG_COLOR_EXPLODE_RGB(col, r, g, b);
	glUniform3f(iUniform, r / 255.0f, g / 255.0f, b / 255.0f);
}

void CShader::SetUniform3f(const char* szUniform, COLOR col)
{
	SetUniform3f(GetUniform(szUniform), col);
}

void CShader::SetUniform4f(int iUniform, const Vector4f &v)
{
	ASSERT(iUniform != -1);
	glUniform4f(iUniform, v(1), v(2), v(3), v(4));
}

void CShader::SetUniform4f(const char* szUniform, const Vector4f &v)
{
	SetUniform4f(GetUniform(szUniform), v);
}

void CShader::SetUniform4f(int iUniform, COLOR col)
{
	ASSERT(iUniform != -1);
	COLOR_VALUE r, g, b, a;
	MRAG_COLOR_EXPLODE_RGBA(col, r, g, b, a);
	glUniform4f(iUniform, r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f);
}

void CShader::SetUniform4f(const char* szUniform, COLOR col)
{
	SetUniform4f(GetUniform(szUniform), col);
}

void CShader::SetUniformSampler(int iUniform, CTexture &texture)
{
	ASSERT(iUniform != -1);

	int iSlot = sha_saSamplers.Count();

	glActiveTexture(GL_TEXTURE0 + iSlot);
	SDL_GL_BindTexture(texture, NULL, NULL);
	glUniform1i(iUniform, iSlot);

	sha_saSamplers.Push(&texture);
}

void CShader::SetUniformSampler(const char* szUniform, CTexture &texture)
{
	SetUniformSampler(GetUniform(szUniform), texture);
}

#define X_TO_GL(x) (((2.0f / (float)sha_pGame->gam_iWidth) * (x)) - 1.0f)
#define Y_TO_GL(y) -(((2.0f / (float)sha_pGame->gam_iHeight) * (y)) - 1.0f)

void CShader::Use()
{
	ASSERT(sha_saSamplers.Count() == 0);

	// bind program
	glUseProgram(sha_iProgram);

	// enable attributes
	glEnableVertexAttribArray(sha_iPosAttrib);
	glEnableVertexAttribArray(sha_iTexCoordAttrib);
}

void CShader::Release()
{
	// unbind samplers
	while(sha_saSamplers.Count() > 0) {
		glActiveTexture(GL_TEXTURE0 + sha_saSamplers.Count() - 1);
		SDL_GL_UnbindTexture(*sha_saSamplers.Pop());
	}

	// disable attributes
	glDisableVertexAttribArray(sha_iPosAttrib);
	glDisableVertexAttribArray(sha_iTexCoordAttrib);

	// unbind program
	glUseProgram(0);
}

void CShader::PutQuad(float x, float y, float w, float h)
{
	float fTopLeftX = X_TO_GL(x);
	float fTopLeftY = Y_TO_GL(y);
	float fBotRightX = X_TO_GL(x + w);
	float fBotRightY = Y_TO_GL(y + h);

	if(sha_saSamplers.Count() > 0) {
		float aVertexData[] = {
			// vertices
			/*
			-0.5f, -0.5f,
			 0.5f, -0.5f,
			 0.5f,  0.5f,
			-0.5f,  0.5f,
			*/
			fTopLeftX, fTopLeftY,
			fBotRightX, fTopLeftY,
			fBotRightX, fBotRightY,
			fTopLeftX, fBotRightY,

			// texcoords
			-1.0f, -1.0f,
			 1.0f, -1.0f,
			 1.0f,  1.0f,
			-1.0f,  1.0f
		};
		sha_vbo.Set(aVertexData, 4, true);
	} else {
		float aVertexData[] = {
			// vertices
			fTopLeftX, fTopLeftY,
			fBotRightX, fTopLeftY,
			fBotRightX, fBotRightY,
			fTopLeftX, fBotRightY
		};
		sha_vbo.Set(aVertexData, 4, false);
	}

	// set layout of vertex data
	glBindBuffer(GL_ARRAY_BUFFER, sha_vbo.vbo_iVBO);
	glVertexAttribPointer(sha_iPosAttrib, 2, GL_FLOAT, GL_FALSE, 0, NULL);

	// set layout of texcoord data if needed
	if(sha_saSamplers.Count() > 0) {
		glVertexAttribPointer(sha_iTexCoordAttrib, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), (void*)(8 * sizeof(GLfloat)));
	}

	// set index data and render
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, sha_vbo.vbo_iIBO);
	glDrawElements(GL_TRIANGLE_FAN, 4, GL_UNSIGNED_INT, NULL);
}

#undef XY_TO_GL

MRAGPP_NAMESPACE_END;


text:
Tasks list

    {{remaining()}} task/s remaining of {{count}}
    {{msgAlert}}
    <button ng-click="delSelectedTasks()" class="btn btn-default btn-danger btDelete">DELETE
        {{countDelete}}</button>

                        <input type="checkbox" ng-change="selection(task)" ng-model="task.done">

                    {{task.text}}

<form ng-submit="addTask()">

            <input type="text" class="form-control empty-{{empty}}" placeholder="Add an item"
                   ng-model="textNewTask" ng-change="verifyText()">

                        <button class="btn btn-default btn-primary" type="submit">Add</button>

</form>


text:
<?php

namespace Diside\SecurityComponent\Gateway;

use Diside\SecurityComponent\Model\Page;

interface Gateway
{
    /**
     * @param array $filters
     * @param int $pageIndex
     * @param int $pageSize
     * @return array
     */
    public function findAll(array $filters = array(), $pageIndex = 0, $pageSize = PHP_INT_MAX);

    /**
     * @return int
     */
    public function countAll(array $filters = array());

    /**
     * @return string
     */
    public function getName();
}


text:
from pycket                          import values
from pycket.arity                    import Arity
from pycket.base                     import W_Object
from pycket.cont                     import call_cont, continuation, BaseCont
from pycket.error                    import SchemeException
from pycket.hash.persistent_hash_map import make_persistent_hash_type
from rpython.rlib                    import jit, objectmodel
from rpython.rlib.rarithmetic        import r_uint

@objectmodel.always_inline
def compute_hash(x):
    assert objectmodel.we_are_translated() or type(x) is ParamKey
    return r_uint(objectmodel.compute_hash(x))

@objectmodel.always_inline
def equal(a, b):
    assert objectmodel.we_are_translated() or type(a) is ParamKey
    assert objectmodel.we_are_translated() or type(b) is ParamKey
    return a is b

ParameterizationHashTable = make_persistent_hash_type(
    super   = W_Object,
    name    = "ParameterizationHashTable",
    hashfun = compute_hash,
    equal   = equal)

# This is a Scheme_Parameterization in Racket
class RootParameterization(object):
    _attrs_ = ["table"]
    def __init__(self):
        # This table maps ParamKey -> W_ThreadCell
        self.table = {}

# This is a Scheme_Config in Racket
# Except that Scheme_Config uses a functional hash table and this uses a list that we copy
class W_Parameterization(W_Object):
    _immutable_fields_ = ["root", "map"]
    _attrs_ = ["root", "map"]
    errorname = "parameterization"
    def __init__(self, root, map):
        self.root = root
        self.map  = map

    @jit.look_inside_iff(lambda self, params, vals: \
            jit.loop_unrolling_heuristic(params, len(params), values.UNROLLING_CUTOFF) and
            jit.loop_unrolling_heuristic(vals, len(vals), values.UNROLLING_CUTOFF))
    def extend(self, params, vals):
        assert len(params) == len(vals)
        map = self.map
        for i, param in enumerate(params):
            cell = values.W_ThreadCell(vals[i], True)
            map = map.assoc(param.get_key(), cell)
        return W_Parameterization(self.root, map)

    @jit.elidable
    def get(self, param):
        key = param.key
        result = self.map.val_at(key, None)
        if result is not None:
            return result
        result = self.root.table[key]
        assert result is not None
        return result

    def tostring(self):
        return "#<parameterization>"

# This will need to be thread-specific
top_level_config = W_Parameterization(RootParameterization(), ParameterizationHashTable.EMPTY)

def find_param_cell(cont, param):
    assert isinstance(cont, BaseCont)
    p = cont.get_mark_first(values.parameterization_key)
    assert isinstance(p, W_Parameterization)
    assert isinstance(param, W_Parameter)
    v = p.get(param)
    assert isinstance(v, values.W_ThreadCell)
    return v

@continuation
def param_set_cont(cell, env, cont, vals):
    from pycket.interpreter import check_one_val, return_value
    v = check_one_val(vals)
    cell.set(v)
    return return_value(values.w_void, env, cont)

# a token
# Must be a subclass of W_Object to fit into immutable hash tables
class ParamKey(W_Object):
    _attrs_ = []
    def __init__(self):
        pass

class W_BaseParameter(W_Object):
    errorname = "parameter"
    _attrs_ = ["guard"]
    _immutable_fields_ = ["guard"]

    ARITY = Arity.oneof(0, 1)

    def __init__(self, guard=None):
        self.guard = None if guard is values.w_false else guard

    def iscallable(self):
        return True

    def get_key(self):
        raise NotImplementedError("abstract base class")

    def get_arity(self, promote=False):
        return W_BaseParameter.ARITY

    def tostring(self):
        return "#<parameter-procedure>"

class W_Parameter(W_BaseParameter):
    _immutable_fields_ = ["key"]
    _attrs_ = ["key"]

    def __init__(self, val, guard=None):
        W_BaseParameter.__init__(self, guard)
        self.key = ParamKey()
        cell = values.W_ThreadCell(val, True)
        top_level_config.root.table[self.key] = cell

    def get(self, cont):
        return self.get_cell(cont).get()

    def get_cell(self, cont):
        cell = find_param_cell(cont, self)
        assert isinstance(cell, values.W_ThreadCell)
        return cell

    def get_key(self):
        return self.key

    def call(self, args, env, cont):
        from pycket.interpreter import return_value
        if len(args) == 0:
            return return_value(self.get(cont), env, cont)
        elif len(args) == 1:
            cell = find_param_cell(cont, self)
            assert isinstance(cell, values.W_ThreadCell)
            if self.guard:
                return self.guard.call([args[0]], env, param_set_cont(cell, env, cont))
            else:
                cell.set(args[0])
                return return_value(values.w_void, env, cont)
        else:
            raise SchemeException("wrong number of arguments to parameter")

class W_DerivedParameter(W_BaseParameter):
    _immutable_fields_ = ["parameter", "wrap"]
    _attrs_ = ["parameter", "wrap"]

    def __init__(self, param, guard, wrap):
        W_BaseParameter.__init__(self, guard)
        self.parameter = param
        self.wrap      = wrap

    def get(self, cont):
        return self.parameter.get(cont)

    def get_cell(self, cont):
        return self.parameter.get_cell(cont)

    def get_key(self):
        return self.parameter.get_key()

    def call(self, args, env, cont):
        from pycket.interpreter import return_value

        if len(args) == 0:
            return self.parameter.call(args, env, call_cont(self.wrap, env, cont))
        elif len(args) == 1:
            if self.guard:
                return self.guard.call(args, env,
                        call_cont(self.parameter, env, cont))
            return self.parameter.call(args, env, cont)
        else:
            raise SchemeException("wrong number of arguments to parameter")


text:
using System.Threading.Tasks;
using Apricot.WebServices.Plant;
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;

namespace Apricot.UnitTest.WebServices.Plant
{
    /// <summary>
    ///     Tests for <see cref="MeasureService" /> class.
    /// </summary>
    [TestClass]
    public class MeasureServiceTests
    {
        #region Members.

        /// <summary>
        ///     Measure service.
        /// </summary>
        private readonly MeasureService _measureService;

        #endregion Members.

        #region Constructors.

        /// <summary>
        ///     Constructor.
        /// </summary>
        public MeasureServiceTests()
        {
            _measureService = new MeasureService();
        }

        #endregion Constructors.

        #region Methods.

        /// <summary>
        ///     Test for the <see cref="MeasureService.GetAll"/> method.
        /// </summary>
        [TestMethod]
        public async Task GetAllTestAsync()
        {
            var result = await _measureService.GetAll(0, 1);
            Assert.IsNotNull(result, "The model is null.");
        }

        /// <summary>
        ///     Test for the <see cref="MeasureService.GetLast"/> method.
        /// </summary>
        [TestMethod]
        public async Task GetLastTestAsync()
        {
            var result = await _measureService.GetLast(0);
            Assert.IsNotNull(result, "The model is null.");
        }

        #endregion Methods.
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2014 Haruki Hasegawa

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <!-- OpenSLMediaPlayer -->
        <TextView
            style="@style/About.TextView.LibraryName"
            android:text="@string/about_openslmediaplayer_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <TextView
            style="@style/About.TextView.LibraryUrl"
            android:text="@string/about_openslmediaplayer_url"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <TextView
            style="@style/About.TextView.LibraryLicense"
            android:text="@string/about_openslmediaplayer_license"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <!-- cxxporthelper -->
        <TextView
            style="@style/About.TextView.LibraryName"
            android:text="@string/about_cxxporthelper_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <TextView
            style="@style/About.TextView.LibraryUrl"
            android:text="@string/about_cxxporthelper_url"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <TextView
            style="@style/About.TextView.LibraryLicense"
            android:text="@string/about_cxxporthelper_license"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <!-- lockfreedatastructure -->
        <TextView
            style="@style/About.TextView.LibraryName"
            android:text="@string/about_lockfreedatastructure_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <TextView
            style="@style/About.TextView.LibraryUrl"
            android:text="@string/about_lockfreedatastructure_url"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <TextView
            style="@style/About.TextView.LibraryLicense"
            android:text="@string/about_lockfreedatastructure_license"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <!-- cxxdasp -->
        <TextView
            style="@style/About.TextView.LibraryName"
            android:text="@string/about_cxxdasp_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <TextView
            style="@style/About.TextView.LibraryUrl"
            android:text="@string/about_cxxdasp_url"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <TextView
            style="@style/About.TextView.LibraryLicense"
            android:text="@string/about_cxxdasp_license"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <!-- OpenSL ES CXX -->
        <TextView
            style="@style/About.TextView.LibraryName"
            android:text="@string/about_openslescxx_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <TextView
            style="@style/About.TextView.LibraryUrl"
            android:text="@string/about_openslescxx_url"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <TextView
            style="@style/About.TextView.LibraryLicense"
            android:text="@string/about_openslescxx_license"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <!-- PFFFT -->
        <TextView
            style="@style/About.TextView.LibraryName"
            android:text="@string/about_pffft_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <TextView
            style="@style/About.TextView.LibraryUrl"
            android:text="@string/about_pffft_url"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <TextView
            style="@style/About.TextView.LibraryLicense"
            android:text="@string/about_pffft_license"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <!-- Ne10 -->
        <TextView
            style="@style/About.TextView.LibraryName"
            android:text="@string/about_ne10_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <TextView
            style="@style/About.TextView.LibraryUrl"
            android:text="@string/about_ne10_url"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <TextView
            style="@style/About.TextView.LibraryLicense"
            android:text="@string/about_ne10_license"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <!-- Android Utility Function Library (/platform/system/core, libutils) -->
        <TextView
            style="@style/About.TextView.LibraryNameNoUrl"
            android:text="@string/about_android_platform_system_core_libutils_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <TextView
            style="@style/About.TextView.LibraryLicense"
            android:text="@string/about_android_platform_system_core_libutils_license"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <!-- Android platform code (/platform/system/media, libaudio_utis) -->
        <TextView
            style="@style/About.TextView.LibraryNameNoUrl"
            android:text="@string/about_android_platform_system_media_libaudio_utils_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <TextView
            style="@style/About.TextView.LibraryLicense"
            android:text="@string/about_android_platform_system_media_libaudio_utils_license"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <!-- Android platform code (/platform/frameworks/av, libmedia) -->
        <TextView
            style="@style/About.TextView.LibraryNameNoUrl"
            android:text="@string/about_android_platform_frameworks_av_libmedia_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <TextView
            style="@style/About.TextView.LibraryLicense"
            android:text="@string/about_android_platform_frameworks_av_libmedia_license"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <!-- Android platform code (/platform/frameworks/av, libeffect) -->
        <TextView
            style="@style/About.TextView.LibraryNameNoUrl"
            android:text="@string/about_android_platform_frameworks_av_libeffect_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <TextView
            style="@style/About.TextView.LibraryLicense"
            android:text="@string/about_android_platform_frameworks_av_libeffect_license"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <!-- Android platform code (/platform/frameworks/base) -->
        <TextView
            style="@style/About.TextView.LibraryNameNoUrl"
            android:text="@string/about_android_platform_frameworks_base_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <TextView
            style="@style/About.TextView.LibraryLicense"
            android:text="@string/about_android_platform_frameworks_base_license"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <!-- Android v4 Support Library -->
        <TextView
            style="@style/About.TextView.LibraryName"
            android:text="@string/about_support_v4_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <TextView
            style="@style/About.TextView.LibraryUrl"
            android:text="@string/about_support_v4_url"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <TextView
            style="@style/About.TextView.LibraryLicense"
            android:text="@string/about_support_v4_license"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <!-- Android v7 Support Library -->
        <TextView
            style="@style/About.TextView.LibraryName"
            android:text="@string/about_support_v7_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <TextView
            style="@style/About.TextView.LibraryUrl"
            android:text="@string/about_support_v7_url"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <TextView
            style="@style/About.TextView.LibraryLicense"
            android:text="@string/about_support_v7_license"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </LinearLayout>
</ScrollView>