text:
package org.apache.camel.component.kubernetes.config_maps;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.fabric8.kubernetes.api.model.ConfigMap;
import io.fabric8.kubernetes.api.model.ConfigMapBuilder;
import io.fabric8.kubernetes.api.model.ConfigMapList;
import io.fabric8.kubernetes.api.model.StatusDetails;
import org.apache.camel.Exchange;
import org.apache.camel.component.kubernetes.AbstractKubernetesEndpoint;
import org.apache.camel.component.kubernetes.KubernetesConstants;
import org.apache.camel.component.kubernetes.KubernetesHelper;
import org.apache.camel.component.kubernetes.KubernetesOperations;
import org.apache.camel.support.DefaultProducer;
import org.apache.camel.util.ObjectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.apache.camel.component.kubernetes.KubernetesHelper.prepareOutboundMessage;

public class KubernetesConfigMapsProducer extends DefaultProducer {

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

    public KubernetesConfigMapsProducer(AbstractKubernetesEndpoint endpoint) {
        super(endpoint);
    }

    @Override
    public AbstractKubernetesEndpoint getEndpoint() {
        return (AbstractKubernetesEndpoint) super.getEndpoint();
    }

    @Override
    public void process(Exchange exchange) throws Exception {
        String operation = KubernetesHelper.extractOperation(getEndpoint(), exchange);

        switch (operation) {

            case KubernetesOperations.LIST_CONFIGMAPS:
                doList(exchange);
                break;

            case KubernetesOperations.LIST_CONFIGMAPS_BY_LABELS_OPERATION:
                doListConfigMapsByLabels(exchange);
                break;

            case KubernetesOperations.GET_CONFIGMAP_OPERATION:
                doGetConfigMap(exchange);
                break;

            case KubernetesOperations.CREATE_CONFIGMAP_OPERATION:
                doCreateConfigMap(exchange);
                break;

            case KubernetesOperations.DELETE_CONFIGMAP_OPERATION:
                doDeleteConfigMap(exchange);
                break;

            default:
                throw new IllegalArgumentException("Unsupported operation " + operation);
        }
    }

    protected void doList(Exchange exchange) {
        ConfigMapList configMapsList = getEndpoint().getKubernetesClient().configMaps().inAnyNamespace().list();

        prepareOutboundMessage(exchange, configMapsList.getItems());
    }

    protected void doListConfigMapsByLabels(Exchange exchange) {
        Map<String, String> labels = exchange.getIn().getHeader(KubernetesConstants.KUBERNETES_CONFIGMAPS_LABELS, Map.class);
        ConfigMapList configMapsList = getEndpoint().getKubernetesClient()
                .configMaps()
                .inAnyNamespace()
                .withLabels(labels)
                .list();

        prepareOutboundMessage(exchange, configMapsList.getItems());
    }

    protected void doGetConfigMap(Exchange exchange) {
        ConfigMap configMap = null;
        String cfMapName = exchange.getIn().getHeader(KubernetesConstants.KUBERNETES_CONFIGMAP_NAME, String.class);
        String namespaceName = exchange.getIn().getHeader(KubernetesConstants.KUBERNETES_NAMESPACE_NAME, String.class);
        if (ObjectHelper.isEmpty(cfMapName)) {
            LOG.error("Get a specific ConfigMap require specify a ConfigMap name");
            throw new IllegalArgumentException("Get a specific ConfigMap require specify a ConfigMap name");
        }
        if (namespaceName != null) {
            configMap = getEndpoint().getKubernetesClient().configMaps().inNamespace(namespaceName).withName(cfMapName).get();
        } else {
            configMap = getEndpoint().getKubernetesClient().configMaps().withName(cfMapName).get();
        }

        prepareOutboundMessage(exchange, configMap);
    }

    protected void doCreateConfigMap(Exchange exchange) {
        ConfigMap configMap = null;
        String cfMapName = exchange.getIn().getHeader(KubernetesConstants.KUBERNETES_CONFIGMAP_NAME, String.class);
        String namespaceName = exchange.getIn().getHeader(KubernetesConstants.KUBERNETES_NAMESPACE_NAME, String.class);
        HashMap<String, String> configMapData
                = exchange.getIn().getHeader(KubernetesConstants.KUBERNETES_CONFIGMAP_DATA, HashMap.class);
        if (ObjectHelper.isEmpty(cfMapName)) {
            LOG.error("Create a specific configMap require specify a configMap name");
            throw new IllegalArgumentException("Create a specific configMap require specify a configMap name");
        }
        if (ObjectHelper.isEmpty(namespaceName)) {
            LOG.error("Create a specific configMap require specify a namespace name");
            throw new IllegalArgumentException("Create a specific configMap require specify a namespace name");
        }
        if (ObjectHelper.isEmpty(configMapData)) {
            LOG.error("Create a specific configMap require specify a data map");
            throw new IllegalArgumentException("Create a specific configMap require specify a data map");
        }
        Map<String, String> labels = exchange.getIn().getHeader(KubernetesConstants.KUBERNETES_CONFIGMAPS_LABELS, Map.class);
        ConfigMap cfMapCreating = new ConfigMapBuilder().withNewMetadata().withName(cfMapName).withLabels(labels).endMetadata()
                .withData(configMapData).build();
        configMap = getEndpoint().getKubernetesClient().configMaps().inNamespace(namespaceName).create(cfMapCreating);

        prepareOutboundMessage(exchange, configMap);
    }

