text:
package terris.kilcli.gui;

import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JCheckBox;
import javax.swing.JTabbedPane;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.JScrollPane;
import javax.swing.plaf.*;
import javax.swing.plaf.metal.*;
import javax.swing.plaf.basic.*;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.IOException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import terris.kilcli.KilCli;
import terris.kilcli.resource.*;
import terris.kilcli.thread.*;

/**
 * ColorEditor for KilCli is the class used to edit the color

 * configuration through a gui

 * Ver: 1.0.0
 */

public class ColorEditor extends JDialog {
    private JScrollPane jScroll = new JScrollPane();
    private JScrollPane jScroll2 = new JScrollPane();
    private JScrollPane jScroll3 = new JScrollPane();
    private JSplitPane	jSplit;
	private JTabbedPane tabbedpane;
	private ColorEditorPanel R;
	private ColorEditorPanel r;
	private ColorEditorPanel G;
	private ColorEditorPanel g;
	private ColorEditorPanel W;
	private ColorEditorPanel w;
	private ColorEditorPanel C;
	private ColorEditorPanel c;
	private ColorEditorPanel V;
	private ColorEditorPanel v;
	private ColorEditorPanel B;
	private ColorEditorPanel b;
	private ColorEditorPanel O;
	private ColorEditorPanel o;
	private ColorEditorPanel Y;
	private ColorEditorPanel y;
	private ColorEditorPanel P;
	private ColorEditorPanel p;
	private ColorEditorPanel K;
	private ColorEditorPanel k;
	private ColorEditorPanel T;
	private ColorEditorPanel t;
	private String[] errorMsgs;

	private String[] colorConfig;

	public void updateTheme() {
		repaint();
	}

	/**
	 * ColorEditor constructor, with no arguments creates

	 * a GUI to edit the colors
	 */

    public ColorEditor() {
        super(KilCliThread.getKilCli(), "Color Editor", false);
		JPanel bottom = new JPanel();
		JButton ok = new JButton("Ok");
		ok.addActionListener(new ActionListener() {
			//function for when someone clicks OK
		    public void actionPerformed(ActionEvent e) {
				update();
				close();
		    }
		});
		JButton apply = new JButton("Apply");
		apply.addActionListener(new ActionListener() {
			//function for when someone clicks Apply
			public void actionPerformed(ActionEvent e) {
				update();
			}
		});
		JButton reset = new JButton("Reset");
		reset.addActionListener(new ActionListener() {
			//function for when someone clicks Reset
			public void actionPerformed(ActionEvent e) {
				clear();
			}
		});
		JButton cancel = new JButton("Cancel");
		cancel.addActionListener(new ActionListener() {
			//function to clear fields;
		    public void actionPerformed(ActionEvent e) {
				close();
		    }
		});
		bottom.add(ok);
		bottom.add(apply);
		bottom.add(reset);
		bottom.add(cancel);

		colorConfig = KilCli.getColors();
		errorMsgs = new String[colorConfig.length];
		errorMsgs[0] = "Red";
		errorMsgs[1] = "Dark Red";
		errorMsgs[2] = "Green";
		errorMsgs[3] = "Dark Green";
		errorMsgs[4] = "White";
		errorMsgs[5] = "Dark White";
		errorMsgs[6] = "Cyan";
		errorMsgs[7] = "Dark Cyan";
		errorMsgs[8] = "Violet";
		errorMsgs[9] = "Dark Violet";
		errorMsgs[10] = "Blue";
		errorMsgs[11] = "Dark Blue";
		errorMsgs[12] = "Orange";
		errorMsgs[13] = "Dark Orange";
		errorMsgs[14] = "Yellow";
		errorMsgs[15] = "Dark Yellow";
		errorMsgs[16] = "Pink";
		errorMsgs[17] = "Dark Pink";
		errorMsgs[18] = "Highlight (K)";
		errorMsgs[19] = "Highlight (K)";
		errorMsgs[20] = "Highlight (k)";
		errorMsgs[21] = "Highlight (k)";
		errorMsgs[22] = "Brown";
		errorMsgs[23] = "Dark Brown";

        tabbedpane = new JTabbedPane();
        tabbedpane.setTabPlacement(JTabbedPane.TOP);
        jSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, false, tabbedpane, bottom);
        jSplit.setDividerSize(0);

		getContentPane().add(jSplit, BorderLayout.CENTER);

		String name = "Normal Colors";
		createColors();
		tabbedpane.add(name, jScroll);

		name = "Dark Colors";
		createDarks();
		tabbedpane.add(name, jScroll2);

		name = "Highlight Colors";
		createHighlights();
		tabbedpane.add(name, jScroll3);

		//get screen dimensions
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

        //set tabbed pane visible
		tabbedpane.setVisible(true);

        //...Then set the window size
        setSize((int)(screenSize.width * 0.50), (int)(screenSize.height * 0.40));

        //Set the window's location.
        setLocation((int)(screenSize.width * 0.25), (int)(screenSize.height * 0.25));
        jSplit.setDividerLocation((int)(this.getHeight() * 0.8));
        setVisible(true);

	}

	/**
	 * Resets all the colors to the last saved set
	 */
	private void clear() {
		createColors();
		createDarks();
	}

	/**
	 * Closes the editor
	 */
	private void close() {
		this.dispose();
	}

	/**
	 * Gets the values from the text fields and updates the colors in the KilCli program
	 */
	private void update() {
		colorConfig[0] = R.getText();
		colorConfig[1] = r.getText();
		colorConfig[2] = G.getText();
		colorConfig[3] = g.getText();
		colorConfig[4] = W.getText();
		colorConfig[5] = w.getText();
		colorConfig[6] = C.getText();
		colorConfig[7] = c.getText();
		colorConfig[8] = V.getText();
		colorConfig[9] = v.getText();
		colorConfig[10] = B.getText();
		colorConfig[11] = b.getText();
		colorConfig[12] = O.getText();
		colorConfig[13] = o.getText();
		colorConfig[14] = Y.getText();
		colorConfig[15] = y.getText();
		colorConfig[16] = P.getText();
		colorConfig[17] = p.getText();
		colorConfig[18] = K.getText();
		colorConfig[19] = K.getText2();
		colorConfig[20] = k.getText();
		colorConfig[21] = k.getText2();
		colorConfig[22] = T.getText();
		colorConfig[23] = t.getText();
		for (int i = 0; i < 24; i++) {
			if (colorConfig[i].length() != 6) {
				new JOptionPane().showMessageDialog(this, "Error! Bad color code (not 6 characters) in " + errorMsgs[i] + " color. Update failed");
				return;
			}
		}

		KilCli.updateColors(colorConfig);
		JOptionPane confirm = new JOptionPane();
		confirm.showMessageDialog(this, "Colors Updated");
	}

	/**
	 * Creates the normal colors pane
	 */
	private void createColors() {
		jScroll.setVerticalScrollBarPolicy(22);
		JPanel view = new JPanel();
		view.setLayout(new GridLayout(10, 1, 0, 1));

		R = new ColorEditorPanel("Red Text (R):", colorConfig[0]);
		view.add(R);

		G = new ColorEditorPanel("Green Text (G):", colorConfig[2]);
		view.add(G);

		W = new ColorEditorPanel("White Text (W):", colorConfig[4]);
		view.add(W);

		C = new ColorEditorPanel("Cyan Text (C):", colorConfig[6]);
		view.add(C);

		V = new ColorEditorPanel("Violet Text (V):", colorConfig[8]);
		view.add(V);

		B = new ColorEditorPanel("Blue Text (B):", colorConfig[10]);
		view.add(B);

		O = new ColorEditorPanel("Orange Text (O):", colorConfig[12]);
		view.add(O);

		Y = new ColorEditorPanel("Yellow Text (Y):", colorConfig[14]);
		view.add(Y);

		P = new ColorEditorPanel("Pink Text (P):", colorConfig[16]);
		view.add(P);

		T = new ColorEditorPanel("Brown Text (T):", colorConfig[22]);
		view.add(T);

		jScroll.setViewportView(view);
	}

	/**
	 * Creates the dark colors pane
	 */
	private void createDarks() {
		jScroll2.setVerticalScrollBarPolicy(22);
		JPanel view = new JPanel();
		view.setLayout(new GridLayout(10, 1, 0, 1));

		r = new ColorEditorPanel("Red Text (r):", colorConfig[1]);
		view.add(r);

		g = new ColorEditorPanel("Green Text (g):", colorConfig[3]);
		view.add(g);

		w = new ColorEditorPanel("White Text (w):", colorConfig[5]);
		view.add(w);

		c = new ColorEditorPanel("Cyan Text (c):", colorConfig[7]);
		view.add(c);

		v = new ColorEditorPanel("Violet Text (v):", colorConfig[9]);
		view.add(v);

		b = new ColorEditorPanel("Blue Text (b):", colorConfig[11]);
		view.add(b);

		o = new ColorEditorPanel("Orange Text (o):", colorConfig[13]);
		view.add(o);

		y = new ColorEditorPanel("Yellow Text (y):", colorConfig[15]);
		view.add(y);

		p = new ColorEditorPanel("Pink Text (p):", colorConfig[17]);
		view.add(p);

		t = new ColorEditorPanel("Brown Text (t):", colorConfig[23]);
		view.add(t);

		jScroll2.setViewportView(view);
	}

	/**
	 * Creates the highlight colors pane
	 */
	private void createHighlights() {
		jScroll3.setVerticalScrollBarPolicy(22);
		JPanel view = new JPanel();
		JPanel cell = new JPanel();
		JLabel pix = new JLabel();
		view.setLayout(new GridLayout(2, 1, 0, 1));

		K = new ColorEditorPanel("Background (K):", "Text (K):", colorConfig[18], colorConfig[19]);
		view.add(K);

		k = new ColorEditorPanel("Background (k):", "Text(k):", colorConfig[20], colorConfig[21]);
		view.add(k);

		jScroll3.setViewportView(view);
	}

}


text:
static const CGFloat kPanMinTranslationY            = 15.0f;

static const CGFloat kSlideOpenAnimationDuration    = 0.3f;
static const CGFloat kSlideCloseAnimationDuration   = 0.3f;

typedef NS_ENUM(NSInteger, JPVerticalSlidePanningState) {
    JPVerticalSlidePanningStateStopped,
    JPVerticalSlidePanningStateDown,
    JPVerticalSlidePanningStateUp
};

@interface JPVerticalSlideViewController ()
{

    JPVerticalSlidePanningState panningState;
    BOOL panStarted;
}

@property (strong, nonatomic) UIView *overlayView;

- (void) _addGestures;
- (void) _disableGestures;
- (void) _enableGestures;
- (void) _setup;

@end

@implementation JPVerticalSlideViewController

#pragma mark - Init -

+ (instancetype) verticalSlideMenuWithMainVC:(UIViewController *) mainViewController
                                    andTopVC:(UIViewController *) topViewController
                                 andBottomVC:(UIViewController *) bottomViewController{

    JPVerticalSlideViewController* verticalSlideVC  = [[JPVerticalSlideViewController alloc] init];

    if (verticalSlideVC) {

        verticalSlideVC.mainVC                          = mainViewController;
        verticalSlideVC.topVC                           = topViewController;
        verticalSlideVC.bottomVC                        = bottomViewController;
    }

    return verticalSlideVC;
}

#pragma mark - Lifecycle -

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self _setup];
}

#pragma mark - Datasource -

- (CGFloat) topVCHeight
{
    return 400.0f;
}

- (CGFloat) bottomVCHeight
{
    return 400.0f;
}

- (CGFloat) panGestureWorkingAreaPercent
{
    return 100.0f;
}

#pragma mark - Private Methods -

- (void) _addGestures
{
    if (self.overlayView)
    {
        [self.overlayView removeFromSuperview];
    }
    else
    {
        self.overlayView = [[UIView alloc] initWithFrame:self.view.bounds];
    }

    CGRect frame            = self.overlayView.frame;
    frame.size              = self.view.bounds.size;
    self.overlayView.frame  = frame;

    self.overlayView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.overlayView];

    [self.overlayView addGestureRecognizer:self.tapGesture];
    [self.overlayView addGestureRecognizer:self.panGesture];
}

- (void) _disableGestures
{
    self.tapGesture.enabled = NO;
}

- (void) _enableGestures
{
    self.tapGesture.enabled = YES;
}

