text:
<!DOCTYPE html>

<meta charset="UTF-8">
<title>PetFinder</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="css/style.css" type="text/css">
<link href='http://fonts.googleapis.com/css?family=Roboto|Ubuntu' rel='stylesheet' type='text/css'>

<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />

            <button type="button" data-target="#navbarCollapse" data-toggle="collapse" class="navbar-toggle">
                Toggle navigation

            </button>
            PetFinder

Karte

Registrieren

            <form role="search" class="navbar-form navbar-left">

                    <input type="text" placeholder="Suchen" class="form-control">

            </form>

Contact


text:
import { Component, Input, OnChanges, OnInit, SimpleChanges } from "@angular/core";
import { ProjectWebhookService } from "../webhook.service";
import { WebhookLastTrigger } from "../../../../../../ng-swagger-gen/models/webhook-last-trigger";

@Component({
    selector: 'last-trigger',
    templateUrl: 'last-trigger.component.html',
    styleUrls: ['./last-trigger.component.scss']
})
export class LastTriggerComponent implements  OnInit , OnChanges {
    @Input()  inputLastTriggers: WebhookLastTrigger[];
    @Input()  webhookName: string;
    lastTriggers: WebhookLastTrigger[] = [];
    constructor(private webhookService: ProjectWebhookService) {
    }
    ngOnChanges(changes: SimpleChanges): void {
       if (changes && changes['inputLastTriggers']) {
           this.lastTriggers = [];
           this.inputLastTriggers.forEach(item => {
             if (this.webhookName === item.policy_name) {
                 this.lastTriggers.push(item);
             }
           });
       }
    }
    ngOnInit(): void {
    }
    eventTypeToText(eventType: string): string {
        return this.webhookService.eventTypeToText(eventType);
    }
}

redpajama_set_name: RedPajamaGithub


text:
from setuptools import setup, find_packages
import sys
import platform
from imp import load_source

# Required test dependencies.
test_dependencies = [
    # Test runner.
    'pytest',

    # Ensure PEP8 conformance.
    'pytest-pep8',

    # Ensure test coverage.
    'pytest-cov',

    # Benchmarking.
    'pytest-bench',

    # Installs a WSGI application that intercepts requests made to a hostname
    # and port combination for testing.
    'wsgi_intercept >= 0.6.0',

    # HTTP request abstraction layer over httplib.
    'httplib2',

    # The Web framework for perfectionists with deadlines.
    'django',

    # A microframework based on Werkzeug, Jinja2 and good intentions.
    'flask',

    # Bottle is a fast and simple micro-framework for small web applications.
    'bottle',

    # SQLAlchemy is the Python SQL toolkit and Object Relational Mapper
    # that gives application developers the full power and flexibility of SQL.
    'sqlalchemy',
]

if sys.version_info[0] == 2:
    if platform.python_implementation() != 'PyPy':
        # Test dependencies that don't work in PyPy.
        test_dependencies += [
            # gevent is a coroutine-based Python networking library that uses
            # greenlet to provide a high-level synchronous API on top of the
            # libevent event loop.
            'gevent',
        ]

setup(
    name='armet',
    version=load_source('', 'armet/_version.py').__version__,
    description='Clean and modern framework for creating RESTful APIs.',
    license='MIT',
    author='Concordus Applications',
    author_email='support@concordusapps.com',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Framework :: Bottle',
        'Framework :: Flask',
        'Framework :: Django',
        # 'Framework :: CherryPy',
        # 'Framework :: Twisted',
        # 'Framework :: Pylons',
        # 'Framework :: Pyramid',
        # 'Framework :: SQLAlchemy',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: Implementation :: PyPy',
        'Topic :: Database',
        'Topic :: Internet',
        'Topic :: Software Development',
        'Topic :: Software Development :: Libraries',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ],
    url='http://github.com/armet/python-armet',
    packages=find_packages('.'),
    install_requires=[
        # Python 2 and 3 normalization layer
        'six',

        # For parsing accept and content-type headers
        'python-mimeparse',

        # Ultra fast JSON encoder and decoder for Python.
        'ujson'
    ],
    extras_require={
        'test': test_dependencies
    }
)


text:
import { assert } from 'ember-metal/debug';
import { set } from 'ember-metal/property_set';
import { inspect } from 'ember-metal/utils';
import { meta as metaFor, peekMeta } from 'ember-metal/meta';
import expandProperties from 'ember-metal/expand_properties';
import EmberError from 'ember-metal/error';
import {
  Descriptor,
  defineProperty
} from 'ember-metal/properties';
import {
  propertyWillChange,
  propertyDidChange
} from 'ember-metal/property_events';
import {
  addDependentKeys,
  removeDependentKeys
} from 'ember-metal/dependent_keys';

/**
@module ember
@submodule ember-metal
*/

function UNDEFINED() { }

// ..........................................................
// COMPUTED PROPERTY
//

/**
  A computed property transforms an object literal with object's accessor function(s) into a property.

  By default the function backing the computed property will only be called
  once and the result will be cached. You can specify various properties
  that your computed property depends on. This will force the cached
  result to be recomputed if the dependencies are modified.

  In the following example we declare a computed property - `fullName` - by calling
  `.Ember.computed()` with property dependencies (`firstName` and `lastName`) as leading arguments and getter accessor function. The `fullName` getter function
  will be called once (regardless of how many times it is accessed) as long
  as its dependencies have not changed. Once `firstName` or `lastName` are updated
  any future calls (or anything bound) to `fullName` will incorporate the new
  values.

  ```javascript
  let Person = Ember.Object.extend({
    // these will be supplied by `create`
    firstName: null,
    lastName: null,

    fullName: Ember.computed('firstName', 'lastName', function() {
      let firstName = this.get('firstName'),
          lastName  = this.get('lastName');

      return firstName + ' ' + lastName;
    })
  });

  let tom = Person.create({
    firstName: 'Tom',
    lastName: 'Dale'
  });

  tom.get('fullName') // 'Tom Dale'
  ```

  You can also define what Ember should do when setting a computed property by providing additional function (`set`) in hash argument.
  If you try to set a computed property, it will try to invoke setter accessor function with the key and
  value you want to set it to as arguments.

  ```javascript
  let Person = Ember.Object.extend({
    // these will be supplied by `create`
    firstName: null,
    lastName: null,

    fullName: Ember.computed('firstName', 'lastName', {
      get(key) {
        let firstName = this.get('firstName'),
            lastName  = this.get('lastName');

        return firstName + ' ' + lastName;
      },
      set(key, value) {
        let [firstName, lastName] = value.split(' ');

        this.set('firstName', firstName);
        this.set('lastName', lastName);

        return value;
      }
    })
  });

  let person = Person.create();

  person.set('fullName', 'Peter Wagenet');
  person.get('firstName'); // 'Peter'
  person.get('lastName');  // 'Wagenet'
  ```

  You can overwrite computed property with normal property (no longer computed), that won't change if dependencies change, if you set computed property and it won't have setter accessor function defined.

  You can also mark computed property as `.readOnly()` and block all attempts to set it.

  ```javascript
  let Person = Ember.Object.extend({
    // these will be supplied by `create`
    firstName: null,
    lastName: null,

    fullName: Ember.computed('firstName', 'lastName', {
      get(key) {
        let firstName = this.get('firstName');
        let lastName  = this.get('lastName');

        return firstName + ' ' + lastName;
      }
    }).readOnly()
  });

  let person = Person.create();
  person.set('fullName', 'Peter Wagenet'); // Uncaught Error: Cannot set read-only property "fullName" on object: <(...):emberXXX>
  ```

  Additional resources:
  - [New CP syntax RFC](https://github.com/emberjs/rfcs/blob/master/text/0011-improved-cp-syntax.md)
  - [New computed syntax explained in "Ember 1.12 released" ](http://emberjs.com/blog/2015/05/13/ember-1-12-released.html#toc_new-computed-syntax)

  @class ComputedProperty
  @namespace Ember
  @constructor
  @public
*/
function ComputedProperty(config, opts) {
  this.isDescriptor = true;
  if (typeof config === 'function') {
    this._getter = config;
  } else {
    assert('Ember.computed expects a function or an object as last argument.', typeof config === 'object' && !Array.isArray(config));
    assert('Config object pased to a Ember.computed can only contain `get` or `set` keys.', (function() {
      let keys = Object.keys(config);
      for (let i = 0; i < keys.length; i++) {
        if (keys[i] !== 'get' && keys[i] !== 'set') {
          return false;
        }
      }
      return true;
    })());
    this._getter = config.get;
    this._setter = config.set;
  }
  assert('Computed properties must receive a getter or a setter, you passed none.', !!this._getter || !!this._setter);
  this._dependentKeys = undefined;
  this._suspended = undefined;
  this._meta = undefined;
  this._volatile = false;
  this._dependentKeys = opts && opts.dependentKeys;
  this._readOnly =  false;
}

