text:
Methods, functions and objects that are not part of the standard, written with
EcmaScript conventions in mind.

## Installation

Can be used in any environment that implements EcmaScript 5th edition.
Many extensions will also work with ECMAScript 3rd edition, if they're not let [es5-shim](https://github.com/kriskowal/es5-shim) be your aid.

### NPM:

	$ npm install es5-ext

### Browser:

For browser, you can create custom toolset with help of
[modules-webmake](https://github.com/medikoo/modules-webmake)

## Usage

__es5-ext__ mostly offer methods (not functions) which can directly be
assigned to native object's prototype:

	Function.prototype.partial = require('es5-ext/lib/Function/prototype/partial');

	Array.prototype.flatten = require('es5-ext/lib/Array/prototype/flatten');

	String.prototype.startsWith = require('es5-ext/lib/String/prototype/starts-with');

If you decide not to extend native prototypes, which in many cases is good idea (see
[extending-javascript-natives](http://javascriptweblog.wordpress.com/2011/12/05/extending-javascript-natives/)
for more views on that matter), you can use methods as
functions:

	var util = {};
	var call = Function.prototype.call;

	util.partial = call.bind(require('es5-ext/lib/Function/prototype/partial'));

	util.flatten = call.bind(require('es5-ext/lib/Array/prototype/flatten'));

	util.startsWith = call.bind(require('es5-ext/lib/String/prototype/starts-with'));

As with native ones most methods are generic and can be run on any object.
In more detail:

* `Array.prototype`, `Number.prototype` and `String.prototype`, methods can be run on any object (any
value that's neither _null_ nor _undefined_),
* `Date.prototype` methods should be called only on `Date` instances.
* `Function.prototype` methods can be called on any callable objects (not
necessarily functions)

API doesn't provide any methods for `Object.prototype` (extending such in any case should be avoided). All `Object` utils are provided as fuctions and most of them expect first input argument to be a valid object (any value that's neither _null_ nor _undefined_).

# API

## Global extensions

### global

Object that represents global scope

### reserved

List of EcmaScript 5th edition reserved keywords.
Additionally under _keywords_, _future_ and _futureStrict_ properties we have lists grouped thematically.

## Array Constructor extensions

### from(x)

_In EcmaScript 6th Edition draft_
Convert array-like object to an Array

### generate([length[, …fill]])

Generate an array of pregiven _length_ built of repeated arguments.

### of([…items])

_In EcmaScript 6th Edition draft_
Create an array from given arguments.

## Array Prototype extensions

### binarySearch(compareFn)

In __sorted__ list search for index of item for which _compareFn_ returns value closest to _0_.
It's variant of binary search algorithm

### clear()

Clears the array

### commonLeft([…lists])

Returns first index at which _lists_ start to differ

### compact()

Returns a copy of the list with all falsy values removed.

### contains(searchElement[, position])

Whether list contains the given value.

### copy()

Returns a copy of the list

### diff(other)

Returns the array of elements that are present in context list but not present in other list.

### eIndexOf(searchElement[, fromIndex])

[_egal_](http://wiki.ecmascript.org/doku.php?id=harmony:egal) version of `indexOf` method

### eLastIndexOf(searchElement[, fromIndex])

[_egal_](http://wiki.ecmascript.org/doku.php?id=harmony:egal) version of `lastIndexOf` method

### exclusion([…lists]])

Returns the array of elements that are found only in context list or lists given in arguments.

### find(query[, thisArg])

Return first element for which given function returns true

### first()

Returns value for first declared index

### firstIndex()

Returns first declared index of the array

### flatten()

Returns flattened version of the array

### forEachRight(cb[, thisArg])

`forEach` starting from last element

### group(cb[, thisArg])

Group list elements by value returned by _cb_ function

### indexesOf(searchElement[, fromIndex])

Returns array of all indexes of given value

### intersection([…lists])

Computes the array of values that are the intersection of all lists (context list and lists given in arguments)

### isCopy(other)

Returns true if both context and _other_ lists have same content

### isUniq()

Returns true if all values in array are unique

### last()

Returns value for last declared index

### lastIndex()

Returns last declared index of the array

### remove(value)

Remove value from the array

### someRight(cb[, thisArg])

`some` starting from last element

### uniq()

Returns duplicate-free version of the array

## Boolean Constructor extensions

### isBoolean(x)

Whether value is boolean

## Date Constructor extensions

### isDate(x)

Whether value is date instance

### validDate(x)

If given object is not date throw TypeError in other case return it.

## Date Prototype extensions

### copy(date)

Returns a copy of the date object

### daysInMonth()

Returns number of days of date's month

### floorDay()

Sets the date time to 00:00:00.000

### floorMonth()

Sets date day to 1 and date time to 00:00:00.000

### floorYear()

Sets date month to 0, day to 1 and date time to 00:00:00.000

### format(pattern)

Formats date up to given string. Supported patterns:

* `%Y` - Year with century, 1999, 2003
* `%y` - Year without century, 99, 03
* `%m` - Month, 01..12
* `%d` - Day of the month 01..31
* `%H` - Hour (24-hour clock), 00..23
* `%M` - Minute, 00..59
* `%S` - Second, 00..59
* `%L` - Milliseconds, 000..999

## Error Constructor extensions

### isError(x)

Whether value is error.
It returns true for all Error instances and Exception host instances (e.g. DOMException)

### validError(x)

If given object is not error throw TypeError in other case return it.

## Error Prototype extensions

### throw()

Throws error

## Function Constructor extensions

Some of the functions were inspired by [Functional JavaScript](http://osteele.com/sources/javascript/functional/) project by Olivier Steele

### i(x)

Identity function. Returns first argument

_i(x)  =def  x_

### insert(name, value)

Returns a function that will set _name_ to _value_ on given object

_insert(name, value)(obj)  =def  object\[name\] = value_

### invoke(name[, …args])

Returns a function that takes an object as an argument, and applies object's
_name_ method to arguments.
_name_ can be name of the method or method itself.

_invoke(name, …args)(object, …args2)  =def  object\[name\]\(…args, …args2\)_

### isArguments(x)

Whether value is arguments object

### isFunction(arg)

Wether value is instance of function

### k(x)

Returns a constant function that returns pregiven argument

_k(x)(y)  =def  x_

### noop()

No operation function

### pluck(name)

Returns a function that takes an object, and returns the value of its _name_
property

_pluck(name)(obj)  =def  obj[name]_

### remove(name)

Returns a function that takes an object, and deletes object's _name_ property

_remove(name)(obj)  =def  delete obj[name]_

### validFunction(arg)

If given object is not function throw TypeError in other case return it.

## Function Prototype extensions

Some of the methods were inspired by [Functional JavaScript](http://osteele.com/sources/javascript/functional/) project by Olivier Steele

### chain([…fns])

Applies the functions in argument-list order.

_f1.chain(f2, f3, f4)(…args)  =def  f4(f3(f2(f1(…arg))))_

### curry([n])

Invoking the function returned by this function only _n_ arguments are passed to the underlying function. If the underlying function is not saturated, the result is a function that passes all its arguments to the underlying function.
If _n_ is not provided then it defaults to context function length

_f.curry(4)(arg1, arg2)(arg3)(arg4)  =def  f(arg1, args2, arg3, arg4)_

### lock([…args])

Returns a function that applies the underlying function to _args_, and ignores its own arguments.

_f.lock(…args)(…args2)  =def  f(…args)_

_Named after it's counterpart in Google Closure_

### match()

Returns a function that applies underlying function with first list argument

_f.match()(args)  =def  f.apply(null, args)_

### not()

Returns a function that returns boolean negation of value returned by underlying function.

_f.not()(…args)  =def !f(…args)_

### partial([…args])

Returns a function that when called will behave like context function called with initially passed arguments. If more arguments are suplilied, they are appended to initial args.

_f.partial(…args1)(…args2)  =def  f(…args1, …args2)_

### silent()

Returns a function that when called silents any error thrown by underlying function.
If underlying function throws error, it is the result fo the function.

_function () { throw err; }.silent()()  ==def  err_

### wrap(fn)

Wrap function with other function, it allows to specify before and after behavior, transform return value or prevent original function from being called.

Inspired by [Prototype's wrap](http://api.prototypejs.org/language/Function/prototype/wrap/)

## Number Constructor extensions

### isNaN(x)

_In EcmaScript 6th Edition draft_

Whether value is NaN. Differs from global isNaN that it doesn't do type coercion.
See http://wiki.ecmascript.org/doku.php?id=harmony:number.isnan

### isNumber(x)

Whether given value is number

### toInt(x)

_In EcmaScript 6th Edition draft_

Converts value to integer

### toUint(x)

Converts value to unsigned integer

### toUint32(x)

Converts value to unsigned 32 bit integer. This type is used for array lengths.
See: http://www.2ality.com/2012/02/js-integers.html

## Number Prototype extensions

### pad(length[, precision])

Pad given number with zeros. Returns string

## Object Constructor extensions

### clear(obj)

Remove all enumerable own properties of the object

### compact(obj)

Returns copy of the object with all enumerable properties that have no falsy values

### compare(obj1, obj2)

Universal cross-type compare function. To be used for e.g. array sort.

### copy(obj[, deep])

Returns copy of the object with all enumerable properties. Additionally nested objects can be copied as well

### count(obj)

Counts number of enumerable own properties on object

### descriptor([mode[, value]])
### descriptor.gs([mode[, get[, set]]])

Descriptor factory.
_mode_ is string, through we which we define whether value should be _configurable_, _enumerable_ and/or _writable_, it's accepted as string of tokens, e.g.: `c`, `ce`, `cew`, `cw`, `e`, `ew`, `w`
If _mode_ is not provided than `cw` _mode_ is assumed (it's how standard methods are defined on native objects).
To setup descriptor with getter and/or setter use `descriptor.gs`, _mode_ is configured same way as in _value_ version, only difference is that settings for _writable_ attribute are ignored.

### diff(obj1, obj2)

Returns differences between two objects (taking into account only its own enumerable properties).  Returned object is array of three arrays. Each array holds property names:

* 0 - properties that were not present in `obj2`
* 1 - properties that have different values
* 2 - properties that were not present in `obj1`

### every(obj, cb[, thisArg[, compareFn]])

Analogous to Array.prototype.every. Returns true if every key-value pair in this object satisfies the provided testing function.
Optionally _compareFn_ can be provided which assures that keys are tested in given order. If provided _compareFn_ is equal to `true`, then order is alphabetical (by key).

### extend(dest[, …src])

Extend _dest_ by enumerable own properties of other objects. Properties found in both objects will be overwritten.

### extendDeep(dest[, …src])

Extend _dest_ by enumerable own properties of other objects. Properties found in both objects will be overwritten with exception of plain objects which again reiterated so only matching properties from other nested plain objects are affected

### extendProperties(dest[, …src])

Extend _dest_ by all own properties of other objects. Properties found in both objects will be overwritten (unless they're not configrable and cannot be overwritten).

### filter(obj, cb[, thisArg])

Analogous to Array.prototype.filter. Returns new object with properites for which _cb_ function returned truthy value.

### flatten(obj)

Returns new object, with flatten properties of input object

_flatten({ a: { b: 1 }, c: { d: 1 } })  =def  { b: 1, d: 1 }_

### forEach(obj, cb[, thisArg[, compareFn]])

Analogous to Array.prototype.forEach. Calls a function for each key-value pair found in object
Optionally _compareFn_ can be provided which assures that properties are iterated in given order. If provided _compareFn_ is equal to `true`, then order is alphabetical (by key).

### getPropertyNames()

Get all (not just own) property names of the object

### is(x, y)

_In EcmaScript 6th Edition draft as `is` operator_

Whether two values are equal, takes into account NaN and -0/+0 cases

### isCallable(x)

Whether object is callable

### isCopy(x, y[, depth])

Two values are considered a copy of same value when they meet following rules:

1. Are of same type (`typeof` check)
2. Have same string representation
3. (Objects only) Own enumerable properties of first object match own
enumerable properties of other object. Optionally depth can be provided at which relaxed comparision rules need to be applied. This allows deep comparision of different objects.

Objects can contain self references, algorithm is aware of possible infinite loop traps and won't into them.

### isEmpty(obj)

True if object doesn't have any own enumerable property

### isList(x)

Whether object is array-like object

### isObject(arg)

Whether value is not primitive

### isPlainObject(arg)

Whether object is plain object, its protototype should be Object.prototype and it cannot be host object.

### keyOf(obj, searchValue)

Search object for value

### map(obj, cb[, thisArg])

Analogous to Array.prototype.map. Creates a new object with properties which values are results of calling a provided function on every key-value pair in this object.

### mapKeys(obj, cb[, thisArg])

Create new object with same values, but remapped keys

### mapToArray(obj[, cb[, thisArg[, compareFn]]])

Creates an array of results of calling a provided function on every key-value pair in this object.
Optionally _compareFn_ can be provided which assures that results are added in given order. If provided _compareFn_ is equal to `true`, then order is alphabetical (by key).

### reduce(obj, cb[, initial[, compareFn]])

Analogous to Array.prototype.reduce. Apply a function against an accumulator and each value of the object.
Optionally _compareFn_ can be provided which assures that object keys are iterated in given order. If _compareFn_ is equal to `true`, then order is alphabetical (by key).
If we need to provide _compareFn_ but don't want to provide _initial_ value, then we have to pass `reduce.NO_INITIAL` as initial argument.

### safeTraverse(obj[, …names])

Save navigation of object properties. See http://wiki.ecmascript.org/doku.php?id=strawman:existential_operator

### some(obj, cb[, thisArg[, compareFn]])

Analogous to Array.prototype.some Returns true if any key-value pair satisfies the provided
testing function.
Optionally _compareFn_ can be provided which assures that keys are tested in given order. If provided _compareFn_ is equal to `true`, then order is alphabetical (by key).

### toPlainObject(x)

Returns plain object build from x object and it's prototypes enumerable properties
If x is not given, then empty object is returned.

### validCallable(x)

If given object is not callable throw TypeError in other case return it.

### validValue(x)

Throws error if given value is `null` or `undefined`, otherwise returns value.

### values(obj)

Return array of object own enumerable properties

## RegExp Constructor extensions

### isRegExp(x)

Whether object is regular expression

## String Constructor extensions

### isString(x)

Whether object is string

## String Prototype extensions

### camelToHyphen()

Convert camelCase string to hyphen separated, e.g. one-two-three -> oneTwoThree.
Useful when converting names from js property convention into filename convention.

### capitalize()

Capitalize first character of a string

### caseInsensitiveCompare(str)

Case insensitive compare

### contains(searchString[, position])

_In EcmaScript 6th Edition draft_
Whether string contains given string.

### endsWith(searchString[, endPosition])

_In EcmaScript 6th Edition draft_
Whether strings ends with given string

### format(fmap[, thisArg])

Formats given template up to provided map, e.g.:

```javascript
"%capital is a capital of %country".format({
	capital: "Warsaw",
	country: "Poland"
}); // -> "Warsaw is a capital of Poland"
```
Map may also provide not direct values but functions that resolve value, in that case optional _thisArg_ determines the context in which functions are called.

### hyphenToCamel()

Convert hyphen separated string to camelCase, e.g. one-two-three -> oneTwoThree.
Useful when converting names from filename convention to js property name convention.

### indent(str[, count])

Indents each line with provided _str_ (if _count_ given then _str_ is repeated _count_ times).

### last()

Return last character

### pad(fill[, length])

Pad string with _fill_.
If _length_ si given than _fill_ is reapated _length_ times.
If _length_ is negative then pad is applied from right.

### repeat(n)

Repeat given string _n_ times

### simpleReplace(search, replace)

Simple `replace` version. Doesn't support regular expressions. Replaces just first occurence of search string. Doesn't support insert patterns, therefore it is safe to replace text with text obtained programmatically (there's no need for additional _$_ characters escape in such case).

### startsWith(searchString[, position])

_In EcmaScript 6th Edition draft_
Whether strings starts with given string

### trimCommonLeft([…strings])

Returns string left trimmed by characters same for all strings

## Math Object extensions

### sign(n)

_In EcmaScript 6th Edition draft_
Returns sign of a number value

## Tests [![Build Status](https://secure.travis-ci.org/medikoo/es5-ext.png?branch=master)](https://secure.travis-ci.org/medikoo/es5-ext)

	$ npm test


text:
package com.dremio.exec.catalog;

import com.dremio.exec.planner.sql.parser.SqlGrant.Privilege;
import com.dremio.service.namespace.NamespaceKey;

/**
 * Interface to perform privilege checking on sources
 */
public interface PrivilegeCatalog {
  /**
   * Validate user's privilege.
   * @param key
   * @param privilege
   */
  void validatePrivilege(NamespaceKey key, Privilege privilege);

  /**
   * Validate user's ownership.
   * @param key
   */
  void validateOwnership(NamespaceKey key);
}

redpajama_set_name: RedPajamaGithub


text:
#include <iostream>
#include <string>
#include <vector>
#include <list>
#include <utility>

#ifndef SRC_VARIABLES_FILES_H_
#define SRC_VARIABLES_FILES_H_

#include "src/variables/variable.h"

namespace modsecurity {

class Transaction;
namespace variables {

DEFINE_VARIABLE_DICT(Files, FILES, m_variableFiles)

}  // namespace variables
}  // namespace modsecurity

#endif  // SRC_VARIABLES_FILES_H_


text:
import React from 'react';
import Activity from './Activity';

class Activities extends React.PureComponent {
  constructor() {
    super();
    this.state = null; // no state in this component, right?
    this._renderActivities = this._renderActivities.bind(this);
  }

  render() {
    const {activities, archived} = this.props;

    return (

Activities

        {this._renderActivities(activities)}
        {Object.keys(archived).length ?

Archived activities

            {this._renderActivities(archived, {archived: true})}

        : null}

    );
  }

  _renderActivities(activities, activityProps={}) {
    const {toggle, edit} = this.props;
    return (

        {getActivityNamesSortedByIdealTime(activities).map(name =>
          <Activity
            {...activityProps}
            data={activities[name]}
            name={name}
            toggle={toggle}
            edit={edit}
            key={name}
          />
        )}

    );
  }
}

function getActivityNamesSortedByIdealTime(activities) {
  const names = Object.keys(activities);
  return names.sort((name1, name2) => {
    const idealTime1 = activities[name1].idealTime;
    const idealTime2 = activities[name2].idealTime;
    if (idealTime1 < idealTime2) {
      return -1;
    }
    return idealTime1 > idealTime2;
  })
}

Activities.defaultProps = {
  activities: {},
  archived: {},
};

export default Activities;


text:
package com.temple.util.json;

import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;

/**
 * TODOC
 *
 * @author Florent Pallaver
 * @version 1.0
 */
public final class StringHandler extends AbstractHandler {

	@Override
	protected void nullSafeAdd(JsonObjectBuilder job, String name, Object value) {
		job.add(name, (String) value);
	}

	@Override
	protected void nullSafeAdd(JsonArrayBuilder jab, Object value) {
		jab.add((String) value);
	}

	@Override
	protected Object getNullSafeValue(JsonObject jo, String name) {
		return jo.getString(name);
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

	<display-name>fieldwork</display-name>

	<listener>
		<listener-class>hn.join.fieldwork.service.AppContext</listener-class>
	</listener>

	<context-param>
		<param-name>webAppRootKey</param-name>
		<param-value>fieldwork.webapp.root</param-value>
	</context-param>
	<context-param>
		<param-name>log4jConfigLocation</param-name>
		<param-value>/WEB-INF/log4j.properties</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
	</listener>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring/root-context.xml</param-value>
	</context-param>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<filter>
		<filter-name>Set Character Encoding</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value><!-- 强制进行转码 -->
		</init-param>
	</filter>

	<filter-mapping>
		<filter-name>Set Character Encoding</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<filter>
		<filter-name>webShiroFilter</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
	</filter>

	<filter-mapping>
		<filter-name>webShiroFilter</filter-name>
		<url-pattern>/</url-pattern>
		<dispatcher>REQUEST</dispatcher>
		<dispatcher>FORWARD</dispatcher>
		<dispatcher>INCLUDE</dispatcher>
		<dispatcher>ERROR</dispatcher>
	</filter-mapping>

	<filter-mapping>
		<filter-name>webShiroFilter</filter-name>
		<url-pattern>/web/*</url-pattern>
		<dispatcher>REQUEST</dispatcher>
		<dispatcher>FORWARD</dispatcher>
		<dispatcher>INCLUDE</dispatcher>
		<dispatcher>ERROR</dispatcher>
	</filter-mapping>

	<servlet>
		<servlet-name>dataUpdateFilesServlet</servlet-name>
		<servlet-class>hn.join.fieldwork.web.DataUpdateFilesServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>dataUpdateFilesServlet</servlet-name>
		<url-pattern>/dataUpdate/*</url-pattern>
	</servlet-mapping>

	<servlet>
		<servlet-name>appServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>/</url-pattern>
		<!-- 这里可以用 / 但不能用 /* ,拦截了所有请求会导致静态资源无法访问,所以要在spring3-servlet.xml中配置mvc:resources -->
	</servlet-mapping>

	<jsp-config>
		<taglib>
			<taglib-uri>shiro-ext</taglib-uri>
			<taglib-location>/WEB-INF/shiro-ext.tld</taglib-location>
		</taglib>
	</jsp-config>

</web-app>


text:
bool JsonDictionaryToMap(const std::string& json,
                         std::map<std::string, std::string>* results) {
  DCHECK(results != NULL);
  JSONStringValueSerializer deserializer(json);
  scoped_ptr<Value> root(deserializer.Deserialize(NULL, NULL));

  // Note that we don't use ASSERT_TRUE here (and in some other places) as it
  // doesn't work inside a function with a return type other than void.
  EXPECT_TRUE(root.get());
  if (!root.get())
    return false;

  EXPECT_TRUE(root->IsType(Value::TYPE_DICTIONARY));
  if (!root->IsType(Value::TYPE_DICTIONARY))
    return false;

  DictionaryValue* dict = static_cast<DictionaryValue*>(root.get());

  for (DictionaryValue::key_iterator it = dict->begin_keys();
       it != dict->end_keys(); ++it) {
    Value* value = NULL;
    bool succeeded = dict->GetWithoutPathExpansion(*it, &value);

    EXPECT_TRUE(succeeded);
    if (!succeeded)
      continue;

    const std::string& key(*it);
    std::string result;

    switch (value->GetType()) {
      case Value::TYPE_STRING:
        succeeded = value->GetAsString(&result);
        break;
      case Value::TYPE_DOUBLE: {
        double double_result;
        succeeded = value->GetAsDouble(&double_result);
        if (succeeded)
          result = base::DoubleToString(double_result);
        break;
      }
      default:
        NOTREACHED() << "Value type not supported!";
        return false;
    }

    EXPECT_TRUE(succeeded);
    if (succeeded)
      results->insert(std::make_pair(key, result));
  }

  return true;
}


text:
using System;

namespace Xamvvm
{
    public class NoPageForPageModelRegisteredException : XamvvmException
    {
        public NoPageForPageModelRegisteredException(string message) : base(message)
        {
        }
    }
}


text:
<meta charset="UTF-8">
<title>RealObject.<init> - mockspresso-api</title>
<link rel="stylesheet" href="../../../style.css">

mockspresso-api / com.episode6.hackit.mockspresso.annotation / RealObject / <init>

<init>

RealObject(<span class="identifier" id="com.episode6.hackit.mockspresso.annotation.RealObject$<init>(kotlin.reflect.KClass((kotlin.Any)))/implementation">implementation: KClass<*>)

Annotation that represents a real object used in a test (as opposed to a mock)


text:
=head1 LICENSE

Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2022] EMBL-European Bioinformatics Institute

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

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=cut

=head1 CONTACT

 Please email comments or questions to the public Ensembl
 developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.

 Questions may also be sent to the Ensembl help desk at
 <http://www.ensembl.org/Help/Contact>.

=cut

=head1 ImportGWAS

This module imports NHGRI-EBI GWAS catalog data. The module fetches the data from
the API hosted at EBI: https://www.ebi.ac.uk/gwas/.

=cut

package Bio::EnsEMBL::Variation::Pipeline::PhenotypeAnnotation::ImportGWAS;

use warnings;
use strict;

use File::Path qw(make_path);
use File::stat;
use File::Basename;
use POSIX qw(strftime);

use base ('Bio::EnsEMBL::Variation::Pipeline::PhenotypeAnnotation::BasePhenotypeAnnotation');

my %source_info;

sub fetch_input {
  my $self = shift;

  my $pipeline_dir = $self->required_param('pipeline_dir');
  my $species      = $self->required_param('species');
  my $run_type     = $self->required_param('run_type');

  $self->debug($self->param('debug_mode'));
  $self->skip_sets(0); #add variation set data
  $self->gwas(1); #run on gwas specific behaviour

  my $gwas_url = 'https://www.ebi.ac.uk/gwas/api/search/downloads/alternative';

  %source_info = (source_description => 'Variants associated with phenotype data from the NHGRI-EBI GWAS catalog',
                  source_url => 'https://www.ebi.ac.uk/gwas/',
                  object_type => 'Variation',
                  source_status => 'germline',
                  set => 'ph_nhgri',
                  source_name       => 'NHGRI-EBI GWAS catalog', #source name in the variation db
                  source_name_short => 'GWAS',                   #source identifier in the pipeline
                  data_types => 'phenotype_feature,study',
                # source_version is set based on file name
                  );

  my $workdir = $pipeline_dir."/".$source_info{source_name_short}."/".$species;
  unless (-d $workdir) {
    my $err;
    make_path($workdir, {error => \$err});
    die "make_path failed: ".Dumper($err) if $err && @$err;
  }
  $self->workdir($workdir);

  open(my $logFH, ">", $workdir."/".'log_import_out_'.$source_info{source_name_short}.'_'.$species) || die ("Failed to open file: $!\n");
  open(my $errFH, ">", $workdir."/".'log_import_err_'.$source_info{source_name_short}.'_'.$species) || die ("Failed to open file: $!\n");
  open(my $pipelogFH, ">", $workdir."/".'log_import_debug_pipe_'.$source_info{source_name_short}.'_'.$species) || die ("Failed to open file: $!\n");
  $self->logFH($logFH);
  $self->errFH($errFH);
  $self->pipelogFH($pipelogFH);

  #get input files:
  my $file_gwas;
  # first look if one already was downloaded, if not then fetch latest
  my @files = glob($workdir. '/gwas_catalog_v*-associations_e*_r*\.tsv' );
  my ($latestFile, $latestFileTime);
  foreach my $f (@files){
    if (defined $latestFile) {
      my $fileTime = strftime("%Y%m%d", localtime(stat($f)->mtime)); #get file date
      if ($fileTime > $latestFileTime) {
        $latestFile = $f; $latestFileTime = $fileTime;
      }
    } else {
      $latestFile = $f;
      $latestFileTime = strftime("%Y%m%d", localtime(stat($latestFile)->mtime));
    }
  }
  if (defined $latestFile) {
    $file_gwas = basename($latestFile);
    print $logFH "Found file (".$workdir."/".$file_gwas.") and will skip new fetch\n";
  } else {
    chdir $workdir;
    my $redirInfo=`curl -w '%{redirect_url}' -JLO $gwas_url `;
    my @tmp = split(/'/, $redirInfo);
    $file_gwas = $tmp[1];
    print $logFH "Fetched new file : $file_gwas\n";
  }

  #parse date from file name
  if ($file_gwas  =~ m/gwas_catalog_v.*-associations_e.*_r(.*)\.tsv/){
    $source_info{source_version} = $1;
    $source_info{source_version} =~ s/-//g;
  } else {
    print $errFH "WARNING: could not parse version from file : $file_gwas\n";
  }
  $self->param('gwas_file', $file_gwas);
}

sub run {
  my $self = shift;

  my $gwas_file = $self->required_param('gwas_file');

  # dump and clean pre-existing phenotype features
  $self->dump_phenotypes($source_info{source_name}, 1);

  # get phenotype data
  my $results = $self->parse_input_file($gwas_file);
  $self->print_pipelogFH("Got ".(scalar @{$results->{'phenotypes'}})." phenotypes \n") if ($self->debug);

  # save phenotypes
  $self->save_phenotypes(\%source_info, $results);

  my %param_source = (source_name => $source_info{source_name_short},
                      type => $source_info{object_type});
  $self->param('output_ids', { source => \%param_source,
                               species => $self->required_param('species'),
                               run_type => $self->required_param('run_type'),
                             });
}

sub write_output {
  my $self = shift;

  $self->print_pipelogFH("Passing $source_info{source_name_short} import (".$self->required_param('species').") for checks (check_phenotypes)\n") if ($self->debug);
  close($self->logFH) if defined $self->logFH ;
  close($self->errFH) if defined $self->errFH ;
  close($self->pipelogFH) if defined $self->pipelogFH ;

  $self->dataflow_output_id($self->param('output_ids'), 2);
}

=head2 parse_input_file

  Arg [1]    : string $infile
               The input file name.
  Example    : $results = $obj->parse_input_file($infile)
  Description: Parse phenotypes from NHGRI-EBI GWAS input file
  Returntype : hashref with results (key 'phenotypes')
  Exceptions : none

=cut

sub parse_input_file {
  my ($self, $infile) = @_;

  my %headers;
  my @phenotypes;

  my $errFH1;
  open($errFH1, ">", $self->workdir."/".'log_import_err_'.$infile) || die ("Could not open file for writing: $!\n");

  # Open the input file for reading
  if($infile =~ /gz$/) {
    open(IN, "zcat ".$self->workdir."/$infile |") || die ("Could not open $infile for reading: $!\n");
  }
  else {
    open(IN,'<',$self->workdir."/".$infile) || die ("Could not open $infile for reading: $!\n");
  }

  # Read through the file and parse out the desired fields
  while (<IN>) {
    chomp;

    my @row_data = split(/\t/,$_);

    # header
    if(/^DATE\s+ADDED\s+TO\s+CATALOG/) {
      $headers{uc($row_data[$_])} = $_ for 0..$#row_data;
    }
    else {
      die ("ERROR: Could not find header data\n") unless %headers;

      my %content;
      $content{$_} = $row_data[$headers{$_}] for keys %headers;

      my $pubmed_id      = $content{'PUBMEDID'};
      my $study          = $content{'STUDY'};
      my $phenotype      = $content{'DISEASE/TRAIT'};
      my $gene           = ($content{'REPORTED GENE(S)'} =~ /\?/) ? '' : $content{'REPORTED GENE(S)'};
      my $rs_risk_allele = ($content{'STRONGEST SNP-RISK ALLELE'} =~ /\?/) ? '' : $content{'STRONGEST SNP-RISK ALLELE'};
      my $rs_id          = $content{'SNPS'};
      my $pvalue         = ($content{'P-VALUE'} ne '') ? $content{'P-VALUE'} : '';
      my $ratio          = $content{'OR OR BETA'};
      my $ratio_info     = $content{'95% CI (TEXT)'};
      my @accessions     = split/\,/, $content{'MAPPED_TRAIT_URI'};

      print $errFH1 "WARNING: 'DISEASE/TRAIT' entry is empty for '$rs_id'\n" if ($phenotype eq '');
      next if ($phenotype eq '');

      my $risk_frequency = '';
      if ($rs_risk_allele =~ /^\s*$rs_id-+\s*(\w+)\s*$/i) {
        $rs_risk_allele = $1;
        $risk_frequency = $content{'RISK ALLELE FREQUENCY'};
      }

      $gene =~ s/\s+//g;
      $gene =~ s/–/-/g;
      $gene =~ s/[^\x00-\x7F]//g; # Remove non ASCII characters
      $gene = '' if $gene eq '-' or $gene eq 'NR'; #Skip uninformative entries, missing data in original curation see GWAS catalog curation

      my %data = (
        'study_type' => 'GWAS',
        'description' => $phenotype,
        'associated_gene' => $gene,
        'risk_allele' => $rs_risk_allele,
        'risk_allele_freq_in_controls' => $risk_frequency,
        'p_value' => $pvalue,
        'study_description' => $study,
        'accessions'   => \@accessions,
        'ontology_mapping_type' =>'is'
      );

      # Post process the ratio data
      if (defined($ratio)) {
        if ($ratio =~ /(\d+)?(\.\d+)$/) {
          my $pre  = $1;
          my $post = $2;
          $ratio = (defined($pre)) ? "$pre$post" : "0$post";
          $ratio = 0 if ($ratio eq '0.00');
        } else {
          $ratio = undef;
        }
      }

      # Add ratio/coef
      if (defined($ratio)) {
        # Parse the ratio info column to extract the unit information (we are not interested in the confidence interval)
        if ($ratio_info =~ /^\s*(\[.+\])?\s*(.+)$/) {
          my $unit = $2;
             $unit =~ s/\(//g;
             $unit =~ s/\)//g;
             $unit =~ s/µ/micro/g;
          if ($unit =~ /^\s+$/ || $ratio >= 1) {
            $data{'odds_ratio'} = $ratio;
          }
          else {
            $data{'beta_coef'} = "$ratio $unit";
          }
        }
        else {
          $data{'odds_ratio'} = $ratio;
        }
      }

      # Parse the ids
      my @ids;
      $rs_id ||= "";
      while ($rs_id =~ m/(rs[0-9]+)/g) {
        push(@ids,$1);
      }
      $data{'variation_names'} = join(',',@ids);
      $data{'study'} = $self->get_pubmed_prefix . $pubmed_id if (defined($pubmed_id));

      # If we did not get any rsIds, skip this row (this will also get rid of the header)
      print $errFH1 "WARNING: Could not parse any rsIds from string '$rs_id'\n" if (!scalar(@ids));
      next if (!scalar(@ids));

      map {
        my %t_data = %{\%data};
        $t_data{'id'} = $_;
        push(@phenotypes,\%t_data)
      } @ids;
    }
  }
  close(IN);
  close($errFH1);

  my %result = ('phenotypes' => \@phenotypes);
  return \%result;
}

1;


text:
<!DOCTYPE html>
<meta charset=utf-8>
<title>Redirecting...</title>
<link rel=canonical href="../憶/index.html">
<meta http-equiv=refresh content="0; url='../憶/index.html'">

Redirecting...

Click here if you are not redirected.


text:
require "spec_helper"

describe "Invoker Power configuration", fakefs: true do
  describe "#create" do
    it "should create a config file given a hash" do
      FileUtils.mkdir_p(inv_conf_dir)
      config = Invoker::Power::Config.create(
        dns_port: 1200, http_port: 1201, ipfw_rule_number: 010
      )
      expect(File.exist?(Invoker::Power::Config.config_file)).to be_truthy

      config = Invoker::Power::Config.load_config()
      expect(config.dns_port).to eq(1200)
      expect(config.http_port).to eq(1201)
      expect(config.ipfw_rule_number).to eq(010)
    end
  end
end


text:
:: use this file to run your own startup commands
:: use  in front of the command to prevent printing the command

:: call "%GIT_INSTALL_ROOT%/cmd/start-ssh-agent.cmd"
:: set "PATH=%CMDER_ROOT%\vendor\whatever;%PATH%"

cd /d %HOME%


text:
import { daysToMs } from '../../../utils/date';

import { ACK } from '../constants';

// cross field validation for form
const validate = (vals) => {
  const errors = {};
  // check end date after start
  if (vals[ACK.START_DATE] && vals[ACK.END_DATE]) {
    if (new Date(vals[ACK.END_DATE]) - new Date(vals[ACK.START_DATE]) < daysToMs(14)) {
      errors[ACK.END_DATE] = '"End Date" must be at least 14 days after "Start Date"';
    }

    if (new Date(vals[ACK.START_DATE]) > new Date(vals[ACK.END_DATE])) {
      errors[ACK.END_DATE] = '"End Date" must be after "Start Date"';
    }
  }
  // check if name but no attachment
  if (vals[ACK.FILE_NAME] && !vals[ACK.FILE_CONTENT]) {
    errors[ACK.FILE_CONTENT] = 'An "Attachment" is required if an "Attachment Name" is provided';
  }
  // check if no name but attachment
  if (!vals[ACK.FILE_NAME] && vals[ACK.FILE_CONTENT]) {
    errors[ACK.FILE_NAME] = 'An "Attachment Name" is required if an "Attachment" is provided';
  }

  return errors;
};

export default validate;


text:
package com.mgmtp.perfload.logging;

import static org.apache.commons.lang3.StringUtils.trimToEmpty;
import static org.testng.Assert.assertEquals;

import java.io.IOException;
import java.net.InetAddress;
import java.util.UUID;

import org.apache.commons.lang3.text.StrBuilder;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import com.mgmtp.perfload.logging.DefaultResultLogger;
import com.mgmtp.perfload.logging.ResultLogger;
import com.mgmtp.perfload.logging.SimpleLogger;
import com.mgmtp.perfload.logging.TimeInterval;

/**
 * @author rnaegele
 */
public class DefaultResultLoggerTest {

	private static final String EXP_RESULT_TEMPLATE =
			"\"1\";\"2\";\"3\";\"%s\";\"-1\";\"-1\";\"operation\";\"target\";\"%s\";\"%s\";\"GET\";"
					+ "\"http://localhost/someUri\";\"someUriAlias\";\"%s\";\"client\";\"%s\";\"%s\"";

	private final String timestamp = DefaultResultLogger.DATE_FORMAT.format(1L);
	private InetAddress localhost;
	private ResultLogger logger;
	private TestLogger tl;
	private UUID requestId;
	private final UUID executionId = UUID.randomUUID();

	@BeforeTest
	public void init() throws IOException {
		tl = new TestLogger();
		localhost = InetAddress.getLocalHost();
		logger = new DefaultResultLogger(tl, localhost, "client", "operation", "target", 1, 2, 3);
		requestId = UUID.randomUUID();
	}

	private String createExpectedResultString(final String errorMsg, final Object... extras) {
		String success = errorMsg != null ? "ERROR" : "SUCCESS";

		StrBuilder sb = new StrBuilder(250);
		sb.setNullText("");

		String result = String.format(EXP_RESULT_TEMPLATE, timestamp, success, trimToEmpty(errorMsg), localhost, executionId,
				requestId);
		sb.append(result);
		if (extras != null) {
			for (Object extra : extras) {
				sb.append(";\"");
				sb.append(extra);
				sb.append("\"");
			}
		}
		return sb.toString();
	}

	@Test
	public void testWithoutExtras() {
		logger.logResult(1L, new TimeInterval(), new TimeInterval(), "GET", "http://localhost/someUri", "someUriAlias",
				executionId, requestId);
		String expected = createExpectedResultString(null);
		assertLogMessage(expected);
	}

	@Test
	public void testWithExtras() {
		logger.logResult(1L, new TimeInterval(), new TimeInterval(), "GET", "http://localhost/someUri", "someUriAlias",
				executionId, requestId, "extra1", "extra2", null);
		String expected = createExpectedResultString(null, "extra1", "extra2", null);
		assertLogMessage(expected);
	}

	@Test
	public void testWithLineBreaks() {
		final String unnormalized = "  foo\"\"  bar\r\nbaz\r\n\r\nblubb\n\n\n\"blah\"   blah\n42\n";
		final String normalized = "  foo\"\"\"\"  bar baz blubb \"\"blah\"\"   blah 42";
		logger.logResult(1L, new TimeInterval(), new TimeInterval(), "GET", "http://localhost/someUri", "someUriAlias",
				executionId, requestId,	unnormalized);
		String expected = createExpectedResultString(null, normalized);
		assertLogMessage(expected);
	}

	@Test
	public void testWithError() {
		final String errorMessage = "my little test error message";
		logger.logResult(errorMessage, 1L, new TimeInterval(), new TimeInterval(), "GET", "http://localhost/someUri",
				"someUriAlias", executionId, requestId);
		String expected = createExpectedResultString(errorMessage);
		assertLogMessage(expected);
	}

	private void assertLogMessage(final String expected) {
		assertEquals(tl.getLastOutput(), expected);
	}

	static class TestLogger implements SimpleLogger {

		private String lastOutput;

		@Override
		public void open() throws IOException {
			// no-op
		}

		@Override
		public void close() {
			// no-op
		}

		@Override
		public void writeln(final String output) {
			this.lastOutput = output;
		}

		/**
		 * @return the lastOutput
		 */
		public String getLastOutput() {
			return lastOutput;
		}
	}
}


text:
<?php
/**
 * WPSEO plugin file.
 *
 * @package WPSEO\Admin\Ajax
 */

/**
 * Class WPSEO_Shortcode_Filter
 *
 * Used for parsing WP shortcodes with AJAX
 */
class WPSEO_Shortcode_Filter {

	/**
	 * Initialize the AJAX hooks
	 */
	public function __construct() {
		add_action( 'wp_ajax_wpseo_filter_shortcodes', array( $this, 'do_filter' ) );
	}

	/**
	 * Parse the shortcodes
	 */
	public function do_filter() {
		check_ajax_referer( 'wpseo-filter-shortcodes', 'nonce' );

		$shortcodes = filter_input( INPUT_POST, 'data', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY );

		$parsed_shortcodes = array();

		foreach ( $shortcodes as $shortcode ) {
			$parsed_shortcodes[] = array(
				'shortcode' => $shortcode,
				'output'    => do_shortcode( $shortcode ),
			);
		}

		wp_die( wp_json_encode( $parsed_shortcodes ) );
	}
}


text:
layout: page
title: Brown - Waller Wedding
date: 2016-05-24
author: Andrew Brock
tags: weekly links, java
status: published
summary: Morbi at venenatis risus. Pellentesque efficitur.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 07/08/2016
  endDate: 07/09/2016
  ctyhocn: SEEMAHX
  groupCode: BWW
published: true
---
Vestibulum mattis urna diam, et aliquet ipsum facilisis nec. Integer tempus, nisl in ullamcorper pharetra, turpis nibh accumsan justo, eget mollis lacus enim ut mauris. Ut tincidunt lectus mauris, in accumsan odio lacinia a. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sed dignissim leo, hendrerit convallis nibh. Praesent venenatis egestas mollis. Aenean rutrum consectetur efficitur. Suspendisse porttitor tempor placerat. Praesent ut purus vel eros rutrum posuere.

1 Pellentesque bibendum turpis eget quam elementum mollis
1 Phasellus interdum orci rutrum consequat facilisis.

Vivamus ac tempus libero, at scelerisque nisl. Pellentesque ut lectus non augue tincidunt rutrum. Curabitur volutpat, erat ut tincidunt ultricies, lacus ex sagittis justo, et feugiat ligula ligula sit amet lacus. Curabitur dignissim eu quam at bibendum. Maecenas eros elit, vestibulum ut eleifend vulputate, posuere id elit. Interdum et malesuada fames ac ante ipsum primis in faucibus. Sed malesuada lectus at eros vehicula cursus. Nulla ut malesuada ante. Nullam sit amet nulla egestas, viverra diam eget, tempor mi. Mauris vehicula commodo consequat. Donec sit amet neque pharetra, maximus leo non, mollis enim. Fusce sit amet euismod odio. Pellentesque sodales neque semper elit mollis, id blandit dui tempor. Maecenas eu diam vel leo tincidunt tristique. Integer feugiat sollicitudin sapien, quis molestie diam consectetur id. Maecenas imperdiet dictum lorem vitae gravida.


text:
package org.carlspring.strongbox.services;

import org.carlspring.strongbox.configuration.Configuration;
import org.carlspring.strongbox.configuration.ProxyConfiguration;
import org.carlspring.strongbox.storage.Storage;
import org.carlspring.strongbox.storage.repository.HttpConnectionPool;
import org.carlspring.strongbox.storage.repository.Repository;
import org.carlspring.strongbox.storage.routing.RoutingRule;
import org.carlspring.strongbox.storage.routing.RoutingRules;
import org.carlspring.strongbox.storage.routing.RuleSet;

import javax.xml.bind.JAXBException;
import java.io.IOException;
import java.util.List;

/**
 * @author mtodorov
 */
public interface ConfigurationManagementService extends ConfigurationService
{

    void setConfiguration(Configuration configuration)
            throws IOException, JAXBException;

    String getBaseUrl()
            throws IOException;

    void setBaseUrl(String baseUrl)
            throws IOException, JAXBException;

    int getPort()
            throws IOException;

    void setPort(int port)
            throws IOException, JAXBException;

    void setProxyConfiguration(String storageId,
                               String repositoryId,
                               ProxyConfiguration proxyConfiguration)
            throws IOException, JAXBException;

    void addOrUpdateStorage(Storage storage)
            throws IOException, JAXBException;

    Storage getStorage(String storageId)
            throws IOException;

    void removeStorage(String storageId)
            throws IOException, JAXBException;

    void addOrUpdateRepository(String storageId, Repository repository)
            throws IOException, JAXBException;

    Repository getRepository(String storageId, String repositoryId)
            throws IOException;

    List<Repository> getGroupRepositories();

    List<Repository> getGroupRepositoriesContaining(String repositoryId);

    void removeRepositoryFromAssociatedGroups(String repositoryId)
            throws IOException, JAXBException;

    void removeRepository(String storageId, String repositoryId)
            throws IOException, JAXBException;

    ProxyConfiguration getProxyConfiguration()
            throws IOException, JAXBException;

    void setProxyRepositoryMaxConnections(String storageId, String repositoryId, int numberOfConnections)
            throws IOException, JAXBException;

    HttpConnectionPool getHttpConnectionPoolConfiguration(String storageId, String repositoryId)
            throws IOException, JAXBException;

    boolean addOrUpdateAcceptedRuleSet(RuleSet ruleSet);

    boolean removeAcceptedRuleSet(String groupRepository);

    boolean addOrUpdateAcceptedRepository(String groupRepository,
                                          RoutingRule routingRule);

    boolean removeAcceptedRepository(String groupRepository,
                                     String pattern,
                                     String repositoryId);

    boolean overrideAcceptedRepositories(String groupRepository,
                                         RoutingRule routingRule);

    RoutingRules getRoutingRules();
}


text:
<?xml version="1.0"?>
<project name="helfy" default="build" basedir=".">
    <property name="build.dir"      value="build"/>
    <property name="src.dir"        value="src"/>
    <property name="test.dir"       value="test"/>
    <property name="lib.dir"        value="lib"/>
    <property name="target.jar"     value="${build.dir}/${ant.project.name}.jar"/>

    <target name="init">
        <mkdir dir="${build.dir}"/>
    </target>

    <target name="clean">
        <delete dir="${build.dir}"/>
    </target>

    <target name="clean-all" depends="clean">
        <delete dir="${lib.dir}"/>
    </target>

    <target name="build" depends="build-jar"/>

    <target name="compile-classes" depends="init">
        <echo message="Compiling classes..."/>
        <mkdir dir="${build.dir}/classes"/>
        <javac srcdir="${src.dir}:${test.dir}" destdir="${build.dir}/classes" includeantruntime="false"/>
    </target>

    <target name="build-jar" depends="compile-classes">
        <echo message="Building ${target.jar}..."/>
        <jar destfile="${target.jar}">
            <fileset dir="${build.dir}/classes" includes="**/*.class" />
        </jar>
    </target>

    <target name="run" depends="compile-classes">
        <java classpath="${build.dir}/classes" classname="one.helfy.HeapInfo"/>
    </target>
</project>


text:
<?php

require_once __DIR__.'/../../../extlibinc/authdata.php';

/**
 * Authorize using YAML data
 *
 * @author Joel Smith, Red Hat, Inc.
 * @package SimpleSAMLphp
 */

class sspmod_authorizeyaml_Auth_Process_Authorize extends SimpleSAML_Auth_ProcessingFilter
{
    private $yaml_authdata_path;

    /**
     * Initialize this filter.
     *
     * @param array $config  Configuration information about this filter.
     * @param mixed $reserved  For future use.
     * @throws SimpleSAML_Error_Exception In case of invalid configuration.
     */
    public function __construct($config, $reserved)
    {
        parent::__construct($config, $reserved);

        assert('is_array($config)');

        $this->yaml_authdata_path = $config['yaml_authdata_path'];
    }

    /**
     * Check to see if this user has rights to access
     * the destination resource, and if so, add the
     * roles to the attribute list.
     *
     * @param array &$request  The current request
     */
    public function process(&$request)
    {
        assert('is_array($request)');
        assert('array_key_exists("Attributes", $request)');

        $authdata = new AuthData($this->yaml_authdata_path);
        $entityid = $request['Destination']['entityid'];

        $user = $request['Attributes']['mail'][0];
        $groups = $authdata->getGroups($user);

        $resource = $authdata->getResource($entityid);
        $role = $authdata->getRoles($resource, $user, $groups);
        if (!is_null($role) && !empty($role))
        {
            $request['Attributes']['role'] = array($role);
        }
        else
        {
            $this->unauthorized($request);
        }
    }

    /**
     * When the process logic determines that the user is not
     * authorized for this service, then forward the user to
     * an 403 unauthorized page.
     *
     * Separated this code into its own method so that child
     * classes can override it and change the action. Forward
     * thinking in case a "chained" ACL is needed, more complex
     * permission logic.
     *
     * @param array $request
     */
    protected function unauthorized(&$request)
    {
        // Save state and redirect to 403 page
        $id = SimpleSAML_Auth_State::saveState($request, 'authorizeyaml:Authorize');
        $url = SimpleSAML_Module::getModuleURL('authorizeyaml/authorizeyaml_403.php');
        \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id));
    }
}


text:
//namespace WeekDays
//{
public enum WeekDay
{
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}
//}


text:
small-cor
========

[![Build Status](https://travis-ci.org/nmartin867/small-cor.png)](https://travis-ci.org/nmartin867/small-cor)

Very light weight middleware for [Express](https://github.com/visionmedia/express) which makes cross origin resource sharing easy.

## Installation
```
npm install small-cor
```
## Sample Usage
```js
var express = require('express');
var app = express();
var smallCOR = require('small-cor');

app.use(smallCOR({
    origin : '*',
	methods : ['GET'],
	headers : ['X-Custom']
}));

app.get('/', function(req, res){
  res.json({message : 'hello'});
});

app.listen(3000);
```
An HTTP GET request to localhost:3000 will result in HTTP response which contains the following headers:
```
Access-Control-Allow-Headers:X-Custom
Access-Control-Allow-Methods:GET
Access-Control-Allow-Origin:*
```
Options
=======
* `origin`  (string): URI of allowed origin. i.e. `'*'` or `'http://mysite.com'`
* `methods` (array): Array of strings containing permitted HTTP verbs i.e. `['GET']` or `['GET','POST']`
* `headers`  (array): Array of strings containing permitted HTTP headers i.e. `['X-Custom']` or `['X-Custom', 'X-PingPong']`
* `credentials`  (bool): Boolean indicating if browser will allow creditials to be sent.


text:
package com.yahoo.messagebus;

import com.yahoo.jrt.ListenFailedException;
import com.yahoo.jrt.Spec;
import com.yahoo.jrt.slobrok.server.Slobrok;
import com.yahoo.messagebus.network.rpc.RPCNetwork;
import com.yahoo.messagebus.network.rpc.RPCNetworkParams;
import com.yahoo.messagebus.network.rpc.test.TestServer;
import com.yahoo.messagebus.routing.RetryTransientErrorsPolicy;
import com.yahoo.messagebus.routing.Route;
import com.yahoo.messagebus.routing.RoutingPolicy;
import com.yahoo.messagebus.routing.test.CustomPolicyFactory;
import com.yahoo.messagebus.test.Receptor;
import com.yahoo.messagebus.test.SimpleMessage;
import com.yahoo.messagebus.test.SimpleProtocol;
import org.junit.jupiter.api.Test;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import static org.junit.jupiter.api.Assertions.*;

public class MessageBusTestCase {

    @Test
    void requireThatBucketSequencingWithResenderEnabledCausesError() throws ListenFailedException {
        Slobrok slobrok = new Slobrok();
        TestServer server = new TestServer(new MessageBusParams()
                        .addProtocol(new SimpleProtocol())
                        .setRetryPolicy(new RetryTransientErrorsPolicy()),
                new RPCNetworkParams()
                        .setSlobrokConfigId(slobrok.configId()));
        Receptor receptor = new Receptor();
        SourceSession session = server.mb.createSourceSession(
                new SourceSessionParams().setTimeout(600.0).setReplyHandler(receptor));
        assertTrue(session.send(new SimpleMessage("foo") {
            @Override
            public boolean hasBucketSequence() {
                return true;
            }
        }.setRoute(Route.parse("bar"))).isAccepted());
        Reply reply = receptor.getReply(60);
        assertNotNull(reply);
        assertEquals(1, reply.getNumErrors());
        assertEquals(ErrorCode.SEQUENCE_ERROR, reply.getError(0).getCode());
        session.destroy();
        server.destroy();
        slobrok.stop();
    }

    @Test
    void testConnectionSpec() throws ListenFailedException, UnknownHostException {
        // Setup servers and sessions.
        Slobrok slobrok = new Slobrok();
        List<TestServer> servers = new ArrayList<>();

        TestServer srcServer = new TestServer("feeder", null, slobrok, null);
        servers.add(srcServer);
        SourceSession src = servers.get(0).mb.createSourceSession(new Receptor());

        List<IntermediateSession> sessions = new ArrayList<>();
        for (int i = 0; i < 10; ++i) {
            TestServer server = new TestServer("intermediate/" + i, null, slobrok, null);
            servers.add(server);
            sessions.add(server.mb.createIntermediateSession("session", true, new Receptor(), new Receptor()));
        }

        TestServer dstServer = new TestServer("destination", null, slobrok, null);
        DestinationSession dst = dstServer.mb.createDestinationSession("session", true, new Receptor());

        assertTrue(srcServer.waitSlobrok("intermediate/*/session", sessions.size()));
        assertTrue(srcServer.waitSlobrok("destination/session", 1));

        StringBuilder route = new StringBuilder();
        for (int i = 0; i < sessions.size(); i++) {
            route.append("intermediate/").append(i).append("/session ");
            route.append(sessions.get(i).getConnectionSpec()).append(" ");
        }
        route.append(dst.getConnectionSpec());

        Message msg = new SimpleMessage("empty");
        assertTrue(src.send(msg, Route.parse(route.toString())).isAccepted());
        for (IntermediateSession itr : sessions) {
            // Received using session name.
            assertNotNull(msg = ((Receptor) itr.getMessageHandler()).getMessage(60));
            itr.forward(msg);

            // Received using connection spec.
            assertNotNull(msg = ((Receptor) itr.getMessageHandler()).getMessage(60));
            itr.forward(msg);
        }
        assertNotNull(msg = ((Receptor) dst.getMessageHandler()).getMessage(60));
        dst.acknowledge(msg);
        for (int i = sessions.size(); --i >= 0; ) {
            IntermediateSession itr = sessions.get(i);

            // Received for connection spec.
            Reply reply = ((Receptor) itr.getReplyHandler()).getReply(60);
            assertNotNull(reply);
            itr.forward(reply);

            // Received for session name.
            assertNotNull(reply = ((Receptor) itr.getReplyHandler()).getReply(60));
            itr.forward(reply);
        }
        assertNotNull(((Receptor) src.getReplyHandler()).getReply(60));

        // Cleanup.
        for (IntermediateSession session : sessions) {
            session.destroy();
        }
        for (TestServer server : servers) {
            server.destroy();
        }
        slobrok.stop();
    }

    @Test
    void testRoutingPolicyCache() throws ListenFailedException, UnknownHostException {
        Slobrok slobrok = new Slobrok();
        String config = "slobrok[1]\nslobrok[0].connectionspec \"" + new Spec("localhost", slobrok.port()).toString() + "\"\n";
        SimpleProtocol protocol = new SimpleProtocol();
        protocol.addPolicyFactory("Custom", new CustomPolicyFactory());
        MessageBus bus = new MessageBus(new RPCNetwork(new RPCNetworkParams().setSlobrokConfigId("raw:" + config)),
                new MessageBusParams().addProtocol(protocol));

        RoutingPolicy all = bus.getRoutingPolicy(SimpleProtocol.NAME, "Custom", null);
        assertNotNull(all);

        RoutingPolicy ref = bus.getRoutingPolicy(SimpleProtocol.NAME, "Custom", null);
        assertNotNull(ref);
        assertSame(all, ref);

        RoutingPolicy allArg = bus.getRoutingPolicy(SimpleProtocol.NAME, "Custom", "Arg");
        assertNotNull(allArg);
        assertNotSame(all, allArg);

        RoutingPolicy refArg = bus.getRoutingPolicy(SimpleProtocol.NAME, "Custom", "Arg");
        assertNotNull(refArg);
        assertSame(allArg, refArg);
    }
}


text:
    <button class="close" ng-click="close()" aria-label="Close" data-dismiss="modal" type="button">
        ×
    </button>

Print My Record

Would you like to include the additional data you've entered?

This would include your notes and the medications you've added yourself

            No

            Yes


text:
<!DOCTYPE html>

            <form id="email-templates-form" class="form-horizontal form-label-left input_mask"
                  th:object="${emailTemplate}" th:action="@{/emailTemplate}" method="post">

                                <button id="top-submit" type="submit" class="btn btn-default btn-md">
                                     Salvează
                                </button>

Adaugă / Editează Email Template

                            <input type="hidden" th:field="*{id}"/>

                                        Nume*

                                            <input type="text" placeholder="Numele" class="form-control col-md-7 col-xs-12" required="" th:field="*{name}"/>

                                        Categoria*

                                            <select class="form-control" name="category" id="category" tabindex="-1" required="" th:field="*{category}">
                                                <option value=""></option>
                                                <option th:each="cat : ${categories}" th:value="${cat.name()}" th:text="#{__${'emailTemplate.category.'+cat}__}"></option>
                                            </select>

                                        Conținut*

                                            <textarea class="resizable_textarea form-control" placeholder="Content"
                                                      id="content" required="" th:field="*{content}" rows="30">
                                            </textarea>

                    <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>

            </form>

                Gentelella - Bootstrap Admin Template by Colorlib


text:
<?php

global $ss_framework;

echo '
';

	do_action( 'shoestrap_in_article_top' );
	shoestrap_title_section( true, 'h2', true );
	do_action( 'shoestrap_entry_meta' );

	echo '
';
		echo apply_filters( 'shoestrap_do_the_excerpt', get_the_excerpt() );
		echo $ss_framework->clearfix();
	echo '
';

	if ( has_action( 'shoestrap_entry_footer' ) ) {
		echo '';
		do_action( 'shoestrap_entry_footer' );
		echo '';
	}

	do_action( 'shoestrap_in_article_bottom' );

echo '
';


text:
{% extends "personal/header.html" %}
{% block content %}
    {% for c in content %}
        <p>{{c}}</p>
    {% endfor %}
{% endblock %}


text:
Šis repozitorijs satur vairākus ar front-end web programmētāja darba prasmēm saistītus jautājumus, ko var izmantot, intervējot potenciālos vakances kandidātus. Nav ieteicams izmantot katru šeit minēto jautājumu, jo tas patērētu ļoti daudz laika. Izvēlieties tikai dažus jautājumus no šī saraksta, kas Jums palīdzēs ātrāk atlasīt kandidātus ar nepieciešamajām prasmēm.

[Rebecca Murphey](http://rmurphey.com/) [Baseline For Front-End Developers](http://rmurphey.com/blog/2012/04/12/a-baseline-for-front-end-developers/) raksts ir ļoti piemērota lasāmviela, kuru izlasīt pirms dodaties uz darba interviju.

**Piezīme:** Paturiet prātā, ka daudzi no šiem jautājumiem ir atvērta tipa, kas varētu izvērsties plašākā diskusijā un ļautu iepazīt cilvēka prasmes daudz labāk nekā tieša atbilde.

## Saturs

  1. [Sākotnējie Kontributori](#contributors)
  1. [Vispārēji Jautājumi](#general)
  1. [HTML Jautājumi](#html)
  1. [CSS Jautājumi](#css)
  1. [JS Jautājumi](#js)
  1. [jQuery Jautājumi](#jquery)
  1. [Kodēšanas Jautājumi](#jscode)
  1. [Interesanti Jautājumi](#fun)
  1. [Citas Lieliskas Atsauces](#references)

####[[⬆]](#toc) Sākotnējie Kontributori:

Vairums no jautājumiem tika paņemti no [oksoclap](http://oksoclap.com/) raksta, ko sākotnēji izveidoja [Paul Irish](http://paulirish.com) ([@paul_irish](http://twitter.com/paul_irish)) un kuru papildināja sekojoši cilvēki:

* [@bentruyman](http://twitter.com/bentruyman) - http://bentruyman.com
* [@cowboy](http://twitter.com/cowboy) - http://benalman.com
* [@ajpiano](http://ajpiano) - http://ajpiano.com
* [@SlexAxton](http://twitter.com/slexaxton) - http://alexsexton.com
* [@boazsender](http://twitter.com/boazsender) - http://boazsender.com
* [@miketaylr](http://twitter.com/miketaylr) - http://miketaylr.com
* [@vladikoff](http://twitter.com/vladikoff) - http://vladfilippov.com
* [@gf3](http://twitter.com/gf3) - http://gf3.ca
* [@jon_neal](http://twitter.com/jon_neal) - http://twitter.com/jon_neal
* [@wookiehangover](http://twitter.com/wookiehangover) - http://wookiehangover.com
* [@iansym](http://twitter.com/iansym) - http://twitter.com/iansym

####[[⬆]](#toc) Vispārēji Jautājumi:

* Ko jaunu Jūs apguvāt vakar/šonedēļ?
* Kas Jūs aizrauj un interesē programmēšanā?
* Kādas UI (lietotāja interfeisa), performances, SEO, apkopes vai tehnoloģijas apsvērumus jūs ņemat vērā, kad veidojat web-aplikāciju vai mājas lapu?
* Pastāstiet par sev vēlemo darba vidi. (Operētājsistēma, pārlūki, rīki utt.)
* Vai variet aprakstīt savu darba procesu, kad veidojiet mājas lapu?
* Vai jūs variet aprakstīt starpību starp "progressive enhancement" un "graceful degradation"?
  * Bonus punkti, ja tiek pieminēta funkciju noteikšana (feature detection).
* Izskaidrojiet, ko nozīmē "Semantisks HTML".
* Kā Jūs optimizētu mājas lapas failus/resurus?
  * Potenciāli vairāki risinājumu, starp kuriem būtu:
    * Failu konkatenācija (savienošana)
    * Failu minimizēšana
    * CDN hostēšana
    * Kešošana
    * u.c.
* Kāpēc ir labāk lapas resurus izvietot uz vairākiem domēniem?
  * Cik daudz resursus pārlūks spēj vienlaicīgi lejuplādēt no viena domēna?
* Nosauciet 3 veidus, kā samazināt lapas ielādes laiku (šķietamo vai faktisko)
* Kā Jūs rīkotos, ja Jūs pievienotos projektam un viņi izmantotu tabulāciju, bet Jūs atstarpes koda atkāpju veidošanai?
  * Ieteiktu projektā izmantot kaut ko līdzīgu EditorConfig (http://editorconfig.org)
  * Pieskaņoties kolēģiem
  * Veikt retabulāciju ar ':retab!' komandu
* Izveidojiet vienkāršū slaidrāža lapu
  * Bonus punkti, ja netiek izmantots JavaScript
* Kādus rīkus Jūs izmantojiet, lai pārbaudītu sava koda veiktspēju (performanci)?
  * Profiler, JSPerf, Dromaeo
* Ja šogad Jūs varētu pilnībā apgūt vienu tehnoloģiju, kura tā būtu?
* Kādas ir atšķirības starp Long-Polling, Websockets un SSE?
* Izskaidrojiet standartu un standartizēšanas komisiju nozīmi.
* Kas ir FOUC? Kā izvairīties no FOUC?

####[[⬆]](#toc) HTML Jautājumi:

* Ko dara `doctype`?
* Kāda ir starpība starp standarta režīmu un quirks režīmu?
* Kādi ir XHTML lapu ierobežojumi?
  * Vai var rasties problēmas, ja lapa tiek servēta kā `application/xhtml+xml`?
* Kā servēt lapu ar saturu vairākās valodās?
  * Par ko ir īpaši jāpiedomā, kad dizainē vai izstrādā vairāku valodu mājas lapas?
* Ar ko ir noderīgi `data-` atribūti?
* Pieņemot, ka HTML5 ir atvērta web-platforma, kas ir HTML5 pamatelementi?
* Aprakstiet atšķirības starp sīkdatnēm (cookies), sessionStorage un localStorage.

####[[⬆]](#toc) CSS Jautājumi:

* Aprakstiet, ko dara "reset" CSS fails un ar ko tas ir noderīgs.
* Aprakstiet Float parametru un to, kā tas strādā.
* Kādas ir dažādas Clear parametra lietošanas tehnikas un kādā kontekstā katra ir vispiemērotākā?
* Izskaidrojiet, kas ir CSS spraiti (sprites) un kā Jūs tos izmantotu lapā?
* Kāda ir Jūsu iecienītākā attēlu aizvietošanas tehnika un kādos brīžos Jūs to izmantojiet?
* CSS parametru hacki, nosacīti iekļauti .css faili vai kas cits?
* Kā Jūs servējat lapas priekš pārlūkiem ar ierobežotu funkcionalitāti?
  * Kādas tehnikas/procesu Jūs piekopjat?
* Kādi ir dažādi paņēmieni, kā vizuāli noslēpt saturu (un padarīt to pieejamu tikai priekš ekrāna lasītājiem)?
* Vai esat kādreiz izmantojis režģa (grid) sistēmu? Ja jā, tad kurai dodiet priekšroku?
* Vai esat izmantojis mediju vaicājumus (media queries) vai izkārtojumus(layouts)/CSS domātus speciāli priekš mobilajām iekārtām?
* Vai esat pazīstams ar SVG stilu definēšanu?
* Kā Jūs optimizējiet mājas lapas priekš printēšanas?
* Kādi ir dažādi triki un paņēmieni (kā arī ar ko der uzmanīties), lai veidotu efektīvu CSS?
* Kādi ir plusi/mīnusi izmantojot CSS preprocesorus? (SASS, Compass, Stylus, LESS)
  * Aprakstiet plusus un mīnusus tiem CSS preprocesoriem, kurus esiet izmantojis.
* Kā Jūs veidotu mājas lapas dizainu, kas izmanto nestandarta fontus?
  * Webonti (tādi fontu servisi kā Google Webfonts, Typekit u.c.)
* Izskaidrojiet kā pārlūks nosaka kuri elementi atbilst CSS selektoriem?
* Izskaidrojiet kā Jūs saprotiet "box model" un kā Jūs ar CSS palīdzību norādītu pārlūkam attēlot izkārtojumu(layout) ar dažādiem "box model" iestatījumiem.

####[[⬆]](#toc) JS Jautājumi:

* Izskaidrojiet notikumu deleģēšanu (event delegation)
* Izskaidrojiet kā `this` strādā JavaScript valodā
* Izskaidrojiet kā strādā prototipiskā mantošana?
* Kā Jūs testējat savu JavaScript kodu?
* AMD vai CommonJS?
* Kas ir asociatīvais masīvs (hashtable)?
* Paskaidrojiet kāpēc šis kods nestrādā kā IIFE: `function foo(){ }();`.
  * Kas ir jāpamaina, lai tā pareizi strādātu kā IIFE?
* Kāda ir atšķirība starp mainīgajiem, kas ir definēti kā: `null`, `undefined` or `undeclared`?
  * Kā jūs pārbaudītu vai mainīgais atbilst kādam no šiem stāvokļiem?
* Kas ir slēgums(closure) un kā/kāpēc Jūs tādu izmantotu?
* Kādos gadījumos parasti tiek izmantotas anonīmās funkcijas?
* Izskaidrojiet "JavaScript module pattern" un kādos gadījumos Jūs to izmantotu.
  * Bonus punkti, ja tiek pieminēta tīra nosaukumvietas uzturēšana (clean namespacing)
  * Gadījumā ja Jūsu moduļi neizmanto nosaukumvietu?
* Kā Jūs organizējat savu kodu? (Moduļu veidā, klasiskā mantošana?)
* Kāda ir atšķirība starp "host" objektiem un "native" objektiem?
* Kāda ir atšķirība starp: `function Person(){}`, `var person = Person()`, un `var person = new Person()`?
* Kāda ir atšķirība starp `.call` un `.apply`?
* Izskaidrojiet `Function.prototype.bind`?
* Kurā brīdī Jūs optimizējiet savu kodu?
* Vai variet izskaidrot kā JavaScript valodā strādā mantošana?
* Kādos gadījumos Jūs izmantotu `document.write()`?
  * Vairums reklāmas joprojām izmanto `document.write()` kaut arī šāda prakse tiek pelta.
* Kāda ir atšķirība starp funkciju noteikšanu (feature detection), funkciju secināšanu (feature inference) un UA virknes (UA string) izmantošanu?
* Izskaidrojiet AJAX cik vien detalizēti iespējams
* Izskaidrojiet kā stradā JSONP (un kā tas atšķiras no AJAX)
* Vai esat jebkad izmantojuši JavaScript šablonošanai (templating)?
  * Ja jā, kuras bibliotēkas Jūs esat izmantojuši? (Mustache.js, Handlebars etc.)
* Izskaidrojiet "hoisting"
* Izskaidrojiet notikumu burbuļošanu (event bubbling)
* Kāda ir atšķirība starp atribūtu un rekvizītu (property)?
* Kāpēc paplašināt iebūvētos JavaScript objektus nav laba doma?
* Kāpēc paplašināt "built ins" ir laba doma?
* Kāda ir atšķirība starp "document load" un "document ready" notikumu?
* Kāda ir atšķirība starp `==` un `===`?
* Paskaidrojiet kā Jūs iegūtu kverija stringa parametru no pārlūka loga URL?
* Izskaidrojiet vietējās izcelsmes (same-origin) noteikumu attiecībā uz JavaScript
* Izskaidrojiet mantošanas paternus JavaScript valodā.
* Lieciet šim strādāt:
```javascript
[1,2,3,4,5].duplicate(); // [1,2,3,4,5,1,2,3,4,5]
```
* Izskaidrojoet memoizācijas stratēģiju (izvairīšanos no aprēķinu atkārtošanas) JavaScript valodā.
* Kāpēc to sauc par ternāru izteiksmi (Ternary expression)? Uz ko norāda vārds ternārs?
* Kas ir funkcijas "arity"?
* Kas ir `"use strict";`? Kādas ir priekšrocības un trūkumi to izmantojot?

####[[⬆]](#toc) jQuery Jautājumi:

* Izskaidrojiet savirknēšanu (chaining).
* Izskaidrojiet novēlojumus (deferreds).
* Kādas ir jQuery specifiskas optimizācijas, ko Jūs spējat ieviest praksē?
* Ko veic `.end()`?
* Kā un kāpēc Jūs nosauktu pievienotu notikumu apdarinātāju (bound event handler)?
* Nosauciet 4 dažādas vērtības, ko Jūs varat padot jQuery metodei
  * Selektoru (virkne), HTML (virkne), atgriezenisko funkciju (funkcija), HTMLElement, Object, Array, Element Array, Jquery Object u.c.
* Kas ir efektu (vai fx) rinda?
* Kāda ir atšķirība starp `.get()`, `[]`, un `.eq()`?
* Kāda ir atšķirība starp `.bind()`, `.live()`, un `.delegate()`?
* Kāda ir atšķirība starp `$` un `$.fn`? Vai vienkārši kas ir `$.fn`?
* Optimizējiet šo selektoru
```javascript
$(".foo div#bar:eq(0)")
```

####[[⬆]](#toc) Kodēšanas Jautājumi:

```javascript
modulo(12, 5) // 2
```
*Jautājums: Izveidojiet modulo funkciju, kas apmierina augstākminēto*

```javascript
"i'm a lasagna hog".split("").reverse().join("");
```
*Jautājums: Kāda vērtība tiek atgriezta no augšākminētā koda?

**Atbilde: "goh angasal a m'i"**

```javascript
( window.foo || ( window.foo = "bar" ) );
```
*Jautājums: Kāda ir `window.foo` vērtība?*

**Atbilde: "bar"** *(vienīgi°ja `window.foo` "falsey", savādāk tas paturētu savu esošo vērtību)*

```javascript
var foo = "Hello"; (function() { var bar = " World"; alert(foo + bar); })(); alert(foo + bar);
```
*Jautājums: Kāds ir abu augstākminēto paziņojumu iznākums?*

**Atbilde: "Hello World" & ReferenceError: bar is not defined**

```javascript
var foo = [];
foo.push(1);
foo.push(2);
```
*Jautājums: Kāda ir `foo.length` vērtība?*

**Atbilde: `2`**

####[[⬆]](#toc) Interesanti Jautājumi:

* Kas ir pati foršākā lieta, ko jebkat esiet uzprogrammējis un ar ko lepojaties?
* Kuras ir Jūsu izstrādes rīku iemīļotākās funkcijas, kuras izmantojiet?
* Vai Jums ir kādi hobiju projekti? Kādi?
* Kāda ir Jūsu iecienītakā Internet Explorer raksturiezīme?

####[[⬆]](#toc) Citas Lieliskas Atsauces:

* http://programmers.stackexchange.com/questions/46716/what-technical-details-should-a-programmer-of-a-web-application-consider-before
* http://www.nczonline.net/blog/2010/01/05/interviewing-the-front-end-engineer/
* http://css-tricks.com/interview-questions-css/


text:
require 'spec_helper'

describe TWW::REST do
  include_examples 'client'

  shared_examples 'changeable endpoint' do |endpoint:, url:|
    subject { WebMock }

    before { TWW.config[:endpoint] = endpoint }

    describe 'deliver' do
      before { client.deliver(phone, message) }
      it { should have_requested(:post, /^#{url}/) }
    end
  end

  it_behaves_like 'changeable endpoint',
    endpoint: :primary,
    url: 'https://webservices.twwwireless.com.br'

  it_behaves_like 'changeable endpoint',
    endpoint: :secondary,
    url: 'https://webservices2.twwwireless.com.br'
end


text:
from ffmpymedia import __author__, __version__, __copyright__, __package__
from os.path import join as joinpath

import unittest

from ffmpymedia.media import *
from tests import TEST_FILE_PATH

class TestMediaStream(unittest.TestCase):
    """
    Testes de criação dos objetos de fluxo de mídia
    """

    def test_invalid_media_stream(self):
        self.assertIsNone(MediaStream())

    def test_invalid_media_stream2(self):
        self.assertIsNone(MediaStream(**{'type': 'Invalid'}))

    def test_video_stream_creation(self):
        self.assertIsInstance(MediaStream(**{'type': 'video'}), MediaStream)

    def test_video_stream_type_repr(self):
        self.assertEqual(repr(MediaStream(**{'type': 'video'})), "MediaStream(**{'type': 'video'})")

    def test_video_stream_repr2(self):
        self.assertDictEqual({'sample_format': 'yuv420p', 'width': '1920', 'type': 'video', 'profile': 'Main',
                              'codec': 'mpeg2video', 'height': '1080', 'metadata': {'encoder': 'FFMPEG'}},
                             MediaStream(**{'sample_format': 'yuv420p', 'width': '1920', 'type': 'video',
                                            'profile': 'Main', 'codec': 'mpeg2video', 'height': '1080',
                                            'metadata': {'encoder': 'FFMPEG'}}).__dict__)

    def test_video_stream_str(self):
        self.assertEqual(str(MediaStream(**{'sample_format': 'yuv420p', 'width': '1920', 'type': 'video',
                                            'profile': 'Main', 'codec': 'mpeg2video', 'height': '1080'})),
                         "video Stream: codec: mpeg2video, height: 1080, profile: Main, sample_format: yuv420p, "
                         "type: video, width: 1920")

    def test_audio_stream_creation(self):
        self.assertIsInstance(MediaStream(**{'type': 'audio'}), MediaStream)

    def test_audio_stream_type_repr(self):
        self.assertEqual(repr(MediaStream(**{'type': 'audio'})), "MediaStream(**{'type': 'audio'})")

    def test_image_stream_creation(self):
        self.assertIsInstance(MediaStream(**{'type': 'image'}), MediaStream)

    def test_image_stream_type_repr(self):
        self.assertEqual(repr(MediaStream(**{'type': 'image'})), "MediaStream(**{'type': 'image'})")

    def test_subtitle_stream_creation(self):
        self.assertIsInstance(MediaStream(**{'type': 'subtitle'}), MediaStream)

    def test_subtitle_type_repr(self):
        self.assertEqual(repr(MediaStream(**{'type': 'subtitle'})), "MediaStream(**{'type': 'subtitle'})")

    def test_data_stream_creation(self):
        self.assertIsInstance(MediaStream(**{'type': 'data'}), MediaStream)

    def test_data_type_repr(self):
        self.assertEqual(repr(MediaStream(**{'type': 'data'})), "MediaStream(**{'type': 'data'})")

    def test_attachment_stream_creation(self):
        self.assertIsInstance(MediaStream(**{'type': 'attachment'}), MediaStream)

    def test_attachment_type_repr(self):
        self.assertEqual(repr(MediaStream(**{'type': 'attachment'})), "MediaStream(**{'type': 'attachment'})")

class TestMediaStreamTemplate(unittest.TestCase):
    """
    Testes de criação dos objetos template de fluxo de mídia
    """

    def test_invalid_media_stream_template(self):
        self.assertIsNone(MediaStreamTemplate())

    def test_invalid_media_stream_template2(self):
        self.assertIsNone(MediaStream(**{'type': 'Invalid'}))

    def test_video_stream_template_creation(self):
        self.assertIsInstance(MediaStreamTemplate(**{'type': 'video'}), MediaStreamTemplate)

    def test_video_stream_template_type_repr(self):
        self.assertEqual(repr(MediaStreamTemplate(**{'type': 'video'})), "MediaStreamTemplate(**{'type': 'video'})")

    def test_video_stream_template_repr2(self):
        self.assertDictEqual({'sample_format': 'yuv420p', 'width': '1920', 'type': 'video', 'profile': 'Main',
                              'codec': 'mpeg2video', 'height': '1080'},
                             MediaStreamTemplate(**{'sample_format': 'yuv420p', 'width': '1920', 'type': 'video',
                                                    'profile': 'Main', 'codec': 'mpeg2video',
                                                    'height': '1080'}).__dict__)

    def test_audio_stream_template_creation(self):
        self.assertIsInstance(MediaStreamTemplate(**{'type': 'audio'}), MediaStreamTemplate)

    def test_audio_stream_template_type_repr(self):
        self.assertEqual(repr(MediaStreamTemplate(**{'type': 'audio'})), "MediaStreamTemplate(**{'type': 'audio'})")

    def test_video_stream_template_str(self):
        self.assertEqual(str(MediaStreamTemplate(**{'sample_format': 'yuv420p', 'width': '1920', 'type': 'video',
                                                    'profile': 'Main', 'codec': 'mpeg2video', 'height': '1080'})),
                         "video stream template: codec: mpeg2video, height: 1080, profile: Main, sample_format: "
                         "yuv420p, type: video, width: 1920")

    def test_image_stream_creation(self):
        self.assertIsInstance(MediaStreamTemplate(**{'type': 'image'}), MediaStreamTemplate)

    def test_image_stream_type_repr(self):
        self.assertEqual(repr(MediaStreamTemplate(**{'type': 'image'})), "MediaStreamTemplate(**{'type': 'image'})")

    def test_subtitle_stream_creation(self):
        self.assertIsInstance(MediaStreamTemplate(**{'type': 'subtitle'}), MediaStreamTemplate)

    def test_subtitle_type_repr(self):
        self.assertEqual(repr(MediaStreamTemplate(**{'type': 'subtitle'})),
                         "MediaStreamTemplate(**{'type': 'subtitle'})")

    def test_data_stream_creation(self):
        self.assertIsInstance(MediaStreamTemplate(**{'type': 'data'}), MediaStreamTemplate)

    def test_data_type_repr(self):
        self.assertEqual(repr(MediaStreamTemplate(**{'type': 'data'})), "MediaStreamTemplate(**{'type': 'data'})")

    def test_attachment_stream_creation(self):
        self.assertIsInstance(MediaStreamTemplate(**{'type': 'attachment'}), MediaStreamTemplate)

    def test_attachment_type_repr(self):
        self.assertEqual(repr(MediaStreamTemplate(**{'type': 'attachment'})),
                         "MediaStreamTemplate(**{'type': 'attachment'})")

class TestMediaStreamTemplateAnalysis(unittest.TestCase):
    """
    Testes das funcionalidades de análise dos templates de fluxos de mídia
    """

    def test_empty_template_equal1(self):
        """
        Deve retornar verdadeiro sempre pois o template não faz nenhuma exigência
        """
        self.assertTrue(MediaStreamTemplate(**{'type': 'video'}) == MediaStream(**{'type': 'video',
                                            'sample_format': 'yuv420p', 'width': '66718', 'height': '643816hsa',
                                            'blablabla': 'sakjhfashkjf'}))

    def test_minimal_template_equality(self):
        self.assertTrue(MediaStreamTemplate(**{'type': 'video'}) == MediaStream(**{'type': 'video',
                            'sample_format': 'yuv420p', 'width': '66718', 'height': '643816hsa',
                            'blablabla': 'sakjhfashkjf'}))

    def test_template_equality(self):
        """
        Testa um Template com todas as informações
        """
        self.assertTrue(MediaStreamTemplate(**{'sample_format': 'yuv420p', 'width': '1920', 'type': 'video',
                                               'profile': 'Main', 'codec': 'mpeg2video',
                                                'height': '1080'}) ==
        MediaStream(**{'sample_format': 'yuv420p', 'width': '1920', 'type': 'video', 'profile': 'Main',
                       'codec': 'mpeg2video', 'height': '1080'}))

    def test_full_template_equal2(self):
        self.assertTrue(MediaStreamTemplate(**{'sample_format': 'yuv420p', 'width': '1920', 'type': 'video',
                                               'profile': 'Main', 'codec': 'mpeg2video', 'height': '1080'}) ==\
            MediaStream(**{'sample_format': 'yuv420p', 'width': '1920', 'type': 'video', 'profile': 'Main',
                           'codec': 'mpeg2video', 'height': '1080'}))

    def test_full_template_equal3(self):
        """
        Testa Um media stream sem uma chave que esta no Template
        """
        self.assertFalse(MediaStreamTemplate(**{'sample_format': 'yuv420p', 'width': '1920', 'type': 'video',
                                               'profile': 'Main', 'codec': 'mpeg2video', 'height': '1080'}) ==\
            MediaStream(**{'sample_format': 'yuv420p', 'width': '1920', 'type': 'video',
                           'codec': 'mpeg2video', 'height': '1080'}))

    def test_stream_difference_with_different_height(self):
        """
        Testa um MediaFile diferente
        """
        self.assertTrue(MediaStreamTemplate(**{'sample_format': 'yuv420p', 'width': '1920', 'type': 'video',
                                               'profile': 'Main', 'codec': 'mpeg2video', 'height': '1080'}).
                        difference(MediaStream(**{'sample_format': 'yuv420p', 'width': '1280', 'type': 'video',
                                                  'profile': 'Main', 'codec': 'mpeg2video', 'height': '720'})))

    def test_stream_difference_with_equal_streams(self):
        """
        Testa a diferença
        """
        self.assertFalse(MediaStreamTemplate(**{'sample_format': 'yuv420p', 'width': '1920', 'type': 'video',
                                                'profile': 'Main', 'codec': 'mpeg2video', 'height': '1080',
                                                'metadata': {'title': 'Test with Metadata'},
                                                'disposition': {"default": 1, "dub": 0, "original": 0, "comment": 0,
                                                                "lyrics": 0, "karaoke": 0, "forced": 1,
                                                                "hearing_impaired": 0, "visual_impaired": 0,
                                                                "clean_effects": 0, "attached_pic": 0}}).
                         difference(MediaStream(**{'sample_format': 'yuv420p', 'width': '1920', 'type': 'video',
                                                   'profile': 'Main', 'codec': 'mpeg2video', 'height': '1080',
                                                   'metadata': {'title': 'Test with Metadata'},
                                                   'disposition': {"default": 1, "dub": 0, "original": 0, "comment": 0,
                                                                   "lyrics": 0, "karaoke": 0, "forced": 1,
                                                                   "hearing_impaired": 0, "visual_impaired": 0,
                                                                   "clean_effects": 0, "attached_pic": 0}})))

    def test_stream_difference_with_different_metadata(self):
        """
        Testa um MediaFile diferente
        """
        self.assertEqual(MediaStreamTemplate(**{'sample_format': 'yuv420p', 'width': '1920', 'type': 'video',
                                                'profile': 'Main', 'codec': 'mpeg2video', 'height': '1080',
                                                'metadata': {'title': 'Test with Metadata'},
                                                'disposition': {"default": 1, "dub": 0, "original": 0, "comment": 0,
                                                                "lyrics": 0, "karaoke": 0, "forced": 1,
                                                                "hearing_impaired": 0, "visual_impaired": 0,
                                                                "clean_effects": 0, "attached_pic": 0}}).
                         difference(MediaStream(**{'sample_format': 'yuv420p', 'width': '1920', 'type': 'video',
                                                   'profile': 'Main', 'codec': 'mpeg2video', 'height': '1080',
                                                   'metadata': {'title': 'Different Metadata!'},
                                                   'disposition': {"default": 1, "dub": 0, "original": 0, "comment": 0,
                                                                   "lyrics": 0, "karaoke": 0, "forced": 1,
                                                                   "hearing_impaired": 0, "visual_impaired": 0,
                                                                   "clean_effects": 0, "attached_pic": 0}}),
                                    include_metadata=True),
                         {'metadata': {'title': ('Different Metadata!', 'Test with Metadata')}})

    def test_stream_difference_with_different_dispositions(self):
        """
        Testa a diferença
        """
        self.assertEqual(MediaStreamTemplate(**{'sample_format': 'yuv420p', 'width': '1920', 'type': 'video',
                                                'profile': 'Main', 'codec': 'mpeg2video', 'height': '1080',
                                                'metadata': {'title': 'Test with Metadata'},
                                                'disposition': {"default": 1, "dub": 0, "original": 0, "comment": 0,
                                                                "lyrics": 0, "karaoke": 0, "forced": 1,
                                                                "hearing_impaired": 0, "visual_impaired": 0,
                                                                "clean_effects": 0, "attached_pic": 0}}).
                         difference(MediaStream(**{'sample_format': 'yuv420p', 'width': '1920', 'type': 'video',
                                                   'profile': 'Main', 'codec': 'mpeg2video', 'height': '1080',
                                                   'metadata': {'title': 'Test with Metadata'},
                                                   'disposition': {"default": 0, "dub": 0, "original": 0, "comment": 0,
                                                                   "lyrics": 0, "karaoke": 0, "forced": 1,
                                                                   "hearing_impaired": 0, "visual_impaired": 0,
                                                                   "clean_effects": 0, "attached_pic": 0}})),
                         {'disposition': {'default': (0, 1)}})

class TestMediaFileCreation(unittest.TestCase):
    """
    Testes das funcionalidades da classe MediaFile
    """
    def setUp(self):
        self.TEST_FILE = os.path.join(TEST_FILE_PATH, 'SIN001 Sinuca.mp4')

    def test_nonexistente_file(self):
        self.assertIsNone(MediaFile(**{'filename': 'NAOEXISTE'}))

    def test_insufficient_parameters(self):
        file_params = probe.MediaProbe.get_media_file_input_params(self.TEST_FILE)
        file_params.__delitem__('duration')
        self.assertIsNone(MediaFile(**file_params))


text:
class GroupUser < ActiveRecord::Base
  belongs_to :group, counter_cache: "user_count"
  belongs_to :user
end

# == Schema Information
#
# Table name: group_users
#
#  id         :integer          not null, primary key
#  group_id   :integer          not null
#  user_id    :integer          not null
#  created_at :datetime         not null
#  updated_at :datetime         not null
#
# Indexes
#
#  index_group_users_on_group_id_and_user_id  (group_id,user_id) UNIQUE
#


text:
{{+bindTo:partials.standard_nacl_article}}

Application Structure

Application components

HTML file and the <embed> element

Manifest Files

Modules and instances

Native Client modules: A closer look

This chapter of the Developer’s Guide describes the general structure of a
Native Client application. The chapter assumes you are familiar with the
material presented in the Technical Overview.

The “Hello, World” example is used here to illustrate basic
Native Client programming techniques. You can find this code in the
/getting_started/part1 directory in the Native Client SDK download.

Application components

A Native Client application typically contains the following components:

an HTML file;

JavaScript code, which can be included in the HTML file or contained in one or
more separate .js files;

CSS styles, which can be included in the HTML file or contained in one or more
separate .css files;

a Native Client manifest file (with a .nmf extension) that specifies how to
load a Native Client module for different processors; and

a Native Client module, written in C or C++, and compiled into a portable
executable file (with a .pexe extension) or (if using the Chrome Web Store),
architecture-specific executable files (with .nexe extensions).

Applications that are published in the Chrome Web Store
also include a Chrome
Web Store manifest file (manifest.json) and one or more icon files.

HTML file and the <embed> element

The <embed> element in an HTML file triggers the loading of a Native Client
module and specifies the rectangle on the web page that is managed by the
module. Here is the <embed> element from the “Hello, World” application:

<embed id="hello_tutorial"
  width=0 height=0
  src="hello_tutorial.nmf"
  type="application/x-pnacl" />

In the <embed> element:

name

is the DOM name attribute for the Native Client module
(“nacl_module” is often used as a convention)

id

specifies the DOM ID for the Native Client module

width, height

specify the size in pixels of the rectangle on the web page that is
managed by the Native Client module (if the module does not have a
visible area, these values can be 0)

src

refers to the Native Client manifest file that is used to determine
which version of a module to load based on the architecture of the
user’s computer (see the following section for more information)

type

specifies the MIME type of the embedded content; for Portable Native Client
modules the type must be “application/x-pnacl”. For architecture-specific
Native Client modules the type must be “application/x-nacl”

Manifest Files

Native Client applications have two types of manifest files: a Chrome Web Store
manifest file and a Native Client manifest file.

A Chrome Web Store manifest file is a file with information about a web
application that is published in the Chrome Web Store. This file, named
manifest.json, is required for applications that are published in the
Chrome Web Store. For more information about this file see Distributing
Your Application.  and the Chrome Web Store manifest file
format.

A Native Client manifest file is a file that specifies which Native Client
module (executable) to load. For PNaCl it specifies a single portable
executable; otherwise it specifies one for each of the supported end-user
computer architectures (for example x86-32, x86-64, or ARM). This file is
required for all Native Client applications. The extension for this file is
.nmf.

Manifest files for applications that use PNaCl are simple. Here is the manifest
for the hello world example:

{
  "program": {
    "portable": {
      "pnacl-translate": {
        "url": "hello_tutorial.pexe"
      }
    }
  }
}

For Chrome Web Store applications that do not use PNaCl, a typical manifest file
contains a JSON dictionary with a single top-level
key/value pair: the “program” key and a value consisting of a nested
dictionary. The nested dictionary contains keys corresponding to the names of
the supported computer architectures, and values referencing the file to load
for a given architecture—specifically, the URL of the .nexe file, given by the
"url" key. URLs are specified relative to the location of the manifest file.
Here is an example:

{
  "program": {
    "x86-32": {
      "url": "hello_tutorial_x86_32.nexe"
    },
    "x86-64": {
      "url": "hello_tutorial_x86_64.nexe"
    },
    "arm": {
      "url": "hello_tutorial_arm.nexe"
    }
  }
}

For applications that use the glibc
library, the manifest file must also contain a “files” key that specifies the
shared libraries that the applications use. This is discussed in detail in
Dynamic Linking and Loading with glibc. To
see some example manifest files, build some of the example applications in the
SDK (run make in the example subdirectories) and look at the generated
manifest files.

In most cases, you can simply use the Python script provided with the SDK,
create_nmf.py, to create a manifest file for your application as part of the
compilation step (see the Makefile in any of the SDK examples for an
illustration of how to do so). The manifest file format is also
documented.

Modules and instances

A Native Client module is C or C++ code compiled into a PNaCl .pexe file or
a NaCl .nexe file.

An instance is a rectangle on a web page that is managed by a module. An
instance may have a dimension of width=0 and height=0, meaning that the instance
does not have any visible component on the web page. An instance is created by
including an <embed> element in a web page. The <embed> element
references a Native Client manifest file that loads the appropriate version of
the module (either portable, or specific to the end-user’s architecture).  A
module may be included in a web page multiple times by using multiple
<embed> elements that refer to the module; in this case the Native Client
runtime system loads the module once and creates multiple instances that are
managed by the module.

Native Client modules: A closer look

A Native Client module must include three components:

a factory function called CreateModule()

a Module class (derived from the pp::Module class)

an Instance class (derived from the pp:Instance class)

In the “Hello tutorial” example (in the getting_started/part1 directory of
the NaCl SDK), these three components are specified in the file
hello_tutorial.cc. Here is the factory function:

Module* CreateModule() {
  return new HelloTutorialModule();
}

Native Client modules do not have a main() function. The CreateModule()
factory function is the main binding point between a module and the browser, and
serves as the entry point into the module. The browser calls CreateModule()
when a module is first loaded; this function returns a Module object derived
from the pp::Module class. The browser keeps a singleton of the Module
object.

Below is the Module class from the “Hello tutorial” example:

class HelloTutorialModule : public pp::Module {
 public:
  HelloTutorialModule() : pp::Module() {}
  virtual ~HelloTutorialModule() {}

  virtual pp::Instance* CreateInstance(PP_Instance instance) {
    return new HelloTutorialInstance(instance);
  }
};

The Module class must include a CreateInstance() method. The browser calls
the CreateInstance() method every time it encounters an <embed> element
on a web page that references the same module. The CreateInstance() function
creates and returns an Instance object derived from the pp::Instance class.

Below is the Instance class from the “Hello tutorial” example:

class HelloTutorialInstance : public pp::Instance {
 public:
  explicit HelloTutorialInstance(PP_Instance instance) : pp::Instance(instance) {}
  virtual ~HelloTutorialInstance() {}

  virtual void HandleMessage(const pp::Var& var_message) {}
};

As in the example above, the Instance class for your module will likely include
an implementation of the HandleMessage() function. The browser calls an
instance’s HandleMessage() function every time the JavaScript code in an
application calls postMessage() to send a message to the instance. See the
Native Client messaging system for more information about
how to send messages between JavaScript code and Native Client modules.

The NaCl code is only invoked to handle various browser-issued
events and callbacks. There is no need to shut down the NaCl instance by
calling the exit() function. NaCl modules will be shut down when the user
leaves the web page, or the NaCl module’s <embed> is otherwise destroyed.
If the NaCl module does call the exit() function, the instance will
issue a crash event
which can be handled in Javascript.

While the CreateModule() factory function, the Module class, and the
Instance class are required for a Native Client application, the code
samples shown above don’t actually do anything. Subsequent chapters in the
Developer’s Guide build on these code samples and add more interesting
functionality.

{{/partials.standard_nacl_article}}


text:
package com.natepaulus.dailyemail.web.service.interfaces;

import com.natepaulus.dailyemail.web.domain.EmailData;

// TODO: Auto-generated Javadoc
/**
 * The Interface EmailService.
 */
public interface EmailService {

	/**
	 * This method uses the spring task scheduler functionality to run once
	 * every minute and gets all the users that would like their email delivered
	 * at the current time in one minute increments.
	 */
	public void retrieveUserListForEmails();

	/**
	 * Generate quick view page.
	 *
	 * @param code the code
	 * @return the data
	 */
	public EmailData generateQuickView(String code);

	/**
	 * Retry sending failed messages.
	 */
	public void retrySendingFailedMessages();

}