- (void) _setup
{

    self.tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                              action:@selector(handleTapGesture:)];
    self.panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self
                                                              action:@selector(handlePanGesture:)];

    self.panGesture.delegate = self;

    self.tapGesture.cancelsTouchesInView = YES;

    [self.view addGestureRecognizer:self.panGesture];

    if (self.topVC) {

        CGRect currentTopFrame  = self.topVC.view.frame;
        currentTopFrame.origin  = CGPointMake(0.0f, -1 * self.topVC.view.frame.size.height);
        self.topVC.view.frame   = currentTopFrame;

        [self.view addSubview:self.topVC.view];
    }

    if (self.mainVC) {

        self.mainVC.view.frame   = self.view.frame;
        [self.view addSubview:self.mainVC.view];
    }

    if (self.bottomVC) {

        CGRect currentBottomFrame  = self.bottomVC.view.frame;
        currentBottomFrame.origin  = CGPointMake(0.0f, self.view.frame.size.height);
        self.bottomVC.view.frame   = currentBottomFrame;

        [self.view addSubview:self.bottomVC.view];
    }
}

#pragma mark - Gesture Recognizers -

- (void)handleTapGesture:(UITapGestureRecognizer *)tap
{
    [self _closeSlide];
}

- (void)handlePanGesture:(UIPanGestureRecognizer *)gesture
{

    static CGPoint panStartPosition = (CGPoint){0,0};

    if (self.topPanDisabled && self.bottomPanDisabled)
    {
        return;
    }

    UIView* panningView = gesture.view;

    if (self.slideState != JPVerticalSlideClosed)
    {
        panningView = panningView.superview;
    }

    CGPoint translation = [gesture translationInView:panningView];

    if ([gesture state] == UIGestureRecognizerStateBegan)
    {
        panStartPosition    = [gesture locationInView:panningView];
        panStarted          = YES;
    }
    else if ([gesture state] == UIGestureRecognizerStateEnded || [gesture state] == UIGestureRecognizerStateCancelled)
    {
        if (_slideState != JPVerticalSlideClosed)
        {
            if (panningState == JPVerticalSlidePanningStateDown)
            {
                if (self.view.frame.size.height - (panningView.frame.origin.y + panningView.frame.size.height) < (2.0f * ([self bottomVCHeight] / 3.0f)))
                {
                    [self closeBottomVC];
                }
                else
                {
                    [self openBottomVC];
                }
            }
            else if (panningState == JPVerticalSlidePanningStateUp)
            {
                if (panningView.frame.origin.y < (2.0f * ([self topVCHeight] / 3.0f)))
                {
                    [self closeTopVC];
                }
                else
                {
                    [self openTopVC];
                }
            }
        }
        else
        {
            if (panningState == JPVerticalSlidePanningStateUp)
            {

                if (self.view.frame.size.height - (panningView.frame.origin.y + panningView.frame.size.height) < ([self bottomVCHeight] / 3.0f))
                {
                    [self closeBottomVC];
                }
                else
                {
                    [self openBottomVC];
                }
            }
            if (panningState == JPVerticalSlidePanningStateDown)
            {
                if (panningView.frame.origin.y < ([self topVCHeight] / 3.0f))
                {
                    [self closeTopVC];
                }
                else
                {
                    [self openTopVC];
                }
            }
        }

        panningState = JPVerticalSlidePanningStateStopped;
    }
    else
    {
        if (!CGPointEqualToPoint(panStartPosition, (CGPoint){0,0}))
        {
            CGFloat actualHeight = panningView.frame.size.height * ([self panGestureWorkingAreaPercent] / 100.0f);
            if (panStartPosition.y > actualHeight && panStartPosition.y < panningView.frame.size.height - actualHeight && self.slideState == JPVerticalSlideClosed)
            {
                return;
            }
        }

        //--- Calculate pan position
        if(panStarted)
        {
            panStarted = NO;

            if (panningView.frame.origin.y + translation.y < 0)
            {
                if (self.slideState == JPVerticalSlideClosed) {

                    panningState    = JPVerticalSlidePanningStateUp;

                }else{

                    panningState    = JPVerticalSlidePanningStateDown;
                }

                if (self.slideState == JPVerticalSlideClosed)
                {
                    self.topVC.view.hidden      = YES;
                    self.bottomVC.view.hidden   = NO;
                }
            }
            else if(panningView.frame.origin.y + translation.y > 0)
            {
                if (self.slideState == JPVerticalSlideClosed) {

                    panningState    = JPVerticalSlidePanningStateDown;

                }else{

                    panningState    = JPVerticalSlidePanningStateUp;
                }

                if (self.slideState == JPVerticalSlideClosed)
                {
                    self.topVC.view.hidden      = NO;
                    self.bottomVC.view.hidden   = YES;
                }
            }
        }
        //----

        //----
        if (panningState == JPVerticalSlidePanningStateUp && self.topPanDisabled)
        {
            panningState = JPVerticalSlidePanningStateStopped;
            return;
        }
        else if (panningState == JPVerticalSlidePanningStateDown && self.bottomPanDisabled)
        {
            panningState = JPVerticalSlidePanningStateStopped;
            return;
        }
        //----

        if (self.slideState == JPVerticalSlideTopOpened)
        {
            if ((panningView.frame.origin.y + translation.y) < [self topVCHeight] && (panningView.frame.origin.y + translation.y) >= 0)
            {
                [panningView setCenter:CGPointMake([panningView center].x, [panningView center].y + translation.y)];
            }
        }
        else if (self.slideState == JPVerticalSlideBottomOpened)
        {
            if (self.view.frame.size.height - (panningView.frame.origin.y + panningView.frame.size.height + translation.y) < [self bottomVCHeight] &&
                panningView.frame.origin.y <= 0)
            {
                [panningView setCenter:CGPointMake([panningView center].x, [panningView center].y + translation.y)];
            }
        }
        else if (self.slideState == JPVerticalSlideClosed)
        {
            if (panningState == JPVerticalSlidePanningStateDown && self.topVC)
            {
                if ((panningView.frame.origin.y + translation.y) < [self topVCHeight] && (panningView.frame.origin.y + translation.y) > 0)
                {
                    [panningView setCenter:CGPointMake([panningView center].x, [panningView center].y + translation.y)];
                }
            }
            else if (panningState == JPVerticalSlidePanningStateUp  && self.bottomVC)
            {
                if (self.view.frame.size.height - (panningView.frame.origin.y + panningView.frame.size.height + translation.y) <= [self bottomVCHeight])
                {
                    if (panningView.frame.origin.y + translation.y <= 0)
                    {
                        [panningView setCenter:CGPointMake([panningView center].x, [panningView center].y + translation.y)];
                    }
                }
            }
        }
    }

    [gesture setTranslation:CGPointZero inView:panningView];
}

#pragma mark - Public Actions -

- (void) openTopVC
{
    [self openTopVCAnimated:YES];
}

- (void) openTopVCAnimated:(BOOL)animated
{

    if (self.slideVCDelegate && [self.slideVCDelegate respondsToSelector:@selector(topVCWillOpen)])
        [self.slideVCDelegate topVCWillOpen];

    self.topVC.view.hidden      = NO;
    self.bottomVC.view.hidden   = YES;

    CGRect frame                = self.view.frame;
    frame.origin.y              = [self topVCHeight];

    [UIView animateWithDuration:(animated) ? kSlideOpenAnimationDuration : 0
                     animations:^{
                         self.view.frame = frame;

                     } completion:^(BOOL finished) {

                         [self _addGestures];
                         [self _enableGestures];

                         self.slideState = JPVerticalSlideTopOpened;

                         if (self.slideVCDelegate && [self.slideVCDelegate respondsToSelector:@selector(topVCDidOpen)])
                             [self.slideVCDelegate topVCDidOpen];

                     }];
}

- (void) openBottomVC
{
    [self openBottomVCAnimated:YES];
}

- (void) openBottomVCAnimated:(BOOL)animated{

    if (self.slideVCDelegate && [self.slideVCDelegate respondsToSelector:@selector(bottomVCWillOpen)])
        [self.slideVCDelegate bottomVCWillOpen];

    self.topVC.view.hidden      = YES;
    self.bottomVC.view.hidden   = NO;

    CGRect frame                = self.view.frame;
    frame.origin.y              = -1 * [self bottomVCHeight];

    [UIView animateWithDuration:animated ? kSlideOpenAnimationDuration : 0
                     animations:^{

                         self.view.frame = frame;

                     } completion:^(BOOL finished) {

                         [self _addGestures];
                         [self _enableGestures];

                         self.slideState = JPVerticalSlideBottomOpened;

                         if (self.slideVCDelegate && [self.slideVCDelegate respondsToSelector:@selector(bottomVCDidOpen)])
                             [self.slideVCDelegate bottomVCDidOpen];

                     }];
}

- (void) closeTopVC
{
    [self closeTopVCAnimated:YES];
}

- (void) closeTopVCAnimated:(BOOL)animated
{

    if (self.slideVCDelegate && [self.slideVCDelegate respondsToSelector:@selector(topVCWillClose)])
        [self.slideVCDelegate topVCWillClose];

    CGRect frame    = self.view.frame;
    frame.origin.y  = 0;

    [UIView animateWithDuration:animated ? kSlideCloseAnimationDuration : 0
                     animations:^{

                         self.view.frame = frame;

                     } completion:^(BOOL finished) {

                         [self.overlayView removeFromSuperview];
                         [self _disableGestures];

                         self.slideState = JPVerticalSlideClosed;

                         [self.view addGestureRecognizer:self.panGesture];

                         if (self.slideVCDelegate && [self.slideVCDelegate respondsToSelector:@selector(topVCDidClose)])
                             [self.slideVCDelegate topVCDidClose];

                     }];
}

- (void) closeBottomVC
{
    [self closeBottomVCAnimated:YES];
}

- (void) closeBottomVCAnimated:(BOOL)animated
{

    if (self.slideVCDelegate && [self.slideVCDelegate respondsToSelector:@selector(bottomVCWillClose)])
        [self.slideVCDelegate bottomVCWillClose];

    CGRect frame    = self.view.frame;
    frame.origin.y  = 0;

    [UIView animateWithDuration:animated ? kSlideCloseAnimationDuration : 0
                     animations:^{

                         self.view.frame = frame;

                     } completion:^(BOOL finished) {

                         [self.overlayView removeFromSuperview];
                         [self _disableGestures];

                         self.slideState = JPVerticalSlideClosed;

                         [self.view addGestureRecognizer:self.panGesture];

                         if (self.slideVCDelegate && [self.slideVCDelegate respondsToSelector:@selector(bottomVCDidClose)])
                             [self.slideVCDelegate bottomVCDidClose];

                     }];
}

- (void) _closeSlide
{
    if (self.slideState == JPVerticalSlideBottomOpened)
    {
        [self closeBottomVC];
    }
    else if (self.slideState == JPVerticalSlideTopOpened)
    {
        [self closeTopVC];
    }
}

#pragma mark - UIGestureRecognizer Delegate Methods -

- (BOOL)gestureRecognizerShouldBegin:(UIPanGestureRecognizer *)panGestureRecognizer {

    CGPoint translation = [panGestureRecognizer translationInView:panGestureRecognizer.view];

    return fabs(translation.y) > fabs(translation.x);
}

@end

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace app\components\socials;

use GuzzleHttp\Client;

/*
 * todo: реализовать функционал парсинга лайков по симлинкам (искать short ссылки)
 * http://cgit.drupalcode.org/shareaholic/tree/lib/social-share-counts/share_count.php?id=0af9ade973a91ee7744f61c9820e5779b9241bfc
 */
abstract class Social
{
    /**
     * @var Client
     */
    protected $httpClient;

    /**
     * @param Client $httpClient
     */
    public function __construct(Client $httpClient)
    {
        $this->httpClient = $httpClient;
    }

    /**
     * Get social name
     * @return string
     */
    abstract public function getName();

    /**
     * Get class name with namespace
     * @return string
     */
    public static function getClassName()
    {
        return get_called_class();
    }
}


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

<title>NodeStructure</title>
<meta name="date" content="2017-01-04">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.drip.analytics.definition

Class NodeStructure

java.lang.Object

org.drip.analytics.definition.NodeStructure

All Implemented Interfaces:

Curve, LatentState

Direct Known Subclasses:

BasisSplineTermStructure, VolatilityCurve

public abstract class NodeStructure
extends java.lang.Object
implements Curve

NodeStructure exposes the stub that implements the latent state's Node Structure (e.g., a Deterministic
  Term Structure) - by Construction, this is expected to be non-local.

Author:

Lakshmi Krishnamurthy

Method Summary

All Methods Instance Methods Abstract Methods Concrete Methods

Modifier and Type
Method and Description

CalibratableComponent[]
calibComp()

Retrieve the Calibration Components

java.lang.String
currency()

Get the Currency

LatentState
customTweakManifestMeasure(java.lang.String strManifestMeasure,
                          ManifestMeasureTweak rvtp)

Create a LatentState Instance from the Manifest Measure Tweak Parameters

LatentState
customTweakQuantificationMetric(ManifestMeasureTweak rvtp)

Create a LatentState Instance from the Quantification Metric Tweak Parameters

JulianDate
epoch()

Get the Epoch Date

LatentStateLabel
label()

Get the Curve Latent State Identifier Label