ComputedProperty.prototype = new Descriptor();

var ComputedPropertyPrototype = ComputedProperty.prototype;

/**
  Call on a computed property to set it into non-cached mode. When in this
  mode the computed property will not automatically cache the return value.

  It also does not automatically fire any change events. You must manually notify
  any changes if you want to observe this property.

  Dependency keys have no effect on volatile properties as they are for cache
  invalidation and notification when cached value is invalidated.

  ```javascript
  let outsideService = Ember.Object.extend({
    value: Ember.computed(function() {
      return OutsideService.getValue();
    }).volatile()
  }).create();
  ```

  @method volatile
  @return {Ember.ComputedProperty} this
  @chainable
  @public
*/
ComputedPropertyPrototype.volatile = function() {
  this._volatile = true;
  return this;
};

/**
  Call on a computed property to set it into read-only mode. When in this
  mode the computed property will throw an error when set.

  ```javascript
  let Person = Ember.Object.extend({
    guid: Ember.computed(function() {
      return 'guid-guid-guid';
    }).readOnly()
  });

  let person = Person.create();

  person.set('guid', 'new-guid'); // will throw an exception
  ```

  @method readOnly
  @return {Ember.ComputedProperty} this
  @chainable
  @public
*/
ComputedPropertyPrototype.readOnly = function() {
  this._readOnly = true;
  assert('Computed properties that define a setter using the new syntax cannot be read-only', !(this._readOnly && this._setter && this._setter !== this._getter));
  return this;
};

/**
  Sets the dependent keys on this computed property. Pass any number of
  arguments containing key paths that this computed property depends on.

  ```javascript
  let President = Ember.Object.extend({
    fullName: Ember.computed(function() {
      return this.get('firstName') + ' ' + this.get('lastName');

      // Tell Ember that this computed property depends on firstName
      // and lastName
    }).property('firstName', 'lastName')
  });

  let president = President.create({
    firstName: 'Barack',
    lastName: 'Obama'
  });

  president.get('fullName'); // 'Barack Obama'
  ```

  @method property
  @param {String} path* zero or more property paths
  @return {Ember.ComputedProperty} this
  @chainable
  @public
*/
ComputedPropertyPrototype.property = function() {
  var args;

  var addArg = function(property) {
    assert(
      `Depending on arrays using a dependent key ending with \`@each\` is no longer supported. ` +
        `Please refactor from \`Ember.computed('${property}', function() {});\` to \`Ember.computed('${property.slice(0, -6)}.[]', function() {})\`.`,
      property.slice(-5) !== '@each'
    );
    args.push(property);
  };

  args = [];
  for (var i = 0, l = arguments.length; i < l; i++) {
    expandProperties(arguments[i], addArg);
  }

  this._dependentKeys = args;
  return this;
};

/**
  In some cases, you may want to annotate computed properties with additional
  metadata about how they function or what values they operate on. For example,
  computed property functions may close over variables that are then no longer
  available for introspection.

  You can pass a hash of these values to a computed property like this:

  ```
  person: Ember.computed(function() {
    let personId = this.get('personId');
    return App.Person.create({ id: personId });
  }).meta({ type: App.Person })
  ```

  The hash that you pass to the `meta()` function will be saved on the
  computed property descriptor under the `_meta` key. Ember runtime
  exposes a public API for retrieving these values from classes,
  via the `metaForProperty()` function.

  @method meta
  @param {Object} meta
  @chainable
  @public
*/

ComputedPropertyPrototype.meta = function(meta) {
  if (arguments.length === 0) {
    return this._meta || {};
  } else {
    this._meta = meta;
    return this;
  }
};

// invalidate cache when CP key changes
ComputedPropertyPrototype.didChange = function(obj, keyName) {
  // _suspended is set via a CP.set to ensure we don't clear
  // the cached value set by the setter
  if (this._volatile || this._suspended === obj) {
    return;
  }

  // don't create objects just to invalidate
  let meta = peekMeta(obj);
  if (!meta || meta.source !== obj) {
    return;
  }

  let cache = meta.readableCache();
  if (cache && cache[keyName] !== undefined) {
    cache[keyName] = undefined;
    removeDependentKeys(this, obj, keyName, meta);
  }
};

/**
  Access the value of the function backing the computed property.
  If this property has already been cached, return the cached result.
  Otherwise, call the function passing the property name as an argument.

  ```javascript
  let Person = Ember.Object.extend({
    fullName: Ember.computed('firstName', 'lastName', function(keyName) {
      // the keyName parameter is 'fullName' in this case.
      return this.get('firstName') + ' ' + this.get('lastName');
    })
  });

  let tom = Person.create({
    firstName: 'Tom',
    lastName: 'Dale'
  });

  tom.get('fullName') // 'Tom Dale'
  ```

  @method get
  @param {String} keyName The key being accessed.
  @return {Object} The return value of the function backing the CP.
  @public
*/
ComputedPropertyPrototype.get = function(obj, keyName) {
  if (this._volatile) {
    return this._getter.call(obj, keyName);
  }

  let meta = metaFor(obj);
  let cache = meta.writableCache();

  let result = cache[keyName];
  if (result === UNDEFINED) {
    return undefined;
  } else if (result !== undefined) {
    return result;
  }

  let ret = this._getter.call(obj, keyName);
  if (ret === undefined) {
    cache[keyName] = UNDEFINED;
  } else {
    cache[keyName] = ret;
  }

  let chainWatchers = meta.readableChainWatchers();
  if (chainWatchers) {
    chainWatchers.revalidate(keyName);
  }
  addDependentKeys(this, obj, keyName, meta);

  return ret;
};

