text:
package com.aspectran.core.util;

import com.aspectran.core.lang.Nullable;

import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;

/**
 * Miscellaneous class utility methods.
 */
public abstract class ClassUtils {

    /** The package separator character '.' */
    public static final char PACKAGE_SEPARATOR_CHAR = '.';

    /** The ".class" file suffix */
    public static final String CLASS_FILE_SUFFIX = ".class";

    /**
     * Method that can be called to try to create an instance of
     * specified type. Instantiation is done using default no-argument
     * constructor.
     * @param <T> the generic type
     * @param cls the class to check
     * @return an instantiated object
     * @throws IllegalArgumentException if instantiation fails for any reason;
     *      except for cases where constructor throws an unchecked exception
     *      (which will be passed as is)
     */
    public static <T> T createInstance(Class<T> cls) {
        Constructor<T> ctor;
        try {
            ctor = findConstructor(cls);
        } catch (NoSuchMethodException e) {
            throw new IllegalArgumentException("Class " + cls.getName() +
                    " has no default (no arg) constructor");
        }
        try {
            return ctor.newInstance();
        } catch (Exception e) {
            throw ExceptionUtils.unwrapAndThrowAsIAE(e, "Unable to instantiate class " +
                    cls.getName() + ": " + e.getMessage());
        }
    }

    /**
     * Method that can be called to try to create an instantiate of
     * specified type.
     * @param <T> the generic type
     * @param cls the class to check
     * @param args the arguments
     * @return an instantiated object
     * @throws IllegalArgumentException if instantiation fails for any reason;
     *      except for cases where constructor throws an unchecked exception
     *      (which will be passed as is)
     */
    public static <T> T createInstance(Class<T> cls, Object... args) {
        Class<?>[] argTypes = new Class<?>[args.length];
        for (int i = 0; i < args.length; i++) {
            argTypes[i] = args[i].getClass();
        }
        return createInstance(cls, args, argTypes);
    }

    /**
     * Method that can be called to try to create an instance of
     * specified type.
     * @param <T> the generic type
     * @param cls the class to check
     * @param args the arguments
     * @param argTypes the argument types of the desired constructor
     * @return an instantiated object
     * @throws IllegalArgumentException if instantiation fails for any reason;
     *      except for cases where constructor throws an unchecked exception
     *      (which will be passed as is)
     */
    public static <T> T createInstance(Class<T> cls, Object[] args, Class<?>[] argTypes) {
        Constructor<T> ctor;
        try {
            ctor = findConstructor(cls, argTypes);
        } catch (NoSuchMethodException e) {
            throw new IllegalArgumentException("Class " + cls.getName() +
                    " has no constructor which can accept the given arguments");
        }
        try {
            return ctor.newInstance(args);
        } catch (Exception e) {
            throw ExceptionUtils.unwrapAndThrowAsIAE(e, "Unable to instantiate class " + cls.getName()
                    + ", problem: " + e.getMessage());
        }
    }

    /**
     * Obtain an accessible constructor for the given class and parameters.
     * @param cls the class to check
     * @param argTypes the argument types of the desired constructor
     * @param <T> the generic type
     * @return the constructor reference
     * @throws NoSuchMethodException if no such constructor exists
     */
    public static <T> Constructor<T> findConstructor(Class<T> cls, Class<?>... argTypes)
            throws NoSuchMethodException {
        Constructor<T> ctor;
        try {
            ctor = cls.getDeclaredConstructor(argTypes);
        } catch (NoSuchMethodException e) {
            throw e;
        } catch (Exception e) {
            throw new IllegalArgumentException("Unable to find constructor of class " + cls.getName() +
                    ", problem: " + e.getMessage(), ExceptionUtils.getRootCause(e));
        }
        // must be public
        if (!Modifier.isPublic(ctor.getModifiers())) {
            throw new IllegalArgumentException("Constructor for " + cls.getName() +
                    " is not accessible (non-public?): not allowed to try modify access via Reflection: can not instantiate type");
        }
        return ctor;
    }

    /**
     * Check whether the given class is visible in the given ClassLoader.
     * @param clazz the class to check (typically an interface)
     * @param classLoader the ClassLoader to check against
     *      (may be {@code null} in which case this method will always return {@code true})
     * @return true if the given class is visible; otherwise false
     * @since 6.0.0
     */
    public static boolean isVisible(Class<?> clazz, ClassLoader classLoader) {
        if (classLoader == null) {
            return true;
        }
        try {
            if (clazz.getClassLoader() == classLoader) {
                return true;
            }
        } catch (SecurityException ex) {
            // Fall through to loadable check below
        }

        // Visible if same Class can be loaded from given ClassLoader
        return isLoadable(clazz, classLoader);
    }

    /**
     * Check whether the given class is loadable in the given ClassLoader.
     * @param clazz the class to check (typically an interface)
     * @param classLoader the ClassLoader to check against
     * @return true if the given class is loadable; otherwise false
     * @since 6.0.0
     */
    private static boolean isLoadable(Class<?> clazz, ClassLoader classLoader) {
        try {
            return (clazz == classLoader.loadClass(clazz.getName()));
            // Else: different class with same name found
        } catch (ClassNotFoundException ex) {
            // No corresponding class found at all
            return false;
        }
    }

    /**
     * Returns the default class loader within the current context.
     * If there is a context classloader it is returned, otherwise the classloader
     * which loaded the ClassUtils Class is returned.
     * @return the appropriate default classloader which is guaranteed to be non-null
     */
    public static ClassLoader getDefaultClassLoader() {
        ClassLoader cl = null;
        try {
            cl = Thread.currentThread().getContextClassLoader();
        } catch (Throwable ex) {
            // ignore
        }
        if (cl == null) {
            cl = ClassUtils.class.getClassLoader();
        }
        if (cl == null) {
            cl = ClassLoader.getSystemClassLoader();
        }
        return cl;
    }

    /**
     * Override the thread context ClassLoader with the environment's bean ClassLoader
     * if necessary, i.e. if the bean ClassLoader is not equivalent to the thread
     * context ClassLoader already.
     * @param classLoaderToUse the actual ClassLoader to use for the thread context
     * @return the original thread context ClassLoader, or {@code null} if not overridden
     */
    @Nullable
    public static ClassLoader overrideThreadContextClassLoader(@Nullable ClassLoader classLoaderToUse) {
        Thread currentThread = Thread.currentThread();
        ClassLoader threadContextClassLoader = currentThread.getContextClassLoader();
        if (classLoaderToUse != null && !classLoaderToUse.equals(threadContextClassLoader)) {
            currentThread.setContextClassLoader(classLoaderToUse);
            return threadContextClassLoader;
        } else {
            return null;
        }
    }

    public static void restoreThreadContextClassLoader(@Nullable ClassLoader classLoader) {
        if (classLoader != null) {
            Thread.currentThread().setContextClassLoader(classLoader);
        }
    }

}


text:
/* mapSts.h was originally generated by the autoSql program, which also
 * generated mapSts.c and mapSts.sql.  This header links the database and the RAM
 * representation of objects. */

#ifndef MAPSTS_H
#define MAPSTS_H

struct mapSts
/* An STS based map in relationship to golden path */
    {
    struct mapSts *next;  /* Next in singly linked list. */
    char *chrom;	/* Chromosome */
    unsigned chromStart;	/* Start position in chrom */
    unsigned chromEnd;	/* End position in chrom */
    char *name;	/* Name of STS marker */
    unsigned score;	/* Score of a marker - depends on how many contigs it hits */
    unsigned identNo;	/* Identification number of STS */
    char *rhChrom;	/* Chromosome number from the RH map - 0 if there is none */
    float distance;	/* Distance from the RH map */
    char *ctgAcc;	/* Contig accession number */
    char *otherAcc;	/* Accession number of other contigs that the marker hits */
    };

void mapStsStaticLoad(char **row, struct mapSts *ret);
/* Load a row from mapSts table into ret.  The contents of ret will
 * be replaced at the next call to this function. */

struct mapSts *mapStsLoad(char **row);
/* Load a mapSts from row fetched with select * from mapSts
 * from database.  Dispose of this with mapStsFree(). */

struct mapSts *mapStsCommaIn(char **pS, struct mapSts *ret);
/* Create a mapSts out of a comma separated string.
 * This will fill in ret if non-null, otherwise will
 * return a new mapSts */

void mapStsFree(struct mapSts **pEl);
/* Free a single dynamically allocated mapSts such as created
 * with mapStsLoad(). */

void mapStsFreeList(struct mapSts **pList);
/* Free a list of dynamically allocated mapSts's */

void mapStsOutput(struct mapSts *el, FILE *f, char sep, char lastSep);
/* Print out mapSts.  Separate fields with sep. Follow last field with lastSep. */

#define mapStsTabOut(el,f) mapStsOutput(el,f,'\t','\n');
/* Print out mapSts as a line in a tab-separated file. */

#define mapStsCommaOut(el,f) mapStsOutput(el,f,',',',');
/* Print out mapSts as a comma separated list including final comma. */

#endif /* MAPSTS_H */

redpajama_set_name: RedPajamaGithub


text:
# jQuery accessible autocomplete list
This jQuery plugin will transform and enhance a simple text input with a datalist into a wonderful and shiny input with autocomplete, and accessible.

The demo is here: https://a11y.nicolas-hoffmann.net/autocomplete-list/

## How it works

This plugin:

- starts from a classical input completed by a datalist;
- then takes the elements in your datalist, reorder them and store them into Javascript arrays;
- then wraps the input into a container, adds status/help text zones and a "clear" button;
- then it listens when you type something in the field, and proposes you some suggestions.

## Why it is cool

As it is made using __progressive enhancement__, if the JavaScript fails to load or is blocked by your visitor, your website will still be ok.

It is __accessible__: it works with VoiceOver, NVDA, Jaws, and it loves keyboard.

It is __easy to customize__ there is a default configuration that can be changed/adapted, and you can override it using data-* attributes if you need it.