CaseInsensitiveTreeMap<java.lang.Double>
manifestMeasure(java.lang.String strInstr)

Retrieve the Manifest Measure Map of the given Instrument used to construct the Curve

abstract double
node(int iPredictorOrdinate)

Get the Market Node at the given Predictor Ordinate

double
node(JulianDate dt)

Get the Market Node at the given Maturity

double
node(java.lang.String strTenor)

Get the Market Node at the given Maturity

abstract double
nodeDerivative(int iPredictorOrdinate,
              int iOrder)

Get the Market Node Derivative at the given Predictor Ordinate

double
nodeDerivative(JulianDate dt,
              int iOrder)

Get the Market Node Derivative at the given Maturity

double
nodeDerivative(java.lang.String strTenor,
              int iOrder)

Get the Market Node Derivative at the given Maturity

LatentState
parallelShiftManifestMeasure(java.lang.String strManifestMeasure,
                            double dblShift)

Create a LatentState Instance from the Manifest Measure Parallel Shift

LatentState
parallelShiftQuantificationMetric(double dblShift)

Create a LatentState Instance from the Quantification Metric Parallel Shift

boolean
setCCIS(CurveConstructionInputSet ccis)

Set the Curve Construction Input Set Parameters

LatentState
shiftManifestMeasure(int iSpanIndex,
                    java.lang.String strManifestMeasure,
                    double dblShift)

Create a LatentState Instance from the Shift of the Specified Manifest Measure

Methods inherited from class java.lang.Object

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

Method Detail

label

public LatentStateLabel label()

Description copied from interface: Curve

Get the Curve Latent State Identifier Label

Specified by:

label in interface Curve

Returns:

The Curve Latent State Identifier Label

currency

public java.lang.String currency()

Description copied from interface: Curve

Get the Currency

Specified by:

currency in interface Curve

Returns:

Currency

epoch

public JulianDate epoch()

Description copied from interface: Curve

Get the Epoch Date

Specified by:

epoch in interface Curve

Returns:

The Epoch Date

setCCIS

public boolean setCCIS(CurveConstructionInputSet ccis)

Description copied from interface: Curve

Set the Curve Construction Input Set Parameters

Specified by:

setCCIS in interface Curve

Parameters:

ccis - The Curve Construction Input Set Parameters

Returns:

TRUE - Inputs successfully Set

calibComp

public CalibratableComponent[] calibComp()

Description copied from interface: Curve

Retrieve the Calibration Components

Specified by:

calibComp in interface Curve

Returns:

Array of Calibration Components

manifestMeasure

public CaseInsensitiveTreeMap<java.lang.Double> manifestMeasure(java.lang.String strInstr)

Description copied from interface: Curve

Retrieve the Manifest Measure Map of the given Instrument used to construct the Curve

Specified by:

manifestMeasure in interface Curve

Parameters:

strInstr - The Calibration Instrument's Code whose Manifest Measure Map is sought

Returns:

The Manifest Measure Map of the given Instrument used to construct the Curve

parallelShiftManifestMeasure

public LatentState parallelShiftManifestMeasure(java.lang.String strManifestMeasure,
                                                double dblShift)

Description copied from interface: LatentState

Create a LatentState Instance from the Manifest Measure Parallel Shift

Specified by:

parallelShiftManifestMeasure in interface LatentState

Parameters:

strManifestMeasure - The Specified Manifest Measure

dblShift - Parallel shift of the Manifest Measure

Returns:

New LatentState Instance corresponding to the Parallel Shifted Manifest Measure

shiftManifestMeasure

public LatentState shiftManifestMeasure(int iSpanIndex,
                                        java.lang.String strManifestMeasure,
                                        double dblShift)

Description copied from interface: LatentState

Create a LatentState Instance from the Shift of the Specified Manifest Measure

Specified by:

shiftManifestMeasure in interface LatentState

Parameters:

iSpanIndex - Index into the Span that identifies the Instrument

strManifestMeasure - The Specified Manifest Measure

dblShift - Shift of the Manifest Measure

Returns:

New LatentState Instance corresponding to the Shift of the Specified Manifest Measure

customTweakManifestMeasure

public LatentState customTweakManifestMeasure(java.lang.String strManifestMeasure,
                                              ManifestMeasureTweak rvtp)

Description copied from interface: LatentState

Create a LatentState Instance from the Manifest Measure Tweak Parameters

Specified by:

customTweakManifestMeasure in interface LatentState

Parameters:

strManifestMeasure - The Specified Manifest Measure

rvtp - Manifest Measure Tweak Parameters

Returns:

New LatentState Instance corresponding to the Tweaked Manifest Measure

parallelShiftQuantificationMetric

public LatentState parallelShiftQuantificationMetric(double dblShift)

Description copied from interface: LatentState

Create a LatentState Instance from the Quantification Metric Parallel Shift

Specified by:

parallelShiftQuantificationMetric in interface LatentState

Parameters:

dblShift - Parallel shift of the Quantification Metric

Returns:

New LatentState Instance corresponding to the Parallel Shifted Quantification Metric

customTweakQuantificationMetric

public LatentState customTweakQuantificationMetric(ManifestMeasureTweak rvtp)

Description copied from interface: LatentState

Create a LatentState Instance from the Quantification Metric Tweak Parameters

Specified by:

customTweakQuantificationMetric in interface LatentState

Parameters:

rvtp - Quantification Metric Tweak Parameters

Returns:

New LatentState Instance corresponding to the Tweaked Quantification Metric

node

public abstract double node(int iPredictorOrdinate)
                     throws java.lang.Exception

Get the Market Node at the given Predictor Ordinate

Parameters:

iPredictorOrdinate - The Predictor Ordinate

Returns:

The Node evaluated from the Term Structure

Throws:

java.lang.Exception - Thrown if the Inputs are Invalid

nodeDerivative

public abstract double nodeDerivative(int iPredictorOrdinate,
                                      int iOrder)
                               throws java.lang.Exception

Get the Market Node Derivative at the given Predictor Ordinate

Parameters:

iPredictorOrdinate - The Predictor Ordinate

iOrder - Order of the Derivative

Returns:

The Node Derivative evaluated from the Term Structure

Throws:

java.lang.Exception - Thrown if the Inputs are Invalid

node

public double node(JulianDate dt)
            throws java.lang.Exception

Get the Market Node at the given Maturity

Parameters:

dt - The Julian Maturity Date

Returns:

The Node evaluated from the Term Structure

Throws:

java.lang.Exception - Thrown if the Inputs are Invalid

node

public double node(java.lang.String strTenor)
            throws java.lang.Exception

Get the Market Node at the given Maturity

Parameters:

strTenor - The Maturity Tenor

Returns:

The Node evaluated from the Term Structure

Throws:

java.lang.Exception - Thrown if the Inputs are Invalid

nodeDerivative

public double nodeDerivative(JulianDate dt,
                             int iOrder)
                      throws java.lang.Exception

Get the Market Node Derivative at the given Maturity

Parameters:

dt - The Julian Maturity Date

iOrder - Order of the Derivative

Returns:

The Node Derivative evaluated from the Term Structure

Throws:

java.lang.Exception - Thrown if the Inputs are Invalid

nodeDerivative

public double nodeDerivative(java.lang.String strTenor,
                             int iOrder)
                      throws java.lang.Exception

Get the Market Node Derivative at the given Maturity

Parameters:

strTenor - The Maturity Tenor

iOrder - Order of the Derivative

Returns:

The Node Derivative evaluated from the Term Structure

Throws:

java.lang.Exception - Thrown if the Inputs are Invalid

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
Django relish
=============

Contains some useful code for django.


text:
class EmptyTester
  include PerformLater

  def do_work; end
end

class DoWorkTester
  include PerformLater

  perform_later :do_work

  def do_work; end
end

class DoWorkWithAsTester
  include PerformLater

  perform_later :do_work, as: 'entry_point_asynchronously'

  def do_work; end
end

class DoWorkWithArrayAsTester
  include PerformLater

  perform_later :do_work, as: ['entry_point_asynchronously', :entry_point_alias_asynchronously]

  def do_work; end
end

class DoWorkWithDeserializationTester
  include PerformLater
  attr_accessor :foo

  perform_later :do_work

  def do_work; end

  module Async
    def deserialize(arg1)
      DoWorkWithDeserializationTester.new.tap do |o|
        o.foo = arg1
      end
    end
  end
end

class DoWorkWithSerializationTester
  include PerformLater

  perform_later :do_work

  def do_work; end

  module Async
    def serialize(*args)
      args.map{ |a| a.hash }
    end
  end
end


text:
module MediaWiktory::Wikipedia
  module Actions
    # Create and edit pages.
    #
    # Usage:
    #
    # ```ruby
    # api.edit.title(value).perform # returns string with raw output
    # # or
    # api.edit.title(value).response # returns output parsed and wrapped into Response object
    # ```
    #
    # See {Base} for generic explanation of working with MediaWiki actions and
    # {MediaWiktory::Wikipedia::Response} for working with action responses.
    #
    # All action's parameters are documented as its public methods, see below.
    #
    class Edit < MediaWiktory::Wikipedia::Actions::Post

      # Title of the page to edit. Cannot be used together with pageid.
      #
      # @param value [String]
      # @return [self]
      def title(value)
        merge(title: value.to_s)
      end

      # Page ID of the page to edit. Cannot be used together with title.
      #
      # @param value [Integer]
      # @return [self]
      def pageid(value)
        merge(pageid: value.to_s)
      end

      # Section number. 0 for the top section, new for a new section.
      #
      # @param value [String]
      # @return [self]
      def section(value)
        merge(section: value.to_s)
      end

      # The title for a new section.
      #
      # @param value [String]
      # @return [self]
      def sectiontitle(value)
        merge(sectiontitle: value.to_s)
      end

      # Page content.
      #
      # @param value [String]
      # @return [self]
      def text(value)
        merge(text: value.to_s)
      end

      # Edit summary. Also section title when section=new and sectiontitle is not set.
      #
      # @param value [String]
      # @return [self]
      def summary(value)
        merge(summary: value.to_s)
      end

      # Change tags to apply to the revision.
      #
      # @param values [Array<String>] Allowed values: "ProveIt edit", "WPCleaner", "huggle", "large plot addition".
      # @return [self]
      def tags(*values)
        values.inject(self) { |res, val| res._tags(val) or fail ArgumentError, "Unknown value for tags: #{val}" }
      end

      # @private
      def _tags(value)
        defined?(super) && super || ["ProveIt edit", "WPCleaner", "huggle", "large plot addition"].include?(value.to_s) && merge(tags: value.to_s, replace: false)
      end

      # Minor edit.
      #
      # @return [self]
      def minor()
        merge(minor: 'true')
      end

      # Non-minor edit.
      #
      # @return [self]
      def notminor()
        merge(notminor: 'true')
      end

      # Mark this edit as a bot edit.
      #
      # @return [self]
      def bot()
        merge(bot: 'true')
      end

      # Timestamp of the base revision, used to detect edit conflicts. May be obtained through action=query&prop=revisions&rvprop=timestamp.
      #
      # @param value [Time]
      # @return [self]
      def basetimestamp(value)
        merge(basetimestamp: value.iso8601)
      end

      # Timestamp when the editing process began, used to detect edit conflicts. An appropriate value may be obtained using curtimestamp when beginning the edit process (e.g. when loading the page content to edit).
      #
      # @param value [Time]
      # @return [self]
      def starttimestamp(value)
        merge(starttimestamp: value.iso8601)
      end

      # Override any errors about the page having been deleted in the meantime.
      #
      # @return [self]
      def recreate()
        merge(recreate: 'true')
      end

      # Don't edit the page if it exists already.
      #
      # @return [self]
      def createonly()
        merge(createonly: 'true')
      end

      # Throw an error if the page doesn't exist.
      #
      # @return [self]
      def nocreate()
        merge(nocreate: 'true')
      end

      # Add the page to the current user's watchlist.
      #
      # @return [self]
      def watch()
        merge(watch: 'true')
      end

      # Remove the page from the current user's watchlist.
      #
      # @return [self]
      def unwatch()
        merge(unwatch: 'true')
      end

      # Unconditionally add or remove the page from the current user's watchlist, use preferences or do not change watch.
      #
      # @param value [String] One of "watch", "unwatch", "preferences", "nochange".
      # @return [self]
      def watchlist(value)
        _watchlist(value) or fail ArgumentError, "Unknown value for watchlist: #{value}"
      end

      # @private
      def _watchlist(value)
        defined?(super) && super || ["watch", "unwatch", "preferences", "nochange"].include?(value.to_s) && merge(watchlist: value.to_s)
      end

      # The MD5 hash of the text parameter, or the prependtext and appendtext parameters concatenated. If set, the edit won't be done unless the hash is correct.
      #
      # @param value [String]
      # @return [self]
      def md5(value)
        merge(md5: value.to_s)
      end

      # Add this text to the beginning of the page. Overrides text.
      #
      # @param value [String]
      # @return [self]
      def prependtext(value)
        merge(prependtext: value.to_s)
      end

      # Add this text to the end of the page. Overrides text.
      #
      # @param value [String]
      # @return [self]
      def appendtext(value)
        merge(appendtext: value.to_s)
      end

      # Undo this revision. Overrides text, prependtext and appendtext.
      #
      # @param value [Integer]
      # @return [self]
      def undo(value)
        merge(undo: value.to_s)
      end

      # Undo all revisions from undo to this one. If not set, just undo one revision.
      #
      # @param value [Integer]
      # @return [self]
      def undoafter(value)
        merge(undoafter: value.to_s)
      end

      # Automatically resolve redirects.
      #
      # @return [self]
      def redirect()
        merge(redirect: 'true')
      end

      # Content serialization format used for the input text.
      #
      # @param value [String] One of "application/json", "text/x-wiki", "text/javascript", "text/css", "text/plain".
      # @return [self]
      def contentformat(value)
        _contentformat(value) or fail ArgumentError, "Unknown value for contentformat: #{value}"
      end

      # @private
      def _contentformat(value)
        defined?(super) && super || ["application/json", "text/x-wiki", "text/javascript", "text/css", "text/plain"].include?(value.to_s) && merge(contentformat: value.to_s)
      end

      # Content model of the new content.
      #
      # @param value [String] One of "GadgetDefinition", "SecurePoll", "MassMessageListContent", "JsonSchema", "wikitext", "javascript", "json", "css", "text", "Scribunto".
      # @return [self]
      def contentmodel(value)
        _contentmodel(value) or fail ArgumentError, "Unknown value for contentmodel: #{value}"
      end

      # @private
      def _contentmodel(value)
        defined?(super) && super || ["GadgetDefinition", "SecurePoll", "MassMessageListContent", "JsonSchema", "wikitext", "javascript", "json", "css", "text", "Scribunto"].include?(value.to_s) && merge(contentmodel: value.to_s)
      end

      # A "csrf" token retrieved from action=query&meta=tokens
      #
      # @param value [String]
      # @return [self]
      def token(value)
        merge(token: value.to_s)
      end

      # Answer to the CAPTCHA
      #
      # @param value [String]
      # @return [self]
      def captchaword(value)
        merge(captchaword: value.to_s)
      end

      # CAPTCHA ID from previous request
      #
      # @param value [String]
      # @return [self]
      def captchaid(value)
        merge(captchaid: value.to_s)
      end
    end
  end
