text:
using Breeze.WebApi;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Web.Http.OData.Query;

namespace Breeze.WebApi.NH
{
    /// <summary>
    /// Applies the BreezeNHQueryableAttribute to all controller methods except those
    /// that already have a QueryableAttribute or an ODataQueryOptions parameter.
    /// </summary>
    [AttributeUsage(AttributeTargets.Class)]
    public class BreezeNHControllerAttribute : BreezeControllerAttribute
    {
        internal BreezeQueryableAttribute nhFilter = new BreezeNHQueryableAttribute();

        protected override IFilterProvider GetQueryableFilterProvider(BreezeQueryableAttribute defaultFilter)
        {
            return new BreezeNHQueryableFilterProvider(nhFilter);
        }

    }

    internal class BreezeNHQueryableFilterProvider : IFilterProvider
    {
        public BreezeNHQueryableFilterProvider(BreezeQueryableAttribute filter)
        {
            _filter = filter;
        }

        public IEnumerable<FilterInfo> GetFilters(HttpConfiguration configuration, HttpActionDescriptor actionDescriptor)
        {
            if (actionDescriptor == null ||
              actionDescriptor.GetCustomAttributes<QueryableAttribute>().Any() || // if method already has a QueryableAttribute (or subclass) then skip it.
              actionDescriptor.GetParameters().Any(parameter => typeof(ODataQueryOptions).IsAssignableFrom(parameter.ParameterType))
            )
            {
                return Enumerable.Empty<FilterInfo>();
            }

            return new[] { new FilterInfo(_filter, FilterScope.Global) };
        }

        private readonly BreezeQueryableAttribute _filter;
    }

}


text:
import datetime
import logging
import time

import usb
# import usb.util

from src.common.database import db
from src.models.timedb.timedb import TimeDbModel

# TODO How to interupt while loop when running?

class Timy(object):
    """Class responsible for communication with the ALGE TIMY 3
    """
    TIMY_VEND = 0x0c4a  # USB Vendor ID
    TIMY_PROD = 0x0889  # USB Product ID
    READEP = 0x81  # Interrupt input endpoint ID
    WRITEEP = 0x01  # Interrupt output endpoint ID
    CMDS_ALL = ['TIMYINIT', 'NSF', 'KL0', 'CHK1', 'PRE4',
            'RR0', 'BE1', 'DTS00.02', 'DTF00.02', 'EMU0',
            'PRIIGN1', 'PRILF', 'DTP------------',
            'PS1', 'PROG', 'CLR',
            ]
    CMDS= ['TIMYINIT', 'EMU0', 'CLR']

    def __init__(self, timeout=720000, logging=True, logfile="timylog.txt"):
        self.logging = logging
        self.logfile = logfile
        self.timeout = timeout
        self.device_handle = None
        self.kill = False

        if self.logging:
            Timy.logging_init(self.logfile)

        self.find_device()

    def find_device(self):
        """Verifies if ALGE TIMY3 USB device is connected."""

        self.device_handle = usb.core.find(
            idVendor=Timy.TIMY_VEND,
            idProduct=Timy.TIMY_PROD)

        if self.device_handle is None:
            logging.error("ALGE TIMY3 not found. Time capture not possible.")
            return False

        self.device_handle.set_configuration()

    def capture_start(self):
        """Starts neverending loop, listens what is received and save received times to the database."""

        if self.device_handle is None:
            logging.error("ALGE TIMY3 not found. Time capture not possible.")
            return False

        self.kill = False
        self.device_handle.write(Timy.WRITEEP, '\r')
        try:
            while True:
                if self.kill:
                    print("stopping the loop")
                    break
                try:
                    if len(Timy.CMDS) > 0:
                        cmd = Timy.CMDS.pop(0)
                        self.device_handle.write(Timy.WRITEEP, cmd + '\r')
                        print(bytearray(self.device_handle.read(Timy.READEP, 32, timeout=self.timeout)))

                    received = bytearray(self.device_handle.read(
                                        Timy.READEP,
                                        32,
                                        timeout=self.timeout))\
                        .decode("UTF-8")

                    print(received)
                    time_received = received.split()

                    if len(time_received) == 4:
                        if time_received[1] == "c1M":
                            print(time_received)
                            logging.debug("Received values: %s - %s - %s - %s", *time_received)
                            if self._save_to_db(time_received[2], time_received[3]):
                                logging.debug("Time saved to the database")
                            else:
                                logging.error("Problem with saving to the database")
                    else:
                        print(time_received)
                    time.sleep(0.1)

                except usb.core.USBError as e:
                    if e.args[0] == 60:
                        # To capture usb.core.USBError timeout exception raised after TIMEOUT expires with the code 60
                        # usb.core.USBError: [Errno 60] Operation timed out
                        print("Timeout exception occured.")
                        logging.warning(
                            "Configured timeout %s msec has expired. Recommendation: Increase its value.",
                            self.timeout)
                        pass

                    if e.args[0] == 19:
                        # Device has been disconnected
                        # usb.core.USBError: [Errno 19] No such device (it may have been disconnected)
                        print("Timeout exception occured.")
                        logging.error(
                            "ALGE TIMY USB device has been disconnected",
                            self.timeout)
                        break
                    else:
                        raise e
        finally:
            print("device reset - ending the loop")
            self.device_handle.reset()

    def capture_stop(self):
        """By calling this method, the neverending loop should be terminated"""
        # TODO it does not work yet. Figure out how to stop the loop.

        if self.device_handle is None:
            logging.error("ALGE TIMY3 not found. Time capture not possible.")
            return False

        self.kill = True

    def _save_to_db(self, timy_time_format, order_number):
        """Save the time to the database."""
        try:
            deltatime = Timy.convert_time_to_delta(timy_time_format)
            record = TimeDbModel(deltatime, order_number)
            record.save_to_db()
        except:
            return False
        return True

    @staticmethod
    def logging_init(logfile):
        """Initialize logging for debuggin purposes."""

        logging.basicConfig(filename=logfile,
                            format='%(asctime)s %(levelname)s %(message)s',
                            level=logging.DEBUG)

    @staticmethod
    def convert_time_to_delta(input_value):
        """Function coverts string into to the time.timedelta object for database storage.

        :param input_value: (str) example: 00:00:10.82
        :return: deltatime
        """
        epoch = datetime.datetime.utcfromtimestamp(0)

        time_entered = input_value.strip()
        datetime_composite = "1 Jan 1970 {}".format(time_entered)
        time_converted = datetime.datetime.strptime(datetime_composite, '%d %b %Y %H:%M:%S.%f')
        delta_time = time_converted - epoch
        return delta_time

def main():
    timy = Timy()
    timy.capture_start()
    timy.capture_stop()

if __name__ == "__main__":
    main()

redpajama_set_name: RedPajamaGithub


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

<title>LayoutStyle (Java Platform SE 8 )</title>
<meta name="date" content="2014-12-17">
<meta name="keywords" content="javax.swing.LayoutStyle class">
<meta name="keywords" content="setInstance()">
<meta name="keywords" content="getInstance()">
<meta name="keywords" content="getPreferredGap()">
<meta name="keywords" content="getContainerGap()">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

javax.swing

Class LayoutStyle

java.lang.Object

javax.swing.LayoutStyle

public abstract class LayoutStyle
extends Object

LayoutStyle provides information about how to position
 components.  This class is primarily useful for visual tools and
 layout managers.  Most developers will not need to use this class.

 You typically don't set or create a
 LayoutStyle.  Instead use the static method
 getInstance to obtain the current instance.

Since:

1.6

Nested Class Summary

Nested Classes

Modifier and Type
Class and Description

static class
LayoutStyle.ComponentPlacement

ComponentPlacement is an enumeration of the
 possible ways two components can be placed relative to each
 other.

Constructor Summary

Constructors

Constructor and Description

LayoutStyle()

Creates a new LayoutStyle.

Method Summary

All Methods Static Methods Instance Methods Abstract Methods Concrete Methods

Modifier and Type
Method and Description

abstract int
getContainerGap(JComponent component,
               int position,
               Container parent)

Returns the amount of space to place between the component and specified
 edge of its parent.

static LayoutStyle
getInstance()

Returns the shared instance of LayoutStyle.

abstract int
getPreferredGap(JComponent component1,
               JComponent component2,
               LayoutStyle.ComponentPlacement type,
               int position,
               Container parent)

Returns the amount of space to use between two components.

static void
setInstance(LayoutStyle style)

Sets the shared instance of LayoutStyle.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

LayoutStyle

public LayoutStyle()

Creates a new LayoutStyle.  You generally don't
 create a LayoutStyle.  Instead use the method
 getInstance to obtain the current
 LayoutStyle.

Method Detail

setInstance

public static void setInstance(LayoutStyle style)

Sets the shared instance of LayoutStyle.  Specifying
 null results in using the LayoutStyle from
 the current LookAndFeel.

Parameters:

style - the LayoutStyle, or null

See Also:

getInstance()

getInstance

public static LayoutStyle getInstance()

Returns the shared instance of LayoutStyle.  If an instance
 has not been specified in setInstance, this will return
 the LayoutStyle from the current LookAndFeel.

Returns:

the shared instance of LayoutStyle

See Also:

LookAndFeel.getLayoutStyle()

getPreferredGap

public abstract int getPreferredGap(JComponent component1,
                                    JComponent component2,
                                    LayoutStyle.ComponentPlacement type,
                                    int position,
                                    Container parent)

Returns the amount of space to use between two components.
 The return value indicates the distance to place
 component2 relative to component1.
 For example, the following returns the amount of space to place
 between component2 and component1
 when component2 is placed vertically above
 component1:

   int gap = getPreferredGap(component1, component2,
                             ComponentPlacement.RELATED,
                             SwingConstants.NORTH, parent);

 The type parameter indicates the relation between
 the two components.  If the two components will be contained in
 the same parent and are showing similar logically related
 items, use RELATED.  If the two components will be
 contained in the same parent but show logically unrelated items
 use UNRELATED.  Some look and feels may not
 distinguish between the RELATED and
 UNRELATED types.

 The return value is not intended to take into account the
 current size and position of component2 or
 component1.  The return value may take into
 consideration various properties of the components.  For
 example, the space may vary based on font size, or the preferred
 size of the component.

Parameters:

component1 - the JComponent
               component2 is being placed relative to

component2 - the JComponent being placed

position - the position component2 is being placed
        relative to component1; one of
        SwingConstants.NORTH,
        SwingConstants.SOUTH,
        SwingConstants.EAST or
        SwingConstants.WEST

type - how the two components are being placed

parent - the parent of component2; this may differ
        from the actual parent and it may be null

Returns:

the amount of space to place between the two components

Throws:

NullPointerException - if component1,
         component2 or type is
         null

IllegalArgumentException - if position is not
         one of SwingConstants.NORTH,
         SwingConstants.SOUTH,
         SwingConstants.EAST or
         SwingConstants.WEST

Since:

1.6

See Also:

LookAndFeel.getLayoutStyle()

getContainerGap

public abstract int getContainerGap(JComponent component,
                                    int position,
                                    Container parent)

Returns the amount of space to place between the component and specified
 edge of its parent.

Parameters:

component - the JComponent being positioned

position - the position component is being placed
        relative to its parent; one of
        SwingConstants.NORTH,
        SwingConstants.SOUTH,
        SwingConstants.EAST or
        SwingConstants.WEST

parent - the parent of component; this may differ
        from the actual parent and may be null

Returns:

the amount of space to place between the component and specified
         edge

Throws:

IllegalArgumentException - if position is not
         one of SwingConstants.NORTH,
         SwingConstants.SOUTH,
         SwingConstants.EAST or
         SwingConstants.WEST

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

 Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
 Copyright © 1993, 2015, Oracle and/or its affiliates.  All rights reserved.