For the design, you can also __customize the CSS to fullfil your needs__.

## How to use it

First, add a class js-combobox on an input with a working datalist:
```html
<input type="text" name="mysuper_field" id="id_mysuper_field" class="js-combobox" list="beers" data-combobox-prefix-class="combobox" />
 <datalist id="beers">
  <option value="Meteor">
  <option value="Pils">
  <option value="Kronenbourg">
  <option value="Kronenbourg 2 (for test)">
  <option value="Kronenbourg 3 (for test)">
  <option value="Grimbergen">
 </datalist>
```

Then download the plugin and use jQuery of course. This plugin is also available on NPMjs.com and can be installed using ```npm i jquery-accessible-autocomplete-list-aria```: https://www.npmjs.com/package/jquery-accessible-autocomplete-list-aria

You may also get it from Bower: ```bower install jquery-accessible-autocomplete-list-aria```.

You may use some options, so have a look at plugin options.

## Options

At the beginning of the plugin, a global configuration is available:
```js
var $js_combobox = $('.js-combobox'),
 $body = $('body'),
 default_text_help = 'Use tabulation (or down) key to access and browse suggestions after input. Confirm your choice with enter key, or esc key to close suggestions box.',
 default_class_for_invisible_text = 'invisible',
 suggestion_single = 'There is ',
 suggestion_plural = 'There are ',
 suggestion_word = 'suggestion',
 suggestion_word_plural = 'suggestions',
 button_clear_title = 'clear this field',
 button_clear_text = 'X',
 case_sensitive = 'yes',
 min_length = 0,
 limit_number_suggestions = 666,
 search_option = 'beginning', // or 'containing'
 see_more_text = 'See more results…',
 tablo_suggestions = [];
```

You may adapt texts to your need with it. However, if you need to customize one autocomplete field, you may use ```data-*``` attributes to override global configuration. Here is the list:

- ```data-combobox-prefix-class="foo"```: prefix all generated classes by ```foo```.
- ```data-combobox-case-sensitive="yes/no"```: plugin is case-sensitive by default, which means "KROW" will be before "Kron". If you set it up to ```="no"```, the plugin will order all elements without caring of the case (see first example).
- ```data-combobox-help-text```: to override ```default_text_help``` in the config.
- ```data-combobox-button-title```: to override ```button_clear_title``` in the config, will be the title of the clear button.
- ```data-suggestion-single```: to override ```suggestion_single``` in the config, will be vocalized when there is 1 suggestion.
- ```data-suggestion-plural```: to override ```suggestion_plural``` in the config, will be vocalized when there are more several suggestions.
- ```data-suggestion-word```: to override ```suggestion_word``` in the config.
- ```data-suggestion-word-plural```: to override ```suggestion_word_plural``` in the config.
- ```data-combobox-min-length="xx"```: to override ```min_length``` in the config, a minimal length of text from which will be displayed suggestions.
- ```data-combobox-limit-number-suggestions="3"```: to override ```limit_number_suggestions```, the maximum number of suggestions displayed.
- ```data-combobox-search-option="beginning/containing"```: when plugin is searching a match with foo in the suggestions, ```beginning``` value will search suggestions beginning with foo, ```containing``` will search suggestions containing foo.
- ```data-combobox-see-more-text="<text>"```: if the number limit of suggestions is reached, the plugin will put this text as last suggestion.
- ```data-combobox-notab-options="yes"```: if you don't want to enable the tab key to go into/through suggestions.