end


text:
<?php

namespace Kevinbai\Admin\Form\Field;

class DatetimeRange extends DateRange
{
    protected $format = 'YYYY-MM-DD HH:mm:ss';
}


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 Utilitaire;

import Entite.Resultat;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 * @author jeoffrey
 */
public class Resultat_DAO {

     public static void CreerResultat(Resultat resultat,Connection connection )
{

    Statement stmt = null;
      try
    {
    stmt = connection.createStatement();

  stmt.executeUpdate("Insert Into resultats(Res_date,Res_lib,Res_cat,Res_classement,Res_nb_participants,Type_Tournoi_Typ_tn_id,Equipe_Equ_id) Values('"
          + resultat.getRes_date()+ "', "
          + resultat.getRes_lib()+",'"
          + resultat.getRes_cat()+"',"
          + resultat.getRes_classement()+"',"
          + resultat.getRes_nbr_participant()+"',"
          + resultat.getType_tournoi_id()+"',"
          + resultat.getEquipe_id()+"',");

     ResultSet res =  stmt.executeQuery("SELECT MAX(Res_id) FROM resultats");
       if(res.next())
       {

           int id = res.getInt(1);
           resultat.setRes_id(id);
       }

        System.out.println("Insertion réusssite " );

    } catch(Exception ex){ex.printStackTrace();}

    finally
    {
        if (stmt != null)
        {
            try
            {
                stmt.close();
            }catch( SQLException ex){

            }
        }

    }

}
}


text:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <errno.h>

#include <cutils/properties.h>

#include "hal-log.h"
#include "hal.h"
#include "hal-msg.h"
#include "ipc-common.h"
#include "hal-ipc.h"
#include "hal-utils.h"

static const bt_callbacks_t *bt_hal_cbacks = NULL;

#define enum_prop_to_hal(prop, hal_prop, type) do { \
	static type e; \
	prop.val = &e; \
	prop.len = sizeof(e); \
	e = *((uint8_t *) (hal_prop->val)); \
} while (0)

#define enum_prop_from_hal(prop, hal_len, hal_val, enum_type) do { \
	enum_type e; \
	if (prop->len != sizeof(e)) { \
		error("invalid HAL property %u (%u vs %zu), aborting ", \
					prop->type, prop->len, sizeof(e)); \
		exit(EXIT_FAILURE); \
	} \
	memcpy(&e, prop->val, sizeof(e)); \
	*((uint8_t *) hal_val) = e; /* enums are mapped to 1 byte */ \
	*hal_len = 1; \
} while (0)

static void handle_adapter_state_changed(void *buf, uint16_t len, int fd)
{
	struct hal_ev_adapter_state_changed *ev = buf;

	DBG("state: %s", bt_state_t2str(ev->state));

	if (bt_hal_cbacks->adapter_state_changed_cb)
		bt_hal_cbacks->adapter_state_changed_cb(ev->state);
}

static void adapter_props_to_hal(bt_property_t *send_props,
					struct hal_property *prop,
					uint8_t num_props, uint16_t len)
{
	void *buf = prop;
	uint8_t i;

	for (i = 0; i < num_props; i++) {
		if (sizeof(*prop) + prop->len > len) {
			error("invalid adapter properties(%zu > %u), aborting",
					sizeof(*prop) + prop->len, len);
			exit(EXIT_FAILURE);
		}

		send_props[i].type = prop->type;

		switch (prop->type) {
		case HAL_PROP_ADAPTER_TYPE:
			enum_prop_to_hal(send_props[i], prop,
							bt_device_type_t);
			break;
		case HAL_PROP_ADAPTER_SCAN_MODE:
			enum_prop_to_hal(send_props[i], prop,
							bt_scan_mode_t);
			break;
		case HAL_PROP_ADAPTER_SERVICE_REC:
		default:
			send_props[i].len = prop->len;
			send_props[i].val = prop->val;
			break;
		}

		DBG("prop[%d]: %s", i, btproperty2str(&send_props[i]));

		len -= sizeof(*prop) + prop->len;
		buf += sizeof(*prop) + prop->len;
		prop = buf;
	}

	if (!len)
		return;

	error("invalid adapter properties (%u bytes left), aborting", len);
	exit(EXIT_FAILURE);
}

static void adapter_prop_from_hal(const bt_property_t *property, uint8_t *type,
						uint16_t *len, void *val)
{
	/* type match IPC type */
	*type = property->type;

	switch (property->type) {
	case HAL_PROP_ADAPTER_SCAN_MODE:
		enum_prop_from_hal(property, len, val, bt_scan_mode_t);
		break;
	case BT_PROPERTY_BDNAME:
	case BT_PROPERTY_BDADDR:
	case BT_PROPERTY_UUIDS:
	case BT_PROPERTY_CLASS_OF_DEVICE:
	case BT_PROPERTY_TYPE_OF_DEVICE:
	case BT_PROPERTY_SERVICE_RECORD:
	case BT_PROPERTY_ADAPTER_BONDED_DEVICES:
	case BT_PROPERTY_ADAPTER_DISCOVERY_TIMEOUT:
	case BT_PROPERTY_REMOTE_FRIENDLY_NAME:
	case BT_PROPERTY_REMOTE_RSSI:
	case BT_PROPERTY_REMOTE_VERSION_INFO:
	case BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP:
#if ANDROID_VERSION >= PLATFORM_VER(5, 0, 0)
	case BT_PROPERTY_LOCAL_LE_FEATURES:
#endif
	default:
		*len = property->len;
		memcpy(val, property->val, property->len);
		break;
	}
}

static void device_props_to_hal(bt_property_t *send_props,
				struct hal_property *prop, uint8_t num_props,
				uint16_t len)
{
	void *buf = prop;
	uint8_t i;

	for (i = 0; i < num_props; i++) {
		if (sizeof(*prop) + prop->len > len) {
			error("invalid device properties (%zu > %u), aborting",
					sizeof(*prop) + prop->len, len);
			exit(EXIT_FAILURE);
		}

		send_props[i].type = prop->type;

		switch (prop->type) {
		case HAL_PROP_DEVICE_TYPE:
			enum_prop_to_hal(send_props[i], prop,
							bt_device_type_t);
			break;
		case HAL_PROP_DEVICE_VERSION_INFO:
		{
			static bt_remote_version_t e;
			const struct hal_prop_device_info *p;

			send_props[i].val = &e;
			send_props[i].len = sizeof(e);

			p = (struct hal_prop_device_info *) prop->val;

			e.manufacturer = p->manufacturer;
			e.sub_ver = p->sub_version;
			e.version = p->version;
		}
			break;
		case HAL_PROP_DEVICE_SERVICE_REC:
		{
			static bt_service_record_t e;
			const struct hal_prop_device_service_rec *p;

			send_props[i].val = &e;
			send_props[i].len = sizeof(e);

			p = (struct hal_prop_device_service_rec *) prop->val;

			memset(&e, 0, sizeof(e));
			memcpy(&e.channel, &p->channel, sizeof(e.channel));
			memcpy(e.uuid.uu, p->uuid, sizeof(e.uuid.uu));
			memcpy(e.name, p->name, p->name_len);
		}
			break;
		default:
			send_props[i].len = prop->len;
			send_props[i].val = prop->val;
			break;
		}

		len -= sizeof(*prop) + prop->len;
		buf += sizeof(*prop) + prop->len;
		prop = buf;

		DBG("prop[%d]: %s", i, btproperty2str(&send_props[i]));
	}

	if (!len)
		return;

	error("invalid device properties (%u bytes left), aborting", len);
	exit(EXIT_FAILURE);
}

static void handle_adapter_props_changed(void *buf, uint16_t len, int fd)
{
	struct hal_ev_adapter_props_changed *ev = buf;
	bt_property_t props[ev->num_props];

	DBG("");

	if (!bt_hal_cbacks->adapter_properties_cb)
		return;

	len -= sizeof(*ev);
	adapter_props_to_hal(props, ev->props, ev->num_props, len);

	bt_hal_cbacks->adapter_properties_cb(ev->status, ev->num_props, props);
}

static void handle_bond_state_change(void *buf, uint16_t len, int fd)
{
	struct hal_ev_bond_state_changed *ev = buf;
	bt_bdaddr_t *addr = (bt_bdaddr_t *) ev->bdaddr;

	DBG("state %u", ev->state);

	if (bt_hal_cbacks->bond_state_changed_cb)
		bt_hal_cbacks->bond_state_changed_cb(ev->status, addr,
								ev->state);
}

static void handle_pin_request(void *buf, uint16_t len, int fd)
{
	struct hal_ev_pin_request *ev = buf;
	/* Those are declared as packed, so it's safe to assign pointers */
	bt_bdaddr_t *addr = (bt_bdaddr_t *) ev->bdaddr;
	bt_bdname_t *name = (bt_bdname_t *) ev->name;

	DBG("");

	if (bt_hal_cbacks->pin_request_cb)
		bt_hal_cbacks->pin_request_cb(addr, name, ev->class_of_dev);
}

static void handle_ssp_request(void *buf, uint16_t len, int fd)
{
	struct hal_ev_ssp_request *ev = buf;
	/* Those are declared as packed, so it's safe to assign pointers */
	bt_bdaddr_t *addr = (bt_bdaddr_t *) ev->bdaddr;
	bt_bdname_t *name = (bt_bdname_t *) ev->name;

	DBG("");

	if (bt_hal_cbacks->ssp_request_cb)
		bt_hal_cbacks->ssp_request_cb(addr, name, ev->class_of_dev,
							ev->pairing_variant,
							ev->passkey);
}

void bt_thread_associate(void)
{
	if (bt_hal_cbacks->thread_evt_cb)
		bt_hal_cbacks->thread_evt_cb(ASSOCIATE_JVM);
}

void bt_thread_disassociate(void)
{
	if (bt_hal_cbacks->thread_evt_cb)
		bt_hal_cbacks->thread_evt_cb(DISASSOCIATE_JVM);
}

static bool interface_ready(void)
{
	return bt_hal_cbacks != NULL;
}

static void handle_discovery_state_changed(void *buf, uint16_t len, int fd)
{
	struct hal_ev_discovery_state_changed *ev = buf;

	DBG("");

	if (bt_hal_cbacks->discovery_state_changed_cb)
		bt_hal_cbacks->discovery_state_changed_cb(ev->state);
}