/**
  Set the value of a computed property. If the function that backs your
  computed property does not accept arguments then the default action for
  setting would be to define the property on the current object, and set
  the value of the property to the value being set.

  Generally speaking if you intend for your computed property to be set
  you should pass `set(key, value)` function in hash as argument to `Ember.computed()` along with `get(key)` function.

  ```javascript
  let Person = Ember.Object.extend({
    // these will be supplied by `create`
    firstName: null,
    lastName: null,

    fullName: Ember.computed('firstName', 'lastName', {
      // getter
      get() {
        let firstName = this.get('firstName');
        let lastName = this.get('lastName');

        return firstName + ' ' + lastName;
      },
      // setter
      set(key, value) {
        let [firstName, lastName] = value.split(' ');

        this.set('firstName', firstName);
        this.set('lastName', lastName);

        return value;
      }
    })
  });

  let person = Person.create();

  person.set('fullName', 'Peter Wagenet');
  person.get('firstName'); // 'Peter'
  person.get('lastName');  // 'Wagenet'
  ```

  @method set
  @param {String} keyName The key being accessed.
  @param {Object} newValue The new value being assigned.
  @return {Object} The return value of the function backing the CP.
  @public
*/
ComputedPropertyPrototype.set = function computedPropertySetEntry(obj, keyName, value) {
  if (this._readOnly) {
    this._throwReadOnlyError(obj, keyName);
  }

  if (!this._setter) {
    return this.clobberSet(obj, keyName, value);
  }

  if (this._volatile) {
    return this.volatileSet(obj, keyName, value);
  }

  return this.setWithSuspend(obj, keyName, value);
};

ComputedPropertyPrototype._throwReadOnlyError = function computedPropertyThrowReadOnlyError(obj, keyName) {
  throw new EmberError(`Cannot set read-only property "${keyName}" on object: ${inspect(obj)}`);
};

ComputedPropertyPrototype.clobberSet = function computedPropertyClobberSet(obj, keyName, value) {
  let cachedValue = cacheFor(obj, keyName);
  defineProperty(obj, keyName, null, cachedValue);
  set(obj, keyName, value);
  return value;
};

ComputedPropertyPrototype.volatileSet = function computedPropertyVolatileSet(obj, keyName, value) {
  return this._setter.call(obj, keyName, value);
};

ComputedPropertyPrototype.setWithSuspend = function computedPropertySetWithSuspend(obj, keyName, value) {
  let oldSuspended = this._suspended;
  this._suspended = obj;
  try {
    return this._set(obj, keyName, value);
  } finally {
    this._suspended = oldSuspended;
  }
};

ComputedPropertyPrototype._set = function computedPropertySet(obj, keyName, value) {
  // cache requires own meta
  let meta           = metaFor(obj);
  // either there is a writable cache or we need one to update
  let cache          = meta.writableCache();
  let hadCachedValue = false;
  let cachedValue;
  if (cache[keyName] !== undefined) {
    if (cache[keyName] !== UNDEFINED) {
      cachedValue = cache[keyName];
    }
    hadCachedValue = true;
  }

  let ret = this._setter.call(obj, keyName, value, cachedValue);

  // allows setter to return the same value that is cached already
  if (hadCachedValue && cachedValue === ret) {
    return ret;
  }

  let watched = meta.peekWatching(keyName);
  if (watched) {
    propertyWillChange(obj, keyName);
  }

  if (hadCachedValue) {
    cache[keyName] = undefined;
  }

  if (!hadCachedValue) {
    addDependentKeys(this, obj, keyName, meta);
  }

  if (ret === undefined) {
    cache[keyName] = UNDEFINED;
  } else {
    cache[keyName] = ret;
  }

  if (watched) {
    propertyDidChange(obj, keyName);
  }

  return ret;
};

/* called before property is overridden */
ComputedPropertyPrototype.teardown = function(obj, keyName) {
  if (this._volatile) {
    return;
  }
  let meta = metaFor(obj);
  let cache = meta.readableCache();
  if (cache && cache[keyName] !== undefined) {
    removeDependentKeys(this, obj, keyName, meta);
    cache[keyName] = undefined;
  }
};

/**
  This helper returns a new property descriptor that wraps the passed
  computed property function. You can use this helper to define properties
  with mixins or via `Ember.defineProperty()`.

  If you pass a function as an argument, it will be used as a getter. A computed
  property defined in this way might look like this:

  ```js
  let Person = Ember.Object.extend({
    init() {
      this._super(...arguments);

      this.firstName = 'Betty';
      this.lastName = 'Jones';
    },

    fullName: Ember.computed('firstName', 'lastName', function() {
      return `${this.get('firstName')} ${this.get('lastName')}`;
    })
  });

  let client = Person.create();

  client.get('fullName'); // 'Betty Jones'

  client.set('lastName', 'Fuller');
  client.get('fullName'); // 'Betty Fuller'
  ```

  You can pass a hash with two functions, `get` and `set`, as an
  argument to provide both a getter and setter:

  ```js
  let Person = Ember.Object.extend({
    init() {
      this._super(...arguments);

      this.firstName = 'Betty';
      this.lastName = 'Jones';
    },

    fullName: Ember.computed({
      get(key) {
        return `${this.get('firstName')} ${this.get('lastName')}`;
      },
      set(key, value) {
        let [firstName, lastName] = value.split(/\s+/);
        this.setProperties({ firstName, lastName });
        return value;
      }
    });
  })

  let client = Person.create();
  client.get('firstName'); // 'Betty'

  client.set('fullName', 'Carroll Fuller');
  client.get('firstName'); // 'Carroll'
  ```

  The `set` function should accept two parameters, `key` and `value`. The value
  returned from `set` will be the new value of the property.

  _Note: This is the preferred way to define computed properties when writing third-party
  libraries that depend on or use Ember, since there is no guarantee that the user
  will have [prototype Extensions](http://emberjs.com/guides/configuring-ember/disabling-prototype-extensions/) enabled._

  The alternative syntax, with prototype extensions, might look like:

  ```js
  fullName() {
    return this.get('firstName') + ' ' + this.get('lastName');
  }.property('firstName', 'lastName')
  ```

  @class computed
  @namespace Ember
  @constructor
  @static
  @param {String} [dependentKeys*] Optional dependent keys that trigger this computed property.
  @param {Function} func The computed property function.
  @return {Ember.ComputedProperty} property descriptor instance
  @public
*/
export default function computed(func) {
  var args;

  if (arguments.length > 1) {
    args = [].slice.call(arguments);
    func = args.pop();
  }

  var cp = new ComputedProperty(func);

  if (args) {
    cp.property.apply(cp, args);
  }

  return cp;
}

/**
  Returns the cached value for a property, if one exists.
  This can be useful for peeking at the value of a computed
  property that is generated lazily, without accidentally causing
  it to be created.

  @method cacheFor
  @for Ember
  @param {Object} obj the object whose property you want to check
  @param {String} key the name of the property whose cached value you want
    to return
  @return {Object} the cached value
  @public
*/
function cacheFor(obj, key) {
  var meta = peekMeta(obj);
  var cache = meta && meta.source === obj && meta.readableCache();
  var ret = cache && cache[key];

  if (ret === UNDEFINED) {
    return undefined;
  }
  return ret;
}