    protected void doDeleteConfigMap(Exchange exchange) {
        String configMapName = exchange.getIn().getHeader(KubernetesConstants.KUBERNETES_CONFIGMAP_NAME, String.class);
        String namespaceName = exchange.getIn().getHeader(KubernetesConstants.KUBERNETES_NAMESPACE_NAME, String.class);
        if (ObjectHelper.isEmpty(configMapName)) {
            LOG.error("Delete a specific config map require specify a config map name");
            throw new IllegalArgumentException("Delete a specific config map require specify a config map name");
        }
        if (ObjectHelper.isEmpty(namespaceName)) {
            LOG.error("Delete a specific config map require specify a namespace name");
            throw new IllegalArgumentException("Delete a specific config map require specify a namespace name");
        }
        List<StatusDetails> statusDetails
                = getEndpoint().getKubernetesClient().configMaps().inNamespace(namespaceName).withName(configMapName).delete();
        boolean cfMapDeleted = ObjectHelper.isNotEmpty(statusDetails);

        prepareOutboundMessage(exchange, cfMapDeleted);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package kr.kkiro.roguebox.game.status;

import kr.kkiro.roguebox.util.I18n;

public class ResistanceEffect extends StatusEffect {

  public ResistanceEffect(int ticksLeft) {
    super(ticksLeft);
  }

  @Override
  public void tick() {
  }

  @Override
  public void dispose() {
    getCharacter().defense -= 5;
  }

  @Override
  public void register() {
    getCharacter().defense += 5;
  }

  public String getName() {
    return I18n._("resistanceEffect");
  };

}


text:
layout: post
title: /bin/sh execve Stack
date: '2016-12-02T18:15:00.000-06:00'
author: Sanjiv Kawa
tags:
- Stack
- Shellcode
- nasm
- assembly
- execve
comments: true
---
### The execve SYSCALL
A useful SYSCALL that can help with executing a shell is `execve`.

Looking at the man page for `execve`, there are three main arguments.

~~~ bash
SYNOPSIS
       #include <unistd.h>

       int execve(const char *filename, char *const argv[], char *const envp[]);
~~~

Argument 1 (`*filename`): The program that you want to execute.

Argument 2 (`argv[]`): An array of argument strings passed to the program. By convention, the first of these strings should contain the filename associated with the file being executed.

Argument 3 (`envp[]`): The third argument is an array of strings that you can pass in as an additional environment to the program before it is executed. This argument is typically occupied with nulls as it is not used often.

To execute `/bin/sh`, the first argument, `*filename`, should contain a pointer to a string which reads `/bin/sh`. The second argument, `argv[]` will contain the memory address for a string that contains `/bin/sh` as it's first element, the second element will be `0x00000000` to null terminate the array. Lastly, the thrid argument, `envp[]`, will contain `0x00000000`.

### Building execve-stack.nasm
Based on the arguments required by `execve`, the following general purpose registers will contain the corresponding values:

`EBX`: `/bin/sh0x0` - to satisfy the requirements of `*filename`

`ECX`: the address of `/bin/sh,0x00000000` - to satisfy the requirements of `argv[]`

`EDX`: `0x00000000` - to satisfy the requirements of `envp[]`

`execve` does require a fair number of null bytes, this is an inconvenience as this would almost certainly prevent the execution of the shellcode. As a result, the Stack can be used to store all of the arguments required by `execve`. This is advantageous as memory locations are referenced to the various registers and null bytes themselves are never actually stored in registers.

#### Things to consider
`/bin/sh` is 7 bytes, however adding another `/` does not affect the execution of the shell. `//bin/sh` is 8 bytes, this alleviates any offset issues that may arise.

At times the Stack can be like the "Upside Down". Push things on in reverse order, and remember that the Stack is Last in First Out (LIFO). This means that the last thing that was pushed on to the Stack will be pointed to by the Stack pointer register.

~~~ nasm
;execve //bin/sh
global _start

section .text
_start:

  xor eax, eax  ;zero out eax
  push eax      ;push 00000000 on to the stack

  push 0x68732f6e ;push hex hs/n on to the stack
  push 0x69622f2f ;push hex ib// on to the stack

  ;at this point the stack contains //bin/sh0x00000000
  mov ebx, esp  ;this satisfies the requirements for *filename (first argument of execve)

  push eax      ;push 00000000 on to the stack

  ;at this point the stack contains 0x00000000//bin/sh0x00000000
  mov edx, esp  ;we cant pop 0x00000000 into EDX as the shellcode cannot have any null characters.
                ;instead we move the current address pointed to by ESP into EDX.
                ;this address contains the last value pushed on to the stack, which is 0x00000000
                ;this satisfies the requirements for envp (third argument of execve)

  push ebx      ;ebx contains the memory address of the stack where //bin/sh0x00000000 is.
  mov ecx, esp  ;this satisfies the requirements for argv (second argument of execve)

  mov al, 11     ;execve syscall number, 0xb works also.
  int 0x80       ;initiate
~~~
Source code can also be found here.

I built on top of Vivek\'s nasm linker and assembler shell script and added the opcode extractor and C compiler used in the SLAE course. You can find `super-compile.sh` here.

~~~ bash
skawa@ubuntu:~/Desktop/code/execve$ ls
execve-stack.nasm  super-compile.sh
skawa@ubuntu:~/Desktop/code/execve$ ./super-compile.sh execve-stack
[+] Assembling with Nasm
[+] Linking
[+] Extracting Opcodes
"\x31\xc0\x50\x68\x6e\x2f\x73\x68\x68\x2f\x2f\x62\x69\x89\xe3\x50\x89\xe2\x53\x89\xe1\xb0\x0b\xcd\x80"

[+] Creating Shellcode
[+] Compiling Shellcode
[+] Done!
skawa@ubuntu:~/Desktop/code/execve$ ls
execve-stack       execve-stack.o          shellcode-execve-stack.c
execve-stack.nasm  shellcode-execve-stack  super-compile.sh
skawa@ubuntu:~/Desktop/code/execve$ ./shellcode-execve-stack
Shellcode Length: 25
$ exit
skawa@ubuntu:~/Desktop/code/execve$
~~~


text:
package org.apache.eagle.log.entity.repo;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.eagle.log.base.taggedlog.TaggedLogAPIEntity;
import org.apache.eagle.log.entity.meta.EntitySerDeser;

/**
 * Entity repository is used to store entity definition class. Each domain should define its own entities.
 * Eagle entity framework will scan all derived class implementations to get all entity definitions, then
 * register them to EntityDefinitionManager.
 */
public abstract class EntityRepository {

    protected Set<Class<? extends TaggedLogAPIEntity>> entitySet = new HashSet<Class<? extends TaggedLogAPIEntity>>();
    protected Map<Class<?>, EntitySerDeser<?>> serDeserMap = new HashMap<Class<?>, EntitySerDeser<?>>();

    public synchronized Collection<Class<? extends TaggedLogAPIEntity>> getEntitySet() {
        return new ArrayList<Class<? extends TaggedLogAPIEntity>>(entitySet);
    }

    public synchronized Map<Class<?>, EntitySerDeser<?>> getSerDeserMap() {
        return new HashMap<Class<?>, EntitySerDeser<?>>(serDeserMap);
    }

    public synchronized void registerEntity(Class<? extends TaggedLogAPIEntity> clazz) {
        entitySet.add(clazz);
    }

    public synchronized void registerSerDeser(Class<?> clazz, EntitySerDeser<?> serDeser) {
        serDeserMap.put(clazz, serDeser);
    }

}


text:
require 'sensu-plugin/check/cli'
require 'sensu-plugins-aws'
require 'aws-sdk'
require 'resolv'

class CheckVpcNameservers < Sensu::Plugin::Check::CLI
  include Common
  option :queries,
         short:       '-q queries',
         long:        '--queries google.com,example1.com',
         proc:        proc { |a| a.split(',') },
         default:     ['google.com'],
         description: 'Comma seperated dns queries to test'

  option :vpc_id,
         short:       '-v vpc_id',
         long:        '--vpc_id vpc-12345678',
         required:    true,
         description: 'The vpc_id of the dhcp option set'

  option :aws_region,
         short:       '-r R',
         long:        '--region REGION',
         description: 'AWS region',
         default: 'us-east-1'

  def run
    errors = []
    ec2 = Aws::EC2::Client.new

    dhcp_option_id = ec2.describe_vpcs(vpc_ids: [config[:vpc_id]]).vpcs[0].dhcp_options_id

    options = ec2.describe_dhcp_options(dhcp_options_ids: [dhcp_option_id])

    options.dhcp_options.each do |option|
      option.dhcp_configurations.each do |map|
        next if map.key != 'domain-name-servers'
        map.values.each do |value| # rubocop:disable Performance/HashEachMethods
          ip = value.value
          config[:queries].each do |query|
            begin
              Resolv::DNS.open(nameserver: [ip]).getaddress(query)
            rescue Resolv::ResolvError => res_err
              errors << "[#{ip}] #{res_err} "
            end
          end
        end
      end
    end

    if errors.empty?
      ok
    else
      warning errors.join("\n")
    end
  end
end


text:
<!DOCTYPE html>

<meta charset="utf-8">
<title>Verify that line width limits are enforced.</title>
<link rel="stylesheet" href="../../resources/js-test-style.css"/>

<canvas id="example" width="4" height="4" style="width: 40px; height: 30px;"></canvas>


text:
Replaces the standard Discord emotes with Google Emojis.

## Usage
Using this .CSS requires a Discord modification, such as [BeautifulDiscord](https://github.com/leovoel/BeautifulDiscord). Simply add this to your .CSS file to install:
`@import url(https://rawgit.com/Noahkiq/GoogleEmoji.css/master/GoogleEmoji.css);`
Note that the Emoji Picker does not contain the edited emojis due to Discord using a spritesheet for the emoji picker. This might be fixed one day but I currently don't have plans to do so.

## Notes
- Pull Requests to add new emojis are welcome.
- Future added emotes will be from Android 7.0, but Android 4.4 blobs will be added to the default skin tone emojis upon [pull] request. (ie `:cop:` will be a blob, while `:cop::skin-tone-1:` will be an Android 7.0 cop.)
- Android O emotes are not welcome.
- I will be doing my own periodic updates to continue adding emotes.


text:
package com.bison.crash.catcher;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

/**
 * Created by oeager on 2015/11/19.
 * email:oeager@foxmail.com
 */
public class LogViewActivity extends Activity{

    private TextView detailTex;

    private Button positiveBtn;

    private Button negativeBtn;

    private String logDetail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.app_log_view_layout);
        initTitleBar();
        initComponents();
        initComponentsData();
    }

    private void initTitleBar() {
        getActionBar().setDisplayShowHomeEnabled(false);
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setDisplayShowTitleEnabled(true);
        getActionBar().setTitle(getString(R.string.send_report));
        getActionBar().setBackgroundDrawable(new ColorDrawable(0xffffff));
    }

    private void initComponents() {
        detailTex = (TextView) findViewById(R.id.detail_message);
        negativeBtn = (Button) findViewById(R.id.negativeBtn);
        positiveBtn = (Button) findViewById(R.id.positiveBtn);
        negativeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        positiveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LogReportService.start(LogViewActivity.this,getIntent().getExtras());
                finish();
            }
        });

    }

    private void initComponentsData() {
        logDetail = getIntent().getExtras().getString(CrashCatcher.CRASH_DATA);
        detailTex.setText(logDetail);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(1,1,1,getString(R.string.copy));
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                finish();
                return true;
            case 1:
                ClipboardManager cmb = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
                cmb.setPrimaryClip(ClipData.newPlainText(null, logDetail));
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}


text:
class Feature
  class Gitaly
    PREFIX = "gitaly_"

    class << self
      def enabled?(feature_flag)
        return false unless Feature::FlipperFeature.table_exists?

        Feature.enabled?("#{PREFIX}#{feature_flag}")
      rescue ActiveRecord::NoDatabaseError, PG::ConnectionBad
        false
      end

      def server_feature_flags
        # We need to check that both the DB connection and table exists
        return {} unless ::Gitlab::Database.cached_table_exists?(FlipperFeature.table_name)

        Feature.persisted_names
          .select { |f| f.start_with?(PREFIX) }
          .map do |f|
          flag = f.delete_prefix(PREFIX)

          ["gitaly-feature-#{flag.tr('_', '-')}", enabled?(flag).to_s]
        end.to_h
      end
    end
  end
end


text:
<?php
class Doctrine_Template_Attachable extends Doctrine_Template
{
  protected $_options = array('types' => array());

  /**
   * Constructor for Attachable Template
   *
   * @param array $options
   * @return void
   * @author Brent Shaffer
   */
  public function __construct(array $options = array())
  {
    $this->_options = Doctrine_Lib::arrayDeepMerge($this->_options, $options);
  }

  public function setup()
  {
  }

  public function setTableDefinition()
  {
     $this->addListener(new Doctrine_Template_Listener_Attachable());
  }

  public function getAttachmentsQuery()
  {
    $object = $this->getInvoker();
    $query = Doctrine_Core::getTable('Attachment')->createQuery();
    $query->addWhere('Attachment.object_class = ?', get_class($object))
          ->addWhere('Attachment.object_id = ?', $object->getId());

    return $query;
  }
  public function getAttachments()
  {
    $object = $this->getInvoker();
    return $object->getAttachmentsQuery()->execute();
  }
  public function setAttachments($attachments)
  {
    foreach ($attachments as $attachment)
    {
      $this->addAttachment($attachment);
    }
  }
  public function hasAttachments()
  {
    return ($this->getAttachmentsQuery()->count() > 0);
  }
  public function hasAttachmentsOfType($type)
  {
    return ($this->getAttachmentsByTypeQuery($type)->count() > 0);
  }
  public function addAttachment($attachment)
  {
    $object = $this->getInvoker();
    $attachment->setObjectClass(get_class($object));
    if(!$object['id'])
    {
      $object->save();
    }
    $attachment->setObjectId($object->getId());
    $attachment->save();
  }

  public function getAttachmentsByTypeQuery($type)
  {
    return Doctrine_Core::getTable('Attachment')
                  ->createQuery()
                  ->where('object_class = ?', get_class($this->getInvoker()))
                  ->andWhere('object_id = ?', $this->getInvoker()->getId())
                  ->andWhere('type = ?', strtolower($type));
  }