static void handle_device_found(void *buf, uint16_t len, int fd)
{
	struct hal_ev_device_found *ev = buf;
	bt_property_t props[ev->num_props];

	DBG("");

	if (!bt_hal_cbacks->device_found_cb)
		return;

	len -= sizeof(*ev);
	device_props_to_hal(props, ev->props, ev->num_props, len);

	bt_hal_cbacks->device_found_cb(ev->num_props, props);
}

static void handle_device_state_changed(void *buf, uint16_t len, int fd)
{
	struct hal_ev_remote_device_props *ev = buf;
	bt_property_t props[ev->num_props];

	DBG("");

	if (!bt_hal_cbacks->remote_device_properties_cb)
		return;

	len -= sizeof(*ev);
	device_props_to_hal(props, ev->props, ev->num_props, len);

	bt_hal_cbacks->remote_device_properties_cb(ev->status,
						(bt_bdaddr_t *)ev->bdaddr,
						ev->num_props, props);
}

static void handle_acl_state_changed(void *buf, uint16_t len, int fd)
{
	struct hal_ev_acl_state_changed *ev = buf;
	bt_bdaddr_t *addr = (bt_bdaddr_t *) ev->bdaddr;

	DBG("state %u", ev->state);

	if (bt_hal_cbacks->acl_state_changed_cb)
		bt_hal_cbacks->acl_state_changed_cb(ev->status, addr,
								ev->state);
}

static void handle_dut_mode_receive(void *buf, uint16_t len, int fd)
{
	struct hal_ev_dut_mode_receive *ev = buf;

	DBG("");

	if (len != sizeof(*ev) + ev->len) {
		error("invalid dut mode receive event (%u), aborting", len);
		exit(EXIT_FAILURE);
	}

	if (bt_hal_cbacks->dut_mode_recv_cb)
		bt_hal_cbacks->dut_mode_recv_cb(ev->opcode, ev->data, ev->len);
}

static void handle_le_test_mode(void *buf, uint16_t len, int fd)
{
	struct hal_ev_le_test_mode *ev = buf;

	DBG("");

	if (bt_hal_cbacks->le_test_mode_cb)
		bt_hal_cbacks->le_test_mode_cb(ev->status, ev->num_packets);
}

static void handle_energy_info(void *buf, uint16_t len, int fd)
{
#if ANDROID_VERSION >= PLATFORM_VER(5, 0, 0)
	struct hal_ev_energy_info *ev = buf;
	bt_activity_energy_info info;

	DBG("");

	info.ctrl_state = ev->ctrl_state;
	info.energy_used = ev->energy_used;
	info.idle_time = ev->idle_time;
	info.rx_time = ev->rx_time;
	info.status = ev->status;
	info.tx_time = ev->status;

	if (bt_hal_cbacks->energy_info_cb)
		bt_hal_cbacks->energy_info_cb(&info);
#endif
}

/*
 * handlers will be called from notification thread context,
 * index in table equals to 'opcode - HAL_MINIMUM_EVENT'
 */
static const struct hal_ipc_handler ev_handlers[] = {
	/* HAL_EV_ADAPTER_STATE_CHANGED */
	{ handle_adapter_state_changed, false,
				sizeof(struct hal_ev_adapter_state_changed) },
	/* HAL_EV_ADAPTER_PROPS_CHANGED */
	{ handle_adapter_props_changed, true,
				sizeof(struct hal_ev_adapter_props_changed) +
				sizeof(struct hal_property) },
	/* HAL_EV_REMOTE_DEVICE_PROPS */
	{ handle_device_state_changed, true,
				sizeof(struct hal_ev_remote_device_props) +
				sizeof(struct hal_property) },
	/* HAL_EV_DEVICE_FOUND */
	{ handle_device_found, true, sizeof(struct hal_ev_device_found) +
				sizeof(struct hal_property) },
	/* HAL_EV_DISCOVERY_STATE_CHANGED */
	{ handle_discovery_state_changed, false,
				sizeof(struct hal_ev_discovery_state_changed) },
	/* HAL_EV_PIN_REQUEST */
	{ handle_pin_request, false, sizeof(struct hal_ev_pin_request) },
	/* HAL_EV_SSP_REQUEST */
	{ handle_ssp_request, false, sizeof(struct hal_ev_ssp_request) },
	/* HAL_EV_BOND_STATE_CHANGED */
	{ handle_bond_state_change, false,
				sizeof(struct hal_ev_bond_state_changed) },
	/* HAL_EV_ACL_STATE_CHANGED */
	{ handle_acl_state_changed, false,
				sizeof(struct hal_ev_acl_state_changed) },
	/* HAL_EV_DUT_MODE_RECEIVE */
	{ handle_dut_mode_receive, true,
				sizeof(struct hal_ev_dut_mode_receive) },
	/* HAL_EV_LE_TEST_MODE */
	{ handle_le_test_mode, false, sizeof(struct hal_ev_le_test_mode) },
	/* HAL_EV_ENERGY_INFO */
	{ handle_energy_info, false, sizeof(struct hal_ev_energy_info) },
};

static uint8_t get_mode(void)
{
	char value[PROPERTY_VALUE_MAX];

	if (get_config("mode", value, NULL) > 0) {
		if (!strcasecmp(value, "bredr"))
			return HAL_MODE_BREDR;

		if (!strcasecmp(value, "le"))
			return HAL_MODE_LE;
	}

	return HAL_MODE_DEFAULT;
}

static uint16_t add_prop(const char *prop, uint8_t type, void *buf)
{
	struct hal_config_prop *hal_prop = buf;

	hal_prop->type = type;
	hal_prop->len = strlen(prop) + 1;
	memcpy(hal_prop->val, prop, hal_prop->len);

	return sizeof(*hal_prop) + hal_prop->len;
}

static int send_configuration(void)
{
	char buf[IPC_MTU];
	struct hal_cmd_configuration *cmd = (void *) buf;
	char prop[PROPERTY_VALUE_MAX];
	uint16_t len = sizeof(*cmd);

	cmd->num = 0;

	if (get_config("vendor", prop, "ro.product.manufacturer") > 0) {
		len += add_prop(prop, HAL_CONFIG_VENDOR, buf + len);
		cmd->num++;
	}

	if (get_config("name", prop, "ro.product.name") > 0) {
		len += add_prop(prop, HAL_CONFIG_NAME, buf + len);
		cmd->num++;
	}

	if (get_config("model", prop, "ro.product.model") > 0) {
		len += add_prop(prop, HAL_CONFIG_MODEL, buf + len);
		cmd->num++;
	}

	if (get_config("serialno", prop, "ro.serialno") > 0) {
		len += add_prop(prop, HAL_CONFIG_SERIAL_NUMBER, buf + len);
		cmd->num++;
	}

	if (get_config("systemid", prop, NULL) > 0) {
		len += add_prop(prop, HAL_CONFIG_SYSTEM_ID, buf + len);
		cmd->num++;
	}

	if (get_config("pnpid", prop, NULL) > 0) {
		len += add_prop(prop, HAL_CONFIG_PNP_ID, buf + len);
		cmd->num++;
	}

	if (get_config("fwrev", prop, "ro.build.version.release") > 0) {
		len += add_prop(prop, HAL_CONFIG_FW_REV, buf + len);
		cmd->num++;
	}

	if (get_config("hwrev", prop, "ro.board.platform") > 0) {
		len += add_prop(prop, HAL_CONFIG_HW_REV, buf + len);
		cmd->num++;
	}

	return hal_ipc_cmd(HAL_SERVICE_ID_CORE, HAL_OP_CONFIGURATION, len, cmd,
							NULL, NULL, NULL);
}

static int init(bt_callbacks_t *callbacks)
{
	struct hal_cmd_register_module cmd;
	int status;

	DBG("");

	if (interface_ready())
		return BT_STATUS_DONE;

	hal_ipc_register(HAL_SERVICE_ID_BLUETOOTH, ev_handlers,
				sizeof(ev_handlers)/sizeof(ev_handlers[0]));

	if (!hal_ipc_init(BLUEZ_HAL_SK_PATH, sizeof(BLUEZ_HAL_SK_PATH)))
		return BT_STATUS_FAIL;

	bt_hal_cbacks = callbacks;

	/* Start Android Bluetooth daemon service */
	if (property_set("bluetooth.start", "daemon") < 0) {
		error("Failed to set bluetooth.start=daemon");
		hal_ipc_cleanup();
		bt_hal_cbacks = NULL;
		return BT_STATUS_FAIL;
	}

	if (!hal_ipc_accept()) {
		hal_ipc_cleanup();
		bt_hal_cbacks = NULL;
		return BT_STATUS_FAIL;
	}

	status = send_configuration();
	if (status != BT_STATUS_SUCCESS) {
		error("Failed to send configuration");
		goto fail;
	}

	cmd.service_id = HAL_SERVICE_ID_BLUETOOTH;
	cmd.mode = get_mode();
	cmd.max_clients = 1;

	status = hal_ipc_cmd(HAL_SERVICE_ID_CORE, HAL_OP_REGISTER_MODULE,
					sizeof(cmd), &cmd, NULL, NULL, NULL);
	if (status != BT_STATUS_SUCCESS) {
		error("Failed to register 'bluetooth' service");
		goto fail;
	}

	cmd.service_id = HAL_SERVICE_ID_SOCKET;
	cmd.max_clients = 1;

#if ANDROID_VERSION >= PLATFORM_VER(5, 0, 0)
	cmd.mode = HAL_MODE_SOCKET_DYNAMIC_MAP;
#else
	cmd.mode = HAL_MODE_DEFAULT;
#endif

	status = hal_ipc_cmd(HAL_SERVICE_ID_CORE, HAL_OP_REGISTER_MODULE,
					sizeof(cmd), &cmd, NULL, NULL, NULL);
	if (status != BT_STATUS_SUCCESS) {
		error("Failed to register 'socket' service");
		goto fail;
	}

	return status;

fail:
	hal_ipc_cleanup();
	bt_hal_cbacks = NULL;

	hal_ipc_unregister(HAL_SERVICE_ID_BLUETOOTH);

	return status;
}

static int enable(void)
{
	DBG("");

	if (!interface_ready())
		return BT_STATUS_NOT_READY;

	return hal_ipc_cmd(HAL_SERVICE_ID_BLUETOOTH, HAL_OP_ENABLE, 0, NULL,
							NULL, NULL, NULL);
}

static int disable(void)
{
	DBG("");

	if (!interface_ready())
		return BT_STATUS_NOT_READY;

	return hal_ipc_cmd(HAL_SERVICE_ID_BLUETOOTH, HAL_OP_DISABLE, 0, NULL,
							NULL, NULL, NULL);
}

static void cleanup(void)
{
	DBG("");

	if (!interface_ready())
		return;

	hal_ipc_cleanup();

	hal_ipc_unregister(HAL_SERVICE_ID_BLUETOOTH);

	bt_hal_cbacks = NULL;
}

static int get_adapter_properties(void)
{
	DBG("");

	if (!interface_ready())
		return BT_STATUS_NOT_READY;

	return hal_ipc_cmd(HAL_SERVICE_ID_BLUETOOTH, HAL_OP_GET_ADAPTER_PROPS,
						0, NULL, NULL, NULL, NULL);
}

static int get_adapter_property(bt_property_type_t type)
{
	struct hal_cmd_get_adapter_prop cmd;

	DBG("prop: %s (%d)", bt_property_type_t2str(type), type);

	if (!interface_ready())
		return BT_STATUS_NOT_READY;

	/* type match IPC type */
	cmd.type = type;

	return hal_ipc_cmd(HAL_SERVICE_ID_BLUETOOTH, HAL_OP_GET_ADAPTER_PROP,
					sizeof(cmd), &cmd, NULL, NULL, NULL);
}

static int set_adapter_property(const bt_property_t *property)
{
	char buf[IPC_MTU];
	struct hal_cmd_set_adapter_prop *cmd = (void *) buf;
	size_t len;

	DBG("prop: %s", btproperty2str(property));

	if (!interface_ready())
		return BT_STATUS_NOT_READY;

	adapter_prop_from_hal(property, &cmd->type, &cmd->len, cmd->val);

	len = sizeof(*cmd) + cmd->len;

	return hal_ipc_cmd(HAL_SERVICE_ID_BLUETOOTH, HAL_OP_SET_ADAPTER_PROP,
						len, cmd, NULL, NULL, NULL);
}

static int get_remote_device_properties(bt_bdaddr_t *remote_addr)
{
	struct hal_cmd_get_remote_device_props cmd;

	DBG("bdaddr: %s", bdaddr2str(remote_addr));

	if (!interface_ready())
		return BT_STATUS_NOT_READY;

	memcpy(cmd.bdaddr, remote_addr, sizeof(cmd.bdaddr));

	return hal_ipc_cmd(HAL_SERVICE_ID_BLUETOOTH,
					HAL_OP_GET_REMOTE_DEVICE_PROPS,
					sizeof(cmd), &cmd, NULL, NULL, NULL);
}