cacheFor.set = function(cache, key, value) {
  if (value === undefined) {
    cache[key] = UNDEFINED;
  } else {
    cache[key] = value;
  }
};

cacheFor.get = function(cache, key) {
  var ret = cache[key];
  if (ret === UNDEFINED) {
    return undefined;
  }
  return ret;
};

cacheFor.remove = function(cache, key) {
  cache[key] = undefined;
};

export {
  ComputedProperty,
  computed,
  cacheFor
};


text:
package librdkafka

// #cgo CFLAGS: -I/usr/local/include -std=c99
// #cgo LDFLAGS: -L/usr/local/lib -L/usr/local/opt/librdkafka/lib -lrdkafka
// #include "wrapper.h"
import "C"

import (
	"reflect"
	"unsafe"
)

// Message is the interface used to send exchange data with kafka
type Message interface {
	GetKey() []byte
	GetPayload() []byte
	GetUserdata() []byte
}

// MessageDelivery is used to handle message delivery errors
type MessageDelivery interface {
	OnMessageError(reason string, userdata []byte)
	OnMessageDelivered(userdata []byte)
}

//export goDeliveryHandler
func goDeliveryHandler(clientHandle *C.rd_kafka_t, code C.int, bufferPtr *C.buffer_t) {
	clientGuard.RLock()
	handler, handlerExists := clients[clientHandle]
	clientGuard.RUnlock()

	if handlerExists {
		buffer := UnmarshalBuffer(bufferPtr)
		if code == C.RD_KAFKA_RESP_ERR_NO_ERROR {
			handler.OnMessageDelivered(buffer)
		} else {
			handler.OnMessageError(codeToString(int(code)), buffer)
		}
	}
}

// UnmarshalBuffer creates a byte slice copy from a buffer_t handle.
func UnmarshalBuffer(bufferPtr *C.buffer_t) []byte {
	length := int(bufferPtr.len)
	buffer := make([]byte, length)
	copy(buffer, (*[1 << 30]byte)(bufferPtr.data)[:length:length])
	return buffer
}

type nativeMessage struct {
	key        unsafe.Pointer
	payload    unsafe.Pointer
	keyLen     C.size_t
	payloadLen C.size_t
}

func newBuffer(data []byte) *C.buffer_t {
	size := C.size_t(len(data))
	if size == 0 {
		return (*C.buffer_t)(nil)
	}

	nativeCopy := allocCopy(data)
	return C.CreateBuffer(size, nativeCopy)
}

func freeBuffer(buffer *C.buffer_t) {
	C.DestroyBuffer(buffer)
}

func newNativeMessage(msg Message) nativeMessage {
	key := msg.GetKey()
	pay := msg.GetPayload()

	return nativeMessage{
		key:        allocCopy(key),
		keyLen:     C.size_t(len(key)),
		payload:    allocCopy(pay),
		payloadLen: C.size_t(len(pay)),
	}
}

func allocCopy(data []byte) unsafe.Pointer {
	size := C.size_t(len(data))
	if size == 0 {
		return unsafe.Pointer(nil)
	}

	nativePtr := C.Alloc(size)
	slice := unsafe.Pointer(&reflect.SliceHeader{
		Data: uintptr(nativePtr),
		Len:  len(data),
		Cap:  len(data),
	})

	byteSlice := (*[]byte)(slice)
	copy(*byteSlice, data)
	return nativePtr
}

func (n *nativeMessage) free() {
	C.Free(n.key)
	C.Free(n.payload)
}


text:
package de.peeeq.wurstscript.intermediatelang.optimizer;

import de.peeeq.datastructures.Worklist;
import de.peeeq.wurstscript.intermediatelang.optimizer.ControlFlowGraph.Node;
import de.peeeq.wurstscript.jassIm.*;
import de.peeeq.wurstscript.translation.imoptimizer.OptimizerPass;
import de.peeeq.wurstscript.translation.imtranslation.ImHelper;
import de.peeeq.wurstscript.translation.imtranslation.ImTranslator;
import de.peeeq.wurstscript.types.TypesHelper;
import io.vavr.Tuple2;
import io.vavr.collection.HashMap;
import org.eclipse.jdt.annotation.Nullable;

import java.util.Map;

public class ConstantAndCopyPropagation implements OptimizerPass {
    private int totalPropagated = 0;

    public int optimize(ImTranslator trans) {
        ImProg prog = trans.getImProg();

        totalPropagated = 0;
        for (ImFunction func : ImHelper.calculateFunctionsOfProg(prog)) {
            if (!func.isNative() && !func.isBj()) {
                optimizeFunc(func);
            }
        }
        return totalPropagated;
    }

    @Override
    public String getName() {
        return "Constant and Copy Propagated";
    }

    static class Value {
        // one of the two is null
        final @Nullable
        ImVar copyVar;
        final @Nullable
        ImConst constantValue;
        ImTupleExpr constantTuple;

        public Value(ImVar copyVar) {
            this.copyVar = copyVar;
            this.constantValue = null;
            this.constantTuple = null;
            if(copyVar.isGlobal()) {
                throw new IllegalArgumentException("copyVar must not be a Global.");
            }
        }

        public Value(ImConst constantValue) {
            this.copyVar = null;
            this.constantValue = constantValue;
            this.constantTuple = null;
        }

        public Value(ImTupleExpr tupleExpr) {
            this.copyVar = null;
            this.constantValue = null;
            this.constantTuple = tupleExpr;

            for(ImExpr e :  tupleExpr.getExprs()) {
                if(tryValue(e) == null) {
                    throw new IllegalArgumentException("tupleExpr must only contain constant values.");
                }
            }
        }

        public static Value tryValue(ImExpr e) {
            try {
                if (e instanceof ImVarAccess) {
                    return new Value(((ImVarAccess) e).getVar());
                }
                if (e instanceof ImConst) {
                    return new Value((ImConst) e);
                }
                if (e instanceof ImTupleExpr) {
                    return new Value((ImTupleExpr) e);
                }
            } catch (IllegalArgumentException ignored) {
            }
            return null;
        }

        @Override
        public boolean equals(@Nullable Object obj) {
            if (obj instanceof Value) {
                return equalValue((Value) obj);
            }
            return false;
        }

        public boolean equalValue(Value other) {
            if (copyVar != null && other.copyVar != null) {
                return copyVar == other.copyVar;
            } else if (constantValue != null && other.constantValue != null) {
                return constantValue.equalValue(other.constantValue);
            } else if (constantTuple != null && other.constantTuple != null) {
                ImTupleExpr a = constantTuple;
                ImTupleExpr b = other.constantTuple;
                if(!a.attrTyp().equalsType(b.attrTyp())) {
                    return false;
                }
                for(int i = 0; i < a.getExprs().size() ;++i) {
                    Value aV = tryValue(a.getExprs().get(i));
                    Value bV = tryValue(b.getExprs().get(i));
                    if(!aV.equalValue(bV)) {
                        return false;
                    }
                }
                return true;
            }
            return false;
        }

        @Override
        public String toString() {
            if (copyVar != null) {
                return "copy of " + copyVar;
            } else if (constantValue != null) {
                return "constant " + constantValue;
            } else {
                return "tuple of " + constantTuple;
            }
        }

    }