  public function getAttachmentsByType($type)
  {
    if(in_array($type, $this->_options['types']))
    {
      return $this->getAttachmentsByTypeQuery($type)
                  ->execute();
    }
    $table = strtolower($type) == 'other' ? 'Attachment' : sfInflector::classify($type.'_attachment');
    return new Doctrine_Collection($table);
  }
  public function getSupportedAttachmentTypes()
  {
    return $this->getAttachableConfig('types');
  }
  public function getAttachableConfig($index = null)
  {
    if($index)
    {
      return $this->_options[$index];
    }
    return $this->_options;
  }
  public function getVideoAttachments()
  {
    return $this->getAttachmentsByType('Video');
  }
  public function getImageAttachments()
  {
    return $this->getAttachmentsByType('Image');
  }
  public function getDocumentAttachments()
  {
    return $this->getAttachmentsByType('Document');
  }
  public function getOtherAttachments()
  {
    return $this->getAttachmentsByType('Other');
  }
  public function getModelAttachments()
  {
    return $this->getAttachmentsByType('Model');
  }

  // This method only works if "Attachable" is added as the final behavior!
  // public function __call($method, $arguments)
  // {
  //   foreach ($this->_options['types'] as $type)
  //   {
  //     if(sfInflector::camelize('get_'.$type.'_attachments') == $method)
  //     {
  //       return $this->getAttachmentsByType($type);
  //     }
  //   }
  //   throw new Exception("Method $method not found");
  // }
}


text:
import happyforms

from django import forms
from django.contrib import messages

from remo.base.tasks import send_remo_mail
from remo.profiles.models import UserProfile

class BaseEmailUsersForm(happyforms.Form):
    """Base form to send email to multiple users."""
    subject = forms.CharField(label='', widget=(
        forms.TextInput(attrs={'placeholder': 'Subject',
                               'required': 'required',
                               'class': 'input-text big'})))
    body = forms.CharField(label='', widget=(
        forms.Textarea(attrs={'placeholder': 'Body of email',
                              'required': 'required',
                              'class': 'flat long'})))

class EmailUsersForm(BaseEmailUsersForm):
    """Generic form to send email to multiple users."""

    def __init__(self, users, *args, **kwargs):
        """Initialize form.

        Dynamically set fields for the recipients of the mail.
        """
        super(EmailUsersForm, self).__init__(*args, **kwargs)
        for user in users:
            # Insert method is used to override the order of form fields
            form_widget = forms.CheckboxInput(
                attrs={'class': 'input-text-big'})
            self.fields.update([(str(user.id), forms.BooleanField(label=user,
                                                                  initial=False,
                                                                  required=False,
                                                                  widget=form_widget))])

    def send_mail(self, request):
        """Send mail to recipients list."""
        recipients_list = []
        for field in self.fields:
            if (isinstance(self.fields[field], forms.BooleanField) and
                    self.cleaned_data[field]):
                recipients_list.append(long(field))

        if recipients_list:
            from_email = '%s <%s>' % (request.user.get_full_name(),
                                      request.user.email)
            send_remo_mail.delay(sender=from_email,
                                 recipients_list=recipients_list,
                                 subject=self.cleaned_data['subject'],
                                 message=self.cleaned_data['body'])
            messages.success(request, 'Email sent successfully.')
        else:
            messages.error(request, ('Email not sent. Please select at '
                                     'least one recipient.'))

class EmailMentorForm(BaseEmailUsersForm):
    """Generic form to send email to a user's mentor."""
    subject = forms.CharField(required=False)

    def send_email(self, request, subject='', message=None,
                   template=None, data=None):
        """Send an email to user's mentor"""
        mentor = request.user.userprofile.mentor
        from_email = '%s <%s>' % (request.user.get_full_name(),
                                  request.user.email)
        send_remo_mail.delay(sender=from_email,
                             recipients_list=[mentor.id],
                             subject=subject,
                             message=message,
                             email_template=template,
                             data=data)

class EditSettingsForm(happyforms.ModelForm):
    """Form to edit user settings regarding mail preferences."""
    receive_email_on_add_comment = forms.BooleanField(
        required=False, initial=True,
        label=('Receive email when a user comments on a report.'))
    receive_email_on_add_event_comment = forms.BooleanField(
        required=False, initial=True,
        label=('Receive email when a user comments on an event.'))
    receive_email_on_add_voting_comment = forms.BooleanField(
        required=False, initial=True,
        label=('Receive email when a user comments on an poll.'))

    class Meta:
        model = UserProfile
        fields = ['receive_email_on_add_comment',
                  'receive_email_on_add_event_comment',
                  'receive_email_on_add_voting_comment']


text:
package com.sciencelk.dataaccess.entities;
// Generated Jul 13, 2015 9:30:45 PM by Hibernate Tools 4.3.1

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

import static javax.persistence.GenerationType.IDENTITY;

/**
 * Privilege generated by hbm2java
 */
@Entity
@Table(name="privilege"
)
public class Privilege  implements java.io.Serializable {

     private Integer id;
     private String type;
     private Set<User> users = new HashSet<User>(0);

    public Privilege() {
    }

    public Privilege(String type) {
        this.type = type;
    }
    public Privilege(String type, Set<User> users) {
       this.type = type;
       this.users = users;
    }

     @Id @GeneratedValue(strategy=IDENTITY)

    @Column(name="ID", unique=true, nullable=false)
    public Integer getId() {
        return this.id;
    }

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

    @Column(name="TYPE", nullable=false, length=45)
    public String getType() {
        return this.type;
    }

    public void setType(String type) {
        this.type = type;
    }

@OneToMany(fetch=FetchType.LAZY, mappedBy="privilege")
    public Set<User> getUsers() {
        return this.users;
    }