Have a look at [the second example of the demo](http://a11y.nicolas-hoffmann.net/autocomplete-list/) if you want to see data attributes in action.

## How to style it

In these examples, I've used ```data-combobox-prefix-class="combobox"```, which means all classes will be prefixed by combobox-. Here are minimal styles needed:

```css
.invisible {
  border: 0;
  clip: rect(0 0 0 0);
  height: 1px;
  margin: -1px;
  overflow: hidden;
  padding: 0;
  position: absolute;
  width: 1px;
}

.combobox-container {
  position: relative;
  max-width: 250px;
}

.combobox-suggestions {
  position: absolute;
}
.combobox-suggestion {
  cursor: pointer;
}

.combobox-clear-button {
  position: absolute;
  right: 1px;
  font-family: inherit;
  font-size: 1em;
  padding: .5em;
  background: transparent
}
```

Here is a full example really nicer and more pleasant to use:

```css
.invisible {
  border: 0;
  clip: rect(0 0 0 0);
  height: 1px;
  margin: -1px;
  overflow: hidden;
  padding: 0;
  position: absolute;
  width: 1px;
}

.combobox-container {
  position: relative;
  max-width: 250px;
  margin: 0 auto;
}

.combobox-suggestions {
  position: absolute;
  left: 0;
  width: 250px;
  background: #fff;
}
.combobox-suggestion {
  color: #666;
  border-bottom: 1px solid #000;
  border-left: 1px solid #000;
  border-right: 1px solid #000;
  cursor: pointer;
  text-align: left;
}
.combobox-suggestion:first-child {
  border-top: 1px solid #000;
}
.combobox-suggestion:hover,
.combobox-suggestion:focus {
  color: #000;
}

.combobox-clear-button {
  position: absolute;
  right: 1px;
  font-family: inherit;
  font-size: 1em;
  padding: .5em;
  background: transparent
}

/* http://geektnt.com/how-to-remove-x-from-search-input-field-on-chrome-and-ie.html */
.js-combobox[type=text]::-ms-clear { display: none; width: 0; height: 0; }
.js-combobox[type=text]::-ms-reveal { display: none; width: 0; height: 0; }
```

With these styles, the focus/hover looks far better, and a border is added aroung suggestion list.

## Keys

__When focus is on the text input__

- You may use tab to reach suggestions and continue through them (activated by default, can be removed using ```data-combobox-notab-options="yes"```);
- Esc will close suggestion list;
- You can also use Down to reach the suggestion list.

__When focus is on the suggestions__

- __Tab/Shift+Tab__ allow to navigate through options (activated by default, can be removed using ```data-combobox-notab-options="yes"```);
- __Enter__ or __Space__ update the value of the input with the currently highlighted option, close the drop-down list and move the focus back to the input;
- __Esc__ will close suggestion list, give focus back to the text input and remove suggestion in the input (go back to what was typed in);
- You can also use __Down/Up__ arrows to navigate between suggestions.

## Other informations

### License

No license problem, it uses MIT license, so it's free, open-source and you can do whatever you want with it, including commercial use. This permission notice shall be included in all copies or substantial portions of it.

However, it is not prohibited to tell me that you've used it, or send me a little "thank you". ;)

### Weight

It is lightweight: 19kb(development), 6.8kb (minified), only 2.1kb minified and gzipped.

### Tribute

The idea of this script is inspired by [Heydon's basic autocomplete with listbox demo](https://twitter.com/heydonworks/status/655433134813655040). Aurélien Levy enhanced it with a working prototype, and I've finished the work (packaging, reutilisability, progressive enhancement, etc.) with Aurélien.


text:
package io.crate.planner.consumer;

import io.crate.expression.symbol.InputColumn;
import io.crate.expression.symbol.Literal;
import io.crate.expression.symbol.Symbol;
import io.crate.metadata.Reference;
import org.elasticsearch.test.ESTestCase;
import io.crate.testing.TestingHelpers;
import io.crate.types.DataTypes;
import org.junit.Test;

import java.util.List;

public class OrderByPositionVisitorTest extends ESTestCase {

    @Test
    public void testOrderByPositionInputs() throws Exception {
        int[] orderByPositions = OrderByPositionVisitor.orderByPositions(
            List.<Symbol>of(new InputColumn(0), new InputColumn(1), new InputColumn(0)),
            List.<Symbol>of(Literal.BOOLEAN_TRUE, Literal.of(1))
        );
        assertArrayEquals(new int[]{0, 1, 0}, orderByPositions);
    }

    @Test
    public void testSymbols() throws Exception {
        Reference ref = TestingHelpers.createReference("column", DataTypes.STRING);
        int[] orderByPositions = OrderByPositionVisitor.orderByPositions(
            List.of(ref, new InputColumn(1), new InputColumn(0)),
            List.of(ref, Literal.of(1))
        );
        assertArrayEquals(new int[]{0, 1, 0}, orderByPositions);
    }
}


text:
//
//  ViewWidget.h
//  EOSClient2
//
//  Created by Song on 10/17/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <CAPKit/CAPView.h>

/**The View Widget*/
@interface CAPViewWidget : CAPAbstractUIWidget<IViewWidget>{
    NSMutableArray *internalSubitems;
    CGRect contentRect;
    UIView *view;

    BOOL initedSubview;
}

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-property-synthesis"
@property (nonatomic, readonly) CAPViewM *model;
@property (nonatomic, readonly) CAPViewM *stableModel;
#pragma clang diagnostic pop

@property (nonatomic, readonly, getter=getSubitems) NSArray *subitems;

@property (nonatomic, assign) BOOL destroyOnRemoved;

- (void) addWidget: (CAPAbstractUIWidget *) widget;
- (void) addWidget: (CAPAbstractUIWidget *) widget At: (int) idx;

-(id)initWithModel:(UIWidgetM *)m withView: (UIView *) v withPageSandbox: (CAPPageSandbox *) sandbox;

- (void) reLayoutChildren;
- (void) removeAllChildren;

#ifdef DEBUG_EOS
- (NSUInteger) childrenCount;
- (NSUInteger) affectCount;
#endif

@end


text:
const CGFloat FORWARD_BACKWARD_TILT_ANGLE_LIMIT = 20;
const CGFloat CALIBRATED_ANGLE_LIMIT = 30;
const CGFloat LEFT_RIGHT_TILT_ANGLE_LIMIT = 10;
const CGFloat CONTENTOFFSET_LIMIT = -64;

@interface RAPTiltToScroll ()
@property (nonatomic) CMMotionManager *motionManager;
@property (nonatomic) CGFloat lastContentOffset;
@property (nonatomic) BOOL selectModeIsOn;
@property (nonatomic) BOOL selectModeHasBeenSwitched;
@property (nonatomic) BOOL scrollingSessionHasStarted;
@property (nonatomic) float calibratedAngle;
@end

@implementation RAPTiltToScroll

-(instancetype)init
{
    self = [super init];
    if (self)
    {
        self.calibratedAngle = [[[NSUserDefaults standardUserDefaults] objectForKey:@"calibratedAngle"] floatValue];
        //NSLog(@"calibratedangle is %f", self.calibratedAngle);
    }
    return self;
}

-(void)setCalibratedAngle:(float)calibratedAngle
{
    if (calibratedAngle < -CALIBRATED_ANGLE_LIMIT)
    {
        _calibratedAngle = -CALIBRATED_ANGLE_LIMIT;
    }
    else if (calibratedAngle > CALIBRATED_ANGLE_LIMIT)
    {
        _calibratedAngle = CALIBRATED_ANGLE_LIMIT;
    }
    else
    {
        _calibratedAngle = calibratedAngle;
    }
}

-(void)postCreateRectSelectorNotification
{
    [[NSNotificationCenter defaultCenter] postNotificationName:RAPCreateRectSelectorNotification object:self];
}

-(void)setScrollingSessionHasStarted:(BOOL)scrollingSessionHasStarted
{
    //NSLog(@"scrollingsessionstarted is being set to %d", scrollingSessionHasStarted);
    _scrollingSessionHasStarted = scrollingSessionHasStarted;
}
-(void)startTiltToScrollWithSensitivity:(float)sensitivity forScrollView:(UIScrollView *)scrollView inWebView:(BOOL)isInWebView
{
    self.selectModeIsOn = NO;

    self.hasStarted = YES;
    //NSLog(@"Contentoffset.y is %f", scrollView.contentOffset.y);
    [self.motionManager startDeviceMotionUpdatesUsingReferenceFrame:CMAttitudeReferenceFrameXArbitraryZVertical toQueue:[NSOperationQueue mainQueue] withHandler:^(CMDeviceMotion *motion, NSError *error)
     {
         [[NSOperationQueue mainQueue] addOperationWithBlock:^{

             CGFloat tiltAngleLeftOrRight = [self LeftOrRightAngleInDegreesUsingXGravity:motion.gravity.x
                                                                                YGravity:motion.gravity.y
                                                                             andZGravity:motion.gravity.z];
             CGFloat tiltAngleForwardorBackward = [self ForwardOrBackwardAngleInDegreesUsingXGravity:motion.gravity.x
                                                                                YGravity:motion.gravity.y
                                                                                andZGravity:motion.gravity.z];
             // NSLog(@"forwardorbackward is %f", tiltAngleForwardorBackward);

             if (self.isCalibrating)
             {
                 //remove rects
                 //turn selectmode off
                 self.selectModeIsOn = NO;
                 self.selectModeHasBeenSwitched = NO;
                 self.scrollingSessionHasStarted = NO;
                 [[NSNotificationCenter defaultCenter] postNotificationName:RAPRemoveRectSelectorNotification object:self];

                 if (self.hasCalibrated)
                 {
                     self.calibratedAngle = tiltAngleForwardorBackward;
                     [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithFloat:self.calibratedAngle] forKey:@"calibratedAngle"];
                     //NSLog(@"calibratedangle is %f", self.calibratedAngle);
                     self.isCalibrating = NO;
                     self.hasCalibrated = NO;
                 }
             }

             // Invalid angles
             if (!self.isCalibrating && tiltAngleLeftOrRight != 90.0 && tiltAngleForwardorBackward != 90.0)
             {
                 [self scrollTableViewWithIntensityOfAnglesLeftOrRight:tiltAngleLeftOrRight
                                                     ForwardOrBackward:tiltAngleForwardorBackward
                                                          inScrollView:(UIScrollView *)scrollView
                                                             inWebView:isInWebView];
             }
         }];

     }];
}

-(void)stopTiltToScroll
{
    [self.motionManager stopDeviceMotionUpdates];
    self.selectModeIsOn = NO;
    self.selectModeHasBeenSwitched = NO;
    self.scrollingSessionHasStarted = NO;
    self.hasStarted = NO;
}

#pragma mark Scrolling

-(BOOL)floatIsPositive:(CGFloat)number
{
    return number >= 0 ? YES : NO;
}

-(BOOL)angleIsForward:(CGFloat)angle
{
    //NSLog(@"calibratedangle is %f", self.calibratedAngle);
    return angle > (FORWARD_BACKWARD_TILT_ANGLE_LIMIT + self.calibratedAngle) ? YES : NO;
}

-(void)scrollTableViewWithIntensityOfAnglesLeftOrRight:(CGFloat)leftOrRightAngle ForwardOrBackward:(CGFloat)forwardOrBackwardAngle inScrollView:(UIScrollView *)scrollView inWebView:(BOOL)isInWebView
{
    if (forwardOrBackwardAngle < -80 || forwardOrBackwardAngle > 200)
    {
        // invalid angles!
        return;
    }

    if ((forwardOrBackwardAngle < FORWARD_BACKWARD_TILT_ANGLE_LIMIT + self.calibratedAngle || forwardOrBackwardAngle > -FORWARD_BACKWARD_TILT_ANGLE_LIMIT + self.calibratedAngle) && (leftOrRightAngle > LEFT_RIGHT_TILT_ANGLE_LIMIT || leftOrRightAngle < -LEFT_RIGHT_TILT_ANGLE_LIMIT))
    {
        //NSLog(@"Tilted %f degrees clockwise", leftOrRightAngle);
        if (!isInWebView)
        {
            if (scrollView.contentOffset.y + leftOrRightAngle/5 >= CONTENTOFFSET_LIMIT && !self.selectModeIsOn)
            {
                CGPoint offsetCGPoint = CGPointMake(scrollView.contentOffset.x, scrollView.contentOffset.y + leftOrRightAngle/5);
                scrollView.contentOffset = offsetCGPoint;
                //NSLog(@"Contentoffset.y is %f", scrollView.contentOffset.y);
                if (!self.scrollingSessionHasStarted)
                {
                    // This should happen only ONCE per scrolling session- note when a scrollingsession began and when it ends
                    [self.delegate addObserverForAdjustToNearestRowNotification];
                    NSLog(@"delegate method addObserverForAdjustToNearestRowNotification called");
                    self.scrollingSessionHasStarted = YES;
                }

            }
        }
        else if (isInWebView)
        {
            if (scrollView.frame.size.height > scrollView.contentOffset.y + leftOrRightAngle/5 >= CONTENTOFFSET_LIMIT && !self.selectModeIsOn)
            {
                CGPoint offsetCGPoint = CGPointMake(scrollView.contentOffset.x, scrollView.contentOffset.y + leftOrRightAngle/5);
                scrollView.contentOffset = offsetCGPoint;
                //NSLog(@"Contentoffset.y is %f", scrollView.contentOffset.y);
                if (!self.scrollingSessionHasStarted)
                {
                    self.scrollingSessionHasStarted = YES;
                }
            }
        }

        if (self.selectModeIsOn)
        {
            if (leftOrRightAngle > LEFT_RIGHT_TILT_ANGLE_LIMIT)
            {
                // Post this notification and immediately remove the observer, as we want this to happen only once
                [[NSNotificationCenter defaultCenter] postNotificationName:RAPSelectRowNotification object:self];
                self.selectModeIsOn = NO;
            }
            else if (leftOrRightAngle < -LEFT_RIGHT_TILT_ANGLE_LIMIT)
            {
                [[NSNotificationCenter defaultCenter] postNotificationName:RAPSegueBackNotification object:self];
                self.selectModeIsOn = NO;
            }

        }
        //NSLog(@"Contentoffset.y is %f", scrollView.contentOffset.y);
    }
    if ((forwardOrBackwardAngle > FORWARD_BACKWARD_TILT_ANGLE_LIMIT + self.calibratedAngle || forwardOrBackwardAngle < -FORWARD_BACKWARD_TILT_ANGLE_LIMIT + self.calibratedAngle) && (leftOrRightAngle < LEFT_RIGHT_TILT_ANGLE_LIMIT || leftOrRightAngle > -LEFT_RIGHT_TILT_ANGLE_LIMIT))
    {
        // NSLog(@"Tilted %f degrees", forwardOrBackwardAngle);
        if (!self.selectModeHasBeenSwitched) // selectModeHasBeenSwitched is needed to differentiate between neutral state and selecting state. selectModeIsOn is used to toggle between creating the rect selector and removing it.
        {
            BOOL change = !self.selectModeIsOn;
            self.selectModeIsOn = change;
            self.selectModeHasBeenSwitched = YES;
        }
        if (self.selectModeIsOn)
        {
            // For some reason when separating into a dictionary to put in the notification, the following code does not allow the rect selector to start from the bottom: NSDictionary *dictionaryWithBools = @{[NSNumber numberWithBool:[self floatIsPositive:forwardOrBackwardAngle]]:@"atTop",[NSNumber numberWithBool:isInWebView]:@"inWebView"};
            // Post this notification and immediately remove the observer, as we want this to happen only once
            [[NSNotificationCenter defaultCenter] postNotificationName:RAPCreateRectSelectorNotification object:self userInfo:[NSDictionary dictionaryWithObjects:@[[NSNumber numberWithBool:[self angleIsForward:forwardOrBackwardAngle]], [NSNumber numberWithBool:isInWebView], [NSNumber numberWithFloat:forwardOrBackwardAngle]] forKeys:@[@"atTop",@"inWebView",@"angle"]]];
            //NSLog(@"Attop is %d", [self floatIsPositive:forwardOrBackwardAngle]);
            //NSLog(@"Tilted %f degrees forward", forwardOrBackwardAngle);
        }
        if (!self.selectModeIsOn)
        {
            // Post this notification and immediately remove the observer, as we want this to happen only once
            [[NSNotificationCenter defaultCenter] postNotificationName:RAPRemoveRectSelectorNotification object:self];
        }

    }

    if (forwardOrBackwardAngle < FORWARD_BACKWARD_TILT_ANGLE_LIMIT + self.calibratedAngle && forwardOrBackwardAngle > -FORWARD_BACKWARD_TILT_ANGLE_LIMIT + self.calibratedAngle && leftOrRightAngle < LEFT_RIGHT_TILT_ANGLE_LIMIT && leftOrRightAngle > -LEFT_RIGHT_TILT_ANGLE_LIMIT)
    {
        // Prevent each millisecond of having device tilted turn select mode on/off repeatedly
        self.selectModeHasBeenSwitched = NO;
        self.scrollingSessionHasStarted = NO;
        [[NSNotificationCenter defaultCenter] postNotificationName:RAPTableViewShouldAdjustToNearestRowAtIndexPathNotification object:self];
    }

}

-(void)segueSuccessful
{
    // If segue succeeds, turn off selectMode. If it was unsuccessful, leave selectMode on
    self.selectModeIsOn = NO;
}

#pragma mark Motion Manager

-(CMMotionManager *)motionManager
{
    if (!_motionManager)
    {
        _motionManager = [[CMMotionManager alloc] init];
        _motionManager.deviceMotionUpdateInterval = 5.0 / 60.0;
    }
    return _motionManager;
}

-(void)setupTiltToScrollTableView
{

}

-(CGFloat)LeftOrRightAngleInDegreesUsingXGravity:(CGFloat)xGravity YGravity:(CGFloat)yGravity andZGravity:(CGFloat)zGravity
{
    CGFloat angle = 0;

    switch ([[UIDevice currentDevice] orientation])
    {
        case UIDeviceOrientationLandscapeLeft:
        {
            angle = atan2(xGravity, -yGravity);
            break;
        }
        case UIDeviceOrientationLandscapeRight:
        {
            angle = atan2(-xGravity, yGravity);
            break;
        }
        case UIDeviceOrientationPortrait:
        {
            angle = atan2(yGravity, xGravity);
            break;
        }
        case UIDeviceOrientationPortraitUpsideDown:
        {
            angle = atan2(-yGravity, -xGravity);
            break;
        }
        case UIDeviceOrientationFaceUp:
        {
            break;
        }
        case UIDeviceOrientationFaceDown:
        {
            break;
        }
        case UIDeviceOrientationUnknown:
        {
            break;
        }
    }
    CGFloat angleToReturn = (angle + M_PI_2) * 180.0f / M_PI;
    return angleToReturn;
}

-(CGFloat)ForwardOrBackwardAngleInDegreesUsingXGravity:(CGFloat)xGravity YGravity:(CGFloat)yGravity andZGravity:(CGFloat)zGravity
{
    CGFloat angle = 0;
    switch ([[UIDevice currentDevice] orientation])
    {
        case UIDeviceOrientationLandscapeLeft:
        {
            angle = atan2(xGravity, zGravity);
            break;
        }
        case UIDeviceOrientationLandscapeRight:
        {
            angle = atan2(-xGravity, zGravity);
            break;
        }
        case UIDeviceOrientationPortrait:
        {
            angle = atan2(yGravity, zGravity);
            break;
        }
        case UIDeviceOrientationPortraitUpsideDown:
        {
            angle = atan2(-yGravity, zGravity);
        }
        case UIDeviceOrientationFaceUp:
        {
            break;
        }
        case UIDeviceOrientationFaceDown:
        {
            break;
        }
        case UIDeviceOrientationUnknown:
        {
            break;
        }
    }
    CGFloat angleToReturn = (angle + M_PI_2) * 180.0f / M_PI;
    return angleToReturn;
}

@end


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Rech. anatomiques et physiologiques sur la Garance 55 (1837)

#### Original name
Rhizoctonia rubiae M.J. Decne., 1837

### Remarks
null


text:
package io.quarkus.config.yaml.runtime;

import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.microprofile.config.spi.ConfigSource;
import org.eclipse.microprofile.config.spi.ConfigSourceProvider;

import io.smallrye.config.AbstractLocationConfigSourceLoader;
import io.smallrye.config.source.yaml.YamlConfigSource;

public class ApplicationYamlConfigSourceLoader extends AbstractLocationConfigSourceLoader {
    @Override
    protected String[] getFileExtensions() {
        return new String[] {
                "yaml",
                "yml"
        };
    }

    @Override
    protected ConfigSource loadConfigSource(final URL url, final int ordinal) throws IOException {
        return new YamlConfigSource(url, ordinal);
    }

    public static class InClassPath extends ApplicationYamlConfigSourceLoader implements ConfigSourceProvider {
        @Override
        public List<ConfigSource> getConfigSources(final ClassLoader classLoader) {
            List<ConfigSource> configSources = new ArrayList<>();
            configSources.addAll(loadConfigSources("application.yaml", 255, classLoader));
            configSources.addAll(loadConfigSources("application.yml", 255, classLoader));
            return configSources;
        }

        @Override
        protected List<ConfigSource> tryFileSystem(final URI uri, final int ordinal) {
            return new ArrayList<>();
        }
    }

    public static class InFileSystem extends ApplicationYamlConfigSourceLoader implements ConfigSourceProvider {
        @Override
        public List<ConfigSource> getConfigSources(final ClassLoader classLoader) {
            List<ConfigSource> configSources = new ArrayList<>();
            configSources.addAll(loadConfigSources(
                    Paths.get(System.getProperty("user.dir"), "config", "application.yaml").toUri().toString(), 265,
                    classLoader));
            configSources.addAll(
                    loadConfigSources(Paths.get(System.getProperty("user.dir"), "config", "application.yml").toUri().toString(),
                            265, classLoader));
            return configSources;
        }

        @Override
        protected List<ConfigSource> tryClassPath(final URI uri, final int ordinal, final ClassLoader classLoader) {
            return new ArrayList<>();
        }
    }
}


text:
module minerva.controls.stackpanel.arrange.tapins {
    export function doVertical (input: IInput, state: IState, output: IOutput, tree: core.IUpdaterTree, finalRect: Rect): boolean {
        if (input.orientation !== Orientation.Vertical)
            return true;

        var fs = state.finalSize;
        var arranged = state.arrangedSize;
        arranged.height = 0;
        var childRect = state.childRect;

        var child: core.Updater;
        var childDesired: Size;
        for (var walker = tree.walk(); walker.step();) {
            child = walker.current;
            childDesired = child.assets.desiredSize;
            childDesired.width = fs.width;
            Size.copyTo(childDesired, childRect);
            childRect.y = arranged.height;

            if (Rect.isEmpty(childRect))
                childRect.x = childRect.y = childRect.width = childRect.height = 0;
            child.arrange(childRect);

            arranged.width = Math.max(arranged.width, childDesired.width);
            arranged.height += childDesired.height;
        }

        arranged.height = Math.max(arranged.height, state.finalSize.height);

        return true;
    }
}


text:
using System;
using System.Globalization;
using System.Linq;
using OmniXaml.TypeConversion;
using Perspex.Collections;
using Perspex.Utilities;

namespace Perspex.Markup.Xaml.Converters
{
    public class PerspexListTypeConverter<T> : ITypeConverter
    {
        public bool CanConvertFrom(IXamlTypeConverterContext context, Type sourceType)
        {
            return sourceType == typeof(string);
        }

        public bool CanConvertTo(IXamlTypeConverterContext context, Type destinationType)
        {
            return false;
        }

        public object ConvertFrom(IXamlTypeConverterContext context, CultureInfo culture, object value)
        {
            var result = new PerspexList<T>();
            var values = ((string)value).Split(',');

            foreach (var s in values)
            {
                object v;

                if (TypeUtilities.TryConvert(typeof(T), s, culture, out v))
                {
                    result.Add((T)v);
                }
                else
                {
                    throw new InvalidCastException($"Could not convert '{s}' to {typeof(T)}.");
                }
            }

            return result;
        }

        public object ConvertTo(IXamlTypeConverterContext context, CultureInfo culture, object value, Type destinationType)
        {
            throw new NotImplementedException();
        }
    }
}


text:
<?php

namespace JMS\Serializer\Tests\Fixtures;

use JMS\Serializer\Annotation\Type;
use JMS\Serializer\Annotation\XmlAttribute;
use JMS\Serializer\Annotation\XmlElement;
use JMS\Serializer\Annotation\XmlNamespace;

/**
 * @XmlNamespace(prefix="old_foo", uri="http://old.foo.example.org");
 * @XmlNamespace(prefix="foo", uri="http://foo.example.org");
 * @XmlNamespace(prefix="new_foo", uri="http://new.foo.example.org");
 */
class SimpleClassObject
{
    /**
     * @Type("string")
     * @XmlAttribute(namespace="http://old.foo.example.org")
     */
    public $foo;

    /**
     * @Type("string")
     * @XmlElement(namespace="http://foo.example.org")
     */
    public $bar;

    /**
     * @Type("string")
     * @XmlElement(namespace="http://new.foo.example.org")
     */
    public $moo;

}


text:
import abc

from typing import Any, Optional

from pyflink.common.time import Duration
from pyflink.java_gateway import get_gateway

class WatermarkStrategy(object):
    """
    The WatermarkStrategy defines how to generate Watermarks in the stream sources. The
    WatermarkStrategy is a builder/factory for the WatermarkGenerator that generates the watermarks
    and the TimestampAssigner which assigns the internal timestamp of a record.

    The convenience methods, for example forBoundedOutOfOrderness(Duration), create a
    WatermarkStrategy for common built in strategies.
    """
    def __init__(self, j_watermark_strategy):
        self._j_watermark_strategy = j_watermark_strategy
        self._timestamp_assigner = None

    def with_timestamp_assigner(self, timestamp_assigner: 'TimestampAssigner') -> \
            'WatermarkStrategy':
        """
        Creates a new WatermarkStrategy that wraps this strategy but instead uses the given a
        TimestampAssigner by implementing TimestampAssigner interface.

        Example:
        ::

            >>> watermark_strategy = WatermarkStrategy.for_monotonous_timestamps() \\
            >>>     .with_timestamp_assigner(MyTimestampAssigner())

        :param timestamp_assigner: The given TimestampAssigner.
        :return: A WaterMarkStrategy that wraps a TimestampAssigner.
        """
        self._timestamp_assigner = timestamp_assigner
        return self

    def with_idleness(self, idle_timeout: Duration) -> 'WatermarkStrategy':
        """
        Creates a new enriched WatermarkStrategy that also does idleness detection in the created
        WatermarkGenerator.

        Example:
        ::

            >>> WatermarkStrategy \\
            ...     .for_bounded_out_of_orderness(Duration.of_seconds(20)) \\
            ...     .with_idleness(Duration.of_minutes(1))

        :param idle_timeout: The idle timeout.
        :return: A new WatermarkStrategy with idle detection configured.
        """
        return WatermarkStrategy(self._j_watermark_strategy.withIdleness(idle_timeout._j_duration))

    def with_watermark_alignment(self, watermark_group: str, max_allowed_watermark_drift: Duration,
                                 update_interval: Optional[Duration] = None) -> 'WatermarkStrategy':
        """
        Creates a new :class:`WatermarkStrategy` that configures the maximum watermark drift from
        other sources/tasks/partitions in the same watermark group. The group may contain completely
        independent sources (e.g. File and Kafka).

        Once configured Flink will "pause" consuming from a source/task/partition that is ahead
        of the emitted watermark in the group by more than the maxAllowedWatermarkDrift.

        Example:
        ::

            >>> WatermarkStrategy \\
            ...     .for_bounded_out_of_orderness(Duration.of_seconds(20)) \\
            ...     .with_watermark_alignment("alignment-group-1", Duration.of_seconds(20),
            ...         Duration.of_seconds(1))

        :param watermark_group: A group of sources to align watermarks
        :param max_allowed_watermark_drift: Maximal drift, before we pause consuming from the
            source/task/partition
        :param update_interval: How often tasks should notify coordinator about the current
            watermark and how often the coordinator should announce the maximal aligned watermark.
            If is None, default update interval (1000ms) is used.
        :return: A new WatermarkStrategy with watermark alignment configured.

        .. versionadded:: 1.16.0
        """
        if update_interval is None:
            return WatermarkStrategy(self._j_watermark_strategy.withWatermarkAlignment(
                watermark_group, max_allowed_watermark_drift._j_duration
            ))
        else:
            return WatermarkStrategy(self._j_watermark_strategy.withWatermarkAlignment(
                watermark_group,
                max_allowed_watermark_drift._j_duration,
                update_interval._j_duration,
            ))

    @staticmethod
    def for_monotonous_timestamps() -> 'WatermarkStrategy':
        """
        Creates a watermark strategy for situations with monotonously ascending timestamps.

        The watermarks are generated periodically and tightly follow the latest timestamp in the
        data. The delay introduced by this strategy is mainly the periodic interval in which the
        watermarks are generated.
        """
        JWaterMarkStrategy = get_gateway().jvm\
            .org.apache.flink.api.common.eventtime.WatermarkStrategy
        return WatermarkStrategy(JWaterMarkStrategy.forMonotonousTimestamps())

    @staticmethod
    def for_bounded_out_of_orderness(max_out_of_orderness: Duration) -> 'WatermarkStrategy':
        """
        Creates a watermark strategy for situations where records are out of order, but you can
        place an upper bound on how far the events are out of order. An out-of-order bound B means
        that once the an event with timestamp T was encountered, no events older than (T - B) will
        follow any more.
        """
        JWaterMarkStrategy = get_gateway().jvm \
            .org.apache.flink.api.common.eventtime.WatermarkStrategy
        return WatermarkStrategy(
            JWaterMarkStrategy.forBoundedOutOfOrderness(max_out_of_orderness._j_duration))

    @staticmethod
    def no_watermarks() -> 'WatermarkStrategy':
        """
        Creates a watermark strategy that generates no watermarks at all. This may be useful in
        scenarios that do pure processing-time based stream processing.

        .. versionadded:: 1.16.0
        """
        JWaterMarkStrategy = get_gateway().jvm \
            .org.apache.flink.api.common.eventtime.WatermarkStrategy
        return WatermarkStrategy(JWaterMarkStrategy.noWatermarks())

class TimestampAssigner(abc.ABC):
    """
    A TimestampAssigner assigns event time timestamps to elements. These timestamps are used by all
    functions that operate on event time, for example event time windows.

    Timestamps can be an arbitrary int value, but all built-in implementations represent it as the
    milliseconds since the Epoch (midnight, January 1, 1970 UTC), the same way as time.time() does
    it.
    """
    @abc.abstractmethod
    def extract_timestamp(self, value: Any, record_timestamp: int) -> int:
        """
        Assigns a timestamp to an element, in milliseconds since the Epoch. This is independent of
        any particular time zone or calendar.

        The method is passed the previously assigned timestamp of the element.
        That previous timestamp may have been assigned from a previous assigner. If the element did
        not carry a timestamp before, this value is the minimum value of int type.

        :param value: The element that the timestamp will be assigned to.
        :param record_timestamp: The current internal timestamp of the element, or a negative value,
                                 if no timestamp has been assigned yet.
        :return: The new timestamp.
        """
        pass

class AssignerWithPeriodicWatermarksWrapper(object):
    """
    The AssignerWithPeriodicWatermarks assigns event time timestamps to elements, and generates
    low watermarks that signal event time progress within the stream. These timestamps and
    watermarks are used by functions and operators that operate on event time, for example event
    time windows.
    """

    def __init__(self, j_assigner_with_periodic_watermarks):
        self._j_assigner_with_periodic_watermarks = j_assigner_with_periodic_watermarks


text:
/**
 * Module dependencies.
 */

var should = require('../')
  , assert = require('assert');

function err(fn, msg) {
  try {
    fn();
    should.fail('expected an error');
  } catch (err) {
    should.equal(msg, err.message);
  }
}

module.exports['should'] = {
  'test double require': function(){
    require('../').should.equal(should);
  },

  'test assertion': function(){
    'test'.should.be.a.string;
    should.equal('foo', 'foo');
  },

  'test .expected and .actual': function(){
    try {
      'foo'.should.equal('bar');
    } catch (err) {
      assert('foo' == err.actual, 'err.actual');
      assert('bar' == err.expected, 'err.expected');
    }
  },

  'test chaining': function(){
    var user = { name: 'tj', pets: ['tobi', 'loki', 'jane', 'bandit'] };

    user.should.be.an.instanceOf(Object).and.have.property('name', 'tj');

    user.should.have.ownProperty('name')
      .which.not.have.length(3)
        .and.be.equal('tj');
  }
};


text:
<project
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>de.frvabe.spring</groupId>
    <artifactId>spring-boot-external-config-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <properties>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.source>1.8</maven.compiler.source>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>io.spring.platform</groupId>
                <artifactId>platform-bom</artifactId>
                <version>Brussels-SR2</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <!-- testing -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
    </dependencies>

</project>


text:
from params import *
import numpy as np
import radialVelocity
import alphenRadius

def rad(r):
    return StarInduction * np.square(StarRadius / r)

def phi(r, t):
    Ra = alphenRadius.get(t)
    return rad(r) * SolarOmega * r / radialVelocity.getsgs(r, t) * np.square(alphenRadius.Lambda(r, t)) \
           * (1 - np.square(Ra / r)) / (1 - np.square(alphenRadius.Lambda(r, t)))


text:
package com.smartstudio.deviceinfo.ui;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.smartstudio.deviceinfo.R;

/**
 * TODO Add a class header comment
 */
public class PropertyLayout extends ViewGroup {
    private TextView mTxtTitle;
    private TextView mTxtValue;

    public PropertyLayout(Context context) {
        super(context);
        init(null);
    }

    public PropertyLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public PropertyLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    private void init(AttributeSet attrs) {
        inflate(getContext(), R.layout.view_property, this);
        mTxtTitle = (TextView) getChildAt(0);
        mTxtValue = (TextView) getChildAt(1);

        if (attrs != null) {
            TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.PropertyView, 0, 0);
            setTitle(a.getText(R.styleable.PropertyView_title_text));
            setValue(a.getText(R.styleable.PropertyView_value_text));
            mTxtTitle.setTextColor(a.getColor(R.styleable.PropertyView_title_color, Color.WHITE));
            mTxtTitle.setTextColor(a.getColor(R.styleable.PropertyView_value_color, Color.WHITE));
            a.recycle();
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
        return new MarginLayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
        return new MarginLayoutParams(p);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(), attrs);
    }

    public void setTitle(CharSequence title) {
        mTxtTitle.setText(title);
    }

    public void setValue(CharSequence value) {
        mTxtValue.setText(value);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        MarginLayoutParams titleParams = (MarginLayoutParams) mTxtTitle.getLayoutParams();
        MarginLayoutParams valueParams = (MarginLayoutParams) mTxtValue.getLayoutParams();

        int childLeft;
        int childRight;
        int childTop;
        int childBottom;

        //TxtTitle layout
        childLeft = titleParams.leftMargin + getPaddingLeft();
        childRight = childLeft + mTxtTitle.getMeasuredWidth();

        if (mTxtTitle.getMeasuredHeight() < mTxtValue.getMeasuredHeight()) {
            childTop = titleParams.topMargin + getPaddingTop() + mTxtValue.getMeasuredHeight() / 2
                    - mTxtTitle.getMeasuredHeight() / 2;
        } else {
            childTop = titleParams.topMargin + getPaddingTop();
        }

        childBottom = childTop + mTxtTitle.getMeasuredHeight();
        mTxtTitle.layout(childLeft, childTop, childRight, childBottom);

        //TxtValue layout
        childLeft = childRight + valueParams.leftMargin;
        childRight = childLeft + mTxtValue.getMeasuredWidth();

        if (mTxtValue.getMeasuredHeight() < mTxtTitle.getMeasuredHeight()) {
            childTop = titleParams.topMargin + getPaddingTop() + mTxtTitle.getMeasuredHeight() / 2
                    - mTxtValue.getMeasuredHeight() / 2;
        } else {
            childTop = titleParams.topMargin + getPaddingTop();
        }

        childBottom = childTop + mTxtValue.getMeasuredHeight();
        mTxtValue.layout(childLeft, childTop, childRight, childBottom);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthPadding = getPaddingLeft() + getPaddingRight();
        int heightPadding = getPaddingBottom() + getPaddingTop();

        int parentWidth = MeasureSpec.getSize(widthMeasureSpec);

        measureChildWithMargins(mTxtTitle, widthMeasureSpec, widthPadding, heightMeasureSpec, heightPadding);
        measureChildWithMargins(mTxtValue, widthMeasureSpec, widthPadding, heightMeasureSpec, heightPadding);

        int height = Math.max(mTxtTitle.getMeasuredHeight(), mTxtValue.getMeasuredHeight());
        MarginLayoutParams params = (MarginLayoutParams) mTxtTitle.getLayoutParams();
        //TODO Handle textViews margins
        setMeasuredDimension(parentWidth, height + params.topMargin + params.bottomMargin + heightPadding);
    }

    @Override
    protected void measureChildWithMargins(View child, int parentWidthMeasureSpec,
                                           int widthUsed, int parentHeightMeasureSpec, int heightUsed) {
        int parentWidth = MeasureSpec.getSize(parentWidthMeasureSpec);

        MarginLayoutParams params = (MarginLayoutParams) getLayoutParams();
        MarginLayoutParams childParams = (MarginLayoutParams) child.getLayoutParams();

        int padding = child == mTxtTitle ? getPaddingLeft() : getPaddingRight();
        int totalMargin = params.leftMargin + params.rightMargin;
        int margin = child == mTxtTitle ? params.leftMargin : params.rightMargin;

        int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
                childParams.leftMargin + childParams.rightMargin + widthUsed, (parentWidth + totalMargin) / 2
                        - childParams.leftMargin - childParams.rightMargin - padding - margin);
        int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
                childParams.topMargin + childParams.bottomMargin + heightUsed, childParams.height);

        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }
}