    static class Knowledge {
        HashMap<ImVar, Value> varKnowledge = HashMap.empty();
        HashMap<ImVar, Value> varKnowledgeOut = HashMap.empty();

        @Override
        public String toString() {
            return "[in =" + varKnowledge + ", out=" + varKnowledgeOut + "]";
        }

    }

    void optimizeFunc(ImFunction func) {
        ControlFlowGraph cfg = new ControlFlowGraph(func.getBody());
        Map<Node, Knowledge> knowledge = calculateKnowledge(cfg);
        rewriteCode(cfg, knowledge);
    }

    private void rewriteCode(ControlFlowGraph cfg, Map<Node, Knowledge> knowledge) {
        for (Node node : cfg.getNodes()) {
            ImStmt stmt = node.getStmt();
            if (stmt == null) {
                continue;
            }
            Knowledge kn = knowledge.get(node);
            stmt.accept(new ImStmt.DefaultVisitor() {

                @Override
                public void visit(ImSet imSet) {
                    ImLExpr e = imSet.getLeft();
                    if (e instanceof ImMemberAccess) {
                        ImMemberAccess ma = (ImMemberAccess) e;
                        ma.accept(this);
                    } else if (e instanceof ImVarArrayAccess) {
                        ImVarArrayAccess vaa = (ImVarArrayAccess) e;
                        for (ImExpr ie : vaa.getIndexes()) {
                            ie.accept(this);
                        }
                    }
                    imSet.getRight().accept(this);
                }

                @Override
                public void visit(ImVarAccess va) {
                    if (va.isUsedAsLValue()) {
                        return;
                    }
                    Value val = kn.varKnowledge.get(va.getVar()).getOrNull();
                    if (val == null) {
                        return;
                    }
                    if (val.constantValue != null) {
                        va.replaceBy(val.constantValue.copy());
                        totalPropagated++;
                    } else if (val.copyVar != null) {
                        va.setVar(val.copyVar);
                        // recursive call, because maybe it is possible to also replace the new var
                        visit(va);
                    } else if (val.constantTuple != null) {
                        // Tuple literals are not always propagated, because they are more expensive (multiple values).
                        if(va.getParent() instanceof ImTupleSelection) {
                            // Tuple selections of constant tuples are replaced by the selected constant value.
                            ImTupleSelection ts = (ImTupleSelection) va.getParent();
                            Element t = ts;
                            ImExpr constT = val.constantTuple;
                            while(t instanceof ImTupleSelection) {
                                ts = (ImTupleSelection) t;
                                // follow the constant tuple according to the tuple selection index
                                constT = ((ImTupleExpr) constT).getExprs().get(ts.getTupleIndex());
                                // follow the tuple selection to get to the full tuple
                                t = ts.getParent();
                            }
                            // constT now holds the literal that is selected
                            // Only perform replacement, if the literal is small enough.
                            boolean replace = true;
                            if(constT instanceof ImTupleExpr) {
                                ImTupleExpr te = (ImTupleExpr) constT;
                                if (te.getExprs().size() != 1 || te.getExprs().get(0) instanceof ImTupleSelection) {
                                    replace = false;
                                }
                            }
                            if(replace) {
                                ts.replaceBy(constT.copy());
                            }

                        } else {
                            // Only perform replacement, if the literal is small enough.
                            if(val.constantTuple.getExprs().size() == 1 && !(val.constantTuple.getExprs().get(0) instanceof ImTupleSelection)) {
                                va.replaceBy(val.constantTuple.copy());
                            }
                        }
                        totalPropagated++;
                    }
                }
            });

        }

    }

    private Map<Node, Knowledge> calculateKnowledge(ControlFlowGraph cfg) {
        Map<Node, Knowledge> knowledge = new java.util.HashMap<>();

        // initialize with empty knowledge:
        for (Node n : cfg.getNodes()) {
            knowledge.put(n, new Knowledge());
        }

        Worklist<Node> todo = new Worklist<>(cfg.getNodes());

        while (!todo.isEmpty()) {
            Node n = todo.poll();

            Knowledge kn = knowledge.get(n);

            // get knowledge from predecessor out
            HashMap<ImVar, Value> newKnowledge = HashMap.empty();
            if (!n.getPredecessors().isEmpty()) {
                Node pred1 = n.getPredecessors().get(0);
                HashMap<ImVar, Value> predKnowledgeOut = knowledge.get(pred1).varKnowledgeOut;

                // only keep knowledge that is the same for all predecessors:
                newKnowledge = predKnowledgeOut;
                if (n.getPredecessors().size() > 1) {
                    for (Tuple2<ImVar, Value> e : predKnowledgeOut) {
                        ImVar var = e._1();
                        Value val = e._2();
                        boolean allSame = true;
                        for (int i = 1; i < n.getPredecessors().size(); i++) {
                            Node predi = n.getPredecessors().get(i);
                            Value predi_val = knowledge.get(predi).varKnowledgeOut.get(var).getOrNull();
                            if (predi_val == null || !predi_val.equalValue(val)) {
                                allSame = false;
                                break;
                            }
                        }
                        if (!allSame) {
                            newKnowledge = newKnowledge.remove(var);
                        }
                    }
                }
            }

            // at the output get all from the input knowledge
            HashMap<ImVar, Value> newOut = newKnowledge;

            ImStmt stmt = n.getStmt();
            if (stmt instanceof ImSet) {
                ImSet imSet = (ImSet) stmt;
                if (imSet.getLeft() instanceof ImVarAccess) {
                    ImVar var = ((ImVarAccess) imSet.getLeft()).getVar();
                    if (!var.isGlobal()) {
                        Value newValue = null;
                        ImExpr right = imSet.getRight();
                        if (right instanceof ImConst) {
                            newValue = Value.tryValue(right);
                        } else if (right instanceof ImVarAccess) {
                            // If there already is a value, prefer it.
                            // Tuples are not always propagated, because tuple literals are more expensive (multiple values).
                            // However, by using the existing value, the knowledge of a tuple literal is preserved
                            // and may be used later to access a specific value within the tuple literal.
                            ImVar varRight = ((ImVarAccess) right).getVar();
                            if(newOut.containsKey(varRight)) {
                                newValue = newOut.get(varRight).getOrNull();
                            } else {
                                newValue = Value.tryValue(right);
                            }
                        } else if(right instanceof ImTupleExpr) {
                            newValue = Value.tryValue(right);
                        }
                        if (newValue == null) {
                            // invalidate old value
                            newOut = newOut.remove(var);
                        } else {
                            newOut = newOut.put(var, newValue);
                        }
                        // invalidate copies of the lhs
                        // for example:
                        // x = a; [x->a]
                        // y = b; [x->a, y->b]
                        // a = 5; [y->b, a->5] // here [x->a] has been invalidated
                        Value varAsValue = new Value(var);
                        for (Tuple2<ImVar, Value> p : newOut) {
                            if (p._2().equalValue(varAsValue)) {
                                newOut = newOut.remove(p._1());
                            }
                        }
                    }
                } else if(imSet.getLeft() instanceof ImTupleSelection) {
                    ImVar var = TypesHelper.getSimpleAndPureTupleVar((ImTupleSelection) imSet.getLeft());
                    if(var != null) {
                        Value rightVal = Value.tryValue(imSet.getRight());
                        Value existingValue = newOut.get(var).getOrNull();
                        if (rightVal != null && existingValue != null && existingValue.constantTuple != null) {
                            // rightVal is constant or copy
                            // existingValue is constant tuple (the existing knowledge is altered partially, which does not work on copies)
                            // update known constant tuple
                            ImTupleExpr te = existingValue.constantTuple.copy();
                            ImExpr knownTuple = te;
                            Element left = imSet.getLeft();
                            // go to innermost selection
                            while (left instanceof ImTupleSelection) {
                                left = ((ImTupleSelection) left).getTupleExpr();
                            }
                            // go back to the initial selection and follow along in the known tuple
                            while (left != imSet.getLeft()) {
                                left = left.getParent();
                                knownTuple = ((ImTupleExpr) knownTuple).getExprs().get(((ImTupleSelection) left).getTupleIndex());
                            }
                            knownTuple.replaceBy(imSet.getRight().copy());
                            // update value
                            newOut = newOut.put(var, new Value(te));
                        } else {
                            // cannot update knowledge of lhs
                            // value of lhs unknown
                            newOut = newOut.remove(var);
                        }
                        // either way, lhs has now a new value and copies of it must be invalidated
                        Value varAsValue = new Value(var);
                        for (Tuple2<ImVar, Value> p : newOut) {
                            if (p._2().equalValue(varAsValue)) {
                                newOut = newOut.remove(p._1());
                            }
                        }
                    }
                }
            }

            // if there are changes, revisit successors:
            if (!kn.varKnowledgeOut.equals(newOut)) {
                todo.addAll(n.getSuccessors());
            }

            // update knowledge
            kn.varKnowledge = newKnowledge;
            kn.varKnowledgeOut = newOut;

        }
        return knowledge;
    }

}