text:
__credits__ = "https://github.com/biocore/micronota/graphs/contributors"
__version__ = "1.0.dev0"

from .format import cmscan, sam, aragorn, rnammer, transtermhp, tandem_repeats_finder  # noqa


text:
package com.example.padlabear.hw;

import com.example.padlabear.hw.http.HttpClient;
import com.example.padlabear.hw.json.gson.GsonUser;
import com.example.padlabear.hw.json.gson.GsonUserList;
import com.example.padlabear.hw.json.gson.GsonUserListParser;
import com.example.padlabear.hw.json.gson.GsonUserParser;
import com.example.padlabear.hw.json.jsonObject.JsonUser;
import com.example.padlabear.hw.json.jsonObject.JsonUserList;
import com.example.padlabear.hw.json.jsonObject.JsonUserListParser;
import com.example.padlabear.hw.json.jsonObject.JsonUserParser;
import com.example.padlabear.hw.util.DateUtil;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

import java.text.ParseException;
import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

@RunWith(RobolectricTestRunner.class)
@Config(
        constants = BuildConfig.class,
        sdk = Constants.SDK_VERSION
)
public class UserParseTest {

    private static final String USER_USER_LIST_JSON = "user/userList.json";
    private static final String USER_USER_JSON = "user/user.json";
    private HttpClient httpClient;
    private String sourceArray;
    private String source;

    @Before
    public void setUp() throws Exception {
        httpClient = mock(HttpClient.class);
        sourceArray = Mocks.stream(USER_USER_LIST_JSON);
        source = Mocks.stream(USER_USER_JSON);
    }

    @Test
    public void parseGsonUserTest() throws Exception {
        when(httpClient.request(anyString())).thenReturn(source);
        final String response = httpClient.request("http://api/someResourse");
        final GsonUser parseResult = new GsonUserParser(response).parse();
        assertNotNull(parseResult);
        checkGsonUser(parseResult);
    }

    @Test
    public void parseGsonUsersTest() throws Exception {
        when(httpClient.request(anyString())).thenReturn(sourceArray);
        final String response = httpClient.request("http://api/someResourse");
        final GsonUserList parseResult = new GsonUserListParser(response).parse();
        assertNotNull(parseResult);
        final List<GsonUser> users = parseResult.getUsers();
        assertEquals(3, users.size());
        final GsonUser user = users.iterator().next();
        checkGsonUser(user);
    }

    @Test
    public void parseJsonUserTest() throws Exception {
        when(httpClient.request(anyString())).thenReturn(source);
        final String response = httpClient.request("http://api/someResourse");
        final JsonUser parseResult = new JsonUserParser(response).parse();
        assertNotNull(parseResult);
        checkJsonUser(parseResult);
    }

    @Test
    public void parseJsonUsersTest() throws Exception {
        when(httpClient.request(anyString())).thenReturn(sourceArray);
        final String response = httpClient.request("http://api/someResourse");
        final JsonUserList parseResult = new JsonUserListParser(response).parse();
        assertNotNull(parseResult);
        final List<JsonUser> users = parseResult.getUsers();
        assertEquals(3, users.size());
        final JsonUser user = users.iterator().next();
        checkJsonUser(user);
    }

    private void checkGsonUser(final GsonUser user) throws ParseException {
        assertEquals("Jon", user.getFirstName());
        assertEquals("Snow", user.getLastName());
        assertEquals("25", user.getAge());
        assertEquals("Winterfall", user.getLocation());
        assertEquals(DateUtil.getDate("10/10/1900"), user.getRegistered());
    }

    private void checkJsonUser(final JsonUser user) throws Exception {
        assertEquals("Jon", user.getFirstName());
        assertEquals("Snow", user.getLastName());
        assertEquals("25", user.getAge());
        assertEquals("Winterfall", user.getLocation());
        assertEquals(DateUtil.getDate("10/10/1900"), user.getRegistered());
    }
}


text:
import {ComponentFactory, ComponentFactoryResolver, Injector, Type} from '@angular/core';

import * as angular from '../angular_js';

import {$INJECTOR, $PARSE, INJECTOR_KEY, REQUIRE_NG1_MODEL} from './constants';
import {DowngradeComponentAdapter} from './downgrade_component_adapter';

let downgradeCount = 0;

/**
 * @whatItDoes
 *
 * *Part of the [upgrade/static](/docs/ts/latest/api/#!?query=upgrade%2Fstatic)
 * library for hybrid upgrade apps that support AoT compilation*
 *
 * Allows an Angular component to be used from AngularJS.
 *
 * @howToUse
 *
 * Let's assume that you have an Angular component called `ng2Heroes` that needs
 * to be made available in AngularJS templates.
 *
 * {@example upgrade/static/ts/module.ts region="ng2-heroes"}
 *
 * We must create an AngularJS [directive](https://docs.angularjs.org/guide/directive)
 * that will make this Angular component available inside AngularJS templates.
 * The `downgradeComponent()` function returns a factory function that we
 * can use to define the AngularJS directive that wraps the "downgraded" component.
 *
 * {@example upgrade/static/ts/module.ts region="ng2-heroes-wrapper"}
 *
 * In this example you can see that we must provide information about the component being
 * "downgraded". This is because once the AoT compiler has run, all metadata about the
 * component has been removed from the code, and so cannot be inferred.
 *
 * We must do the following:
 * * specify the Angular component class that is to be downgraded
 * * specify all inputs and outputs that the AngularJS component expects
 *
 * @description
 *
 * A helper function that returns a factory function to be used for registering an
 * AngularJS wrapper directive for "downgrading" an Angular component.
 *
 * The parameter contains information about the Component that is being downgraded:
 *
 * * `component: Type<any>`: The type of the Component that will be downgraded
 * * `inputs: string[]`: A collection of strings that specify what inputs the component accepts.
 * * `outputs: string[]`: A collection of strings that specify what outputs the component emits.
 *
 * The `inputs` and `outputs` are strings that map the names of properties to camelCased
 * attribute names. They are of the form `"prop: attr"`; or simply `"propAndAttr" where the
 * property and attribute have the same identifier.
 *
 * @experimental
 */
export function downgradeComponent(info: /* ComponentInfo */ {
  component: Type<any>;
  inputs?: string[];
  outputs?: string[];
}): any /* angular.IInjectable */ {
  const idPrefix = `NG2_UPGRADE_${downgradeCount++}_`;
  let idCount = 0;

  const directiveFactory:
      angular.IAnnotatedFunction = function(
                                       $injector: angular.IInjectorService,
                                       $parse: angular.IParseService): angular.IDirective {

    return {
      restrict: 'E',
      require: ['?^' + INJECTOR_KEY, REQUIRE_NG1_MODEL],
      link: (scope: angular.IScope, element: angular.IAugmentedJQuery, attrs: angular.IAttributes,
             required: any[], transclude: angular.ITranscludeFunction) => {

        let parentInjector: Injector = required[0];
        if (parentInjector === null) {
          parentInjector = $injector.get(INJECTOR_KEY);
        }

        const ngModel: angular.INgModelController = required[1];
        const componentFactoryResolver: ComponentFactoryResolver =
            parentInjector.get(ComponentFactoryResolver);
        const componentFactory: ComponentFactory<any> =
            componentFactoryResolver.resolveComponentFactory(info.component);

        if (!componentFactory) {
          throw new Error('Expecting ComponentFactory for: ' + info.component);
        }

        const facade = new DowngradeComponentAdapter(
            idPrefix + (idCount++), info, element, attrs, scope, ngModel, parentInjector, $parse,
            componentFactory);
        facade.setupInputs();
        facade.createComponent();
        facade.projectContent();
        facade.setupOutputs();
        facade.registerCleanup();
      }
    };
  };

  directiveFactory.$inject = [$INJECTOR, $PARSE];
  return directiveFactory;
}


text:
build/
  ├── exe.<platform>-<python version>/
  ├── README.md <- The file you are reading.
  ├── resources/
  └── scripts/
         └──compile_ui.py

### exe.<platform>-<python version>/

A set of folders containing all final bundled executables created by cx_freeze in the build process.

Built for a  64 bit linux machine with python3.3 this will look like:

```exe.linux-x86_64-3.3```

These folders are not tracked by version control

### scripts/

All scripts used by the build process

### resources/

All resources created during the build process.

This includes:
  * All bundled extensions
  * Compiled assets file ( commotion_assets_rc.py )

This folder is not tracked by version control

## cx_freeze instructions

### Get cx_freeze