static int get_remote_device_property(bt_bdaddr_t *remote_addr,
						bt_property_type_t type)
{
	struct hal_cmd_get_remote_device_prop cmd;

	DBG("bdaddr: %s prop: %s", bdaddr2str(remote_addr),
						bt_property_type_t2str(type));

	if (!interface_ready())
		return BT_STATUS_NOT_READY;

	memcpy(cmd.bdaddr, remote_addr, sizeof(cmd.bdaddr));

	/* type match IPC type */
	cmd.type = type;

	return hal_ipc_cmd(HAL_SERVICE_ID_BLUETOOTH,
					HAL_OP_GET_REMOTE_DEVICE_PROP,
					sizeof(cmd), &cmd, NULL, NULL, NULL);
}

static int set_remote_device_property(bt_bdaddr_t *remote_addr,
						const bt_property_t *property)
{
	char buf[IPC_MTU];
	struct hal_cmd_set_remote_device_prop *cmd = (void *) buf;
	size_t len;

	DBG("bdaddr: %s prop: %s", bdaddr2str(remote_addr),
				bt_property_type_t2str(property->type));

	if (!interface_ready())
		return BT_STATUS_NOT_READY;

	memcpy(cmd->bdaddr, remote_addr, sizeof(cmd->bdaddr));

	/* type match IPC type */
	cmd->type = property->type;
	cmd->len = property->len;
	memcpy(cmd->val, property->val, property->len);

	len = sizeof(*cmd) + cmd->len;

	return hal_ipc_cmd(HAL_SERVICE_ID_BLUETOOTH,
					HAL_OP_SET_REMOTE_DEVICE_PROP,
					len, cmd, NULL, NULL, NULL);
}

static int get_remote_service_record(bt_bdaddr_t *remote_addr, bt_uuid_t *uuid)
{
	struct hal_cmd_get_remote_service_rec cmd;

	DBG("bdaddr: %s", bdaddr2str(remote_addr));

	if (!interface_ready())
		return BT_STATUS_NOT_READY;

	memcpy(cmd.bdaddr, remote_addr, sizeof(cmd.bdaddr));
	memcpy(cmd.uuid, uuid, sizeof(cmd.uuid));

	return hal_ipc_cmd(HAL_SERVICE_ID_BLUETOOTH,
					HAL_OP_GET_REMOTE_SERVICE_REC,
					sizeof(cmd), &cmd, NULL, NULL, NULL);
}

static int get_remote_services(bt_bdaddr_t *remote_addr)
{
	struct hal_cmd_get_remote_services cmd;

	DBG("bdaddr: %s", bdaddr2str(remote_addr));

	if (!interface_ready())
		return BT_STATUS_NOT_READY;

	memcpy(cmd.bdaddr, remote_addr, sizeof(cmd.bdaddr));

	return hal_ipc_cmd(HAL_SERVICE_ID_BLUETOOTH, HAL_OP_GET_REMOTE_SERVICES,
					sizeof(cmd), &cmd, NULL, NULL, NULL);
}

static int start_discovery(void)
{
	DBG("");

	if (!interface_ready())
		return BT_STATUS_NOT_READY;

	return hal_ipc_cmd(HAL_SERVICE_ID_BLUETOOTH, HAL_OP_START_DISCOVERY, 0,
						NULL, NULL, NULL, NULL);
}

static int cancel_discovery(void)
{
	DBG("");

	if (!interface_ready())
		return BT_STATUS_NOT_READY;

	return hal_ipc_cmd(HAL_SERVICE_ID_BLUETOOTH, HAL_OP_CANCEL_DISCOVERY, 0,
						NULL, NULL, NULL, NULL);
}

static int create_bond_real(const bt_bdaddr_t *bd_addr, int transport)
{
	struct hal_cmd_create_bond cmd;

	DBG("bdaddr: %s", bdaddr2str(bd_addr));

	if (!interface_ready())
		return BT_STATUS_NOT_READY;

	cmd.transport = transport;

	memcpy(cmd.bdaddr, bd_addr, sizeof(cmd.bdaddr));

	return hal_ipc_cmd(HAL_SERVICE_ID_BLUETOOTH, HAL_OP_CREATE_BOND,
					sizeof(cmd), &cmd, NULL, NULL, NULL);
}

#if ANDROID_VERSION >= PLATFORM_VER(5, 0, 0)
static int create_bond(const bt_bdaddr_t *bd_addr, int transport)
{
	return create_bond_real(bd_addr, transport);
}
#else
static int create_bond(const bt_bdaddr_t *bd_addr)
{
	return create_bond_real(bd_addr, BT_TRANSPORT_UNKNOWN);
}
#endif

static int cancel_bond(const bt_bdaddr_t *bd_addr)
{
	struct hal_cmd_cancel_bond cmd;

	DBG("bdaddr: %s", bdaddr2str(bd_addr));

	if (!interface_ready())
		return BT_STATUS_NOT_READY;

	memcpy(cmd.bdaddr, bd_addr, sizeof(cmd.bdaddr));

	return hal_ipc_cmd(HAL_SERVICE_ID_BLUETOOTH, HAL_OP_CANCEL_BOND,
					sizeof(cmd), &cmd, NULL, NULL, NULL);
}

static int remove_bond(const bt_bdaddr_t *bd_addr)
{
	struct hal_cmd_remove_bond cmd;

	DBG("bdaddr: %s", bdaddr2str(bd_addr));

	if (!interface_ready())
		return BT_STATUS_NOT_READY;

	memcpy(cmd.bdaddr, bd_addr, sizeof(cmd.bdaddr));

	return hal_ipc_cmd(HAL_SERVICE_ID_BLUETOOTH, HAL_OP_REMOVE_BOND,
					sizeof(cmd), &cmd, NULL, NULL, NULL);
}

static int pin_reply(const bt_bdaddr_t *bd_addr, uint8_t accept,
				uint8_t pin_len, bt_pin_code_t *pin_code)
{
	struct hal_cmd_pin_reply cmd;

	DBG("bdaddr: %s", bdaddr2str(bd_addr));

	if (!interface_ready())
		return BT_STATUS_NOT_READY;

	memcpy(cmd.bdaddr, bd_addr, sizeof(cmd.bdaddr));
	cmd.accept = accept;
	cmd.pin_len = pin_len;
	memcpy(cmd.pin_code, pin_code, sizeof(cmd.pin_code));

	return hal_ipc_cmd(HAL_SERVICE_ID_BLUETOOTH, HAL_OP_PIN_REPLY,
					sizeof(cmd), &cmd, NULL, NULL, NULL);
}

static int ssp_reply(const bt_bdaddr_t *bd_addr, bt_ssp_variant_t variant,
					uint8_t accept, uint32_t passkey)
{
	struct hal_cmd_ssp_reply cmd;

	DBG("bdaddr: %s", bdaddr2str(bd_addr));

	if (!interface_ready())
		return BT_STATUS_NOT_READY;

	memcpy(cmd.bdaddr, bd_addr, sizeof(cmd.bdaddr));
	/* type match IPC type */
	cmd.ssp_variant = variant;
	cmd.accept = accept;
	cmd.passkey = passkey;

	return hal_ipc_cmd(HAL_SERVICE_ID_BLUETOOTH, HAL_OP_SSP_REPLY,
					sizeof(cmd), &cmd, NULL, NULL, NULL);
}

static const void *get_profile_interface(const char *profile_id)
{
	DBG("%s", profile_id);

	if (!interface_ready())
		return NULL;

	if (!strcmp(profile_id, BT_PROFILE_SOCKETS_ID))
		return bt_get_socket_interface();

	if (!strcmp(profile_id, BT_PROFILE_HIDHOST_ID))
		return bt_get_hidhost_interface();

	if (!strcmp(profile_id, BT_PROFILE_PAN_ID))
		return bt_get_pan_interface();

	if (!strcmp(profile_id, BT_PROFILE_ADVANCED_AUDIO_ID))
		return bt_get_a2dp_interface();

	if (!strcmp(profile_id, BT_PROFILE_AV_RC_ID))
		return bt_get_avrcp_interface();

	if (!strcmp(profile_id, BT_PROFILE_HANDSFREE_ID))
		return bt_get_handsfree_interface();

	if (!strcmp(profile_id, BT_PROFILE_GATT_ID))
		return bt_get_gatt_interface();

	if (!strcmp(profile_id, BT_PROFILE_HEALTH_ID))
		return bt_get_health_interface();

#if ANDROID_VERSION >= PLATFORM_VER(5, 0, 0)
	if (!strcmp(profile_id, BT_PROFILE_AV_RC_CTRL_ID))
		return bt_get_avrcp_ctrl_interface();

	if (!strcmp(profile_id, BT_PROFILE_HANDSFREE_CLIENT_ID))
		return bt_get_hf_client_interface();

	if (!strcmp(profile_id, BT_PROFILE_MAP_CLIENT_ID))
		return bt_get_map_client_interface();

	if (!strcmp(profile_id, BT_PROFILE_ADVANCED_AUDIO_SINK_ID))
		return bt_get_a2dp_sink_interface();
#endif

	return NULL;
}

static int dut_mode_configure(uint8_t enable)
{
	struct hal_cmd_dut_mode_conf cmd;

	DBG("enable %u", enable);

	if (!interface_ready())
		return BT_STATUS_NOT_READY;

	cmd.enable = enable;

	return hal_ipc_cmd(HAL_SERVICE_ID_BLUETOOTH, HAL_OP_DUT_MODE_CONF,
					sizeof(cmd), &cmd, NULL, NULL, NULL);
}

static int dut_mode_send(uint16_t opcode, uint8_t *buf, uint8_t buf_len)
{
	char cmd_buf[IPC_MTU];
	struct hal_cmd_dut_mode_send *cmd = (void *) cmd_buf;
	size_t len;

	DBG("opcode %u len %u", opcode, buf_len);

	if (!interface_ready())
		return BT_STATUS_NOT_READY;

	cmd->opcode = opcode;
	cmd->len = buf_len;
	memcpy(cmd->data, buf, cmd->len);

	len = sizeof(*cmd) + cmd->len;

	return hal_ipc_cmd(HAL_SERVICE_ID_BLUETOOTH, HAL_OP_DUT_MODE_SEND,
						len, cmd, NULL, NULL, NULL);
}

static int le_test_mode(uint16_t opcode, uint8_t *buf, uint8_t buf_len)
{
	char cmd_buf[IPC_MTU];
	struct hal_cmd_le_test_mode *cmd = (void *) cmd_buf;
	size_t len;

	DBG("opcode %u len %u", opcode, buf_len);

	if (!interface_ready())
		return BT_STATUS_NOT_READY;

	cmd->opcode = opcode;
	cmd->len = buf_len;
	memcpy(cmd->data, buf, cmd->len);

	len = sizeof(*cmd) + cmd->len;

	return hal_ipc_cmd(HAL_SERVICE_ID_BLUETOOTH, HAL_OP_LE_TEST_MODE,
						len, cmd, NULL, NULL, NULL);
}

static int config_hci_snoop_log(uint8_t enable)
{
	const char *property;

	DBG("enable %u", enable);

	property = enable ? "bluetooth.start" : "bluetooth.stop";

	if (property_set(property, "snoop") < 0) {
		error("Failed to set %s=snoop", property);
		return BT_STATUS_FAIL;
	}

	return BT_STATUS_SUCCESS;
}

#if ANDROID_VERSION >= PLATFORM_VER(5, 0, 0)
static int get_connection_state(const bt_bdaddr_t *bd_addr)
{
	struct hal_cmd_get_connection_state cmd;
	struct hal_rsp_get_connection_state rsp;
	size_t rsp_len = sizeof(rsp);
	bt_status_t status;

	DBG("bdaddr: %s", bdaddr2str(bd_addr));

	if (!interface_ready())
		return 0;

	memcpy(cmd.bdaddr, bd_addr, sizeof(cmd.bdaddr));

	status = hal_ipc_cmd(HAL_SERVICE_ID_BLUETOOTH,
			HAL_OP_GET_CONNECTION_STATE, sizeof(cmd), &cmd,
			&rsp_len, &rsp, NULL);

	if (status != BT_STATUS_SUCCESS)
		return 0;

	return rsp.connection_state;
}

static int set_os_callouts(bt_os_callouts_t *callouts)
{
	DBG("callouts: %p", callouts);

	/* TODO: implement */

	return BT_STATUS_SUCCESS;
}

static int read_energy_info(void)
{
	DBG("");

	if (!interface_ready())
		return BT_STATUS_NOT_READY;

	return hal_ipc_cmd(HAL_SERVICE_ID_BLUETOOTH, HAL_OP_READ_ENERGY_INFO, 0,
							NULL, NULL, NULL, NULL);
}
#endif