text:
const db = require('./db.js');
const q = require('q');
const areas = require('../areas.js');
const utils = require('../utils.js');
const subqueries = require('./subqueries.js');

const find = (filters) => {
	const dollarConversionRate = require('../dollar.js');
	let deferred = q.defer();
	areas.getArea(filters.name).then(area => {
		let params = [dollarConversionRate];
		let operationType = subqueries.operationType(filters.operationType, params);
		let rooms = subqueries.rooms(filters.rooms, params);
		let propertyType = subqueries.propertyType(filters.propertyType, params);
		let minSurface = subqueries.minSurface(filters.minSurface, params);
		let maxSurface = subqueries.maxSurface(filters.maxSurface, params);
		let polygon = subqueries.polygons(area, params);
		let query = `
			SELECT
			(CASE WHEN price_currency = 'USD' THEN price * ? ELSE price END) AS value,
			CAST(TRIM(REPLACE(REPLACE(REPLACE(area_covered, 'm', ''), '²', ''),',','.')) AS UNSIGNED) AS surface
			FROM inmobiliaria.propiedades
			WHERE price IS NOT NULL
			${operationType}
			${rooms}
			${propertyType}
			${minSurface}
			${maxSurface}
			${polygon}
			ORDER BY 1
		`;
		db.query(query, params, (error, results) => {
			if(error){
				deferred.reject(error);
			}
			else{
				let data = {
					name: area.name,
					coords: area.coords,
					count: results.length
				};
				if(results.length > 0){
					data.value = utils.median(results.map(r => r.value));
					data.dollarValue = Math.ceil(data.value / dollarConversionRate);
					data.minSurface = Math.min(...results.map(r => r.surface));
					data.maxSurface = Math.max(...results.map(r => r.surface));
				}
				deferred.resolve(data);
			}
		});
	});
	return deferred.promise;
};

const findRatio = (filters) => {
	let deferred = q.defer();
	let priceFilters = Object.assign({operationType: 'price'}, filters);
	let rentFilters = Object.assign({operationType: 'rent'}, filters);
	let promises = [
		find(priceFilters),
		find(rentFilters)
	];
	q.all(promises).then((results) => {
		let result = Object.assign({}, results[0]);
		if(!results[0].value || !results[1].value){
			result.value = undefined;
		}
		else {
			result.count = Math.min(results[0].count, results[1].count);
			result.value = Math.ceil(results[0].value / results[1].value);
		}
		delete result.dollarValue;
		deferred.resolve(result);
	});
	return deferred.promise;
};

const findAll = (filters) => {
	return areas.getAreas()
	.then((areas => {
		let promises = [];
		areas.forEach(area => {
			let newFilters = Object.assign({name: area.name}, filters);
			if(filters.operationType === 'ratio'){
				delete newFilters.operationType;
				promises.push(findRatio(newFilters));
			}
			else{
				promises.push(find(newFilters));
			}
		});
		return q.all(promises);
	}))
	.then(data => {
		return {
			dollarConversionRate: require('../dollar.js'),
			surface: {
				min: utils.nullSafeLimit('min', 'minSurface', data),
				max: utils.nullSafeLimit('max', 'maxSurface', data)
			},
			value: {
				min: utils.nullSafeLimit('min', 'value', data),
				max: utils.nullSafeLimit('max', 'value', data)
			},
			dollarValue: {
				min: utils.nullSafeLimit('min', 'dollarValue', data),
				max: utils.nullSafeLimit('max', 'dollarValue', data)
			},
			count: data.reduce((sum, d) => sum + d.count, 0),
			data: data
		};
	});
};

module.exports.findAll = findAll;


text:
module.exports = function(server, options) {
  options = options || {};

  if (!server) { throw new TypeError('oauth2orize.authorizationErrorHandler middleware requires a server argument'); }

  return function authorizationErrorHandler(err, req, res, next) {
    if (!req.oauth2) { return next(err); }

    if (req.oauth2.transactionID && !req.oauth2._endProxied) {
      // proxy end() to delete the transaction
      var end = res.end;
      res.end = function(chunk, encoding) {
        if (server._txnStore.legacy == true) {
          server._txnStore.remove(options, req, req.oauth2.transactionID, function noop(){});
        } else {
          server._txnStore.remove(req, req.oauth2.transactionID, function noop(){});
        }

        res.end = end;
        res.end(chunk, encoding);
      };
    }

    server._respondError(err, req.oauth2, res, function(err) {
      return next(err);
    });
  }
}


text:
Configuration

        Configuration for various payment methods

Guaranteed Invoice, Installment, Direct Debit, Payment on Invoice / Payment in Advance, Alipay Cross-border, Przelewy24, giropay, eps, iDEAL, Sofort., Payolution

        Configuration for Maestro
        Configuration for Unionpay International
        Configuration for WeChat
        Basic configuration for other payment methods


text:
package org.pentaho.di.ui.repository.pur.repositoryexplorer;

import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.ui.repository.pur.repositoryexplorer.model.UIRepositoryObjectRevision;
import org.pentaho.di.ui.repository.pur.repositoryexplorer.model.UIRepositoryObjectRevisions;

public interface IRevisionObject {
  public UIRepositoryObjectRevisions getRevisions() throws KettleException;

  public void restoreRevision( UIRepositoryObjectRevision revision, String commitMessage ) throws KettleException;