    public void setUsers(Set<User> users) {
        this.users = users;
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<GlassEventLog>
  <Command name="setmode ShowParameterValues off">
    <Duration Volatile="True">00:00:00.0082231</Duration>
  </Command>
  <Command name="SetLaunchOptionsString @LaunchOptions.xml">
    <Duration Volatile="True">00:00:00.0001066</Duration>
  </Command>
  <Command name="bp Source1.cpp 26">
    <Duration Volatile="True">00:00:00.0050582</Duration>
  </Command>
   <Command name="bp Source1.cpp 16">
    <Duration Volatile="True">00:00:00.0050582</Duration>
  </Command>
  <Command name="launch MIEngine app_process">
    <Event name="IDebugSessionCreateEvent2" expected="False" />
    <Event name="IDebugProcessCreateEvent2" expected="False" />
    <Duration Volatile="True">00:00:01.4321154</Duration>
    <Event name="IDebugProgramCreateEvent2" expected="False" />
    <Event name="IDebugBreakpointErrorEvent2" expected="False">
      <WarningMessage>module containing this breakpoint has not yet loaded or the breakpoint address could not be obtained.</WarningMessage>
    </Event>
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugThreadCreateEvent2" expected="False" />
    <Event name="IDebugThreadCreateEvent2" expected="False" />
    <Event name="IDebugThreadCreateEvent2" expected="False" />
    <Event name="IDebugThreadCreateEvent2" expected="False" />
    <Event name="IDebugThreadCreateEvent2" expected="False" />
    <Event name="IDebugThreadCreateEvent2" expected="False" />
    <Event name="IDebugThreadCreateEvent2" expected="False" />
    <Event name="IDebugThreadCreateEvent2" expected="False" />
    <Event name="IDebugThreadCreateEvent2" expected="False" />
    <Event name="IDebugThreadCreateEvent2" expected="False" />
    <Event name="IDebugOutputStringEvent2" expected="False" />
    <Event name="IDebugBreakpointBoundEvent2" expected="False">
      <BoundBreakpoint RegEx="^25,0 to 25,0 in (\[Unknown\]|libMultiThreadingCallStack.so)!func5\(\)$"></BoundBreakpoint>
    </Event>
     <Event name="IDebugBreakpointBoundEvent2" expected="False">
      <BoundBreakpoint RegEx="^15,0 to 15,0 in (\[Unknown\]|libMultiThreadingCallStack.so)!func3\(int, int\)$"></BoundBreakpoint>
    </Event>
    <Event name="IDebugModuleLoadEvent2" expected="False" />
    <Event name="IDebugOutputStringEvent2" expected="False" />
    <Event name="IDebugOutputStringEvent2" expected="False" />
    <Event name="IDebugOutputStringEvent2" expected="False" />
    <Event name="IDebugThreadCreateEvent2" expected="False" />
    <Event name="IDebugBreakpointEvent2" expected="True">
      <functionName>func5</functionName>
      <function>func5()</function>
      <file>Source1.cpp</file>
      <line>26</line>
      <col>0</col>
    </Event>
   </Command>
   <Command name="callstack 8">
    <Frame> func5() ***</Frame>
    <Frame> func4()</Frame>
    <Frame> func()</Frame>
    <Frame> android_main(android_app * state)</Frame>
    <Frame> android_app_entry(void * param)</Frame>
    <Frame> libc.so!__pthread_start(void*)</Frame>
    <Frame> libc.so!__start_thread</Frame>
    <Frame> libc.so!__bionic_clone</Frame>
  </Command>
  <!--Break in a new thread then verify its call stack and each frame's corresponding locals-->
  <Command name="go">
    <Event name="IDebugBreakpointEvent2" expected="True">
      <functionName>func3</functionName>
      <function>func3(int x, int y)</function>
      <file>Source1.cpp</file>
      <line>16</line>
      <col>0</col>
    </Event>
  </Command>
  <Command name="callstack 6">
    <Frame> func3(int x, int y) ***</Frame>
    <Frame> func2(int x)</Frame>
    <Frame> func1()</Frame>
    <Frame> libc.so!__pthread_start(void*)</Frame>
    <Frame> libc.so!__start_thread</Frame>
    <Frame> libc.so!__bionic_clone</Frame>
  </Command>
  <Command name="list locals">
    <Local>z</Local>
    <LocalValue Volatile="true">-1217632150</LocalValue>
    <LocalType>int</LocalType>
    <LocalIsExpandable>False</LocalIsExpandable>
    <Local>x</Local>
    <LocalValue>2</LocalValue>
    <LocalType>int</LocalType>
    <LocalIsExpandable>False</LocalIsExpandable>
    <Local>y</Local>
    <LocalValue>3</LocalValue>
    <LocalType>int</LocalType>
    <LocalIsExpandable>False</LocalIsExpandable>
  </Command>
  <Command name="down 1">
    <functionName>func2</functionName>
    <file>Source1.cpp</file>
    <line>10</line>
    <col>0</col>
  </Command>
  <Command name="list locals">
    <Local>x</Local>
    <LocalValue>1</LocalValue>
    <LocalType>int</LocalType>
    <LocalIsExpandable>False</LocalIsExpandable>
  </Command>
  <Command name="down 1">
    <functionName>func1</functionName>
    <file>Source1.cpp</file>
    <line>6</line>
    <col>0</col>
  </Command>
  <Command name="list locals" />
  <Command name="up 2">
    <functionName>func3</functionName>
    <file>Source1.cpp</file>
    <line>16</line>
    <col>0</col>
  </Command>
  <Command name="list locals">
    <Local>z</Local>
    <LocalValue Volatile="true">-1217632150</LocalValue>
    <LocalType>int</LocalType>
    <LocalIsExpandable>False</LocalIsExpandable>
    <Local>x</Local>
    <LocalValue>2</LocalValue>
    <LocalType>int</LocalType>
    <LocalIsExpandable>False</LocalIsExpandable>
    <Local>y</Local>
    <LocalValue>3</LocalValue>
    <LocalType>int</LocalType>
    <LocalIsExpandable>False</LocalIsExpandable>
  </Command>
  <Command name="stopdebugging">
    <Event name="IDebugOutputStringEvent2" expected="False" />
    <Event name="IDebugProgramDestroyEvent2" expected="False" />
    <Event name="IDebugProcessDestroyEvent2" expected="False" />
    <Event name="IDebugSessionDestroyEvent2" expected="True" />
    <Duration Volatile="True">00:00:00.7905758</Duration>
  </Command>
  <Command name="quit">
    <Duration Volatile="True">00:00:00.0075690</Duration>
  </Command>
</GlassEventLog>


text:
var Hello = require('../lib/hello');

exports.testSayHello = function(test) {
	test.expect(2);

	var world = new Hello();
	var maika = new Hello("Maika!");

	test.equal(world.sayHello(), "Hello World!");
	test.equal(maika.sayHello(), "Hello Maika!");

	test.done();
};

exports.testSayBye = function(test) {
	test.expect(2);

	var world = new Hello();
	var maika = new Hello("Maika!");

	test.equal(world.sayBye(), "Goodbye World!");
	test.equal(maika.sayBye(), "Goodbye Maika!");

	test.done();
};


text:
[Source code of released version](https://github.com/meteor/meteor/tree/master/packages/allow-deny) | [Source code of development version](https://github.com/meteor/meteor/tree/devel/packages/allow-deny)
***


text:
#include <libcgc.h>
#include "stdlib.h"
#include "common.h"
#include "service.h"

/*
Service that parses a pcm-encoded file on stdin
and decodes a morse-code-like symbol stream.
The resulting message is printed on stdout
*/

#define MAX_PCM_SIZE 1048576
#define MAX_SAMPLES 524282
#define MAX_SYMBOLS 1024
#define MIN_VARIANCE 0.9
#define MAX_VARIANCE 1.1

extern struct language lh;

// used to identify mark and gap symbols in the data stream
struct time_bucket {
  short valid;
  unsigned int time;
  unsigned int count;
  char mark;
  char gap;
};
struct time_bucket Bucket[4];

/*
Once the pcm file has been decoded into dit and dah symbols
parse those into corresponding english letters
*/
void ParseCode(char *buf, char *output) {
  int i = 0;
  int o = 0;
  struct language *lp = &lh;

  while (buf[i] != '\0') {
    if (o > MAX_SYMBOLS-1) {
      puts("message too long\n");
      _terminate(UNABLE_TO_PARSE_PCM);
    }

    switch (buf[i]) {
      case '|':
        // end of a character
        if (lp) {
          output[o++] = lp->c;
          lp = &lh;
        } else {
          puts("unknown character\n");
          _terminate(UNABLE_TO_PARSE_PCM);
        }
        break;
      case ' ':
        // end of a word
        if (lp == &lh) {
          output[o++] = ' ';
        } else if (lp) {
          output[o++] = lp->c;
          lp = &lh;
          output[o++] = ' ';
        } else {
          puts("unknown character\n");
          _terminate(UNABLE_TO_PARSE_PCM);
        }
        break;
      case '.':
        // dit symbol
        if (lp) {
          lp = lp->dit;
        } else {
          puts("unknown character\n");
          _terminate(UNABLE_TO_PARSE_PCM);
        }
        break;
      case '-':
        // dah symbol
        if (lp) {
          lp = lp->dah;
        } else {
          puts("unknown character\n");
          _terminate(UNABLE_TO_PARSE_PCM);
        }
        break;
      case '\n':
        // newline...just ingore it
        break;

      default:
        puts("invalid symbol\n");
        _terminate(UNABLE_TO_PARSE_PCM);
    }

    i++;
  }
  if (lp) {
    output[o++] = lp->c;
    lp = &lh;
  } else {
    puts("unknown character\n");
    _terminate(UNABLE_TO_PARSE_PCM);
  }
}

/*
 * receive all requested bytes
 */
int recv(int fd, void *buf, size_t count, size_t *rx_bytes) {
	size_t total_bytes = 0;
	size_t rx;
	int rval;

	while (total_bytes < count) {
		rval = receive(fd, buf+total_bytes, 1, &rx);
		if (rval != 0) {
			return(rval);
		}
		if (rx != 1) {
			return(-1);
		}
		total_bytes++;
	}

	*rx_bytes = total_bytes;
	return(0);
}

/*
Read the pcm file from stdin
*/
unsigned char *ReadWav(unsigned char *pcm) {
  size_t size;
  unsigned int total_size;
  struct pcm_header *p;

  // cgc_read in the pcm header
  if (recv(STDIN, pcm, 12, &size) != 0) {
    puts("Read error\n");
    _terminate(READ_ERROR);
  }

  // use our pcm_header struct to check some input values
  p = (struct pcm_header *)pcm;
  if (p->ID != PCM) {
      puts("Invalid PCM format\n");
      _terminate(INVALID_PCM_FMT);
  }
  if (p->NumSamples > MAX_SAMPLES) {
      puts("Invalid PCM length\n");
    _terminate(INVALID_PCM_LEN);
  }
  if (p->NumSamples == 0) {
      puts("Invalid PCM format\n");
    _terminate(INVALID_PCM_FMT);
  }

#ifdef PATCHED
  // make sure the SampleSize value is valid
  if (p->DataSize*8.0 / p->NumSamples != 16.0) {
    puts("Invalid PCM length\n");
    _terminate(INVALID_PCM_LEN);
  }
#else
  // make sure the SampleSize value is valid
  // BUG. Check is done with integer division instead of
  // floating point which leads to an incorrectly
  // checked DataSize
  if (p->DataSize*8/p->NumSamples != 16) {
    puts("Invalid PCM length\n");
    _terminate(INVALID_PCM_LEN);
  }
#endif

  // cgc_read in the data portion of the pcm
  total_size = 0;
  while (total_size != p->DataSize) {
    if (receive(STDIN, pcm+12+total_size, (p->DataSize-total_size), &size) != 0) {
      puts("Read error\n");
      _terminate(READ_ERROR);
      }
    if (size == 0) {
      puts("Read error\n");
      _terminate(READ_ERROR);
    }
    total_size +=  size;
  }

  return(pcm);
}

  /*
For a given symbol detected in the pcm file,
assign it to a paritcular bucket of similar
symbol length.
*/
int AssignToBucket(unsigned int symbol_time) {
  int i;

  // find a valid bucket to hold this symbol
  for (i = 1; i < 4; i++) {
    if (Bucket[i].valid) {
      if (Bucket[i].time > symbol_time*MIN_VARIANCE && Bucket[i].time < symbol_time*MAX_VARIANCE) {
        // found match, count it
        Bucket[i].count++;
        return(i);
      }
    }
  }
  // didn't find one, so allocate a new one (if possible)
  for (i = 1; i < 4; i++) {
      if (Bucket[i].valid == 0) {
        // found emtpy bucket, populate it
        Bucket[i].valid = 1;
        Bucket[i].time = symbol_time;
        Bucket[i].count = 1;
        return(i);
      }
  }

  puts("Couldn't find a bucket\n");
  _terminate(UNABLE_TO_PARSE_PCM);
}

/*
Check that the symbol bucket times are
at the correct ratios
*/
void CheckLimits(int dit, int dah, int word) {
  if (Bucket[dah].time < Bucket[dit].time*3*MIN_VARIANCE || Bucket[dah].time > Bucket[dit].time*3*MAX_VARIANCE) {
    // Bucket dah is outside of our limits
    puts("Too much variance in symbol times\n");
    _terminate(UNABLE_TO_PARSE_PCM);
  }
  if (word) {
    if (Bucket[word].time < Bucket[dit].time*7*MIN_VARIANCE || Bucket[word].time > Bucket[dit].time*7*MAX_VARIANCE) {
      // Bucket word is outside of our limits
      puts("Too much variance in symbol times\n");
      _terminate(UNABLE_TO_PARSE_PCM);
    }
  }
}

/*
Figure out how the pcm symbol timings correlate
to morse-like symbols
*/
void ValidateBuckets(void) {
  int dit = 0;
  int dah = 0;
  int word = 0;

  // if all three buckets are valid,
  // the largest bucket is word gap
  // second largest is inter-char gap or dah
  // third largest is intra-char gap or dit
  if (Bucket[1].valid && Bucket[2].valid && Bucket[3].valid) {
    if (Bucket[1].time > Bucket[2].time && Bucket[1].time > Bucket[3].time) {
      word = 1;
      if (Bucket[2].time > Bucket[3].time) {
        dah = 2;
        dit = 3;
      } else {
        dah = 3;
        dit = 2;
      }
    } else if (Bucket[2].time > Bucket[1].time && Bucket[2].time > Bucket[3].time) {
      word = 2;
      if (Bucket[1].time > Bucket[3].time) {
        dah = 1;
        dit = 3;
      } else {
        dah = 3;
        dit = 1;
      }
    } else if (Bucket[3].time > Bucket[1].time && Bucket[3].time > Bucket[2].time) {
      word = 3;
      if (Bucket[1].time > Bucket[2].time) {
        dah = 1;
        dit = 2;
      } else {
        dah = 2;
        dit = 1;
      }
    }

  // if only two are valid,
  // largest is the inter-char gap or dah
  // second largest is intra-char gap or dit
  } else if (Bucket[1].valid && Bucket[2].valid) {
    word = 0;
    if (Bucket[1].time > Bucket[2].time) {
      dah = 1;
      dit = 2;
    } else {
      dah = 2;
      dit = 1;
    }
  } else {
      puts("Insufficient symbol diversity\n");
      _terminate(INVALID_PCM_FMT);
  }

  Bucket[word].mark = ' ';
  Bucket[word].gap = ' ';
  Bucket[dah].mark = '-';
  Bucket[dah].gap = '|';
  Bucket[dit].mark = '.';
  Bucket[dit].gap = '\0';
  CheckLimits(dit,dah,word);
}

/*
Read the samples in the pcm file looking
for periods of tones and silence
*/
void ParseWav(unsigned char *pcm) {
  unsigned char *pcm_pos;
  unsigned char *end_pcm;
  unsigned int symbol_start;
  unsigned int symbol_end;
  struct pcm_header *p;
  int silence;
  int count;
  short s;
  char Symbols[MAX_SYMBOLS];
  int sp = 0;
  unsigned int symbol_time;
  char output[MAX_SYMBOLS];
  char output2[MAX_SYMBOLS];
  int i;
  int b;
  int first = 1;

  // init some vars
  bzero(Symbols, MAX_SYMBOLS);
  bzero(output, MAX_SYMBOLS);
  sp = 0;
  Bucket[1].valid = 0;
  Bucket[2].valid = 0;
  Bucket[3].valid = 0;
  p = (struct pcm_header *)pcm;

  // calc the end byte of the pcm data
  end_pcm = pcm+12+(p->DataSize);

  // start with the first sample
  pcm_pos = pcm+12;
  symbol_start = 12;
  symbol_end = 0;
  silence = 1;
  count = 0;
  while (pcm_pos < end_pcm && sp < MAX_SYMBOLS-2) {
    // grab the sample's value
    s = *(short *)pcm_pos;

    // see if it's a new silence or a tone
    if ((s > -10 && s < 10) && (!silence || first)) {
      // got a new silence

      // check 50 sample to be sure
      if (++count < 50) {
        pcm_pos+=2;
        continue;
      }

      // see if this is our first symbol
      if (first) {
        silence = 1;
        count = 0;
        first = 0;
        pcm_pos = pcm+12;
        symbol_start = 12;
        symbol_end = 0;
        continue;
      }

      // yep, found new silence, reset our flag vars
      silence = 1;
      count = 0;

      // calc the length of the previous tone symbol
      symbol_end = (int)(pcm_pos-pcm);
      symbol_time = ((symbol_end-(50*2)-symbol_start))/2;

      // get ready for the next symbol
      symbol_start = symbol_end-(50*2);

      // Assign to a symbol bucket
      Symbols[sp++] = AssignToBucket(symbol_time);

    } else if ((s < -10 || s > 10) && (silence || first)) {
      // got a new tone

      // check 50 sample to be sure
      if (++count < 50) {
        pcm_pos+=2;
        continue;
      }

      // see if this is our first symbol
      if (first) {
        silence = 0;
        count = 0;
        first = 0;
        pcm_pos = pcm+12;
        symbol_start = 12;
        symbol_end = 0;
        continue;
      }

      // yep, found new tone, reset our flag vars
      silence = 0;
      count = 0;

      // calc the length of the previous tone symbol
      symbol_end = (int)(pcm_pos-pcm);
      symbol_time = ((symbol_end-(50*2)-symbol_start))/2;

      // get ready for the next symbol
      symbol_start = symbol_end-(50*2);

      // Assign to a symbol bucket
      Symbols[sp++] = AssignToBucket(symbol_time) * -1;
    } else {
      count = 0;
    }
    pcm_pos+=2;
  }

  // handle the last symbol we were processing
  symbol_end = (int)(pcm_pos-pcm);
  symbol_time = ((short)(symbol_end-symbol_start))/2;
  if (!silence) {
    Symbols[sp++] = AssignToBucket(symbol_time);
  }

  // validate the buckets we discovered
  ValidateBuckets();

  // now that we've parsed the tones and silences
  // use that data to build the symbol string
  sp = 0;
  for (i = 0; i < MAX_SYMBOLS-1; i++) {
    if (Symbols[i] == 0) {
      continue;
    }
    // silence
    if (Symbols[i] < 0) {
      b = Symbols[i]*-1;
      if (Bucket[b].gap != '\0') {
        output[sp++] = Bucket[b].gap;
      }

    // tone
    } else {
      b = Symbols[i];
      if (Bucket[b].mark != '\0') {
        output[sp++] = Bucket[b].mark;
      }
    }
  }
  output[sp++] = '\n';

  // parse the symbols back to characters
  ParseCode(output, output2);

  // output the resulting message
  puts(output2);
  puts("\n");

}

int main(void) {
    unsigned char pcm[MAX_PCM_SIZE];

    // zero the pcm var
    bzero(pcm, MAX_PCM_SIZE);

    // init the language data structures
    InitLang(&lh, NULL);

    // cgc_read in the pcm file
    ReadWav(pcm);

    // Read in each symbol
    ParseWav(pcm);

    return(0);
}


text:
<?php

namespace Bolt\Controller;

use Bolt\AccessControl\Token\Token;
use Bolt\Helpers\Deprecated;
use Bolt\Response\TemplateResponse;
use Bolt\Response\TemplateView;
use Bolt\Routing\DefaultControllerClassAwareInterface;
use Bolt\Storage\Entity;
use Bolt\Storage\Repository;
use Bolt\Translation\Translator as Trans;
use Doctrine\DBAL\Exception\TableNotFoundException;
use Silex\Api\ControllerProviderInterface;
use Silex\Application;
use Silex\ControllerCollection;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormTypeInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Csrf\CsrfToken;
use Twig_Template as Template;

/**
 * Base class for all controllers which mainly provides shortcut methods for
 * application services.
 *
 * @author Carson Full <carsonfull@gmail.com>
 */
abstract class Base implements ControllerProviderInterface
{
    /** @var Application */
    protected $app;

    public function connect(Application $app)
    {
        $this->app = $app;

        $c = $app['controllers_factory'];
        if ($c instanceof DefaultControllerClassAwareInterface) {
            $c->setDefaultControllerClass($this);
        }
        $this->addRoutes($c);

        return $c;
    }

    abstract protected function addRoutes(ControllerCollection $c);

    /**
     * Shortcut to abort the current request by sending a proper HTTP error.
     *
     * @param integer $statusCode The HTTP status code
     * @param string  $message    The status message
     * @param array   $headers    An array of HTTP headers
     *
     * @throws HttpExceptionInterface
     */
    protected function abort($statusCode, $message = '', array $headers = [])
    {
        $this->app->abort($statusCode, $message, $headers);
    }

    /**
     * Renders a template.
     *
     * @param string|string[] $template Template name(s)
     * @param array           $context  Context variables
     *
     * @return TemplateResponse|TemplateView
     */
    protected function render($template, array $context = [])
    {
        $twig = $this->app['twig'];
        /** @var Template $template */
        $template = $twig->resolveTemplate($template);

        if ($this->getOption('general/compatibility/template_view', false)) {
            return new TemplateView($template->getTemplateName(), $context);
        }
        Deprecated::warn(
            'Returning a TemplateResponse from Bolt\Controller\Base::render',
            3.3,
            'Be sure no Response methods are used from return value and then set "compatibility/template_view"' .
            ' to true in config.yml. This changes render() to return a TemplateView instead.'
        );

        $content = $template->render($context);
        $response = new TemplateResponse($template->getTemplateName(), $context, $content);

        return $response;
    }

    /**
     * Convert some data into a JSON response.
     *
     * @param mixed $data    The response data
     * @param int   $status  The response status code
     * @param array $headers An array of response headers
     *
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     */
    protected function json($data = [], $status = 200, array $headers = [])
    {
        return new JsonResponse($data, $status, $headers);
    }

    /**
     * Creates and returns a Form instance from the type of the form.
     *
     * @param string|FormTypeInterface $type    The built type of the form
     * @param mixed                    $data    The initial data for the form
     * @param array                    $options Options for the form
     *
     * @return Form
     */
    protected function createForm($type = FormType::class, $data = null, array $options = [])
    {
        return $this->app['form.factory']->create($type, $data, $options);
    }

    /**
     * Returns a form builder.
     *
     * @param string|FormTypeInterface $type    The type of the form
     * @param mixed                    $data    The initial data
     * @param array                    $options The options
     *
     * @return FormBuilderInterface The form builder
     */
    protected function createFormBuilder($type = FormType::class, $data = null, array $options = [])
    {
        return $this->app['form.factory']->createBuilder($type, $data, $options);
    }

    /**
     * Shortcut for {@see UrlGeneratorInterface::generate}.
     *
     * @param string $name          The name of the route
     * @param array  $params        An array of parameters
     * @param int    $referenceType The type of reference to be generated (one of the constants)
     *
     * @return string
     */
    protected function generateUrl($name, $params = [], $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH)
    {
        /** @var UrlGeneratorInterface $generator */
        $generator = $this->app['url_generator'];

        return $generator->generate($name, $params, $referenceType);
    }

    /**
     * Redirects the user to another URL.
     *
     * @param string $url    The URL to redirect to
     * @param int    $status The status code (302 by default)
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    protected function redirect($url, $status = 302)
    {
        return new RedirectResponse($url, $status);
    }

    /**
     * Returns a RedirectResponse to the given route with the given parameters.
     *
     * @param string $route      The name of the route
     * @param array  $parameters An array of parameters
     * @param int    $status     The status code to use for the Response
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    protected function redirectToRoute($route, array $parameters = [], $status = 302)
    {
        return $this->redirect($this->generateUrl($route, $parameters), $status);
    }

    /**
     * Returns the Entity Manager.
     *
     * @return \Bolt\Storage\EntityManager|\Bolt\Legacy\Storage
     */
    protected function storage()
    {
        return $this->app['storage'];
    }

    /**
     * Returns the session.
     *
     * @return \Symfony\Component\HttpFoundation\Session\Session
     */
    protected function session()
    {
        return $this->app['session'];
    }

    /**
     * Gets the flash logger.
     *
     * @return \Bolt\Logger\FlashLoggerInterface
     */
    protected function flashes()
    {
        return $this->app['logger.flash'];
    }

    /**
     * Returns the Authentication object.
     *
     * @return \Bolt\AccessControl\AccessChecker
     */
    protected function accessControl()
    {
        return $this->app['access_control'];
    }

    /**
     * Validates CSRF token and throws HttpException if not.
     *
     * @param string|null $value The token value or null to use "bolt_csrf_token" parameter from request.
     * @param string      $id    The token ID.
     *
     * @throws HttpExceptionInterface
     */
    protected function validateCsrfToken($value = null, $id = 'bolt')
    {
        if (!$this->isCsrfTokenValid($value, $id)) {
            $this->abort(Response::HTTP_BAD_REQUEST, Trans::__('general.phrase.something-went-wrong'));
        }
    }

    /**
     * Check if csrf token is valid.
     *
     * @param string|null $value The token value or null to use "bolt_csrf_token" parameter from request.
     * @param string      $id    The token ID.
     *
     * @return bool
     */
    protected function isCsrfTokenValid($value = null, $id = 'bolt')
    {
        $token = new CsrfToken($id, $value ?: $this->app['request_stack']->getCurrentRequest()->get('bolt_csrf_token'));

        return $this->app['csrf.token_manager']->isTokenValid($token);
    }

    /**
     * Gets the \Bolt\Extensions object.
     *
     * @return \Bolt\Extension\Manager
     */
    protected function extensions()
    {
        return $this->app['extensions'];
    }

    /**
     * Gets the Bolt\Filesystem\Manager object.
     *
     * @return \Bolt\Filesystem\Manager
     */
    protected function filesystem()
    {
        return $this->app['filesystem'];
    }

    /**
     * Returns the Users object.
     *
     * @return \Bolt\Users
     */
    protected function users()
    {
        return $this->app['users'];
    }

    /**
     * Check to see if the user table exists and has records.
     *
     * @return boolean
     */
    protected function hasUsers()
    {
        try {
            $users = $this->app['users']->getUsers();
            if (empty($users)) {
                return false;
            }

            return true;
        } catch (TableNotFoundException $e) {
            return false;
        }
    }

    /**
     * Return current user or user by ID.
     *
     * @param integer|string|null $userId
     *
     * @return Entity\Users|false
     */
    protected function getUser($userId = null)
    {
        if ($userId === null) {
            /** @var Token $sessionAuth */
            if ($this->session()->isStarted() && $sessionAuth = $this->session()->get('authentication')) {
                return $sessionAuth->getUser();
            }

            return false;
        }
        /** @var Repository\UsersRepository $repo */
        $repo = $this->storage()->getRepository(Entity\Users::class);

        return $repo->getUser($userId);
    }

    /**
     * Shortcut for {@see \Bolt\AccessControl\Permissions::isAllowed}.
     *
     * @param string       $what
     * @param mixed        $user        The user to check permissions against.
     * @param string|null  $contenttype
     * @param integer|null $contentid
     *
     * @return boolean
     */
    protected function isAllowed($what, $user = null, $contenttype = null, $contentid = null)
    {
        /** @var Token $sessionAuth */
        if ($user === null && $sessionAuth = $this->session()->get('authentication')) {
            $user = $sessionAuth->getUser()->toArray();
        }

        return $this->app['permissions']->isAllowed($what, $user, $contenttype, $contentid);
    }

    /**
     * Return a repository.
     *
     * @param string $repository
     *
     * @return \Bolt\Storage\Repository
     */
    protected function getRepository($repository)
    {
        return $this->storage()->getRepository($repository);
    }

    /**
     * Shortcut for {@see \Bolt\Legacy\Storage::getContent()}.
     *
     * @param string $textQuery
     * @param array  $parameters
     * @param array  $pager
     * @param array  $whereParameters
     *
     * @return \Bolt\Legacy\Content|\Bolt\Legacy\Content[]
     *
     * @see \Bolt\Legacy\Storage::getContent()
     */
    protected function getContent($textQuery, $parameters = [], &$pager = [], $whereParameters = [])
    {
        $isLegacy = $this->getOption('general/compatibility/setcontent_legacy', true);
        if ($isLegacy) {
            return $this->storage()->getContent($textQuery, $parameters, $pager, $whereParameters);
        }
        $params = array_merge($parameters, $whereParameters);

        return  $this->app['query']->getContent($textQuery, $params);
    }

    /**
     * Get the contenttype as an array, based on the given slug.
     *
     * @param string $slug
     *
     * @return boolean|array
     */
    protected function getContentType($slug)
    {
        return $this->storage()->getContentType($slug);
    }

    /**
     * Helper to get a user's permissions for a ContentType.
     *
     * @param string             $contentTypeSlug
     * @param array|Entity\Users $user
     *
     * @return boolean[]
     */
    protected function getContentTypeUserPermissions($contentTypeSlug, $user = null)
    {
        if ($user === null) {
            return $this->app['permissions']->getContentTypePermissions();
        }

        return $this->app['permissions']->getContentTypeUserPermissions($contentTypeSlug, $user);
    }

    /**
     * Shortcut for {@see \Bolt\Config::get}.
     *
     * @param string $path
     * @param mixed  $default
     *
     * @return string|integer|array|null
     */
    protected function getOption($path, $default = null)
    {
        return $this->app['config']->get($path, $default);
    }

    /**
     * Get an array of query parameters used in the request.
     *
     * @param Request $request
     *
     * @return array
     */
    protected function getRefererQueryParameters(Request $request)
    {
        $referer = $request->server->get('HTTP_REFERER');
        $request = Request::create($referer);

        return (array) $request->query->getIterator();
    }

    /**
     * Return the Bolt\TemplateChooser provider.
     *
     * @return \Bolt\TemplateChooser
     */
    protected function templateChooser()
    {
        return $this->app['templatechooser'];
    }

    /**
     * Return a new Query Builder.
     *
     * @return \Doctrine\DBAL\Query\QueryBuilder
     */
    protected function createQueryBuilder()
    {
        return $this->app['db']->createQueryBuilder();
    }
}


text:
<?php

/* NewsAdminBundle:Articles:detail.html.twig */
class __TwigTemplate_3d2b22bceff296e06fb070c04fdc9cb47eb3f6c7a222fa46c9154edf6dc85ee5 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = $this->env->loadTemplate("NewsAdminBundle::layout.html.twig");

        $this->blocks = array(
            'table' => array($this, 'block_table'),
            'categories' => array($this, 'block_categories'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "NewsAdminBundle::layout.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 3
    public function block_table($context, array $blocks = array())
    {
        echo "

                           Article details

                                  Dashboard

                                 Details / ";
        // line 19
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "titre", array()), "html", null, true);
        echo "

  ";
        // line 27
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "titre", array()), "html", null, true);
        echo "

                env, $this->env->getExtension('routing')->getPath("articles_edit", array("id" => $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "id", array()))), "html", null, true);
        echo "\">
                    <button  type=\"button\" class=\"btn btn-lg btn-primary\">Edit Article</button>

  env, $this->env->getExtension('assets')->getAssetUrl("articles/"), "html", null, true);
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "image", array()), "html", null, true);
        echo "\" width=\"500\" height=\"300\" title=\"";
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "titre", array()), "html", null, true);
        echo "\"  alt=\"";
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "titre", array()), "html", null, true);
        echo "\">