static const bt_interface_t bluetooth_if = {
	.size = sizeof(bt_interface_t),
	.init = init,
	.enable = enable,
	.disable = disable,
	.cleanup = cleanup,
	.get_adapter_properties = get_adapter_properties,
	.get_adapter_property = get_adapter_property,
	.set_adapter_property = set_adapter_property,
	.get_remote_device_properties = get_remote_device_properties,
	.get_remote_device_property = get_remote_device_property,
	.set_remote_device_property = set_remote_device_property,
	.get_remote_service_record = get_remote_service_record,
	.get_remote_services = get_remote_services,
	.start_discovery = start_discovery,
	.cancel_discovery = cancel_discovery,
	.create_bond = create_bond,
	.remove_bond = remove_bond,
	.cancel_bond = cancel_bond,
	.pin_reply = pin_reply,
	.ssp_reply = ssp_reply,
	.get_profile_interface = get_profile_interface,
	.dut_mode_configure = dut_mode_configure,
	.dut_mode_send = dut_mode_send,
	.le_test_mode = le_test_mode,
	.config_hci_snoop_log = config_hci_snoop_log,
#if ANDROID_VERSION >= PLATFORM_VER(5, 0, 0)
	.get_connection_state = get_connection_state,
	.set_os_callouts = set_os_callouts,
	.read_energy_info = read_energy_info,
#endif
};

static const bt_interface_t *get_bluetooth_interface(void)
{
	DBG("");

	return &bluetooth_if;
}

static int close_bluetooth(struct hw_device_t *device)
{
	DBG("");

	cleanup();

	free(device);

	return 0;
}

static int open_bluetooth(const struct hw_module_t *module, char const *name,
					struct hw_device_t **device)
{
	bluetooth_device_t *dev = malloc(sizeof(bluetooth_device_t));

	DBG("");

	if (!dev) {
		error("Failed to allocate memory for device");
		return -ENOMEM;
	}

	memset(dev, 0, sizeof(bluetooth_device_t));
	dev->common.tag = HARDWARE_DEVICE_TAG;
	dev->common.version = 0;
	dev->common.module = (struct hw_module_t *) module;
	dev->common.close = close_bluetooth;
	dev->get_bluetooth_interface = get_bluetooth_interface;

	*device = (struct hw_device_t *) dev;

	return 0;
}

static struct hw_module_methods_t bluetooth_module_methods = {
	.open = open_bluetooth,
};

struct hw_module_t HAL_MODULE_INFO_SYM = {
	.tag = HARDWARE_MODULE_TAG,
	.version_major = 1,
	.version_minor = 0,
	.id = BT_HARDWARE_MODULE_ID,
	.name = "BlueZ Bluetooth stack",
	.author = "Intel Corporation",
	.methods = &bluetooth_module_methods
};


text:
Template.clearing.onRendered(function () {
    $(document).foundation('clearing', 'reflow');
});

Template.clearing.onDestroyed(function () {
    $(document).foundation('clearing', 'off');
});


text:
- (void) testAsyncFaulting
{
// library1 <<persistent root>>
//  |
//  \--photo1 // cross-persistent-root link, default branch
//
// photo1 <<persistent root>>
//  |
//  \--child1 (pretend there are a lot of child objects)

// 1. Set it up in memory

COPersistentRoot *photo1 = [ctx insertNewPersistentRootWithEntityName: @"Anonymous.OutlineItem"];
COObject *child1 = [photo1 insertObjectWithEntityName: @"Anonymous.OutlineItem"];

[[
photo1 rootObject
]
setValue:
@"photo1"
forProperty:
@"label"];
[[
photo1 rootObject
]
insertObject: child1
atIndex: ETUndeterminedIndex
hint: nil
forProperty:
@"contents"];

COPersistentRoot *persistentRoot = [ctx insertNewPersistentRootWithEntityName: @"Anonymous.OutlineItem"];
[[
persistentRoot rootObject
]
insertObject:
[
photo1 rootObject
]
atIndex: ETUndeterminedIndex
hint: nil
forProperty:
@"contents"];

[
ctx commit
];

// 2. Read it into another context

{
COEditingContext *ctx2 = [[COEditingContext alloc] initWithStore: store];
COPersistentRoot *persistentRoot2 = [ctx2 persistentRootForUUID: [persistentRoot persistentRootUUID]];
COPersistentRoot *photo1ctx2 = [[[[persistentRoot2 rootObject] valueForKey: @"contents"] objectAtIndex: 0] persistentRoot];

// This should be a fault
COObject *photo1ctx2RootObject = [photo1ctx2 rootObject];

// The relationship has not loaded yet.
UKObjectsEqual([
NSArray array
], [
photo1ctx2RootObject valueForKey:
@"contents"]);

// Now, suppose that triggers loading.
// Should we automatically notify a delegate?

// FIXME: Check for the loaded contents
}
}


text:
package org.apache.wink.server.internal.providers.entity.html;

import java.text.SimpleDateFormat;
import java.util.List;

import org.apache.wink.common.model.synd.SyndCategory;
import org.apache.wink.common.model.synd.SyndEntry;
import org.apache.wink.common.model.synd.SyndFeed;
import org.apache.wink.common.model.synd.SyndLink;
import org.apache.wink.common.model.synd.SyndPerson;
import org.apache.wink.common.model.synd.SyndText;

/**
 * This adapter is used for default Html Representation of Collection (used in
 * defaultHtmlCollection.jsp). This adapter saves the resource and provides
 * methods to get the metadata in a convenient way.
 */
public class HtmlSyndFeedAdapter {

    private final SyndFeed         syndFeed;

    private final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy"); //$NON-NLS-1$

    /**
     * This constructor sets the resource.
     *
     * @param resource the represented resource
     */
    public HtmlSyndFeedAdapter(SyndFeed syndFeed) {
        this.syndFeed = syndFeed;
    }

    /**
     * Get the ID of the Collection
     *
     * @return the ID of the resource
     */
    public String getId() {
        String id = syndFeed.getId();
        if (id != null) {
            return id;
        }
        return ""; //$NON-NLS-1$
    }

    /**
     * Get the updated field
     *
     * @return the updated value of the resource
     */
    public String getUpdated() {
        if (syndFeed.getUpdated() != null) {
            return simpleDateFormat.format(syndFeed.getUpdated());
        }
        return ""; //$NON-NLS-1$
    }

    /**
     * Get the title field
     *
     * @return the title of the resource
     */
    public String getTitle() {
        SyndText textBean = syndFeed.getTitle();
        if (textBean != null) {
            return textBean.getValue();
        }
        return ""; //$NON-NLS-1$
    }

    /**
     * Get links
     *
     * @return the links of the resource
     */
    public List<SyndLink> getLinks() {
        return syndFeed.getLinks();
    }

    /**
     * Get categories
     *
     * @return the categories of the resource
     */
    public List<SyndCategory> getCategories() {
        return syndFeed.getCategories();
    }

    /**
     * Get author field
     *
     * @return the author of the resource
     */
    public String getAuthor() {
        List<SyndPerson> authors = syndFeed.getAuthors();
        if (!authors.isEmpty()) {
            String name = authors.get(0).getName();
            if (name != null) {
                return name;
            }
        }
        return ""; //$NON-NLS-1$
    }

    /**
     * Get subtitle field
     *
     * @return the sub title of the resource
     */
    public String getSubTitle() {
        SyndText textBean = syndFeed.getSubtitle();
        if (textBean != null) {
            return textBean.getValue();
        }
        return ""; //$NON-NLS-1$
    }

    /**
     * Get the Entry metadata
     *
     * @param i
     * @return the Entry metadata
     */
    public SyndEntry getSyndEntry(int i) {
        List<SyndEntry> entries = syndFeed.getEntries();
        if (i >= 0 && i < entries.size()) {
            return entries.get(i);
        }
        return null;
    }

    /**
     * Get the number of entries
     *
     * @return number of resource's entries
     */
    public int getNumOfEntries() {
        return syndFeed.getEntries().size();
    }

}


text:
#ifndef _DB_HEAP_H_
#define	_DB_HEAP_H_

#if defined(__cplusplus)
extern "C" {
#endif

/* Forward structure declarations. */
struct __heap;		typedef struct __heap HEAP;
struct __heap_cursor;	typedef struct __heap_cursor HEAP_CURSOR;

/*
 * The in-memory, per-heap data structure.
 */
struct __heap {		/* Heap access method. */

	u_int32_t gbytes;	/* Initial heap size. */
	u_int32_t bytes;	/* Initial heap size. */
	u_int32_t region_size;	/* Size of each region. */

	db_pgno_t curregion;	/* The region of the next insert. */
	db_pgno_t maxpgno;	/* Maximum page number of a fixed size heap. */
	u_int32_t curpgindx;	/* The last used offset in the
				 * region's space bitmap. */
};

struct __heap_cursor {
	/* struct __dbc_internal */
	__DBC_INTERNAL

	/* Heap private part */

	u_int32_t	flags;
};

#define	HEAP_PG_FULL	3	/* No space on page. */
#define	HEAP_PG_GT66	2	/* Page greater than 66% full */
#define	HEAP_PG_GT33	1	/* Page greater than 33% full */
#define	HEAP_PG_LT33	0	/* Page less than 33% full */

#define	HEAP_PG_FULL_PCT	5	/* Less than 5% of page is free. */
#define	HEAP_PG_GT66_PCT	33	/* Less than 33% of page is free. */
#define	HEAP_PG_GT33_PCT	66	/* Less than 66% of page is free. */

#if defined(__cplusplus)
}
#endif

#include "dbinc_auto/heap_auto.h"
#include "dbinc_auto/heap_ext.h"
#include "dbinc/db_am.h"
#endif


text:
#ifndef DOCUMENT_TEST_H_
#define DOCUMENT_TEST_H_

#include <EPI/Document/DocumentBase.moc.h>

#include <Universe/NodeTerrain.h>
namespace EPI
{

class LM_API_EPI DocumentTest : public DocumentBase
{
public:
    DocumentTest(GuiDocument& guiGoc, const Ptr<DocumentRenderer>& pDocRdr);
    virtual ~DocumentTest();

    virtual Ptr<Property> getDefaultProperty() const;

    Core::Ptr<Universe::NodeTerrain> _pNodeTerrain;
};

}  // namespace EPI

#endif /*DOCUMENT_TEST_H_*/


text:
typedef void* mmm_hook;

typedef struct mmm_api {
  // Don't touch this
  void* _mmm_bookkeeping_;
  // Insert an instruction at `orig_address` that JMPs to the given
  // `hook_address`.
  mmm_hook (*hook_jmp)(size_t orig_address, size_t hook_address);
  // Insert an instruction at `orig_address` that CALLs the given
  // `hook_address`.
  mmm_hook (*hook_call)(size_t orig_address, size_t hook_address);
  // Replace the vtable entry at `orig_address` by a pointer to `hook_address`.
  mmm_hook (*hook_vtbl)(size_t orig_address, size_t hook_address);
  // Overwrite some bytes starting at `orig_address`.
  mmm_hook (*patch_bytes)(size_t orig_address, const void* buffer,
                          size_t buf_size);
  // Remove a previously installed hook.
  void (*revert_hook)(mmm_hook hook);
  // Check if the mod named `mod_name` is loaded; case sensitive.
  char (*is_mod_loaded)(const char* mod_name);
} mmm_api;

typedef struct mmm_meta {
  const char* version;
  const char* game_base_dir;
  const char* mod_base_dir;
  const char* mod_short_name;
} mmm_meta;

typedef struct mmm_mod_info {
  HINSTANCE instance;
  mmm_meta* meta;
  const char* name;
  const char* version;
  mmm_api* api;
} mmm_mod_info;


text:
<?php

namespace Magento\Framework\Filesystem;

class DriverPoolTest extends \PHPUnit_Framework_TestCase
{
    public function testGetDriver()
    {
        $object = new DriverPool();
        foreach ([DriverPool::FILE, DriverPool::HTTP, DriverPool::HTTPS, DriverPool::ZLIB] as $code) {
            $this->assertInstanceOf('\Magento\Framework\Filesystem\DriverInterface', $object->getDriver($code));
        }
        $default = $object->getDriver('');
        $this->assertInstanceOf('\Magento\Framework\Filesystem\Driver\File', $default);
        $this->assertSame($default, $object->getDriver(''));
    }