  Boolean getVersioningEnabled();

  Boolean getVersionCommentEnabled();
}


text:
package net.ljcomputing.ecsr.domain.person;

import net.ljcomputing.ecsr.domain.AbstractDomain;
import net.ljcomputing.ecsr.domain.Domain;

/**
 * ECSR user password.
 *
 * @author James G. Willmore
 *
 */
public class UserPassword extends AbstractDomain implements Domain {

  /** The Constant serialVersionUID. */
  private static final long serialVersionUID = -6269260883748769879L;

  /** The password. */
  private String password;

  /** The user. */
  private User user;

  /**
   * Gets the password.
   *
   * @return the password
   */
  public String getPassword() {
    return password;
  }

  /**
   * Sets the password.
   *
   * @param password the new password
   */
  public void setPassword(final String password) {
    this.password = password;
  }

  /**
   * Gets the user.
   *
   * @return the user
   */
  public User getUser() {
    return user;
  }

  /**
   * Sets the user.
   *
   * @param user the new user
   */
  public void setUser(final User user) {
    this.user = user;
  }
}


text:
[![license][license-image]][license-url]
[![npm][npm-version-core-image]][npm-version-core-url]
[![dep][daviddm-core-image]][daviddm-core-url]
[![travis][travis-image]][travis-url]
[![appveyor][appveyor-image]][appveyor-url]
[![coveralls][coveralls-image]][coveralls-url]
[![commitizen][commitizen-image]][commitizen-url]