text:
<?php
namespace Neos\Kickstarter\ViewHelpers\Format;

use Neos\FluidAdaptor\Core\ViewHelper\AbstractViewHelper;

/**
 * Wrapper for PHPs ltrim function.
 * @see http://www.php.net/manual/en/ltrim
 *
 * = Examples =
 *
 * <code title="Example">
 * {someVariable -> k:format.ltrim()}
 * </code>
 *
 * Output:
 * content of {someVariable} with ltrim applied
 *
 */
class LtrimViewHelper extends AbstractViewHelper
{
    /**
     * @param string $charlist
     * @return string The altered string.
     */
    public function render($charlist = null)
    {
        $content = $this->renderChildren();
        return ltrim($content, $charlist);
    }
}


text:
<s:Envelope s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body>
    <u:GetDeviceStatusResponse xmlns:u="urn:Belkin:service:bridge:1">
      <DeviceStatusList><?xml version="1.0" encoding="utf-8"?><DeviceStatusList><DeviceStatus><IsGroupAction>YES</IsGroupAction><DeviceID
        available="YES">1432253402</DeviceID><CapabilityID>10006,10008,30008,30009,3000A</CapabilityID><CapabilityValue>1,65:0,0:0,,</CapabilityValue></DeviceStatus></DeviceStatusList>
      </DeviceStatusList>
    </u:GetDeviceStatusResponse>
  </s:Body>