    public function testCustomDriver()
    {
        $customOne = $this->getMockForAbstractClass('\Magento\Framework\Filesystem\DriverInterface');
        $customTwo = get_class($this->getMockForAbstractClass('\Magento\Framework\Filesystem\DriverInterface'));
        $object = new DriverPool(['customOne' => $customOne, 'customTwo' => $customTwo]);
        $this->assertSame($customOne, $object->getDriver('customOne'));
        $this->assertInstanceOf('\Magento\Framework\Filesystem\DriverInterface', $object->getDriver('customOne'));
        $this->assertEquals($customTwo, get_class($object->getDriver('customTwo')));
        $this->assertInstanceOf('\Magento\Framework\Filesystem\DriverInterface', $object->getDriver('customTwo'));
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage The specified type 'stdClass' does not implement DriverInterface.
     */
    public function testCustomDriverException()
    {
        new DriverPool(['custom' => new \StdClass()]);
    }
}


text:
package org.scaladebugger.api.profiles.traits.info

/**
 * Represents the interface for type-checking based interactions.
 */
trait TypeChecker {
  /**
   * Compares type names to see if they are equivalent.
   *
   * @param typeName1 The first type name as a string
   * @param typeName2 The second type name as a string
   * @return True if the types are equivalent, otherwise false
   */
  def equalTypeNames(typeName1: String, typeName2: String): Boolean
}


text:
all: mlockall

mlockall:
	./rebar compile

clean:
	./rebar clean
	rm -rf priv ebin


text:
import angular from 'angular';
import uiRouter from 'angular-ui-router';
import SERVICES_DATASET_MODULE from '../dataset/dataset-module';
import SERVICES_STATE_MODULE from '../state/state-module';
import SERVICES_MESSAGE_MODULE from '../message/message-module';

import UploadWorkflowService from './upload-workflow-service';
import UpdateWorkflowService from './update-workflow-service';

const MODULE_NAME = 'data-prep.services.datasetWorkflowService';

/**
 * @ngdoc object
 * @name data-prep.services.dataset-workflow
 * @description This module contains the services to manage the upload & update of datasets
 * @requires ui.router
 * @requires data-prep.services.dataset
 * @requires data-prep.services.state
 * @requires data-prep.services.utils
 */
angular.module(MODULE_NAME,
	[
		uiRouter,
		SERVICES_DATASET_MODULE,
		SERVICES_STATE_MODULE,
		SERVICES_MESSAGE_MODULE,
	])
	.service('UploadWorkflowService', UploadWorkflowService)
	.service('UpdateWorkflowService', UpdateWorkflowService);

export default MODULE_NAME;


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 datatable;

import dialog.*;

/**
 *
 * @author salim
 */
public class Tank {

    private String id;

    private int year;

 private String capacity;

    public Tank(String id, int year, String capacity) {
        this.id = id;
        this.year = year;
        this.capacity = capacity;
    }

    public String getCapacity() {
        return capacity;
    }

    public void setCapacity(String capacity) {
        this.capacity = capacity;
    }
    /**
     * Get the value of id
     *
     * @return the value of id
     */
    public String getId() {
        return id;
    }

    /**
     * Set the value of id
     *
     * @param id new value of id
     */
    public void setId(String id) {
        this.id = id;
    }

    /**
     * Get the value of year
     *
     * @return the value of year
     */
    public int getYear() {
        return year;
    }

    /**
     * Set the value of year
     *
     * @param year new value of year
     */
    public void setYear(int year) {
        this.year = year;
    }

}


text:
FROM clinicalgenomics/mip_base:2.1

################## METADATA ######################

LABEL base_image="clinicalgenomics/mip_base:2.1"
LABEL version="2"
LABEL software="delly"
LABEL software.version="0.8.7"
LABEL extra.binaries="delly"
LABEL maintainer="Clinical-Genomics/MIP"

RUN conda install delly=0.8.7=he03298f_1 && \
    conda clean -ya

WORKDIR /data/


text:
import {
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  EventEmitter,
  Input,
  isDevMode,
  OnDestroy,
  OnInit,
  Output,
  ViewEncapsulation,
} from '@angular/core';
import { MatRadioChange } from '@angular/material/radio';
import { DomSanitizer } from '@angular/platform-browser';
import { isFunction } from '@terminus/ngx-tools/type-guards';
import {
  hasRequiredControl,
  untilComponentDestroyed,
} from '@terminus/ngx-tools/utilities';
import {
  ControlValueAccessorProviderFactory,
  TsReactiveFormBaseComponent,
  TsStyleThemeTypes,
} from '@terminus/ui/utilities';

/**
 * Define the allowed keys for an item passed to the {@link TsRadioComponent}
 */
export interface TsRadioOption {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  [key: string]: any;
  /**
   * Define if the item is disabled
   */
  disabled?: boolean;
  /**
   * Define the template for the content (used if type is visual)
   */
  template?: string;
}

/**
 * The change event as TsRadioChange. Used by {@link TsRadioGroupComponent}
 */
export class TsRadioChange {
  constructor(
    // The group that emit the change event
    public source: TsRadioGroupComponent,
    // The value of the TsRadioButton
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    public value: any,
  ) {}
}

/**
 * Expose the formatter function type used by {@link TsRadioGroupComponent}
 */
export type TsRadioFormatFn = (v: TsRadioOption) => string;

/**
 * Unique ID for each instance
 */
let nextUniqueId = 0;

/**
 * The radio UI Component
 *
 * @example
 * <ts-radio-group
 *              [ariaDescribedby]="Aria Describedby"
 *              [ariaLabel]="Aria Label"
 *              [ariaLabelledby]="Aria Labelledby"
 *              [centeredContent]="false"
 *              [formatUILabelFn]="myUIFormatter"
 *              [formatUISubLabelFn]="myUISubFormatter"
 *              [formatModelValueFn]="myModelFormatter"
 *              [formControl]="myForm.get('myRadioGroup')"
 *              [id]="uid"
 *              [isDisabled]="true"
 *              [isVisual]="false"
 *              [name]="myName"
 *              [options]="myItemsArray | $async"
 *              [small]=false
 *              [theme]="primary"
 *              (selectionChange)="doSomething($event)"
 * ></ts-radio-group>
 *
 * <example-url>https://getterminus.github.io/ui-demos-release/components/radio-group</example-url>
 */
@Component({
  selector: 'ts-radio-group',
  templateUrl: './radio-group.component.html',
  styleUrls: ['./radio-group.component.scss'],
  host: { class: 'ts-radio-group' },
  providers: [ControlValueAccessorProviderFactory<TsRadioGroupComponent>(TsRadioGroupComponent)],
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None,
  exportAs: 'tsRadioGroup',
})
export class TsRadioGroupComponent extends TsReactiveFormBaseComponent implements OnInit, OnDestroy {
  /**
   * Define the default component ID
   */
  protected _uid = `ts-radio-group-${nextUniqueId++}`;

  /**
   * Define the ripple color.
   * TODO: abstract out to a service or utility function or set as a global default for ripples
   */
  public rippleColor = 'rgba(0, 83, 138, .1)';

  /**
   * Getter to determine if the group is required
   */
  public get isRequired(): boolean {
    return hasRequiredControl(this.formControl);
  }

  // NOTE: Since we are matching standard HTML attributes, we will rename for internal use.
  // eslint:disable: @angular-eslint/no-input-rename
  /**
   * Used to set the 'aria-label' attribute on the underlying input element.
   */
  @Input('aria-label')
  public ariaLabel: string | undefined;

  /**
   * The 'aria-labelledby' attribute takes precedence as the element's text alternative.
   */
  @Input('aria-labelledby')
  public ariaLabelledby: string | undefined;

  /**
   * The 'aria-describedby' attribute is read after the element's label and field type.
   */
  @Input('aria-describedby')
  public ariaDescribedby: string | undefined;
  // eslint:enable: @angular-eslint/no-input-rename

  /**
   * Define if the radio contents should be centered (used with the visual radio group layout)
   */
  @Input()
  public centeredContent = true;

  /**
   * Define a function to retrieve the UI value for an option
   *
   * @param value
   */
  @Input()
  public set formatUILabelFn(value: TsRadioFormatFn) {
    if (!value) {
      return;
    }

    if (isFunction(value)) {
      this._formatUILabelFn = value;
    } else if (isDevMode()) {
      throw Error(`TsRadioGroupComponent: 'formatUILabelFn' must be passed a 'TsRadioFormatFn'.`);
    }
  }
  public get formatUILabelFn(): TsRadioFormatFn {
    return this._formatUILabelFn;
  }
  private _formatUILabelFn!: TsRadioFormatFn;

  /**
   * Define a function to retrieve the UI value for an option
   *
   * @param value
   */
  @Input()
  public set formatUISubLabelFn(value: TsRadioFormatFn) {
    if (!value) {
      return;
    }

    if (isFunction(value)) {
      this._formatUISubLabelFn = value;
    } else if (isDevMode()) {
      throw Error(`TsRadioGroupComponent: 'formatUISubLabelFn' must be passed a 'TsRadioFormatFn'.`);
    }
  }
  public get formatUISubLabelFn(): TsRadioFormatFn {
    return this._formatUISubLabelFn;
  }
  private _formatUISubLabelFn!: TsRadioFormatFn;

  /**
   * Define a function to retrieve the UI value for an option
   *
   * @param value
   */
  @Input()
  public set formatModelValueFn(value: TsRadioFormatFn) {
    if (!value) {
      return;
    }

    if (isFunction(value)) {
      this._formatModelValueFn = value;
    } else if (isDevMode()) {
      throw Error(`TsRadioGroupComponent: 'formatModelValueFn' must be passed a 'TsRadioFormatFn'.`);
    }
  }
  public get formatModelValueFn(): TsRadioFormatFn {
    return this._formatModelValueFn;
  }
  private _formatModelValueFn!: TsRadioFormatFn;

  /**
   * Define an ID for the component
   *
   * @param value
   */
  @Input()
  public set id(value: string) {
    this._id = value || this._uid;
  }
  public get id(): string {
    return this._id;
  }
  protected _id: string = this._uid;

  /**
   * Define if the radio group is disabled
   */
  @Input()
  public isDisabled = false;

  /**
   * Define if the radio group is visual (boxes) or standard (text)
   */
  @Input()
  public isVisual = false;

  /**
   * Define a label for the radio group
   */
  @Input()
  public label!: string;

  /**
   * The HTML name attribute applied to radio buttons in this group.
   *
   * @param value
   */
  @Input()
  public set name(value: string) {
    this._name = value ? value : this._uid;
  }
  public get name(): string {
    return this._name;
  }
  private _name: string = this._uid;

  /**
   * Define whether a validation or a hint needed.
   */
  @Input()
  public noValidationOrHint = false;

  /**
   * Accept an array of radio options in the {@link TsRadioOption} format
   *
   * @param value
   */
  @Input()
  public set options(value: TsRadioOption[]) {
    if (!value) {
      return;
    }

    this._options = value;
  }
  public get options(): TsRadioOption[] {
    return this._options;
  }
  private _options!: TsRadioOption[];

  /**
   * Define if the visual style should be large or small
   */
  @Input()
  public small = false;

  /**
   * Define the theme. {@link TsStyleThemeTypes}
   */
  @Input()
  public theme: TsStyleThemeTypes = 'primary';

  /**
   * Emit event when a selection occurs. {@link TsRadioChange}
   */
  @Output()
  public readonly selectionChange: EventEmitter<TsRadioChange> = new EventEmitter();

  constructor(
    private changeDetectorRef: ChangeDetectorRef,
    public domSanitizer: DomSanitizer,
  ) {
    super();
  }

  /**
   * Update the change detector if the control value changes
   */
  public ngOnInit(): void {
    // istanbul ignore else
    if (this.formControl) {
      this.formControl.valueChanges
        .pipe(
          untilComponentDestroyed(this),
        )
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        .subscribe((v: any) => {
          this.writeValue(v);
          this.changeDetectorRef.markForCheck();
        });
    }
  }

  /**
   * Needed for untilComponentDestroyed
   */
  public ngOnDestroy(): void {}

  /**
   * Retrieve a value determined by the passed in formatter
   *
   * @param option - The radio option
   * @param formatter - The formatter function used to retrieve the value
   * @returns The retrieved value
   */
  public retrieveValue(option: TsRadioOption, formatter?: TsRadioFormatFn): TsRadioOption | string {
    return (formatter && formatter(option)) ? formatter(option) : option;
  }

  /**
   * Handle changes
   *
   * @param option - The selected option
   */
  public radioGroupChange(option: MatRadioChange): void {
    const change = new TsRadioChange(this, option.value);
    this.selectionChange.emit(change);
    this.changeDetectorRef.markForCheck();
  }

  /**
   * Handles changes for visual radio groups
   *
   * @param option - The selected option
   */
  public visualRadioGroupChange(option: TsRadioOption): void {
    const value = this.retrieveValue(option, this.formatModelValueFn);
    const change = new TsRadioChange(this, value);
    this.selectionChange.emit(change);
    this.changeDetectorRef.markForCheck();
  }

  /**
   * Function for tracking for-loops changes
   *
   * @param index - The item index
   * @returns The unique ID
   */
  public trackByFn(index): number {
    return index;
  }
}