Titre	  ";
        // line 40
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "titre", array()), "html", null, true);
        echo "

Categorie	";
        // line 41
        echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "categorie", array()), "titre", array()), "html", null, true);
        echo "

Date	  ";
        // line 42
        echo twig_escape_filter($this->env, twig_date_format_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "date", array()), "Y-m-d"), "html", null, true);
        echo "

 Content	  ";
        // line 43
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "contenue", array()), "html", null, true);
        echo "

                                     ";
        // line 44
        if (($this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "image1", array()) != null)) {
            // line 45
            echo "
 Other photo	   env, $this->env->getExtension('assets')->getAssetUrl("articles/"), "html", null, true);
            echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "image1", array()), "html", null, true);
            echo "\" width=\"300\" height=\"200\" title=\"";
            echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "titre", array()), "html", null, true);
            echo "\"  alt=\"";
            echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "titre", array()), "html", null, true);
            echo "\">

                                         ";
        }
        // line 47
        echo "                                     ";
        if (($this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "parg1", array()) != null)) {
            // line 48
            echo "
 Other section	  ";
            echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "parg1", array()), "html", null, true);
            echo "

                                         ";
        }
        // line 50
        echo "                                           ";
        if (($this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "image2", array()) != null)) {
            // line 51
            echo "
 Other photo	  env, $this->env->getExtension('assets')->getAssetUrl("articles/"), "html", null, true);
            echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "image2", array()), "html", null, true);
            echo "\" width=\"300\" height=\"200\" title=\"";
            echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "titre", array()), "html", null, true);
            echo "\"  alt=\"";
            echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "titre", array()), "html", null, true);
            echo "\">

                                         ";
        }
        // line 53
        echo "                                     ";
        if (($this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "parg2", array()) != null)) {
            // line 54
            echo "
 Other section	  ";
            echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "parg2", array()), "html", null, true);
            echo "

                                         ";
        }
        // line 56
        echo "
                                           ";
        // line 57
        if (($this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "image3", array()) != null)) {
            // line 58
            echo "
 Other photo	  env, $this->env->getExtension('assets')->getAssetUrl("articles/"), "html", null, true);
            echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "image3", array()), "html", null, true);
            echo "\" width=\"300\" height=\"200\" title=\"";
            echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "titre", array()), "html", null, true);
            echo "\"  alt=\"";
            echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "titre", array()), "html", null, true);
            echo "\">

                                          ";
        }
        // line 60
        echo "                                     ";
        if (($this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "parg3", array()) != null)) {
            // line 61
            echo "
 Other section	  ";
            echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "parg3", array()), "html", null, true);
            echo "

                                         ";
        }
        // line 63
        echo "

                                           ";
        // line 65
        if (($this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "image4", array()) != null)) {
            // line 66
            echo "
 Other photo	  env, $this->env->getExtension('assets')->getAssetUrl("articles/"), "html", null, true);
            echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "image4", array()), "html", null, true);
            echo "\" width=\"300\" height=\"200\" title=\"";
            echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "titre", array()), "html", null, true);
            echo "\"  alt=\"";
            echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "titre", array()), "html", null, true);
            echo "\">

                                          ";
        }
        // line 68
        echo "                                     ";
        if (($this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "parg4", array()) != null)) {
            // line 69
            echo "
 Other section	  ";
            echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "parg4", array()), "html", null, true);
            echo "

                                         ";
        }
        // line 71
        echo "

                                           ";
        // line 73
        if (($this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "image5", array()) != null)) {
            // line 74
            echo "
 Other photo	  env, $this->env->getExtension('assets')->getAssetUrl("articles/"), "html", null, true);
            echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "image5", array()), "html", null, true);
            echo "\" width=\"300\" height=\"200\" title=\"";
            echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "titre", array()), "html", null, true);
            echo "\"  alt=\"";
            echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "titre", array()), "html", null, true);
            echo "\">

                                         ";
        }
        // line 76
        echo "                                     ";
        if (($this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "parg5", array()) != null)) {
            // line 77
            echo "
 Other section	  ";
            echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "parg5", array()), "html", null, true);
            echo "

                                         ";
        }
        // line 79
        echo "                                         ";
        if (($this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "video", array()) != null)) {
            // line 80
            echo "

                                        env, $this->env->getExtension('assets')->getAssetUrl("https://www.youtube.com/embed/"), "html", null, true);
            echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "video", array()), "html", null, true);
            echo "\" frameborder=\"0\" allowfullscreen>

                    ";
        }
        // line 84
        echo "

        ";
    }

    // line 108
    public function block_categories($context, array $blocks = array())
    {
        // line 109
        echo "       ";
        $context['_parent'] = (array) $context;
        $context['_seq'] = twig_ensure_traversable((isset($context["categories"]) ? $context["categories"] : $this->getContext($context, "categories")));
        foreach ($context['_seq'] as $context["_key"] => $context["category"]) {
            // line 110
            echo "

                                env, $this->env->getExtension('routing')->getPath("articles", array("id" => $this->getAttribute($context["category"], "id", array()))), "html", null, true);
            echo "\" >";
            echo twig_escape_filter($this->env, $this->getAttribute($context["category"], "titre", array()), "html", null, true);
            echo "

       ";
        }
        $_parent = $context['_parent'];
        unset($context['_seq'], $context['_iterated'], $context['_key'], $context['category'], $context['_parent'], $context['loop']);
        $context = array_intersect_key($context, $_parent) + $_parent;
        // line 114
        echo "                            ";
    }

    public function getTemplateName()
    {
        return "NewsAdminBundle:Articles:detail.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  286 => 114,  275 => 111,  272 => 110,  267 => 109,  264 => 108,  238 => 84,  231 => 81,  228 => 80,  225 => 79,  219 => 77,  216 => 76,  205 => 74,  203 => 73,  199 => 71,  193 => 69,  190 => 68,  179 => 66,  177 => 65,  173 => 63,  167 => 61,  164 => 60,  153 => 58,  151 => 57,  148 => 56,  142 => 54,  139 => 53,  128 => 51,  125 => 50,  119 => 48,  116 => 47,  105 => 45,  103 => 44,  99 => 43,  95 => 42,  91 => 41,  87 => 40,  78 => 39,  65 => 29,  60 => 27,  49 => 19,  29 => 3,);
    }
}