</s:Envelope>


text:
namespace libcgt { namespace camera_wrappers {

// TODO(jiawen): why does this need constructors at all?
class StreamConfig
{
public:

#if 1
    StreamConfig() = default;
    StreamConfig( StreamType _type, const Vector2i& _resolution,
        PixelFormat _pixelFormat, int _fps, bool _mirror ) :
        type( _type ),
        resolution( _resolution ),
        fps( _fps ),
        pixelFormat( _pixelFormat ),
        mirror( _mirror )
    {

    }
    StreamConfig( const StreamConfig& copy ) = default;
    StreamConfig& operator = ( const StreamConfig& copy ) = default;
#endif

    StreamType type = StreamType::UNKNOWN;
    Vector2i resolution = Vector2i();
    PixelFormat pixelFormat = PixelFormat::INVALID;

    int fps = 0;

    // When false, it is a regular camera.
    // When true, it acts like a mirror / webcam.
    bool mirror = false;
};

} } // camera_wrappers, libcgt


text:
package com.grasp.service;

import com.grasp.exception.ServiceException;
import com.grasp.model.dto.UserDTO;
import com.grasp.model.dto.UserListDTO;
import com.grasp.model.entity.User;
import com.grasp.model.entity.UserSubject;
import com.grasp.model.util.EntityConverter;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestClientFactory;
import io.searchbox.core.Delete;
import io.searchbox.core.Index;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