Core library of [paeckchen](https://github.com/paeckchen/paeckchen).

---
[license-image]: https://img.shields.io/github/license/paeckchen/paeckchen.svg
[license-url]: https://github.com/paeckchen/paeckchen

[travis-image]: https://travis-ci.org/paeckchen/paeckchen-core.svg?branch=master
[travis-url]: https://travis-ci.org/paeckchen/paeckchen-core

[appveyor-image]: https://ci.appveyor.com/api/projects/status/r5bibqgy676fbf87/branch/master?svg=true
[appveyor-url]: https://ci.appveyor.com/project/KnisterPeter/paeckchen-core/branch/master

[coveralls-image]: https://coveralls.io/repos/github/paeckchen/paeckchen-core/badge.svg?branch=master
[coveralls-url]: https://coveralls.io/github/paeckchen/paeckchen-core?branch=master

[commitizen-image]: https://img.shields.io/badge/commitizen-friendly-brightgreen.svg
[commitizen-url]: http://commitizen.github.io/cz-cli/

[npm-version-core-image]: https://img.shields.io/npm/v/paeckchen-core.svg
[npm-version-core-url]: https://www.npmjs.com/package/paeckchen-core

[daviddm-core-image]: https://img.shields.io/david/paeckchen/paeckchen-core.svg
[daviddm-core-url]: https://david-dm.org/paeckchen/paeckchen-core


text:
package main

var vertexShaderText = `
#version 330

in vec4 position;
in vec4 color;
smooth out vec4 theColor;
uniform vec3 offset;
uniform mat4 perspectiveMatrix;

void main() {
	vec4 cameraPos = position + vec4(offset.x, offset.y, offset.z, 0.0);
	gl_Position = perspectiveMatrix * cameraPos;
	theColor = color;
}
`

var fragmentShaderText = `
#version 330

smooth in vec4 theColor;
out vec4 outputColor;

void main() {
	outputColor = theColor;
}
`


text:
(function() {
    'use strict';

    angular
        .module('app.forecast')
        .filter('celsius', celsius);

    function celsius() {
        return function(kelvin) {
            return Math.round(parseFloat(kelvin) - 273.15);
        }
    }
})();


text:
import { Injectable } from '@angular/core'
import promiseIpc, { RendererProcessType } from 'electron-promise-ipc'
import { HostAppService, Platform, TranslateService } from 'tabby-core'

import { ShellProvider, Shell } from '../api'

/** @hidden */
@Injectable()
export class MacOSDefaultShellProvider extends ShellProvider {
    private cachedShell?: string

    constructor (
        private hostApp: HostAppService,
        private translate: TranslateService,
    ) {
        super()
    }

    async provide (): Promise<Shell[]> {
        if (this.hostApp.platform !== Platform.macOS) {
            return []
        }
        return [{
            id: 'default',
            name: this.translate.instant('OS default'),
            command: await this.getDefaultShellCached(),
            args: ['--login'],
            hidden: true,
            env: {},
        }]
    }

    private async getDefaultShellCached () {
        if (!this.cachedShell) {
            this.cachedShell = await this.getDefaultShell()
        }
        return this.cachedShell
    }

    private async getDefaultShell (): Promise<string> {
        // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
        return (promiseIpc as RendererProcessType).send('get-default-mac-shell') as Promise<string>
    }
}


text:
CKEDITOR.plugins.setLang( 'pastetext', 'da', {
	button: 'Indsæt som ikke-formateret tekst',
	title: 'Indsæt som ikke-formateret tekst'
});


text:
module Ivory.BSP.STM32F405.SPI
  ( spi1
  , spi2
  , spi3
  ) where

import Ivory.BSP.STM32.Peripheral.SPI

import Ivory.Language
import Ivory.HW

import Ivory.BSP.STM32.ClockConfig

import Ivory.BSP.STM32F405.RCC
import Ivory.BSP.STM32F405.MemoryMap
import qualified Ivory.BSP.STM32F405.Interrupt as F405

spi1, spi2, spi3 :: SPIPeriph
spi1 = mkSPIPeriph spi1_periph_base rccenable rccdisable
         F405.SPI1 PClk2 "spi1"
  where
  rccenable  = modifyReg regRCC_APB2ENR $ setBit rcc_apb2en_spi1
  rccdisable = modifyReg regRCC_APB2ENR $ clearBit rcc_apb2en_spi1

spi2 = mkSPIPeriph spi2_periph_base rccenable rccdisable
         F405.SPI2 PClk1 "spi2"
  where
  rccenable  = modifyReg regRCC_APB1ENR $ setBit rcc_apb1en_spi2
  rccdisable = modifyReg regRCC_APB1ENR $ clearBit rcc_apb1en_spi2

spi3 = mkSPIPeriph spi3_periph_base rccenable rccdisable
         F405.SPI3 PClk1 "spi3"
  where
  rccenable  = modifyReg regRCC_APB1ENR $ setBit rcc_apb1en_spi3
  rccdisable = modifyReg regRCC_APB1ENR $ clearBit rcc_apb1en_spi3


text:
namespace quipper {

namespace {

// Supported perf subcommands.
const char kPerfRecordCommand[] = "record";
const char kPerfStatCommand[] = "stat";
const char kPerfMemCommand[] = "mem";
const char kPerfInjectCommand[] = "inject";

// Reads a perf data file and converts it to a PerfDataProto, which is stored as
// a serialized string in |output_string|. Returns true on success.
bool ParsePerfDataFileToString(const string& filename, string* output_string) {
  // Now convert it into a protobuf.

  PerfParserOptions options;
  // Make sure to remap address for security reasons.
  options.do_remap = true;
  // Discard unused perf events to reduce the protobuf size.
  options.discard_unused_events = true;
  // Read buildids from the filesystem ourself.
  options.read_missing_buildids = true;
  // Resolve split huge pages mappings.
  options.deduce_huge_page_mappings = true;

  PerfDataProto perf_data;
  return SerializeFromFileWithOptions(filename, options, &perf_data) &&
         perf_data.SerializeToString(output_string);
}

// Reads a perf data file and converts it to a PerfStatProto, which is stored as
// a serialized string in |output_string|. Returns true on success.
bool ParsePerfStatFileToString(const string& filename,
                               const std::vector<string>& command_line_args,
                               string* output_string) {
  PerfStatProto perf_stat;
  if (!ParsePerfStatFileToProto(filename, &perf_stat)) {
    LOG(ERROR) << "Failed to parse PerfStatProto from " << filename;
    return false;
  }

  // Fill in the command line field of the protobuf.
  string command_line;
  for (size_t i = 0; i < command_line_args.size(); ++i) {
    const string& arg = command_line_args[i];
    // Strip the output file argument from the command line.
    if (arg == "-o") {
      ++i;
      continue;
    }
    command_line.append(arg + " ");
  }
  command_line.resize(command_line.size() - 1);
  perf_stat.mutable_command_line()->assign(command_line);

  return perf_stat.SerializeToString(output_string);
}

// Checks if the perf record events include cs_etm.
bool IsRecordingETM(const std::vector<string>& perf_args) {
  for (auto it = perf_args.begin(); it != perf_args.end(); ++it) {
    if (*it != "-e") continue;
    ++it;
    if (it == perf_args.end()) return false;
    if (it->find("cs_etm") != std::string::npos) return true;
  }
  return false;
}

}  // namespace

PerfRecorder::PerfRecorder() : PerfRecorder({"/usr/bin/perf"}) {}

PerfRecorder::PerfRecorder(const std::vector<string>& perf_binary_command)
    : perf_binary_command_(perf_binary_command) {}

// Assemble the full command line:
// - Replace "perf" in |perf_args[0]| with |perf_binary_command_| to
//   guarantee we're running a binary we believe we can trust.
// - Add our own paramters.
std::vector<string> PerfRecorder::FullPerfCommand(
    const std::vector<string>& perf_args, const double time_sec,
    const ScopedTempFile& output_file) {
  const string& perf_type = perf_args[1];

  std::vector<string> full_perf_args(perf_binary_command_);
  full_perf_args.insert(full_perf_args.end(),
                        perf_args.begin() + 1,  // skip "perf"
                        perf_args.end());
  full_perf_args.insert(full_perf_args.end(), {"-o", output_file.path()});

  // The perf stat output parser requires raw data from verbose output.
  if (perf_type == kPerfStatCommand) full_perf_args.emplace_back("-v");

  if (perf_type != kPerfInjectCommand) {
    // Append the sleep command to run perf for |time_sec| seconds.
    std::stringstream time_string;
    time_string << time_sec;
    full_perf_args.insert(full_perf_args.end(),
                          {"--", "sleep", time_string.str()});
  } else {
    // We use sudo for all commands and perf inject may complain about the input
    // file is not owned by current user or root.
    full_perf_args.emplace_back("-f");
  }
  return full_perf_args;
}

bool PerfRecorder::RunCommandAndGetSerializedOutput(
    const std::vector<string>& perf_args, const double time_sec,
    const std::vector<string>& inject_args, string* output_string) {
  if (!ValidatePerfCommandLine(perf_args)) {
    LOG(ERROR) << "Perf arguments are not safe to run";
    return false;
  }

  // ValidatePerfCommandLine should have checked perf_args[0] == "perf", and
  // that perf_args[1] is a supported sub-command (e.g. "record" or "stat").
  const string& perf_type = perf_args[1];

  if (perf_type != kPerfRecordCommand && perf_type != kPerfStatCommand &&
      perf_type != kPerfMemCommand) {
    LOG(ERROR) << "Unsupported perf subcommand: " << perf_type;
    return {};
  }

  if (perf_type == kPerfRecordCommand && IsRecordingETM(perf_args) &&
      inject_args.empty()) {
    LOG(ERROR) << "--inject_args must be provided when recording ETM";
    return false;
  }

  ScopedTempFile output_file;
  auto full_perf_args = FullPerfCommand(perf_args, time_sec, output_file);

  // The perf command writes the output to a file, so ignore stdout.
  int status = RunCommand(full_perf_args, nullptr);
  if (status != 0) {
    PLOG(ERROR) << "perf command failed with status: " << status << ", Error";
    return false;
  }

  if (inject_args.empty()) {
    if (perf_type == kPerfRecordCommand || perf_type == kPerfMemCommand)
      return ParsePerfDataFileToString(output_file.path(), output_string);

    // Otherwise, parse as perf stat output.
    return ParsePerfStatFileToString(output_file.path(), full_perf_args,
                                     output_string);
  }

  // If provided, run perf inject on the previous output of perf.
  if (!ValidatePerfCommandLine(inject_args)) {
    LOG(ERROR) << "Perf inject arguments are not safe to run";
    return false;
  }

  const string& inject_command = inject_args[1];
  if (inject_command != kPerfInjectCommand) {
    LOG(ERROR) << "Unsupported perf subcommand for perf inject: "
               << inject_command;
    return false;
  }
  ScopedTempFile& inject_input = output_file;
  ScopedTempFile inject_output;
  auto full_inject_args = FullPerfCommand(inject_args, 0, inject_output);
  full_inject_args.emplace_back("-i");
  full_inject_args.emplace_back(inject_input.path());
  status = RunCommand(full_inject_args, nullptr);
  if (status != 0) {
    PLOG(ERROR) << "perf inject failed with status: " << status << ", Error";
    return false;
  }
  return ParsePerfDataFileToString(inject_output.path(), output_string);
}

}  // namespace quipper


text:
package nessusCreator

import (
	"io"
	"os"
)

func copyFile(src, dst string) error {
	s, err := os.Open(src)
	if err != nil {
		return err
	}
	// no need to check errors on read only file, we already got everything
	// we need from the filesystem, so nothing can go wrong now.
	defer s.Close()
	d, err := os.Create(dst)
	if err != nil {
		return err
	}
	if _, err := io.Copy(d, s); err != nil {
		d.Close()
		return err
	}
	return d.Close()
}


text:
layout: post
title: Plan
date: 2017-04-29 14:00
---

Step by step, from a basic initial set up, create a React SPA
blogging platform (of course), using the Rails server as an API
**only**. The only page that will be built and sent will be the basic
app page that will load the React App component. Everything else,
including styles, scripts, images, etc., i.e., all the bits of a
user-facing web app, will be handled via webpacker.

Along the way, I'll include user signup, login, and authentication
using JSON Web Tokens. I'll be making use of the `localStorage` API
to keep track of the app token the server will be providing the
client.

## Testing

Just a word about testing: most of the time, the things I'm
learning about I just implement without focusing on how I would
test these in an actual application. I want to break that habit
here, and figure out how to do real application testing in both
halves of this, the Rails API server, and the React SPA. It will
be interesting to run both of these.

I've got guard set up on the Rails side, that should be pretty
nice. Selenium is included in the kit, but I'd prefer to use Jest
on the client side to make testing more fun, fast, and lighter
weight, saving the full integration stuff where it's truly needed.