text:
clean
compile


text:
<?php

namespace Ambta\DoctrineEncryptBundle\Tests;

use Ambta\DoctrineEncryptBundle\Encryptors\AES192Encryptor;
use PHPUnit\Framework\TestCase;

/**
 * Class AES256EncryptorTest.
 */
class AES192EncryptorTest extends TestCase
{
    const SECRET_KEY = '624758dbe24e20067b27fc3cef22dc61';

    /**
     * @test
     */
    public function checkEncryptor()
    {
        $aes = new AES192Encryptor(self::SECRET_KEY);

        $data = 'Content some data!';
        $encryptData = $aes->encrypt($data);

        self::assertEquals($data, $aes->decrypt($encryptData));
    }

    /**
     * @test
     * @dataProvider getContentData()
     *
     * @param mixed $data
     */
    public function checkEncryptorWithoutString($data)
    {
        $aes = new AES192Encryptor(self::SECRET_KEY);
        $encryptData = $aes->encrypt($data);

        self::assertEquals($encryptData, $data);
        self::assertEquals($data, $aes->decrypt($encryptData));
    }

    /**
     * @return array
     */
    public function getContentData()
    {
        return [
            [1234],
            [100.123],
            [true],
            [false],
            [null],
        ];
    }
}


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

<title>M-Index</title>
<meta name="date" content="2018-10-07">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G H I L M P R S T U V W X