import static org.elasticsearch.index.query.QueryBuilders.*;

@Service
public class ElasticsearchService {

    private static final int SEARCH_LIMIT = 50;
    private String index = System.getenv("SEARCHBOX_INDEX");
    private JestClient client;
    private EntityConverter entityConverter;

    private final static String TUTOR_TYPE = "tutor";

    @Autowired
    public ElasticsearchService(JestClientFactory clientFactory, EntityConverter entityConverter) {
        this.client = clientFactory.getObject();
        this.entityConverter = entityConverter;
    }

    public void upsertTutor(User user) {
        try {
            client.execute(new Index.Builder(entityConverter.convertToDTO(user)).index(index).type(TUTOR_TYPE).build());
        } catch (Exception e) {
            throw new ServiceException(HttpStatus.INTERNAL_SERVER_ERROR, "ERROR: Unable to build index");
        }
    }

    public void deleteTutor(UUID tutorId) {
        try {
            client.execute(new Delete.Builder(tutorId.toString()).index(index).type(TUTOR_TYPE).build());
        } catch (Exception e) {
            throw new ServiceException(HttpStatus.INTERNAL_SERVER_ERROR, "ERROR: Unable to delete tutor + " + tutorId);
        }
    }

    public UserListDTO searchTutorBySubject(List<UserSubject> subjects, UUID excludeId) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        BoolQueryBuilder qb = boolQuery();

        for (UserSubject subject : subjects) {
            qb.should(matchQuery("tutors.courseCatalog.subject", subject.getSubject()));
        }

        if(excludeId != null) {
            qb.mustNot(matchQuery("id", excludeId));
        }

        sourceBuilder.query(qb).size(SEARCH_LIMIT).from(0);

        return executeQuery(sourceBuilder);
    }

    public UserListDTO searchTutors(String queryString, UUID excludeId) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        MultiMatchQueryBuilder multiMatchQueryBuilder = multiMatchQuery(queryString, "tutors.courseCatalog.description",
                "tutors.courseCatalog.courseName", "tutors.courseCatalog.code", "tutors.courseCatalog.subject",
                "firstName", "lastName", "program");

        BoolQueryBuilder qb = boolQuery();

        multiMatchQueryBuilder.fuzziness(Fuzziness.AUTO);
        multiMatchQueryBuilder.prefixLength(0);
        multiMatchQueryBuilder.maxExpansions(10);

        qb.should(multiMatchQueryBuilder);

        if (excludeId != null) {
            qb.mustNot(matchQuery("id", excludeId));
        }

        sourceBuilder.query(multiMatchQueryBuilder).size(SEARCH_LIMIT).from(0);

        return executeQuery(sourceBuilder);
    }

    private UserListDTO executeQuery(SearchSourceBuilder sourceBuilder) {

        String query = sourceBuilder.toString();

        System.out.println("Executing Query: " + query);

        Search search = new Search.Builder(query)
                .addIndex(index)
                .addType(TUTOR_TYPE)
                .build();

        SearchResult result;

        try {
            result = client.execute(search);
        } catch (IOException e) {
            throw new ServiceException(HttpStatus.INTERNAL_SERVER_ERROR, "ERROR: unable to search for tutors");
        }

        return new UserListDTO(result.getSourceAsObjectList(UserDTO.class));
    }
}


text:
require_relative 'application_seeder'

seeder = ApplicationSeeder.new
seeder.seed!


text:
using System;
using System.IO;
using System.Linq;
using System.Xml.Linq;

namespace Project {
  public class CsProjParser {

    public static ProjectFile Parse( string name, Stream from ) {
      var doc = XDocument.Load( from );
      return Parse( name, doc );
    }

    public static ProjectFile Parse( string name, XDocument doc ) {
      if ( doc == null || doc.Root == null ) {
        throw new ArgumentException( "Stream did not contain a valid XML document", "doc" );
      }

      if ( doc.Root.Name.LocalName != "Project" ) {
        throw new ArgumentException( "Stream did not contain a project", "doc" );
      }

      return new ProjectFile(
        name,
        doc.Root.Elements( doc.Root.Name.Namespace.GetName( "ItemGroup" ) ).Select( ParseItemGroup ).ToList().AsReadOnly()
      );
    }

    private static ItemGroup ParseItemGroup( XElement itemGroupElement ) {
      return new ItemGroup(
        itemGroupElement
          .Elements()
          .Select( e => e.ParseAsItem() )
          .WhereNotNull()
          .ToList()
          .AsReadOnly() );
    }
  }
}