To build cross platform images we use the [cx_freeze](http://cx-freeze.sourceforge.net/) tool.

To install cx_freeze you can [download](http://cx-freeze.sourceforge.net/index.html) it or [build it](http://cx-freeze.sourceforge.net/index.html) from source using the README provided upon downloading it.

#### Fixing Build Errors

  * I can't build cx_freeze.

If you encounter an error like the one below it could be that the version of python you are using was compiled without a shared library.

```
/usr/bin/ld: cannot find -lpython3.3
collect2: error: ld returned 1 exit status
error: command 'gcc' failed with exit status 1
```

You will want to reconfigure & install your version of python using the following option.

```
./configure --enable-shared
```

  * python3.3 does not work when I re-compile it with enable-shared

If you are using python3.3, which is the version of python being used for this project you may have some problems with runing python3.3 after compiling it with enable-shared. The solution to this is to edit /etc/ld.so.conf or create something in /etc/ld.so.conf.d/ to add /usr/local/lib and /usr/local/lib64. Then run ldconfig.

### Preparing the project for building

#### Adding Extensions to Builds

Extensions are built-in to the Commotion client by adding them to the extension folder and then adding that folder name to the core_extensions list in the setup.py.

```
core_extensions = ["config_editor", "main_window", "your_extension_name"]
```

### Creating an executable

Linux:
  * go to the root directory of the project.
  * type ```make linux```
  * The executables folder will be created in the build directory.
  * run the ```Commotion``` executable in the executables folder.

### The setup script

The setup.py script in the root directory is not a traditional distutils setup.py script. It is actually a customized cx_freeze setup script. You can find documentation for it on the [cx_freeze docs site](http://cx-freeze.readthedocs.org/en/latest/distutils.html) and a searchable mailing list on [sourceforge](http://sourceforge.net/p/cx-freeze/mailman/cx-freeze-users/).


text:
var express = require('express'),
    router = express.Router();
var fbMessenger = require('./index');

router.get('/webhook', function(req, res) {
    if (req.query['hub.mode'] === 'subscribe' &&
        req.query['hub.verify_token'] === 'my-secret') {
        console.log("Validating webhook");
        res.status(200).send(req.query['hub.challenge']);
    } else {
      console.error("Failed validation. Make sure the validation tokens match.");
      res.sendStatus(403);
    }
});

router.post('/webhook', function (req, res) {
  var data = req.body;

  // Make sure this is a page subscription
  if (data.object == 'page') {
    // Iterate over each entry
    // There may be multiple if batched
    data.entry.forEach(function(pageEntry) {
      var pageID = pageEntry.id;
      var timeOfEvent = pageEntry.time;

      // Iterate over each messaging event
      pageEntry.messaging.forEach(function(messagingEvent) {
        if (messagingEvent.optin) {
          // receivedAuthentication(messagingEvent);
        } else if (messagingEvent.message) {
          fbMessenger.receivedMessage(messagingEvent);
        } else if (messagingEvent.delivery) {
          fbMessenger.receivedDeliveryConfirmation(messagingEvent);
        } else if (messagingEvent.postback) {
          fbMessenger.receivedPostback(messagingEvent);
        } else {
          console.log("Webhook received unknown messagingEvent: ", messagingEvent);
        }
      });
    });
    res.sendStatus(200);
  }
});

module.exports = router;


text:
package org.arquillian.cube.kubernetes.impl;

import io.fabric8.kubernetes.api.model.v3_1.Endpoints;
import io.fabric8.kubernetes.api.model.v3_1.EndpointsBuilder;
import io.fabric8.kubernetes.api.model.v3_1.EndpointsListBuilder;
import io.fabric8.kubernetes.api.model.v3_1.NamespaceBuilder;
import io.fabric8.kubernetes.api.model.v3_1.Pod;
import io.fabric8.kubernetes.api.model.v3_1.PodBuilder;
import io.fabric8.kubernetes.api.model.v3_1.PodListBuilder;
import io.fabric8.kubernetes.api.model.v3_1.ReplicationController;
import io.fabric8.kubernetes.api.model.v3_1.ReplicationControllerBuilder;
import io.fabric8.kubernetes.api.model.v3_1.ReplicationControllerListBuilder;
import io.fabric8.kubernetes.api.model.v3_1.Service;
import io.fabric8.kubernetes.api.model.v3_1.ServiceBuilder;
import io.fabric8.kubernetes.api.model.v3_1.ServiceListBuilder;
import io.fabric8.kubernetes.api.model.v3_1.WatchEvent;
import io.fabric8.kubernetes.api.model.v3_1.extensions.ReplicaSetBuilder;
import io.fabric8.kubernetes.clnt.v3_1.Config;
import io.fabric8.kubernetes.clnt.v3_1.server.mock.KubernetesMockServer;

import java.io.IOException;
import org.arquillian.cube.kubernetes.api.Configuration;
import org.arquillian.cube.kubernetes.impl.requirement.RequiresKubernetes;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@Suite.SuiteClasses(
    {
        PodInjection.class,
        ReplicationControllerInjection.class,
        ServiceInjection.class,
    }
)
@RequiresKubernetes
public class MockTest {

    private static final KubernetesMockServer MOCK = new KubernetesMockServer();

    @BeforeClass
    public static void setUpClass() throws IOException {

        Pod testPod = new PodBuilder()
            .withNewMetadata()
            .withName("test-pod")
            .endMetadata()
            .withNewStatus()
            .withPhase("Running")
            .addNewCondition()
            .withType("Ready")
            .withStatus("True")
            .endCondition()
            .endStatus()
            .build();

        Pod testPodInSecondaryNamespace = new PodBuilder()
            .withNewMetadata()
            .withName("test-pod-second")
            .withNamespace("test-secondary-namespace")
            .endMetadata()
            .withNewStatus()
            .withPhase("Running")
            .addNewCondition()
            .withType("Ready")
            .withStatus("True")
            .endCondition()
            .endStatus()
            .build();

        Service testService = new ServiceBuilder()
            .withNewMetadata()
            .withName("test-service")
            .endMetadata()
            .withNewSpec()
            .withClusterIP("10.0.0.1")
            .addNewPort()
            .withPort(8080)
            .endPort()
            .endSpec()
            .build();

        Service testServiceInSecondaryNamespace = new ServiceBuilder()
            .withNewMetadata()
            .withName("test-service-second")
            .withNamespace("test-secondary-namespace")
            .endMetadata()
            .withNewSpec()
            .withClusterIP("10.0.0.1")
            .addNewPort()
            .withPort(8080)
            .endPort()
            .endSpec()
            .build();

        Endpoints testEndpoints = new EndpointsBuilder()
            .withNewMetadata()
            .withName("test-service")
            .endMetadata()
            .build();

        Endpoints readyTestEndpoints = new EndpointsBuilder()
            .withNewMetadata()
            .withName("test-service")
            .withResourceVersion("2")
            .endMetadata()
            .addNewSubset()
            .addNewAddress()
            .withHostname("testhostname")
            .endAddress()
            .addNewPort()
            .withName("http")
            .withPort(8080)
            .endPort()
            .endSubset()
            .build();

        ReplicationController testController = new ReplicationControllerBuilder()
            .withNewMetadata()
            .withName("test-controller")
            .endMetadata()
            .withNewSpec()
            .addToSelector("name", "somelabel")
            .withReplicas(1)
            .withNewTemplate()
            .withNewMetadata()
            .addToLabels("name", "somelabel")
            .endMetadata()
            .withNewSpec()
            .addNewContainer()
            .withName("test-container2")
            .withImage("test/image2")
            .endContainer()
            .endSpec()
            .endTemplate()
            .endSpec()
            .withNewStatus()
            .withReplicas(1)
            .withReadyReplicas(1)
            .endStatus()
            .build();

        ReplicationController testControllerInSecondaryNamespace = new ReplicationControllerBuilder()
            .withNewMetadata()
            .withName("test-controller-second")
            .withNamespace("test-secondary-namespace")
            .endMetadata()
            .withNewSpec()
            .addToSelector("name", "somelabel")
            .withReplicas(1)
            .withNewTemplate()
            .withNewMetadata()
            .addToLabels("name", "somelabel")
            .endMetadata()
            .withNewSpec()
            .addNewContainer()
            .withName("test-container2")
            .withImage("test/image2")
            .endContainer()
            .endSpec()
            .endTemplate()
            .endSpec()
            .withNewStatus()
            .withReplicas(1)
            .withReadyReplicas(1)
            .endStatus()
            .build();

        MOCK.expect().get().withPath("/api/v1/namespaces/arquillian").andReturn(200, new NamespaceBuilder()
            .withNewMetadata()
            .withName("arquillian")
            .and().build()).always();

        //test-controller
        MOCK.expect()
            .post()
            .withPath("/api/v1/namespaces/arquillian/replicationcontrollers")
            .andReturn(201, testController)
            .always();
        MOCK.expect()
            .get()
            .withPath("/api/v1/namespaces/arquillian/replicationcontrollers/test-controller")
            .andReturn(404, "")
            .once();
        MOCK.expect()
            .get()
            .withPath("/api/v1/namespaces/arquillian/replicationcontrollers/test-controller")
            .andReturn(200, testController)
            .always();
        MOCK.expect()
            .get()
            .withPath("/api/v1/namespaces/arquillian/replicationcontrollers")
            .andReturn(200, new ReplicationControllerListBuilder()
                .withNewMetadata()
                .withResourceVersion("1")
                .endMetadata()
                .withItems(testController).build())
            .always();

        MOCK.expect()
            .delete()
            .withPath("/api/v1/namespaces/arquillian/replicationcontrollers/test-controller")
            .andReturn(200, "")
            .always();

        //test-controller-second in secondary namespace test-secondary-namespace
        MOCK.expect()
            .get()
            .withPath("/api/v1/namespaces/test-secondary-namespace/replicationcontrollers/test-controller-second")
            .andReturn(200, testControllerInSecondaryNamespace)
            .always();
        MOCK.expect()
            .get()
            .withPath("/api/v1/namespaces/test-secondary-namespace/replicationcontrollers")
            .andReturn(200, new ReplicationControllerListBuilder()
                .withNewMetadata()
                .withResourceVersion("1")
                .endMetadata()
                .withItems(testControllerInSecondaryNamespace).build())
            .always();

        //test-pod
        MOCK.expect().post().withPath("/api/v1/namespaces/arquillian/pods").andReturn(201, testPod).always();
        MOCK.expect().get().withPath("/api/v1/namespaces/arquillian/pods/test-pod").andReturn(404, "").once();
        MOCK.expect().get().withPath("/api/v1/namespaces/arquillian/pods/test-pod").andReturn(200, testPod).always();
        MOCK.expect().get().withPath("/api/v1/namespaces/arquillian/pods").andReturn(200, new PodListBuilder()
            .withNewMetadata()
            .withResourceVersion("1")
            .endMetadata()
            .withItems(testPod)
            .build()).always();
        MOCK.expect().delete().withPath("/api/v1/namespaces/arquillian/pods/test-pod").andReturn(200, "").always();

        //test-pod-second in secondary namespace test-secondary-namespace
        MOCK.expect().get().withPath("/api/v1/namespaces/test-secondary-namespace/pods/test-pod-second").andReturn(200, testPodInSecondaryNamespace).always();
        MOCK.expect().get().withPath("/api/v1/namespaces/test-secondary-namespace/pods").andReturn(200, new PodListBuilder()
            .withNewMetadata()
            .withResourceVersion("1")
            .endMetadata()
            .withItems(testPodInSecondaryNamespace)
            .build()).always();

        //test-service
        MOCK.expect().post().withPath("/api/v1/namespaces/arquillian/services").andReturn(201, testService).always();
        MOCK.expect().get().withPath("/api/v1/namespaces/arquillian/services/test-service").andReturn(404, "").once();
        MOCK.expect()
            .get()
            .withPath("/api/v1/namespaces/arquillian/services/test-service")
            .andReturn(200, testService)
            .always();
        MOCK.expect().get().withPath("/api/v1/namespaces/arquillian/services").andReturn(200, new ServiceListBuilder()
            .withNewMetadata()
            .withResourceVersion("1")
            .endMetadata()
            .withItems(testService)
            .build()).always();
        MOCK.expect()
            .delete()
            .withPath("/api/v1/namespaces/arquillian/services/test-service")
            .andReturn(200, "")
            .always();

        //test-service-second in secondary namespace test-secondary-namespace
        MOCK.expect()
            .get()
            .withPath("/api/v1/namespaces/test-secondary-namespace/services/test-service-second")
            .andReturn(200, testServiceInSecondaryNamespace)
            .always();
        MOCK.expect().get().withPath("/api/v1/namespaces/test-secondary-namespace/services").andReturn(200, new ServiceListBuilder()
            .withNewMetadata()
            .withResourceVersion("1")
            .endMetadata()
            .withItems(testServiceInSecondaryNamespace)
            .build()).always();

        //test-service endpoints
        MOCK.expect().post().withPath("/api/v1/namespaces/arquillian/endpoints").andReturn(201, testEndpoints).always();

        MOCK.expect()
            .get()
            .withPath("/api/v1/namespaces/arquillian/endpoints/test-service")
            .andReturn(200, testEndpoints)
            .once();
        MOCK.expect()
            .get()
            .withPath("/api/v1/namespaces/arquillian/endpoints/test-service")
            .andReturn(200, readyTestEndpoints)
            .always();
        MOCK.expect().get().withPath("/api/v1/namespaces/arquillian/endpoints").andReturn(200, new EndpointsListBuilder()
            .withNewMetadata()
            .withResourceVersion("1")
            .endMetadata()
            .withItems(testEndpoints)
            .build()).always();

        MOCK.expect()
            .get()
            .withPath("/api/v1/namespaces/arquillian/endpoints?resourceVersion=1&watch=true")
            .andUpgradeToWebSocket()
            .open()
            .waitFor(1000)
            .andEmit(new WatchEvent(readyTestEndpoints, "MODIFIED"))
            .done()
            .always();

        MOCK.expect()
            .delete()
            .withPath("/api/v1/namespaces/arquillian/endpoints/test-service")
            .andReturn(200, "")
            .always();

        MOCK.expect()
            .get()
            .withPath("/apis/extensions/v1beta1/namespaces/arquillian/replicasets")
            .andReturn(200, new ReplicaSetBuilder().build())
            .always();

        MOCK.init();

        String masterUrl = MOCK.getServer().url("/").toString();
        System.setProperty(Config.KUBERNETES_MASTER_SYSTEM_PROPERTY, masterUrl);
        System.setProperty(Config.KUBERNETES_TRUST_CERT_SYSTEM_PROPERTY, "true");
        System.setProperty(Config.KUBERNETES_NAMESPACE_SYSTEM_PROPERTY, "arquillian");
        System.setProperty(Configuration.NAMESPACE_TO_USE, "arquillian");
        System.setProperty(Configuration.NAMESPACE_CLEANUP_ENABLED, "true");
        System.setProperty(Configuration.ENVIRONMENT_CONFIG_URL,
            MockTest.class.getResource("/test-kubernetes-1.json").toString());
    }

    @AfterClass
    public static void tearDownClass() throws IOException {
        //MOCK.destroy();
    }
}


text:
goog.provide('app.models.Person');
goog.require('app.models.Model');

app.models.Person = app.models.Model.extend({

    respondTo: function (cmd) {
        if (cmd === 'beep') {
            return 'boop';
        }
    }

});


text:
#ifndef TCPCLIENT_H
#define TCPCLIENT_H

#include <string>
#include <string.h>

class TCPClient
{
public:
    TCPClient(const std::string &host, unsigned short port);
    ~TCPClient();

    TCPClient(const TCPClient &) = delete;
    TCPClient &operator=(const TCPClient &) = delete;

    int sockfd() const;
private:
    int sockfd_;
};

class TCPClientError : public std::exception
{
public:
    explicit TCPClientError(const std::string &message, int error_code = 0)
	: message_(message), error_code_(error_code)
    {
	if (has_error_code())
	{
	    message_ = message_ + ": " + ::strerror(error_code_) +
		", error code: " + std::to_string(error_code_);
	}
    }

    virtual const char * what() const noexcept override
    {
        return message_.c_str();
    }

    bool has_error_code() const
    {
	return error_code_ != 0;
    }

    int error_code() const
    {
	return error_code_;
    }

private:
    std::string message_;
    int error_code_;
};

#endif /* TCPCLIENT_H */


text:
package br.com.trisoft.eventos.lazymodel;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

import br.com.trisoft.eventos.dao.ParticipanteAtividadeDAO;
import br.com.trisoft.eventos.model.Participante;
import br.com.trisoft.eventos.model.relationship.ParticipanteAtividade;

public class MinhasAtividadesLazy extends LazyDataModel<ParticipanteAtividade>implements Serializable {

	private static final long serialVersionUID = 1L;

	private Participante participante;
	private ParticipanteAtividadeDAO participanteAtividadeDAO;

	public MinhasAtividadesLazy(Participante participante, ParticipanteAtividadeDAO participanteAtividadeDAO) {
		this.participante = participante;
		this.participanteAtividadeDAO = participanteAtividadeDAO;
	}

	@Override
	public List<ParticipanteAtividade> load(int first, int pageSize, String sortField, SortOrder sortOrder,
			Map<String, Object> filters) {

		List<ParticipanteAtividade> atividades = this.participanteAtividadeDAO
				.buscarComPaginacaoPorParticipante(participante, first, pageSize);
		this.setRowCount(this.participanteAtividadeDAO.encontrarQuantidadePorParticipante(participante).intValue());

		return atividades;
	}

}


text:
'use strict'

module.exports = function (p) {
  function draw (selection) {
  }

  return draw
}


text:
package com.amazonaws.services.lambda.model;

import com.amazonaws.AmazonServiceException;

/**
 * <p>
 * The AWS Lambda service encountered an internal error.
 * </p>
 */
public class ServiceException extends AmazonServiceException {
    private static final long serialVersionUID = 1L;

    private String type;

    /**
     * Constructs a new ServiceException with the specified error
     * message.
     *
     * @param message Describes the error encountered.
     */
    public ServiceException(String message) {
        super(message);
    }

    /**
     * Returns the value of the Type property for this object.
     *
     * @return The value of the Type property for this object.
     */
    public String getType() {
        return type;
    }

    /**
     * Sets the value of the Type property for this object.
     *
     * @param type The new value for this object's Type property.
     */
    public void setType(String type) {
        this.type = type;
    }
}


text:
BIN_DIR="bin"
SRC_DIR="$BIN_DIR/Sources"

# csharp
ES="Entitas"
CG="Entitas.CodeGenerator"
MIG="Entitas.Migration"
CG_TR="Entitas.CodeGenerator.TypeReflection"
ESU="Entitas.Unity"

ESU_ASSETS="$ESU/Assets"

collect_sources() {
  echo "Collecting sources..."

  rm -rf $BIN_DIR
  mkdir $BIN_DIR $SRC_DIR

  cp -r {"$ES/$ES","$MIG/$MIG","$ESU_ASSETS/$ESU"} $SRC_DIR
  find "./$SRC_DIR" -name "*.meta" -type f -delete

  header_meta="$ESU/Editor/Entitas-Header.png.meta"
  cp "$ESU_ASSETS/$header_meta" "$SRC_DIR/$header_meta"

  icon_meta="$ESU/VisualDebugging/Editor/EntitasHierarchyIcon.png.meta"
  cp "$ESU_ASSETS/$icon_meta" "$SRC_DIR/$icon_meta"

  migration_header_meta="$ESU/Migration/Editor/Entitas-Migration-Header.png.meta"
  cp "$ESU_ASSETS/$migration_header_meta" "$SRC_DIR/$migration_header_meta"

  echo "Collecting sources done."
}

update_project_dependencies() {
  echo "Updating project dependencies..."

  ESU_LIBS_DIR="$ESU_ASSETS/Libraries"

  rm -rf $ESU_LIBS_DIR
  mkdir $ESU_LIBS_DIR

  cp -r $SRC_DIR/{$ES,$MIG} $ESU_LIBS_DIR

  echo "Updating project dependencies done."
}

generateProjectFiles() {
  echo "Generating project files..."
  PWD=$(pwd)

  # Unity bug: https://support.unity3d.com/hc/en-us/requests/36273
  # /Applications/Unity/Unity.app/Contents/MacOS/Unity -quit -batchmode -logfile -projectPath "$PWD/$ESU" -executeMethod Commands.GenerateProjectFiles

  echo "Generating project files done."
}

build() {
  echo "Building..."
  xbuild /target:Clean /property:Configuration=Release Entitas.sln
  xbuild /property:Configuration=Release Entitas.sln
  echo "Building done."
}

runTests() {
  mono Tests/Libraries/NSpec/NSpecRunner.exe Tests/bin/Release/Tests.dll
}

collect_misc_files() {
  echo "Collecting misc files..."

  cp "$MIG/bin/Release/Entitas.Migration.exe" "$SRC_DIR/MigrationAssistant.exe"
  cp README.md "$SRC_DIR/README.md"
  cp RELEASE_NOTES.md "$SRC_DIR/RELEASE_NOTES.md"
  cp EntitasUpgradeGuide.md "$SRC_DIR/EntitasUpgradeGuide.md"
  cp LICENSE.txt "$SRC_DIR/LICENSE.txt"

  echo "Collecting misc files done."
}

create_zip() {
  echo "Creating zip files..."

  TMP_DIR="$BIN_DIR/tmp"

  echo "Creating Entitas-CSharp.zip..."
  mkdir $TMP_DIR
  cp -r $SRC_DIR/$ES $TMP_DIR
  cp "$SRC_DIR/"* $TMP_DIR || true

  pushd $TMP_DIR > /dev/null
    zip -rq ../Entitas-CSharp.zip ./
  popd > /dev/null
  rm -rf $TMP_DIR

  echo "Creating Entitas-Unity.zip..."
  mkdir $TMP_DIR
  cp -r "$SRC_DIR/"* $TMP_DIR || true

  tmp_editor_dir="$TMP_DIR/Editor"
  mkdir $tmp_editor_dir
  mv "$TMP_DIR/Entitas/CodeGenerator/"* $tmp_editor_dir
  mv {"$tmp_editor_dir/Attributes",$tmp_editor_dir} "$TMP_DIR/Entitas/CodeGenerator"

  mkdir $tmp_editor_dir
  mv "$TMP_DIR/$MIG/"* $tmp_editor_dir
  mv $tmp_editor_dir "$TMP_DIR/$MIG"

  pushd $TMP_DIR > /dev/null
    zip -rq ../Entitas-Unity.zip ./
  popd > /dev/null
  rm -rf $TMP_DIR

  echo "Creating zip files done."
}

create_tree_overview() {
  echo "Creating tree overview..."
  tree -I 'bin|obj|Library|Libraries|*Tests|Readme|ProjectSettings|Examples|*.csproj|*.meta|*.sln|*.userprefs|*.properties' --noreport -d > tree.txt
  tree -I 'bin|obj|Library|Libraries|*Tests|Readme|ProjectSettings|Examples|*.csproj|*.meta|*.sln|*.userprefs|*.properties' --noreport --dirsfirst >> tree.txt
  echo "Creating tree overview done."
}


text:
package io.druid.query.groupby.epinephelinae;

import com.google.common.base.Supplier;
import com.google.common.primitives.Ints;
import io.druid.java.util.common.IAE;
import io.druid.java.util.common.ISE;
import io.druid.java.util.common.logger.Logger;
import io.druid.query.aggregation.AggregatorFactory;
import io.druid.query.aggregation.BufferAggregator;
import io.druid.segment.ColumnSelectorFactory;

import java.nio.ByteBuffer;
import java.util.AbstractList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

/**
 * Grouper based around a hash table and companion array in a single ByteBuffer. Not thread-safe.
 *
 * The buffer has two parts: a table arena (offset 0 to tableArenaSize) and an array containing pointers objects in
 * the table (tableArenaSize until the end of the buffer).
 *
 * The table uses open addressing with linear probing on collisions. Each bucket contains the key hash (with the high
 * bit set to signify the bucket is used), the serialized key (which are a fixed size) and scratch space for
 * BufferAggregators (which is also fixed size). The actual table is represented by "tableBuffer", which points to the
 * same memory as positions "tableStart" through "tableStart + buckets * bucketSize" of "buffer". Everything else in
 * the table arena is potentially junk.
 *
 * The array of pointers starts out ordered by insertion order, but might be sorted on calls to
 * {@link #iterator(boolean)}. This sorting is done in-place to avoid materializing the full array of pointers. The
 * first "size" pointers in the array of pointers are valid; everything else is potentially junk.
 *
 * The table is periodically grown to accommodate more keys. Even though starting small is not necessary to control
 * memory use (we already have the entire buffer allocated) or iteration speed (iteration is fast due to the array
 * of pointers) it still helps significantly on initialization times. Otherwise, we'd need to clear the used bits of
 * each bucket in the entire buffer, which is a lot of writes if the buckets are small.
 */
public class BufferGrouper<KeyType> implements Grouper<KeyType>
{
  private static final Logger log = new Logger(BufferGrouper.class);

  private static final int MIN_INITIAL_BUCKETS = 4;
  private static final int DEFAULT_INITIAL_BUCKETS = 1024;
  private static final float DEFAULT_MAX_LOAD_FACTOR = 0.7f;
  private static final int HASH_SIZE = Ints.BYTES;

  private final Supplier<ByteBuffer> bufferSupplier;
  private final KeySerde<KeyType> keySerde;
  private final int keySize;
  private final BufferAggregator[] aggregators;
  private final int[] aggregatorOffsets;
  private final int initialBuckets;
  private final int bucketSize;
  private final int bufferGrouperMaxSize; // Integer.MAX_VALUE in production, only used for unit tests
  private final float maxLoadFactor;

  private ByteBuffer buffer;
  private int tableArenaSize = -1;

  // Buffer pointing to the current table (it moves around as the table grows)
  private ByteBuffer tableBuffer;

  // Offset of tableBuffer within the larger buffer
  private int tableStart;

  // Current number of buckets in the table
  private int buckets;

  // Number of elements in the table right now
  private int size;

  // Maximum number of elements in the table before it must be resized
  private int maxSize;

  private boolean initialized = false;

  public BufferGrouper(
      final Supplier<ByteBuffer> bufferSupplier,
      final KeySerde<KeyType> keySerde,
      final ColumnSelectorFactory columnSelectorFactory,
      final AggregatorFactory[] aggregatorFactories,
      final int bufferGrouperMaxSize,
      final float maxLoadFactor,
      final int initialBuckets
  )
  {
    this.bufferSupplier = bufferSupplier;
    this.keySerde = keySerde;
    this.keySize = keySerde.keySize();
    this.aggregators = new BufferAggregator[aggregatorFactories.length];
    this.aggregatorOffsets = new int[aggregatorFactories.length];
    this.bufferGrouperMaxSize = bufferGrouperMaxSize;
    this.maxLoadFactor = maxLoadFactor > 0 ? maxLoadFactor : DEFAULT_MAX_LOAD_FACTOR;
    this.initialBuckets = initialBuckets > 0 ? Math.max(MIN_INITIAL_BUCKETS, initialBuckets) : DEFAULT_INITIAL_BUCKETS;

    if (this.maxLoadFactor >= 1.0f) {
      throw new IAE("Invalid maxLoadFactor[%f], must be < 1.0", maxLoadFactor);
    }

    int offset = HASH_SIZE + keySize;
    for (int i = 0; i < aggregatorFactories.length; i++) {
      aggregators[i] = aggregatorFactories[i].factorizeBuffered(columnSelectorFactory);
      aggregatorOffsets[i] = offset;
      offset += aggregatorFactories[i].getMaxIntermediateSize();
    }

    this.bucketSize = offset;
  }

  @Override
  public void init()
  {
    if (!initialized) {
      this.buffer = bufferSupplier.get();
      this.tableArenaSize = (buffer.capacity() / (bucketSize + Ints.BYTES)) * bucketSize;
      reset();
      initialized = true;
    }
  }

  @Override
  public boolean isInitialized()
  {
    return initialized;
  }

  @Override
  public boolean aggregate(KeyType key, int keyHash)
  {
    final ByteBuffer keyBuffer = keySerde.toByteBuffer(key);
    if (keyBuffer == null) {
      return false;
    }

    if (keyBuffer.remaining() != keySize) {
      throw new IAE(
          "keySerde.toByteBuffer(key).remaining[%s] != keySerde.keySize[%s], buffer was the wrong size?!",
          keyBuffer.remaining(),
          keySize
      );
    }

    int bucket = findBucket(
        tableBuffer,
        buckets,
        bucketSize,
        size < Math.min(maxSize, bufferGrouperMaxSize),
        keyBuffer,
        keySize,
        keyHash
    );

    if (bucket < 0) {
      if (size < bufferGrouperMaxSize) {
        growIfPossible();
        bucket = findBucket(tableBuffer, buckets, bucketSize, size < maxSize, keyBuffer, keySize, keyHash);
      }

      if (bucket < 0) {
        return false;
      }
    }

    final int offset = bucket * bucketSize;

    // Set up key if this is a new bucket.
    if (!isUsed(bucket)) {
      tableBuffer.position(offset);
      tableBuffer.putInt(keyHash | 0x80000000);
      tableBuffer.put(keyBuffer);

      for (int i = 0; i < aggregators.length; i++) {
        aggregators[i].init(tableBuffer, offset + aggregatorOffsets[i]);
      }

      buffer.putInt(tableArenaSize + size * Ints.BYTES, offset);
      size++;
    }

    // Aggregate the current row.
    for (int i = 0; i < aggregators.length; i++) {
      aggregators[i].aggregate(tableBuffer, offset + aggregatorOffsets[i]);
    }

    return true;
  }

  @Override
  public boolean aggregate(final KeyType key)
  {
    return aggregate(key, Groupers.hash(key));
  }

  @Override
  public void reset()
  {
    size = 0;
    buckets = Math.min(tableArenaSize / bucketSize, initialBuckets);
    maxSize = maxSizeForBuckets(buckets);

    if (buckets < 1) {
      throw new IAE(
          "Not enough capacity for even one row! Need[%,d] but have[%,d].",
          bucketSize + Ints.BYTES,
          buffer.capacity()
      );
    }

    // Start table part-way through the buffer so the last growth can start from zero and thereby use more space.
    tableStart = tableArenaSize - buckets * bucketSize;
    int nextBuckets = buckets * 2;
    while (true) {
      final int nextTableStart = tableStart - nextBuckets * bucketSize;
      if (nextTableStart > tableArenaSize / 2) {
        tableStart = nextTableStart;
        nextBuckets = nextBuckets * 2;
      } else {
        break;
      }
    }

    if (tableStart < tableArenaSize / 2) {
      tableStart = 0;
    }

    final ByteBuffer bufferDup = buffer.duplicate();
    bufferDup.position(tableStart);
    bufferDup.limit(tableStart + buckets * bucketSize);
    tableBuffer = bufferDup.slice();

    // Clear used bits of new table
    for (int i = 0; i < buckets; i++) {
      tableBuffer.put(i * bucketSize, (byte) 0);
    }

    keySerde.reset();
  }

  @Override
  public Iterator<Entry<KeyType>> iterator(final boolean sorted)
  {
    if (sorted) {
      final List<Integer> wrappedOffsets = new AbstractList<Integer>()
      {
        @Override
        public Integer get(int index)
        {
          return buffer.getInt(tableArenaSize + index * Ints.BYTES);
        }

        @Override
        public Integer set(int index, Integer element)
        {
          final Integer oldValue = get(index);
          buffer.putInt(tableArenaSize + index * Ints.BYTES, element);
          return oldValue;
        }

        @Override
        public int size()
        {
          return size;
        }
      };

      final KeyComparator comparator = keySerde.bufferComparator();

      // Sort offsets in-place.
      Collections.sort(
          wrappedOffsets,
          new Comparator<Integer>()
          {
            @Override
            public int compare(Integer lhs, Integer rhs)
            {
              return comparator.compare(
                  tableBuffer,
                  tableBuffer,
                  lhs + HASH_SIZE,
                  rhs + HASH_SIZE
              );
            }
          }
      );

      return new Iterator<Entry<KeyType>>()
      {
        int curr = 0;

        @Override
        public boolean hasNext()
        {
          return curr < size;
        }

        @Override
        public Entry<KeyType> next()
        {
          return bucketEntryForOffset(wrappedOffsets.get(curr++));
        }

        @Override
        public void remove()
        {
          throw new UnsupportedOperationException();
        }
      };
    } else {
      // Unsorted iterator
      return new Iterator<Entry<KeyType>>()
      {
        int curr = 0;

        @Override
        public boolean hasNext()
        {
          return curr < size;
        }

        @Override
        public Entry<KeyType> next()
        {
          final int offset = buffer.getInt(tableArenaSize + curr * Ints.BYTES);
          final Entry<KeyType> entry = bucketEntryForOffset(offset);
          curr++;

          return entry;
        }

        @Override
        public void remove()
        {
          throw new UnsupportedOperationException();
        }
      };
    }
  }

  @Override
  public void close()
  {
    for (BufferAggregator aggregator : aggregators) {
      try {
        aggregator.close();
      }
      catch (Exception e) {
        log.warn(e, "Could not close aggregator, skipping.", aggregator);
      }
    }
  }

  private boolean isUsed(final int bucket)
  {
    return (tableBuffer.get(bucket * bucketSize) & 0x80) == 0x80;
  }

  private Entry<KeyType> bucketEntryForOffset(final int bucketOffset)
  {
    final KeyType key = keySerde.fromByteBuffer(tableBuffer, bucketOffset + HASH_SIZE);
    final Object[] values = new Object[aggregators.length];
    for (int i = 0; i < aggregators.length; i++) {
      values[i] = aggregators[i].get(tableBuffer, bucketOffset + aggregatorOffsets[i]);
    }

    return new Entry<>(key, values);
  }

  private void growIfPossible()
  {
    if (tableStart == 0) {
      // tableStart = 0 is the last growth; no further growing is possible.
      return;
    }

    final int newBuckets;
    final int newMaxSize;
    final int newTableStart;

    if ((tableStart + buckets * 3 * bucketSize) > tableArenaSize) {
      // Not enough space to grow upwards, start back from zero
      newTableStart = 0;
      newBuckets = tableStart / bucketSize;
      newMaxSize = maxSizeForBuckets(newBuckets);
    } else {
      newTableStart = tableStart + tableBuffer.limit();
      newBuckets = buckets * 2;
      newMaxSize = maxSizeForBuckets(newBuckets);
    }

    if (newBuckets < buckets) {
      throw new ISE("WTF?! newBuckets[%,d] < buckets[%,d]", newBuckets, buckets);
    }

    ByteBuffer newTableBuffer = buffer.duplicate();
    newTableBuffer.position(newTableStart);
    newTableBuffer.limit(newTableStart + newBuckets * bucketSize);
    newTableBuffer = newTableBuffer.slice();

    int newSize = 0;

    // Clear used bits of new table
    for (int i = 0; i < newBuckets; i++) {
      newTableBuffer.put(i * bucketSize, (byte) 0);
    }

    // Loop over old buckets and copy to new table
    final ByteBuffer entryBuffer = tableBuffer.duplicate();
    final ByteBuffer keyBuffer = tableBuffer.duplicate();

    for (int oldBucket = 0; oldBucket < buckets; oldBucket++) {
      if (isUsed(oldBucket)) {
        int oldPosition = oldBucket * bucketSize;
        entryBuffer.limit((oldBucket + 1) * bucketSize);
        entryBuffer.position(oldPosition);
        keyBuffer.limit(entryBuffer.position() + HASH_SIZE + keySize);
        keyBuffer.position(entryBuffer.position() + HASH_SIZE);

        final int keyHash = entryBuffer.getInt(entryBuffer.position()) & 0x7fffffff;
        final int newBucket = findBucket(newTableBuffer, newBuckets, bucketSize, true, keyBuffer, keySize, keyHash);

        if (newBucket < 0) {
          throw new ISE("WTF?! Couldn't find a bucket while resizing?!");
        }

        int newPosition = newBucket * bucketSize;
        newTableBuffer.position(newPosition);
        newTableBuffer.put(entryBuffer);

        for (int i = 0; i < aggregators.length; i++) {
          aggregators[i].relocate(
              oldPosition + aggregatorOffsets[i],
              newPosition + aggregatorOffsets[i],
              tableBuffer,
              newTableBuffer
          );
        }

        buffer.putInt(tableArenaSize + newSize * Ints.BYTES, newBucket * bucketSize);
        newSize++;
      }
    }

    buckets = newBuckets;
    maxSize = newMaxSize;
    tableBuffer = newTableBuffer;
    tableStart = newTableStart;

    if (size != newSize) {
      throw new ISE("WTF?! size[%,d] != newSize[%,d] after resizing?!", size, maxSize);
    }
  }

  private int maxSizeForBuckets(int buckets)
  {
    return Math.max(1, (int) (buckets * maxLoadFactor));
  }

  /**
   * Finds the bucket into which we should insert a key.
   *
   * @param keyBuffer key, must have exactly keySize bytes remaining. Will not be modified.
   *
   * @return bucket index for this key, or -1 if no bucket is available due to being full
   */
  private static int findBucket(
      final ByteBuffer tableBuffer,
      final int buckets,
      final int bucketSize,
      final boolean allowNewBucket,
      final ByteBuffer keyBuffer,
      final int keySize,
      final int keyHash
  )
  {
    // startBucket will never be negative since keyHash is always positive (see Groupers.hash)
    final int startBucket = keyHash % buckets;
    int bucket = startBucket;

outer:
    while (true) {
      final int bucketOffset = bucket * bucketSize;

      if ((tableBuffer.get(bucketOffset) & 0x80) == 0) {
        // Found unused bucket before finding our key
        return allowNewBucket ? bucket : -1;
      }

      for (int i = bucketOffset + HASH_SIZE, j = keyBuffer.position(); j < keyBuffer.position() + keySize; i++, j++) {
        if (tableBuffer.get(i) != keyBuffer.get(j)) {
          bucket += 1;
          if (bucket == buckets) {
            bucket = 0;
          }

          if (bucket == startBucket) {
            // Came back around to the start without finding a free slot, that was a long trip!
            // Should never happen unless buckets == maxSize.
            return -1;
          }

          continue outer;
        }
      }

      // Found our key in a used bucket
      return bucket;
    }
  }
}


text:
define([
    'underscore',
    'jquery',
    'backbone',
    'pikaday',
    'json!langs.json',
    'text!templates/createStudentPanel.tpl',
    'models/student',
    'collections/students-collection',
    'collections/events-collection',
    'dropdown',
    'notify'
], function(_, $, Backbone, Pikaday, Langs, Template, StudentModel, StudentsCollection, EventsCollection){
    'use strict';

    return Backbone.View.extend({

        id : 'blankEntry',

        className: 'tab-pane fade in active',

        events : {
            'click #saveBtn': 'save',
            'keyup #passport-input': 'tryFetchStudent'
        },

        configs: {
            passId:     '#passport-input',
            firstName:  '#first-name',
            lastName:   '#last-name',
            birthDate:  '#birth-date',
            coachName:  '#coach-name',
            level:      '#achievement-level',
            semCost:    '#seminar-payment',
            certCost:   '#certification-payment',
            levelType:  '#a-type',
            curLevel:   '#current-lvl',
            curLvlType: '#c-type',
            semType:    '#sem-type'
        },

        initialize: function() {
            this.lang = Backbone.getLang();

            this.template = _.template(Template);

            StudentsCollection.on('sync', this.onSyncSuccess);

            $(Backbone.areas.panelContent).html(this.$el);

            this.delegateEvents();
        },

        render: function() {
            var root = this;

            StudentsCollection.fetch();

            this.$el.append(this.template({ lang: Langs[this.lang].views.createStudent }));

            this.picker = new Pikaday({
                field: $('#birth-date')[0],
                format: 'D MMM YYYY'
            });

            if (!this.areasInitialized) {
                this.areasInitialized = true;

                $.each(root.configs, function(k, v) {
                    root['$' + k] = $(v);
                })
            }

            EventsCollection.fetch({
                success: function(data){
                    data.models.forEach(function(v, k) {
                        var option =
                            $('<option data-subtext=' + v.get('_id') + '>' + v.get('eventID') + ' ' + v.get('eventTitle') + '</option>');
                        $(root.configs.semType).append(option);
                    });
                    $(root.configs.semType).selectpicker('refresh');
                }
            });

            $(this.configs.semType).selectpicker();
            $(this.configs.levelType).selectpicker();
            $(this.configs.curLvlType).selectpicker();

            return this;
        },

        tryFetchStudent: function(e) {
            var passID,
                studentFound,
                seminar,
                event;

            passID = $(this.configs.passId).val();
            studentFound  = StudentsCollection.findWhere({
                passportID: passID
            });

            if (studentFound) {
                event = EventsCollection.findWhere({ _id: studentFound.get('attachedEvent') });

                if (!event) {
                    this.$semType.selectpicker('val', '');
                } else {
                    this.$semType.selectpicker('val', event.get('eventID') + ' ' + event.get('eventTitle'));
                }

                this.$firstName.val(studentFound.get('name'));
                this.$lastName.val(studentFound.get('lastname'));
                this.$birthDate.val(studentFound.get('birthdate'));
                this.$level.val(studentFound.get('levelToAchieve'));
                this.$coachName.val(studentFound.get('coachName'));
                this.$semCost.val(studentFound.get('seminarCost'));
                this.$certCost.val(studentFound.get('certificationCost'));
                this.$levelType.selectpicker('val', studentFound.get('levelType'));
            }
        },

        save: function() {
            var passID,
                studentFound;

            passID = $(this.configs.passId).val();
            studentFound  = StudentsCollection.findWhere({
                passportID: passID
            });

            if (studentFound) {
                this.updateStudent(studentFound);
            } else {
                this.saveStudent();
            }
        },

        saveStudent: function() {
            var model,
                seminar = $(this.configs.semType).
                    siblings().
                    find('li.selected').
                    find('small.text-muted');

            // Backbone.tryLogout();

            model = new StudentModel({
                name: this.$firstName.val(),
                lastname: this.$lastName.val(),
                birthdate: this.$birthDate.val(),
                levelToAchieve: this.$level.val(),
                passportID: this.$passId.val(),
                coachName: this.$coachName.val(),
                seminarCost: this.$semCost.val(),
                certificationCost: this.$certCost.val(),
                levelType: this.$levelType.val(),
                attachedEvent: seminar.text()
            });

            model.on('invalid', function(model, errorArr) {
                errorArr.forEach(function(msg) {
                    $.notify(msg, "error");
                });
            });

            StudentsCollection.create(model);
        },

        updateStudent: function(studentFound) {
            var seminar = $(this.configs.semType).
                    siblings().
                    find('li.selected').
                    find('small.text-muted');

            studentFound.save({
                name: this.$firstName.val(),
                lastname: this.$lastName.val(),
                birthdate: this.$birthDate.val(),
                levelToAchieve: this.$level.val(),
                coachName: this.$coachName.val(),
                seminarCost: this.$semCost.val(),
                certificationCost: this.$certCost.val(),
                levelType: this.$levelType.val(),
                attachedEvent: seminar.text()
            });
        },

        onSyncSuccess: function() {}

    });
});


text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0" />
  <title>CASR3PM</title>

  <link rel="stylesheet" type="" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" crossorigin="anonymous">

  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.8/css/materialize.min.css">

  <link href="css/style.css" type="text/css" rel="stylesheet" media="screen,projection" />
  <link href="css/fromSass.css" type="text/css" rel="stylesheet" media="screen,projection" />
  <link href="css/pgwslider.css" type="text/css" rel="stylesheet" media="screen,projection" />
  <link href="unitegallery/css/unite-gallery.css" rel="stylesheet">
  <link href="unitegallery/themes/default/ug-theme-default.css" rel="stylesheet">
  <link href="css/owl.theme.css" type="text/css" rel="stylesheet" media="screen,projection" />
  <link href="css/owl.transitions.css" type="text/css" rel="stylesheet" media="screen,projection" />

          Téléphone: +221 33 864 29 64 * +221 781 05 29 16

        Se connecter

            CENTRE D'EXCELLENCE

              HISTORIQUE
              ORIGINE
              MISSION
              VISSION
              VALEURS

            PROGRAMMES

              PhD
              MBA
              MASTERS
              EMBA
              SEMINAIRES
              CERTIFICATIONS

            CORPS PROFESSORAL

              Pr. Dr. Christophe N. BREDILLET
              Pr. Dr. Hiroshi TANAKA
              Pr. Dr. Frank ANBARI
              Pr. Dr. Rodney Turner
              Pr. Phil Latimier
              Dr. Sarah ROSS, PhD
              Pr. Dr. Azhar Mansur KHAN
              Pr. Papa Senghane DIOUF
              Pr. Hamdouraby SY
              Dr. Deepak BAJAJ
              Liste compléte

            RESSOURCES

              PUBLICATIONS
              SUJETS DE THESE
              VIDEOS
              LIENS UTILES

            POLITIQUE DE  RECHERCHES

              CASR3PM RISK INSTITUTE
              DOMAINES DE RECHERCHES
              VALORISATION DES RECHERCHES
              CHAIRES D'ENTREPRISE

TEMOIGNAGES

CONTACT

ACCUEIL

CASR3PM

PROGRAMMES

  ETUDIANTS

CORPS PROFESSORAL

RESSOURCES

CONTACT

        menu

CASR3PM

 Ouest Foire Cite Télécom Villa N°28, Dakar, Sénégal

 Fixe: +221 33 864 29 64

 Mob: +221 781 05 29 16

 Email: info@casr3pm.sn

NAVIGATION

 ACCUEIL

A PROPOS DE CASR3PM

PROGRAMMES

ADMISSIONS

CORPS PROFESSORAL

ETUDIANTS

RESSOURCES

CONTACT

PROGRAMMES

Masters

MBA

EMBA

Seminaires

Doctorat

RESSOURCES

Bibliothéque

Photos - Vidéos

Publications

Liens utiles

        © 2016 SYTEK Innovation Response
          THANKS!


text:
from django.conf.urls.defaults import *
import views

urlpatterns = patterns('',
    url(r'$', view=views.index, name='workflow-index'),
)


text:
package com.axemblr.yab.cli;

import com.axemblr.yab.YaB;
import com.google.common.collect.ImmutableList;
import io.airlift.command.Cli;
import io.airlift.command.Command;
import io.airlift.command.Help;

/**
 * Entry point for command line tool
 */
public class Main {

    @Command(name = "version")
    public static class VersionCommand implements Runnable {

        @Override
        public void run() {
            System.out.println("YaB " + YaB.Version.INSTANCE);
            System.out.println("Java " + System.getProperty("java.version"));
        }
    }

    public static void main(String[] args) {
        Cli.CliBuilder<Runnable> builder = Cli.<Runnable>builder("yab")
            .withDescription("YaB: Yet (another) AMI Baker")
            .withDefaultCommand(Help.class)
            .withCommands(ImmutableList.of(Help.class, ListCommand.class,
                CreateCommand.class, CopyCommand.class, DropCommand.class,
                VersionCommand.class));

        Cli<Runnable> parser = builder.build();
        try {
            parser.parse(args).run();

        } catch (RuntimeException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package view.schema;

import control.Xray;
import java.util.ArrayList;
import javafx.collections.ObservableList;
import javafx.geometry.Orientation;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.TilePane;
import javafx.scene.layout.VBox;
import model.Room;
import model.TimeInvestment;
import org.joda.time.DateTimeFieldType;
import org.joda.time.Hours;
import org.joda.time.LocalDate;
import org.joda.time.LocalDateTime;
import view.Frontpage;

/**
 *
 * @author Jonas
 */
public class AssignedRoomRow extends HBox implements HasChildren {

    private Room room;
    private LocalDateTime startTime;
    private ArrayList<TimeInvestment> shifts;
    private RoomTile roomLabel;

    public AssignedRoomRow(Room room, ArrayList<TimeInvestment> shifts, LocalDateTime startTime,
            int startHour, int startMinute, int periodLengthHour, int periodLengthMinute) {
        this.startTime = startTime;
        this.room = room;
        this.shifts = shifts;

        roomLabel = new RoomTile(room.getRoomName());

        //Tilføj rumnavn til venstre.
        this.getChildren().add(roomLabel);

        //Tilføj vagter til dagene på ugen. i0 = mandag, i4 = fredag.
        for (int i = 0; i < 5; i++) {
            LocalDateTime date = startTime.plusDays(i);
            date = date.withField(DateTimeFieldType.hourOfDay(), startHour);
            date = date.withField(DateTimeFieldType.minuteOfHour(), startMinute);
                        //Nulstil sekunder og millisekunder (vigtigt).
            date = date.withSecondOfMinute(0);
            date = date.withMillisOfSecond(0);

            LocalDateTime endDate = new LocalDateTime(date);
            endDate = endDate.plusHours(periodLengthHour).plusMinutes(periodLengthMinute);

            ShiftTile shiftTile = new ShiftTile(Xray.getInstance().getTimeInvestmentControl().
                    getShiftsInPeriod(shifts, date, endDate));

            this.getChildren().add(shiftTile);
        }

    }

    @Override
    public Node[] getChildrenList() {
        ObservableList<Node> sliChildren = this.getChildren();

        Node[] childrenAsArray = new Node[sliChildren.size()];

        for (int i = 0; i < sliChildren.size(); i++) {
            childrenAsArray[i] = sliChildren.get(i);
        }
        return childrenAsArray;
    }

}


text: require_relative "hanami/validations"


text:
Getting Started
===============

This document will show you how to get up and running with Read the Docs.

If you are already using Sphinx_ for your docs, skip ahead to
:ref:`import-docs`.

There is `a screencast`_ that will help you get started if you prefer.

Write Your Docs
---------------

Install Sphinx_, and create a directory inside your project to hold your docs::

    $ cd /path/to/project
    $ mkdir docs

Run ``sphinx-quickstart`` in there::

    $ cd docs
    $ sphinx-quickstart

This will walk you through creating the basic configuration; in most cases, you
can just accept the defaults. When it's done, you'll have an ``index.rst``, a
``conf.py`` and some other files. Add these to revision control.

Now, edit your ``index.rst`` and add some information about your project.
Include as much detail as you like (refer to the reStructuredText_ syntax
or `this template`_ if you need help). Build them to see how they look::

    $ make html

Edit your files and rebuild until you like what you see, then commit your changes and push to your public repository.
Once you have Sphinx documentation in a public repository, you can start using Read the Docs.

.. _import-docs:

Import Your Docs
----------------

`Sign up`_ for an account on RTD, then `log in`_. Visit your dashboard_ and click
Import_ to add your project to the site. Fill in the name and description, then
specify where your repository is located. This is normally the URL or path name
you'd use to checkout, clone, or branch your code. Some examples:

* Git: ``http://github.com/ericholscher/django-kong.git``
* Subversion: ``http://varnish-cache.org/svn/trunk``
* Mercurial: ``https://bitbucket.org/ianb/pip``
* Bazaar: ``lp:pasta``

Add an optional homepage URL and some tags, then click "Create".

Within a few minutes your code will automatically be fetched from your public
repository, and the documentation will be built. Check out our :doc:`builds` page to learn more about how we build your docs, and to troubleshoot any issues that arise.

If you want to keep your code updated as you commit, configure your code repository to hit our `Post Commit Hooks`_. This will rebuild your docs every time you push your code.

If you have any more trouble, don't hesitate to reach out to us. The :doc:`support` page has more information on getting in touch.

.. _a screencast: https://www.youtube.com/watch?feature=player_embedded&v=oJsUvBQyHBs
.. _Sphinx: http://sphinx.pocoo.org/
.. _reStructuredText: http://sphinx.pocoo.org/rest.html
.. _this template: http://docs.writethedocs.org/en/latest/writing/beginners-guide-to-docs/#id1
.. _Sign up: http://readthedocs.org/accounts/register
.. _log in: http://readthedocs.org/accounts/login
.. _dashboard: http://readthedocs.org/dashboard
.. _Import: http://readthedocs.org/dashboard/import
.. _Post Commit Hooks: http://readthedocs.org/docs/read-the-docs/en/latest/webhooks.html


text:
<?php

namespace WPNXM\Updater\Crawler;

use WPNXM\Updater\VersionCrawler;

/**
 * uprofiler (PHP Extension) - Version Crawler
 */
class phpext_uprofiler extends VersionCrawler
{
	public $name = 'phpext_uprofiler';

    public $url = 'https://windows.php.net/downloads/pecl/snaps/uprofiler/';

    private $url_template = 'https://windows.php.net/downloads/pecl/snaps/uprofiler/%version%/php_uprofiler-%version%-%phpversion%-nts-%compiler%-%bitsize%.zip';

    public function crawlVersion()
    {
        return $this->filter('a')->each(function ($node) {
            if (preg_match("#(\d+\.\d+(\.\d+)*)$#", $node->text(), $matches)) {
                $version = $matches[1];

                if (version_compare($version, $this->latestVersion, '>=') === true) {

					$urls = $this->createPhpVersionsArrayForExtension($version, $this->url_template);
					if(empty($urls)) {
						return;
					}

                    return array(
                        'version' => $version,
                        'url'     => $urls,
                    );
                }
            }
        });
    }
}


text:
package pl.exsio.frameset.core.repository;

import java.io.Serializable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.NoRepositoryBean;
import pl.exsio.frameset.core.dao.GenericDao;

/**
 *
 * @author exsio
 * @param <T>
 * @param <ID>
 */
@NoRepositoryBean
public interface GenericJpaRepository<T, ID extends Serializable> extends JpaRepository<T, ID>, GenericDao<T, ID> {

}


text:
package org.apache.pulsar.common.naming;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.SortedSet;
import java.util.concurrent.CompletableFuture;

import org.apache.commons.lang3.tuple.Pair;
import org.apache.pulsar.common.naming.DestinationName;
import org.apache.pulsar.common.naming.NamespaceBundle;
import org.apache.pulsar.common.naming.NamespaceBundleFactory;
import org.apache.pulsar.common.naming.NamespaceBundles;
import org.apache.pulsar.common.naming.NamespaceName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.Test;

import com.github.benmanes.caffeine.cache.AsyncLoadingCache;
import com.google.common.collect.BoundType;
import com.google.common.collect.Range;
import com.google.common.collect.Sets;
import com.google.common.hash.Hashing;

public class NamespaceBundlesTest {

    private final NamespaceBundleFactory factory = NamespaceBundleFactory.createFactory(Hashing.crc32());

    @SuppressWarnings("unchecked")
    @Test
    public void testConstructor() throws Exception {
        try {
            new NamespaceBundles(null, (SortedSet<Long>) null, null);
            fail("Should fail w/ null pointer exception");
        } catch (NullPointerException npe) {
            // OK, expected
        }

        try {
            new NamespaceBundles(new NamespaceName("pulsar/use/ns2"), (SortedSet<Long>) null, null);
            fail("Should fail w/ null pointer exception");
        } catch (NullPointerException npe) {
            // OK, expected
        }

        try {
            new NamespaceBundles(new NamespaceName("pulsar.use.ns2"), (SortedSet<Long>) null, null);
            fail("Should fail w/ illegal argument exception");
        } catch (IllegalArgumentException iae) {
            // OK, expected
        }

        try {
            new NamespaceBundles(new NamespaceName("pulsar/use/ns2"), (SortedSet<Long>) null, factory);
            fail("Should fail w/ null pointer exception");
        } catch (NullPointerException npe) {
            // OK, expected
        }

        SortedSet<Long> partitions = Sets.newTreeSet();
        try {
            new NamespaceBundles(new NamespaceName("pulsar/use/ns2"), partitions, factory);
            fail("Should fail w/ illegal argument exception");
        } catch (IllegalArgumentException iae) {
            // OK, expected
        }

        partitions.add(0l);
        partitions.add(0x10000000l);
        partitions.add(0x40000000l);
        partitions.add(0xffffffffl);
        NamespaceBundles bundles = new NamespaceBundles(new NamespaceName("pulsar/use/ns2"), partitions, factory);
        Field partitionField = NamespaceBundles.class.getDeclaredField("partitions");
        Field nsField = NamespaceBundles.class.getDeclaredField("nsname");
        Field bundlesField = NamespaceBundles.class.getDeclaredField("bundles");
        partitionField.setAccessible(true);
        nsField.setAccessible(true);
        bundlesField.setAccessible(true);
        long[] partFld = (long[]) partitionField.get(bundles);
        // the same instance
        assertEquals(partitions.size(), partFld.length);
        NamespaceName nsFld = (NamespaceName) nsField.get(bundles);
        assertTrue(nsFld.toString().equals("pulsar/use/ns2"));
        ArrayList<NamespaceBundle> bundleList = (ArrayList<NamespaceBundle>) bundlesField.get(bundles);
        assertEquals(bundleList.size(), 3);
        assertEquals(bundleList.get(0),
                factory.getBundle(nsFld, Range.range(0l, BoundType.CLOSED, 0x10000000l, BoundType.OPEN)));
        assertEquals(bundleList.get(1),
                factory.getBundle(nsFld, Range.range(0x10000000l, BoundType.CLOSED, 0x40000000l, BoundType.OPEN)));
        assertEquals(bundleList.get(2),
                factory.getBundle(nsFld, Range.range(0x40000000l, BoundType.CLOSED, 0xffffffffl, BoundType.CLOSED)));
    }

    @Test
    public void testFindBundle() throws Exception {
        SortedSet<Long> partitions = Sets.newTreeSet();
        partitions.add(0l);
        partitions.add(0x40000000l);
        partitions.add(0xa0000000l);
        partitions.add(0xb0000000l);
        partitions.add(0xc0000000l);
        partitions.add(0xffffffffl);
        NamespaceBundles bundles = new NamespaceBundles(new NamespaceName("pulsar/global/ns1"), partitions, factory);
        DestinationName dn = DestinationName.get("persistent://pulsar/global/ns1/topic-1");
        NamespaceBundle bundle = bundles.findBundle(dn);
        assertTrue(bundle.includes(dn));

        dn = DestinationName.get("persistent://pulsar/use/ns2/topic-2");
        try {
            bundles.findBundle(dn);
            fail("Should have failed due to mismatched namespace name");
        } catch (IllegalArgumentException iae) {
            // OK, expected
        }

        Long hashKey = factory.getLongHashCode(dn.toString());
        // The following code guarantees that we have at least two ranges after the hashKey till the end
        SortedSet<Long> tailSet = partitions.tailSet(hashKey);
        tailSet.add(hashKey);
        // Now, remove the first range to ensure the hashKey is not included in newPar
        Iterator<Long> iter = tailSet.iterator();
        iter.next();
        SortedSet<Long> newPar = tailSet.tailSet(iter.next());

        try {
            bundles = new NamespaceBundles(dn.getNamespaceObject(), newPar, factory);
            bundles.findBundle(dn);
            fail("Should have failed due to out-of-range");
        } catch (ArrayIndexOutOfBoundsException iae) {
            // OK, expected
        }
    }

    @Test
    public void testsplitBundles() throws Exception {
        NamespaceName nsname = new NamespaceName("pulsar/global/ns1");
        DestinationName dn = DestinationName.get("persistent://pulsar/global/ns1/topic-1");
        NamespaceBundles bundles = factory.getBundles(nsname);
        NamespaceBundle bundle = bundles.findBundle(dn);
        final int numberSplitBundles = 4;
        // (1) split in 4
        Pair<NamespaceBundles, List<NamespaceBundle>> splitBundles = factory.splitBundles(bundle, numberSplitBundles);
        // existing_no_bundles(1) +
        // additional_new_split_bundle(4) -
        // parent_target_bundle(1)
        int totalExpectedSplitBundles = bundles.getBundles().size() + numberSplitBundles - 1;
        validateSplitBundlesRange(bundles.getFullBundle(), splitBundles.getRight());
        assertEquals(totalExpectedSplitBundles, splitBundles.getLeft().getBundles().size());

        // (2) split in 4: first bundle from above split bundles
        NamespaceBundleFactory utilityFactory = NamespaceBundleFactory.createFactory(Hashing.crc32());
        NamespaceBundles bundles2 = splitBundles.getLeft();
        NamespaceBundle testChildBundle = bundles2.getBundles().get(0);

        Pair<NamespaceBundles, List<NamespaceBundle>> splitChildBundles = splitBundlesUtilFactory(utilityFactory,
                nsname, bundles2, testChildBundle, numberSplitBundles);
        // existing_no_bundles(4) +
        // additional_new_split_bundle(4) -
        // parent_target_bundle(1)
        totalExpectedSplitBundles = bundles2.getBundles().size() + numberSplitBundles - 1;
        validateSplitBundlesRange(testChildBundle, splitChildBundles.getRight());
        assertEquals(totalExpectedSplitBundles, splitChildBundles.getLeft().getBundles().size());

        // (3) split in 3: second bundle from above split bundles
        NamespaceBundle testChildBundl2 = bundles2.getBundles().get(1);

        Pair<NamespaceBundles, List<NamespaceBundle>> splitChildBundles2 = splitBundlesUtilFactory(utilityFactory,
                nsname, bundles2, testChildBundl2, 3);
        // existing_no_bundles(4) +
        // additional_new_split_bundle(3) -
        // parent_target_bundle(1)
        totalExpectedSplitBundles = bundles2.getBundles().size() + 3 - 1;
        validateSplitBundlesRange(testChildBundl2, splitChildBundles2.getRight());
        assertEquals(totalExpectedSplitBundles, splitChildBundles2.getLeft().getBundles().size());
    }

    @Test
    public void testSplitBundleInTwo() throws Exception {
        final int NO_BUNDLES = 2;
        NamespaceName nsname = new NamespaceName("pulsar/global/ns1");
        DestinationName dn = DestinationName.get("persistent://pulsar/global/ns1/topic-1");
        NamespaceBundles bundles = factory.getBundles(nsname);
        NamespaceBundle bundle = bundles.findBundle(dn);
        // (1) split : [0x00000000,0xffffffff] => [0x00000000_0x7fffffff,0x7fffffff_0xffffffff]
        Pair<NamespaceBundles, List<NamespaceBundle>> splitBundles = factory.splitBundles(bundle, NO_BUNDLES);
        assertNotNull(splitBundles);
        assertBundleDivideInTwo(bundle, splitBundles.getRight(), NO_BUNDLES);

        // (2) split: [0x00000000,0x7fffffff] => [0x00000000_0x3fffffff,0x3fffffff_0x7fffffff],
        // [0x7fffffff,0xffffffff] => [0x7fffffff_0xbfffffff,0xbfffffff_0xffffffff]
        NamespaceBundleFactory utilityFactory = NamespaceBundleFactory.createFactory(Hashing.crc32());
        assertBundles(utilityFactory, nsname, bundle, splitBundles, NO_BUNDLES);

        // (3) split: [0x00000000,0x3fffffff] => [0x00000000_0x1fffffff,0x1fffffff_0x3fffffff],
        // [0x3fffffff,0x7fffffff] => [0x3fffffff_0x5fffffff,0x5fffffff_0x7fffffff]
        Pair<NamespaceBundles, List<NamespaceBundle>> splitChildBundles = splitBundlesUtilFactory(utilityFactory,
                nsname, splitBundles.getLeft(), splitBundles.getRight().get(0), NO_BUNDLES);
        assertBundles(utilityFactory, nsname, splitBundles.getRight().get(0), splitChildBundles, NO_BUNDLES);

        // (4) split: [0x7fffffff,0xbfffffff] => [0x7fffffff_0x9fffffff,0x9fffffff_0xbfffffff],
        // [0xbfffffff,0xffffffff] => [0xbfffffff_0xdfffffff,0xdfffffff_0xffffffff]
        splitChildBundles = splitBundlesUtilFactory(utilityFactory, nsname, splitBundles.getLeft(),
                splitBundles.getRight().get(1), NO_BUNDLES);
        assertBundles(utilityFactory, nsname, splitBundles.getRight().get(1), splitChildBundles, NO_BUNDLES);

    }

    private void validateSplitBundlesRange(NamespaceBundle fullBundle, List<NamespaceBundle> splitBundles) {
        assertNotNull(fullBundle);
        assertNotNull(splitBundles);
        Range<Long> fullRange = fullBundle.getKeyRange();
        Range<Long> span = splitBundles.get(0).getKeyRange();
        for (NamespaceBundle bundle : splitBundles) {
            span = span.span(bundle.getKeyRange());
        }
        assertTrue(fullRange.equals(span));
    }

    @SuppressWarnings("unchecked")
    private Pair<NamespaceBundles, List<NamespaceBundle>> splitBundlesUtilFactory(NamespaceBundleFactory utilityFactory,
            NamespaceName nsname, NamespaceBundles bundles, NamespaceBundle targetBundle, int numBundles)
            throws Exception {
        Field bCacheField = NamespaceBundleFactory.class.getDeclaredField("bundlesCache");
        bCacheField.setAccessible(true);
        ((AsyncLoadingCache<NamespaceName, NamespaceBundles>) bCacheField.get(utilityFactory)).put(nsname,
                CompletableFuture.completedFuture(bundles));
        return utilityFactory.splitBundles(targetBundle, numBundles);
    }

    private void assertBundles(NamespaceBundleFactory utilityFactory, NamespaceName nsname, NamespaceBundle bundle,
            Pair<NamespaceBundles, List<NamespaceBundle>> splitBundles, int numBundles) throws Exception {

        NamespaceBundle bundle1 = splitBundles.getRight().get(0);
        NamespaceBundle bundle2 = splitBundles.getRight().get(1);

        NamespaceBundles nspaceBundles = splitBundles.getLeft();
        Pair<NamespaceBundles, List<NamespaceBundle>> bundle1Split = splitBundlesUtilFactory(utilityFactory, nsname,
                nspaceBundles, bundle1, numBundles);
        assertBundleDivideInTwo(bundle1, bundle1Split.getRight(), numBundles);

        Pair<NamespaceBundles, List<NamespaceBundle>> bundle2Split = splitBundlesUtilFactory(utilityFactory, nsname,
                nspaceBundles, bundle2, numBundles);
        assertBundleDivideInTwo(bundle2, bundle2Split.getRight(), numBundles);

    }

    private void assertBundleDivideInTwo(NamespaceBundle bundle, List<NamespaceBundle> bundles, int numBundles) {
        assertTrue(bundles.size() == 2);
        String[] range = bundle.getBundleRange().split("_");
        long lower = Long.decode(range[0]);
        long upper = Long.decode(range[1]);
        long middle = ((upper - lower) / 2) + lower;

        String lRange = String.format("0x%08x_0x%08x", lower, middle);
        String uRange = String.format("0x%08x_0x%08x", middle, upper);
        assertTrue(bundles.get(0).getBundleRange().equals(lRange));
        assertTrue(bundles.get(1).getBundleRange().equals(uRange));
        log.info("[{},{}] => [{},{}]", range[0], range[1], lRange, uRange);
    }

    private static final Logger log = LoggerFactory.getLogger(NamespaceBundlesTest.class);
}


text:
It is used to know the elapsed time between proxy and WAS.

![overview](img/proxy-http-header-overview.png)

## Pinpoint Configuration

pinpoint.config
~~~
profiler.proxy.http.header.enable=true
~~~

## Proxy Configuration
### Apache HTTP Server
* http://httpd.apache.org/docs/2.4/en/mod/mod_headers.html

Add HTTP header.
~~~
Pinpoint-ProxyApache: t=991424704447256 D=3775428 i=51 b=49 app=foo-bar
~~~

e.g.

httpd.conf
~~~
<IfModule mod_jk.c>
...
RequestHeader set Pinpoint-ProxyApache "%t %D %i %b app=foo-bar"
...
</IfModule>
~~~
**%t is required value.**

### Nginx
* http://nginx.org/en/docs/http/ngx_http_core_module.html
* http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_set_header

Add HTTP header.
~~~
Pinpoint-ProxyNginx: t=1504248328.423 D=0.123 app=foo-bar
~~~

e.g.

nginx.conf
~~~
...
  server {
        listen       9080;
        server_name  localhost;

        location / {
            ...
            set $pinpoint_proxy_header "t=$msec D=$request_time app=foo-bar";
            proxy_set_header Pinpoint-ProxyNginx $pinpoint_proxy_header;
        }
  }
...
~~~
or
~~~
http {
...

    proxy_set_header Pinpoint-ProxyNginx t=$msec;

...
}
~~~
**t=$msec is required value.**

### App
Milliseconds since epoch and app information.

Add HTTP header.
~~~
Pinpoint-ProxyApp: t=1502861340 app=foo-bar
~~~
**t=epoch is required value.**


text:
import React from 'react';
import Avatar from 'material-ui/Avatar';
import Icon from 'material-ui/Icon';
import List, { ListItem, ListItemText } from 'material-ui/List';

export default function AvatarListItem() {
  return (
    <div style={{ backgroundColor: '#fff', width: 300 }}>
      <ListItem>
        <Avatar>
          <Icon>folder</Icon>
        </Avatar>
        <ListItemText primary="Avatar" />
      </ListItem>
      <ListItem>
        <Avatar>
          <Icon>folder</Icon>
        </Avatar>
        <ListItemText primary="Avatar" secondary="Secondary" />
      </ListItem>
      <List dense>
        <ListItem>
          <Avatar>
            <Icon>folder</Icon>
          </Avatar>
          <ListItemText primary="Avatar" />
        </ListItem>
        <ListItem>
          <Avatar>
            <Icon>folder</Icon>
          </Avatar>
          <ListItemText primary="Avatar" secondary="Secondary" />
        </ListItem>
      </List>
    </div>
  );
}


text:
require 'spec_helper'
module Alf
  module Lang
    describe ObjectOriented, 'to_array' do
      include ObjectOriented.new(supplier_names_relation)

      let(:ordering){ Ordering.coerce([[:name, :desc]]) }

      context 'with a block' do
        it 'yields the block with a ToArray' do
          seen = nil
          to_array{|x| seen = x}
          seen.should be_a(Engine::ToArray)
        end

        it 'returns the block result' do
          to_array{|x| 12}.should eq(12)
        end

        it 'sets the ordering correctly' do
          to_array(:sort => ordering){|x|
            x.ordering.should eq(ordering)
          }
        end
      end

      context 'without a block' do
        it 'returns an array' do
          to_array.should be_a(Array)
        end

        it 'respect the specified ordering' do
          expected = supplier_names.sort.reverse
          got      = to_array(:sort => ordering).map{|t| t[:name]}
          got.should eq(expected)

          expected = supplier_names.sort
          got      = to_array(:sort => [:name]).map{|t| t[:name]}
          got.should eq(expected)
        end
      end

    end
  end # module Lang
end # module Alf


text:
var filters = require('oam-browser-filters')
var aggregate = require('./union')

var d
module.exports = d = {
  aggregations: {
    footprints: {}
  },
  postAggregations: {
    footprints: {}
  }
}

filters.getAllCombinations().forEach(function (combo) {
  d.aggregations.footprints[combo.key] = aggregate.union(combo.key)
  d.postAggregations.footprints[combo.key + '_count'] = aggregate.count(combo.key)
})


text:
package types

// ContestEffect ...
type ContestEffect struct {
	Appeal        int `json:"appeal"`
	EffectEntries []struct {
		Effect   string `json:"effect"`
		Language struct {
			Name string `json:"name"`
			URL  string `json:"url"`
		} `json:"language"`
	} `json:"effect_entries"`
	FlavorTextEntries []struct {
		FlavorText string `json:"flavor_text"`
		Language   struct {
			Name string `json:"name"`
			URL  string `json:"url"`
		} `json:"language"`
	} `json:"flavor_text_entries"`
	ID  int `json:"id"`
	Jam int `json:"jam"`
}


text:
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace SoundCloud.Api.Entities.Enums
{
    [JsonConverter(typeof(StringEnumConverter))]
    public enum ActivityType
    {
        [EnumMember(Value = "other")]
        Other = 0,

        [EnumMember(Value = "track-repost")]
        TrackRepost,

        [EnumMember(Value = "playlist-repost")]
        PlaylistRepost,

        [EnumMember(Value = "playlist")]
        Playlist,

        [EnumMember(Value = "track")]
        Track,

        [EnumMember(Value = "comment")]
        Comment,

        [EnumMember(Value = "favoriting")]
        Favoriting
    }
}