M

main(String[]) - Static method in class com.ensoftcorp.open.immutability.analysis.codegen.XFieldAdaptYGreaterThanEqualZConstraintSolverGenerator

main(String[]) - Static method in class com.ensoftcorp.open.immutability.analysis.codegen.XGreaterThanEqualYConstraintSolverGenerator

main(String[]) - Static method in class com.ensoftcorp.open.immutability.analysis.codegen.XGreaterThanEqualYFieldAdaptZConstraintSolverGenerator

main(String[]) - Static method in class com.ensoftcorp.open.immutability.analysis.codegen.XGreaterThanEqualYMethodAdaptZConstraintSolverGenerator

main(String[]) - Static method in class com.ensoftcorp.open.immutability.analysis.codegen.XMethodAdaptYGreaterThanEqualZConstraintSolverGenerator

main(String[]) - Static method in class com.ensoftcorp.open.immutability.experimental.AFieldAdaptBGreaterThanEqualCFieldAdaptDConstraintSolverGenerator

main(String[]) - Static method in class com.ensoftcorp.open.immutability.experimental.TestConstraintEquality

MUTABLE - Static variable in class com.ensoftcorp.open.immutability.constants.ImmutabilityTags

Tag applied to fields, parameters, variables, etc.

A B C D E F G H I L M P R S T U V W X

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
<?php
/**
 * AppShell file
 *
 * @link          https://cakephp.org CakePHP(tm) Project
 * @since         CakePHP(tm) v 2.0
 */

App::uses('Shell', 'Console');

/**
 * Application Shell
 *
 * Add your application-wide methods in the class below, your shells
 * will inherit them.
 *
 * @package       app.Console.Command
 */
class AppShell extends Shell {

}


text:
@echo off
cd ../..
cd temp
ctest -V -C RelWithDebInfo
if %errorlevel% neq 0 exit /b %errorlevel%
cd ../build/VisualStudio


text:
package cc.factorie.app.chain

import cc.factorie.la._
import cc.factorie.model._
import cc.factorie.optimize.Example
import cc.factorie.util.DoubleAccumulator
import cc.factorie.variable.{Var, DiscreteDomain, DiscreteVar}

import scala.collection.mutable.ArrayBuffer

/** These classes provide a lightweight, flexible version of chain models that can incorporate arbitrary features for both
  * edges and nodes. For example, sparse edge weights or low-dimensional embeddings for labels and cliques could be used.
  * Serialization can be done with BinarySerializer and inference with ChainHelper, to keep things simple.
  */