text:
Non-Trivial AngularJS Made Easy

    Everything you need to kickstart AngularJS projects: a best-practice
    directory structure, an intelligent build system, and the best web design
    libraries around.

      Read the Docs

      Download

 Good to Go!

        Kickstarts your project quickly, with everything you need, so you can
        focus on what matters: your app.

 Complete Build System

        A smart, Grunt-based build system
        designed to save you time and energy.

 Modularization

        Supports a structure that maintains separation of concerns while
        ensuring maximum code reuse.

 AngularJS

        JavaScript framework that augments browser-based, single-page
        applications with MVC functionality.
        More »

 Sass

        The main difference over the original, the CSS preprocessor of choice is Sass/SCSS.
        More »

 Twitter Bootstrap

        Sleek, intuitive, and powerful front-end framework for faster and easier
        web development.
        More »

 Angular UI Bootstrap

        Pure AngularJS components for Bootstrap written by the
        AngularUI Team.
        More »

 Font Awesome

        The iconic font designed for use with Twitter Bootstrap.

          More »

 Placeholders

        Client-side image and text placeholder directives written in pure
        AngularJS to make designing mock-ups wicked-fast.

          More »


text:
[![arXiv](https://img.shields.io/badge/arXiv-1603.06920-b31b1b.svg)](https://arxiv.org/abs/1603.06920)
[![DOI:10.1103/PhysRevC.93.055201](https://img.shields.io/badge/DOI-10.1103/PhysRevC.93.055201-0000ff.svg)](https://doi.org/10.1103/PhysRevC.93.055201)

This is the Python code used in the reanalysis of Rosenbluth measurements of the proton form factors described in [arXiv:1603.06920](https://arxiv.org/abs/1603.06920) and [Phys. Rev. C 93, 055201](https://doi.org/10.1103/PhysRevC.93.055201) (please consider citing this paper if you use the code). The [radcorr.py](radcorr.py) library may be useful for calculating radiative corrections in single-arm measurements of unpolarized elastic electron-proton scattering.

## Dependencies

The standard Python packages **scipy**, **numpy**, **pandas**, and **matplotlib** are required.

## Source distribution

The source distribution includes the following files:

* DOCUMENTATION
  * [README.md](README.md) (this markdown file)
  * [LICENSE](LICENSE) (the MIT license)
  * [data_input.pdf](data_input.pdf) (input data in a human-readable format)
* SOURCE CODE
  * [reanalysis.py](reanalysis.py) (main analysis routine)
  * [radcorr.py](radcorr.py) (Python library to calculate radiative corrections)
  * [fig1.py](fig1.py) (script to plot Fig. 1 of the paper)
  * [fig2.py](fig2.py) (script to plot Fig. 2 of the paper)
* INPUT DATA
  * [data_input.csv](data_input.csv) (data from the measurements reanalyzed)
  * [data_esepp.csv](data_esepp.csv) (data from [ESEPP](https://github.com/gramolin/esepp/) needed for Fig. 1)
  * [data_unpolarized.csv](data_unpolarized.csv) (results of the original measurements needed for Fig. 2)
  * [data_polarized.csv](data_polarized.csv) (results of the polarized measurements needed for Fig. 2)
* OUTPUT FILES
  * [results_fit.csv](results_fit.csv) (the best-fit parameters and the covariance matrix found)
  * [results_table.csv](results_table.csv) (reanalysis results shown in Table I of the paper)
  * [fig1.pdf](fig1.pdf) and [fig1.png](fig1.png) (Fig. 1 of the paper in the pdf and png formats)
  * [fig2.pdf](fig2.pdf) and [fig2.png](fig2.png) (Fig. 2 of the paper in the pdf and png formats)


text:
package de.whodrivesnext.api;

import java.math.BigDecimal;
import de.whodrivesnext.model.Error;
import de.whodrivesnext.model.Member;
import de.whodrivesnext.model.Ride;
import de.whodrivesnext.model.RidePageableList;

import io.swagger.annotations.*;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import javax.validation.constraints.*;
@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2017-07-03T08:08:09.179+02:00")

@Api(value = "rides", description = "the rides API")
public interface RidesApi {

    @ApiOperation(value = "search for rides", notes = "show the history or search for rides. either an userid or a carpoolId is required. rides can only be found by the driver, the passengers or any member of the associated carpool. ", response = RidePageableList.class, tags={ "carpool", })
    @ApiResponses(value = {
        @ApiResponse(code = 200, message = "the rides", response = RidePageableList.class),
        @ApiResponse(code = 200, message = "Unexpected error", response = RidePageableList.class) })
    @RequestMapping(value = "/rides",
        produces = { "application/json" },
        method = RequestMethod.GET)
    ResponseEntity<RidePageableList> ridesGet( @ApiParam(value = "unique ID of the carpool you want to search rides from") @RequestParam(value = "carpoolId", required = false) String carpoolId,
         @ApiParam(value = "search rides where the user was either driver or passenger. ") @RequestParam(value = "userId", required = false) String userId,
         @ApiParam(value = "search rides since or at that from-date.  date in ??? format ") @RequestParam(value = "from", required = false) String from,
         @ApiParam(value = "search rides before or at that to-date.  date in ??? format ") @RequestParam(value = "to", required = false) String to,
         @ApiParam(value = "search rides in the last number of days from now.  may give unexpected results if you combine this with from/to query parameters. ") @RequestParam(value = "lastDays", required = false) BigDecimal lastDays,
         @ApiParam(value = "Offset the list of returned results by this amount. Default is zero.") @RequestParam(value = "offset", required = false) Integer offset,
         @ApiParam(value = "Number of items to retrieve. Default is 5, maximum is 100.") @RequestParam(value = "limit", required = false) Integer limit);

    @ApiOperation(value = "create a ride - a group of people driving together", notes = "rides can only be added to existing carpools and can be added by any member of the carpool. ", response = Ride.class, tags={ "carpool", })
    @ApiResponses(value = {
        @ApiResponse(code = 200, message = "the created ride", response = Ride.class),
        @ApiResponse(code = 200, message = "Unexpected error", response = Ride.class) })
    @RequestMapping(value = "/rides",
        produces = { "application/json" },
        method = RequestMethod.POST)
    ResponseEntity<Ride> ridesPost(@ApiParam(value = "" ,required=true ) @RequestBody Ride ride);

    @ApiOperation(value = "deletes a ride", notes = "tbd ", response = Void.class, tags={ "carpool", })
    @ApiResponses(value = {
        @ApiResponse(code = 200, message = "the ride has been deleted. Empty response.", response = Void.class),
        @ApiResponse(code = 200, message = "Unexpected error", response = Void.class) })
    @RequestMapping(value = "/rides/{rideId}",
        produces = { "application/json" },
        method = RequestMethod.DELETE)
    ResponseEntity<Void> ridesRideIdDelete(@ApiParam(value = "unique ID of the ride you want to delete",required=true ) @PathVariable("rideId") String rideId);

    @ApiOperation(value = "set a driver to a ride", notes = "one driver can be set to a existing ride. If allready a driver has been set it will be replaced. A ride allways has to have an driver, though no delete is allowed, only replace via put.  the driver must be one of the members of the carpool. ", response = Ride.class, tags={ "carpool", })
    @ApiResponses(value = {
        @ApiResponse(code = 200, message = "the updated ride", response = Ride.class),
        @ApiResponse(code = 200, message = "Unexpected error", response = Ride.class) })
    @RequestMapping(value = "/rides/{rideId}/driver",
        produces = { "application/json" },
        method = RequestMethod.PUT)
    ResponseEntity<Ride> ridesRideIdDriverPut(@ApiParam(value = "unique ID of the ride you want to set the driver to",required=true ) @PathVariable("rideId") String rideId,
        @ApiParam(value = "" ,required=true ) @RequestBody Member driver);

    @ApiOperation(value = "add a passenger a ride", notes = "add a list of passengers to the ride. To add more passengers or to delete a passenger the complete list has to be added again. To delete all passengers a empty list can be posted.  all passengers must be members of the carpool. the driver of a ride can not be a passenger. a user can not be added when having an Off-Time (see #/users/{id}/vavations). ", response = Ride.class, tags={ "carpool", })
    @ApiResponses(value = {
        @ApiResponse(code = 200, message = "the updated ride", response = Ride.class),
        @ApiResponse(code = 200, message = "Unexpected error", response = Ride.class) })
    @RequestMapping(value = "/rides/{rideId}/passengers",
        produces = { "application/json" },
        method = RequestMethod.POST)
    ResponseEntity<Ride> ridesRideIdPassengersPost(@ApiParam(value = "unique ID of the ride you want to set the passenger to",required=true ) @PathVariable("rideId") String rideId,
        @ApiParam(value = "" ,required=true ) @RequestBody Member passenger);

}


text:
package io.prediction.data.webhooks.segmentio

import io.prediction.data.webhooks.{ConnectorException, JsonConnector}
import org.json4s._

private[prediction] object SegmentIOConnector extends JsonConnector {

  //private lazy val supportedAPI = Vector("2", "2.0", "2.0.0")

  implicit val json4sFormats: Formats = DefaultFormats

  override
  def toEventJson(data: JObject): JObject = {
    try {
      val version: String = data.values("version").toString
/*
      if (!supportedAPI.contains(version)) {
        throw new ConnectorException(
          s"Supported segment.io API versions: [2]. got [$version]"
        )
      }
*/
    } catch { case _: Throwable ⇒
      throw new ConnectorException(s"Failed to get segment.io API version.")
    }

    val common = try {
      data.extract[Common]
    } catch {
      case e: Throwable ⇒ throw new ConnectorException(
        s"Cannot extract Common field from $data. ${e.getMessage}", e
      )
    }

    try {
      common.`type` match {
        case "identify" ⇒
          toEventJson(
            common = common,
            identify = data.extract[Events.Identify]
          )

        case "track" ⇒
          toEventJson(
            common = common,
            track = data.extract[Events.Track]
          )

        case "alias" ⇒
          toEventJson(
            common = common,
            alias = data.extract[Events.Alias]
          )

        case "page" ⇒
          toEventJson(
            common = common,
            page = data.extract[Events.Page]
          )

        case "screen" ⇒
          toEventJson(
            common = common,
            screen = data.extract[Events.Screen]
          )

        case "group" ⇒
          toEventJson(
            common = common,
            group = data.extract[Events.Group]
          )

        case _ ⇒
          throw new ConnectorException(
            s"Cannot convert unknown type ${common.`type`} to event JSON."
          )
      }
    } catch {
      case e: ConnectorException => throw e
      case e: Exception =>
        throw new ConnectorException(
          s"Cannot convert $data to event JSON. ${e.getMessage}", e
        )
    }
  }

  def toEventJson(common: Common, identify: Events.Identify ): JObject = {
    import org.json4s.JsonDSL._
    val eventProperties = "traits" → identify.traits
    toJson(common, eventProperties)
  }

  def toEventJson(common: Common, track: Events.Track): JObject = {
    import org.json4s.JsonDSL._
    val eventProperties =
      ("properties" → track.properties) ~
      ("event" → track.event)
    toJson(common, eventProperties)
  }

  def toEventJson(common: Common, alias: Events.Alias): JObject = {
    import org.json4s.JsonDSL._
    toJson(common, "previous_id" → alias.previous_id)
  }

  def toEventJson(common: Common, screen: Events.Screen): JObject = {
    import org.json4s.JsonDSL._
    val eventProperties =
      ("name" → screen.name) ~
      ("properties" → screen.properties)
    toJson(common, eventProperties)
  }

  def toEventJson(common: Common, page: Events.Page): JObject = {
    import org.json4s.JsonDSL._
    val eventProperties =
      ("name" → page.name) ~
      ("properties" → page.properties)
    toJson(common, eventProperties)
  }

  def toEventJson(common: Common, group: Events.Group): JObject = {
    import org.json4s.JsonDSL._
    val eventProperties =
      ("group_id" → group.group_id) ~
      ("traits" → group.traits)
    toJson(common, eventProperties)
  }

  private def toJson(common: Common, props: JObject): JsonAST.JObject = {
    val commonFields = commonToJson(common)
    JObject(("properties" → properties(common, props)) :: commonFields.obj)
  }

  private def properties(common: Common, eventProps: JObject): JObject = {
    import org.json4s.JsonDSL._
    common.context map { context ⇒
      try {
        ("context" → Extraction.decompose(context)) ~ eventProps
      } catch {
        case e: Throwable ⇒
          throw new ConnectorException(
            s"Cannot convert $context to event JSON. ${e.getMessage }", e
          )
      }
    } getOrElse eventProps
  }

  private def commonToJson(common: Common): JObject =
    commonToJson(common, common.`type`)

  private def commonToJson(common: Common, typ: String): JObject = {
    import org.json4s.JsonDSL._
      common.user_id.orElse(common.anonymous_id) match {
        case Some(userId) ⇒
          ("event" → typ) ~
            ("entityType" → "user") ~
            ("entityId" → userId) ~
            ("eventTime" → common.timestamp)

        case None ⇒
          throw new ConnectorException(
            "there was no `userId` or `anonymousId` in the common fields."
          )
      }
  }
}

object Events {

  private[prediction] case class Track(
    event: String,
    properties: Option[JObject] = None
  )

  private[prediction] case class Alias(previous_id: String, user_id: String)

  private[prediction] case class Group(
    group_id: String,
    traits: Option[JObject] = None
  )

  private[prediction] case class Screen(
    name: Option[String] = None,
    properties: Option[JObject] = None
  )

  private[prediction] case class Page(
    name: Option[String] = None,
    properties: Option[JObject] = None
  )

  private[prediction] case class Identify(
    user_id: String,
    traits: Option[JObject]
  )

}

object Common {

  private[prediction] case class Integrations(
    All: Boolean = false,
    Mixpanel: Boolean = false,
    Marketo: Boolean = false,
    Salesforse: Boolean = false
  )

  private[prediction] case class Context(
    ip: String,
    library: Library,
    user_agent: String,
    app: Option[App] = None,
    campaign: Option[Campaign] = None,
    device: Option[Device] = None,
    network: Option[Network] = None,
    location: Option[Location] = None,
    os: Option[OS] = None,
    referrer: Option[Referrer] = None,
    screen: Option[Screen] = None,
    timezone: Option[String] = None
  )

  private[prediction] case class Screen(width: Int, height: Int, density: Int)

  private[prediction] case class Referrer(id: String, `type`: String)

  private[prediction] case class OS(name: String, version: String)

  private[prediction] case class Location(
    city: Option[String] = None,
    country: Option[String] = None,
    latitude: Option[Double] = None,
    longitude: Option[Double] = None,
    speed: Option[Int] = None
  )

  case class Page(
    path: String,
    referrer: String,
    search: String,
    title: String,
    url: String
  )

  private[prediction] case class Network(
    bluetooth: Option[Boolean] = None,
    carrier: Option[String] = None,
    cellular: Option[Boolean] = None,
    wifi: Option[Boolean] = None
  )

  private[prediction] case class Library(name: String, version: String)

  private[prediction] case class Device(
    id: Option[String] = None,
    advertising_id: Option[String] = None,
    ad_tracking_enabled: Option[Boolean] = None,
    manufacturer: Option[String] = None,
    model: Option[String] = None,
    name: Option[String] = None,
    `type`: Option[String] = None,
    token: Option[String] = None
  )

  private[prediction] case class Campaign(
    name: Option[String] = None,
    source: Option[String] = None,
    medium: Option[String] = None,
    term: Option[String] = None,
    content: Option[String] = None
  )

  private[prediction] case class App(
    name: Option[String] = None,
    version: Option[String] = None,
    build: Option[String] = None
  )

}

private[prediction] case class Common(
  `type`: String,
  sent_at: String,
  timestamp: String,
  version: String,
  anonymous_id: Option[String] = None,
  user_id: Option[String] = None,
  context: Option[Common.Context] = None,
  integrations: Option[Common.Integrations] = None
)


text:
/****************************************************************************
 * fs/mount/fs_umount.c
 *
 *   Copyright (C) 2007-2009 Gregory Nutt. All rights reserved.
 *   Author: Gregory Nutt <gnutt@nuttx.org>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name NuttX nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

/****************************************************************************
 * Included Files
 ****************************************************************************/

#include <tinyara/config.h>

#include <sys/mount.h>
#include <errno.h>
#include <tinyara/fs/fs.h>

#include "inode/inode.h"

/****************************************************************************
 * Pre-processor Definitions
 ****************************************************************************/

/****************************************************************************
 * Private Types
 ****************************************************************************/

/****************************************************************************
 * Private Variables
 ****************************************************************************/

/****************************************************************************
 * Public Variables
 ****************************************************************************/

/****************************************************************************
 * Private Functions
 ****************************************************************************/

/****************************************************************************
 * Public Functions
 ****************************************************************************/

/****************************************************************************
 * Name: umount
 *
 * Description:
 *   umount() detaches the filesystem mounted at the path specified by
 *  'target.'
 *
 * Return:
 *   Zero is returned on success; -1 is returned on an error and errno is
 *   set appropriately:
 *
 *   EACCES A component of a path was not searchable or mounting a read-only
 *      filesystem was attempted without giving the MS_RDONLY flag.
 *   EBUSY The target could not be unmounted because it is busy.
 *   EFAULT The pointer argument points outside the user address space.
 *
 ****************************************************************************/

int umount(const char *target)
{
	FAR struct inode *mountpt_inode;
	FAR struct inode *blkdrvr_inode = NULL;
	int errcode = OK;
	int status;

	/* Verify required pointer arguments */

	if (!target) {
		errcode = EFAULT;
		goto errout;
	}

	/* Find the mountpt */

	mountpt_inode = inode_find(target, NULL);
	if (!mountpt_inode) {
		errcode = ENOENT;
		goto errout;
	}

	/* Verify that the inode is a mountpoint */

	if (!INODE_IS_MOUNTPT(mountpt_inode)) {
		errcode = EINVAL;
		goto errout_with_mountpt;
	}

	/* Unbind the block driver from the file system (destroying any fs
	 * private data.
	 */

	if (!mountpt_inode->u.i_mops->unbind) {
		/* The filesystem does not support the unbind operation ??? */

		errcode = EINVAL;
		goto errout_with_mountpt;
	}

	/* The unbind method returns the number of references to the
	 * filesystem (i.e., open files), zero if the unbind was
	 * performed, or a negated error code on a failure.
	 */

	inode_semtake();			/* Hold the semaphore through the unbind logic */
	status = mountpt_inode->u.i_mops->unbind(mountpt_inode->i_private, &blkdrvr_inode);
	if (status < 0) {
		/* The inode is unhappy with the blkdrvr for some reason */

		errcode = -status;
		goto errout_with_semaphore;
	} else if (status > 0) {
		errcode = EBUSY;
		goto errout_with_semaphore;
	}

	/* Successfully unbound */

	mountpt_inode->i_private = NULL;

	/* Successfully unbound, remove the mountpoint inode from
	 * the inode tree.  The inode will not be deleted yet because
	 * there is still at least reference on it (from the mount)
	 */

	status = inode_remove(target);
	inode_semgive();

	/* The return value of -EBUSY is normal (in fact, it should
	 * not be OK)
	 */

	if (status != OK && status != -EBUSY) {
		errcode = -status;
		goto errout_with_mountpt;
	}

	/* Release the mountpoint inode and any block driver inode
	 * returned by the file system unbind above.  This should cause
	 * the inode to be deleted (unless there are other references)
	 */

	inode_release(mountpt_inode);

	/* Did the unbind method return a contained block driver */

	if (blkdrvr_inode) {
		inode_release(blkdrvr_inode);
	}

	return OK;

	/* A lot of goto's!  But they make the error handling much simpler */

errout_with_semaphore:
	inode_semgive();
errout_with_mountpt:
	inode_release(mountpt_inode);
	if (blkdrvr_inode) {
		inode_release(blkdrvr_inode);
	}
errout:
	return errcode;
}