class BasicChainModel[Y <: DiscreteVar](val domain: DiscreteDomain, val featureDomain: DiscreteDomain, val feats: Y => Tensor)
  extends LiteChainModel[Y] {
  val nodeWeights: Weights2 = Weights(new DenseTensor2(featureDomain.size, domain.size))
  val edgeWeights: Weights2 = Weights(new DenseTensor2(domain.size, domain.size))
  def nodeFeatures(node: Y, y: Y#Value): Tensor = feats(node) outer y
  def edgeFeatures(left: Y, right: Y, y1: Y#Value, y2: Y#Value): Tensor = y1 outer y2
}

class SparseEdgeFeatureChainModel[Y <: DiscreteVar](
  val domain: DiscreteDomain, val nodeFeatureDomain: DiscreteDomain, val edgeFeatureDomain: DiscreteDomain,
  val nodeFeats: Y => Tensor, val edgeFeats: (Y, Y) => Tensor)
  extends LiteChainModel[Y] {
  val nodeWeights: Weights2 = Weights(new DenseTensor2(nodeFeatureDomain.size, domain.size))
  val edgeWeights: Weights1 = Weights(new SparseIndexedTensor1(domain.size * domain.size * edgeFeatureDomain.size))
  def nodeFeatures(node: Y, y: Y#Value): Tensor = nodeFeats(node) outer y
  def edgeFeatures(left: Y, right: Y, y1: Y#Value, y2: Y#Value): Tensor = {
    // Take advantage of outer product logic in Sparse1 to map things to good indices
    // This should hit the Sparse outer Sparse case of the pattern match
    val t = new SparseIndexedTensor1(edgeWeights.value.dim1)
    t += edgeFeats(left, right) outer (y1 outer y2)
    t
  }
}

abstract class LiteChainModel[Y <: DiscreteVar] extends Model with Parameters {
  def domain: DiscreteDomain
  def edgeWeights: Weights
  def nodeWeights: Weights

  def edgeFeatures(left: Y, right: Y, y1: Y#Value, y2: Y#Value): Tensor
  def nodeFeatures(node: Y, y: Y#Value): Tensor

  def potentials(obs: Seq[Y]): ChainCliqueValues =
    LiteChainModelHelper.makePotentials(domain.size, obs.size, nodeWeights.value, edgeWeights.value,
      (i, j) => nodeFeatures(obs(i), _idxv(j)),
      (i, j, k) => edgeFeatures(obs(i), obs(i + 1), _idxv(j), _idxv(k)))

  def _idxv(i: Int): Y#Value = domain(i).asInstanceOf[Y#Value]

  override def factors(variables: Iterable[Var]): Iterable[Factor] = {
    val out = new ArrayBuffer[Factor]
    variables.toVector.foreach({
       case v: Y @unchecked if v.isInstanceOf[Y]  =>
        out += new LiteNodeFactor1(v)
    })
    if (variables.size > 1)
      variables.toVector.map({ case v: Y @unchecked if v.isInstanceOf[Y] => v}).sliding(2)
        .map({ case Vector(v1, v2) => new LiteEdgeFactor2(v1, v2)}).foreach(out +=)
    out
  }
  class LiteNodeFactor1(v: Y) extends DotFactor1(v) {
    override def weights: Weights = nodeWeights
    override def statistics(y: Y#Value): Tensor = nodeFeatures(v, y)
  }
  class LiteEdgeFactor2(left: Y, right: Y) extends DotFactor2(left, right) {
    override def weights: Weights = edgeWeights
    override def statistics(y1: Y#Value, y2: Y#Value): Tensor = edgeFeatures(left, right, y1, y2)
  }
}

class LiteChainModelExample[Y <: DiscreteVar](model: LiteChainModel[Y], inst: Seq[Y], label: Y => Y#Value) extends Example {
  override def accumulateValueAndGradient(value: DoubleAccumulator, gradient: WeightsMapAccumulator): Unit = {
    def idxv(i: Int) = model._idxv(i)
    val scores = model.potentials(inst)
    val ChainForwardBackwardResults(logZ, alphas, betas, _) = ChainHelper.inferFast(scores)
    if (value ne null)
      value.accumulate(-logZ)
    val numStates = model.domain.size
    for (n <- 0 until inst.size) {
      val prevAlpha = if (n >= 1) alphas(n - 1) else null.asInstanceOf[Tensor1]
      val curAlpha = alphas(n)
      val curBeta = betas(n)
      val curNodeScores = scores.localValues(n)
      val curEdgeScores = if (n >= 1) scores.transitionValues(n - 1) else null.asInstanceOf[Tensor2]
      val curTargetState = label(inst(n)).intValue
      val prevTargetState = if (n >= 1) label(inst(n - 1)).intValue else -1
      if (value ne null) {
        value.accumulate(curNodeScores(curTargetState))
        if (n >= 1) value.accumulate(curEdgeScores(prevTargetState * numStates + curTargetState))
      }
      if (gradient ne null) {
        gradient.accumulate(model.nodeWeights, model.nodeFeatures(inst(n), idxv(curTargetState)), 1.0)
        val localMarginal = curAlpha + curBeta
        localMarginal.expNormalize(logZ)
        for (s <- 0 until numStates) {
          val sf = model.nodeFeatures(inst(n), idxv(s))
          val m = localMarginal(s)
          gradient.accumulate(model.nodeWeights, sf, -1.0 * m)
        }
        if (n >= 1) {
          gradient.accumulate(model.edgeWeights, model.edgeFeatures(inst(n - 1), inst(n), idxv(prevTargetState), idxv(curTargetState)), 1.0)
          for (s1 <- 0 until numStates; s2 <- 0 until numStates) {
            val ssf = model.edgeFeatures(inst(n - 1), inst(n), idxv(s1), idxv(s2))
            val m = math.exp(prevAlpha(s1) + curEdgeScores(s1 * numStates + s2) + curBeta(s2) + curNodeScores(s2) - logZ)
            gradient.accumulate(model.edgeWeights, ssf, -1.0 * m)
          }
        }
      }
    }
  }
}

object LiteChainModelHelper {
  def makePotentials(numStates: Int, numNodes: Int, nodeWeights: Tensor, edgeWeights: Tensor,
    nodeFeatures: (Int, Int) => Tensor, edgeFeatures: (Int, Int, Int) => Tensor): ChainCliqueValues = {
    val nodePotentials = new ArrayBuffer[DenseTensor1]
    val edgePotentials = new ArrayBuffer[Tensor2]
    val numEdges = numNodes - 1
    for (n <- 0 until numNodes) {
      val nodePotential = new DenseTensor1(numStates)
      for (y <- 0 until numStates) {
        nodePotential(y) = nodeWeights dot nodeFeatures(n, y)
      }
      nodePotentials += nodePotential
    }
    for (e <- 0 until numEdges) {
      val edgePotential = new DenseTensor2(numStates, numStates)
      for (y1 <- 0 until numStates; y2 <- 0 until numStates) {
        edgePotential(y1, y2) = edgeWeights dot edgeFeatures(e, y1, y2)
      }
      edgePotentials += edgePotential
    }
    ChainCliqueValues(nodePotentials, edgePotentials)
  }
}


text:
module EmptyCucumber
  class Create < Thor::Group

    include Thor::Actions

    desc "Generates empty files for a Cucumber project"

    argument :name, :type => :string, :required => true, :desc => "Project name. This will be the root folder."

    def self.source_root
      File.dirname(__FILE__) + "/templates/"
    end

    def create_folders
      empty_directory("#{name}/features")
      empty_directory("#{name}/features/support")
      empty_directory("#{name}/features/step_definitions")
      empty_directory("#{name}/features/support/pages")
    end

    def copy_env
      template "env.rb.tt", "#{name}/features/support/env.rb"
    end

    def copy_hooks
      template "hooks.rb.tt", "#{name}/features/support/hooks.rb"
    end

    def copy_feature_template
      template "feature_example.feature.tt", "#{name}/features/feature_example.feature"
    end

    def copy_cucumber_yml
      template "cucumber.yml.tt", "#{name}/cucumber.yml"
    end

    def copy_steps_def_file
      template "steps_example.rb.tt", "#{name}/features/step_definitions/steps_example.rb"
    end

    def copy_rakefile_file
      template "rakefile.rb.tt", "#{name}/Rakefile"
    end

    def copy_gemfile
      template "Gemfile.tt", "#{name}/Gemfile"
    end

  end
end


text:
namespace df
{
MessageAcceptor::MessageAcceptor()
  : m_infinityWaiting(false)
{}

bool MessageAcceptor::ProcessSingleMessage(bool waitForMessage)
{
  m_infinityWaiting = waitForMessage;
  drape_ptr<Message> message = m_messageQueue.PopMessage(waitForMessage);
  m_infinityWaiting = false;

  if (message == nullptr)
    return false;

  AcceptMessage(make_ref(message));
  return true;
}

void MessageAcceptor::EnableMessageFiltering(MessageQueue::FilterMessageFn && filter)
{
  m_messageQueue.EnableMessageFiltering(std::move(filter));
}

void MessageAcceptor::DisableMessageFiltering()
{
  m_messageQueue.DisableMessageFiltering();
}

void MessageAcceptor::PostMessage(drape_ptr<Message> && message, MessagePriority priority)
{
  m_messageQueue.PushMessage(std::move(message), priority);
}

void MessageAcceptor::CloseQueue()
{
  m_messageQueue.CancelWait();
  m_messageQueue.ClearQuery();
}

void MessageAcceptor::CancelMessageWaiting()
{
  m_messageQueue.CancelWait();
}

bool MessageAcceptor::IsInInfinityWaiting() const
{
  return m_infinityWaiting;
}

#ifdef DEBUG_MESSAGE_QUEUE

bool MessageAcceptor::IsQueueEmpty() const
{
  return m_messageQueue.IsEmpty();
}

size_t MessageAcceptor::GetQueueSize() const
{
  return m_messageQueue.GetSize();
}

#endif
}  // namespace df


text:
import { useState } from 'react'
import { useForm } from 'react-hook-form'

const IndexPage = () => {
  const [user, setUser] = useState()
  const {
    register,
    formState: { errors },
    handleSubmit,
  } = useForm()
  const onSubmit = ({ username, password, remember }) => {
    // You should handle login logic with username, password and remember form data
    setUser({ name: username })
  }

  return (

      {user ? (
        Hello, {user.name}!
      ) : (
        <form onSubmit={handleSubmit(onSubmit)}>

LOGIN

            <input
              type="text"
              placeholder="user name"
              {...register('username', {
                required: { value: true, message: 'User name is required' },
                minLength: {
                  value: 3,
                  message: 'User name cannot be less than 3 character',
                },
              })}
              className={'form-field' + (errors.username ? ' has-error' : '')}
            />
            {errors.username && (
              {errors.username.message}
            )}

            <input
              type="password"
              placeholder="password"
              {...register('password', {
                required: {
                  value: true,
                  message: 'Please enter your password',
                },
              })}
              className={'form-field' + (errors.password ? ' has-error' : '')}
            />
            {errors.password && (
              {errors.password.message}
            )}

            <input type="checkbox" id="remember" {...register('remember')} />

              Remember me

            <button type="submit" className="btn login-btn">
              Login
            </button>

        </form>
      )}

  )
}

export default IndexPage