text:
import { Component } from '@angular/core';
import { NgbAccordionModule } from '@ng-bootstrap/ng-bootstrap';

@Component({
	selector: 'ngbd-accordion-static',
	standalone: true,
	imports: [NgbAccordionModule],
	templateUrl: './accordion-static.html',
})
export class NgbdAccordionStatic {}


text:
package org.apache.logging.log4j.nosql.appender;

import org.junit.Test;

import static org.easymock.EasyMock.createStrictMock;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;

public class NoSqlAppenderTest {
    @Test
    public void testNoProvider() {
        final NoSqlAppender appender = NoSqlAppender.createAppender("myName01", null, null, null, null);
        assertNull("The appender should be null.", appender);
    }

    @Test
    public void testProvider() {
        @SuppressWarnings("unchecked")
        final NoSqlProvider<?> provider = createStrictMock(NoSqlProvider.class);
        replay(provider);
        final NoSqlAppender appender = NoSqlAppender.createAppender("myName01", null, null, null, provider);
        assertNotNull("The appender should not be null.", appender);
        assertEquals("The toString value is not correct.",
                "myName01{ manager=noSqlManager{ description=myName01, bufferSize=0, provider=" + provider + " } }",
                appender.toString());
        appender.stop();
        verify(provider);
    }

    @Test
    public void testProviderBuffer() {
        @SuppressWarnings("unchecked")
        final NoSqlProvider<?> provider = createStrictMock(NoSqlProvider.class);
        replay(provider);
        final NoSqlAppender appender = NoSqlAppender.createAppender("anotherName02", null, null, "25", provider);
        assertNotNull("The appender should not be null.", appender);
        assertEquals("The toString value is not correct.",
                "anotherName02{ manager=noSqlManager{ description=anotherName02, bufferSize=25, provider=" + provider
                        + " } }", appender.toString());
        appender.stop();
        verify(provider);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.wso2.andes.management.ui.views.exchange;

import static org.wso2.andes.management.common.mbeans.ManagedExchange.HDR_BINDING_NUMBER;
import static org.wso2.andes.management.common.mbeans.ManagedExchange.HDR_QUEUE_BINDINGS;
import static org.wso2.andes.management.common.mbeans.ManagedExchange.HDR_QUEUE_NAME;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import javax.management.MBeanServerConnection;
import javax.management.MBeanServerInvocationHandler;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.TabularDataSupport;

import org.wso2.andes.management.ui.ApplicationRegistry;
import org.wso2.andes.management.ui.ManagedBean;
import org.wso2.andes.management.ui.ServerRegistry;
import org.wso2.andes.management.common.mbeans.ManagedExchange;
import org.wso2.andes.management.ui.jmx.JMXManagedObject;
import org.wso2.andes.management.ui.jmx.MBeanUtility;
import org.wso2.andes.management.ui.views.MBeanView;
import org.wso2.andes.management.ui.views.TabControl;
import org.wso2.andes.management.ui.views.ViewUtility;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;

/**
 * Control class for the Headers Exchange mbean Operations tab.
 */
public class HeadersExchangeOperationsTabControl extends TabControl
{
    private FormToolkit _toolkit;
    private ScrolledForm        _form;
    private Table _bindingNumberTable = null;
    private TableViewer _bindingNumberTableViewer = null;
    private Table _headersTable = null;
    private TableViewer _headersTableViewer = null;
    private Composite _paramsComposite = null;

    private TabularDataSupport _bindings = null;
    private ManagedExchange _emb;

    public HeadersExchangeOperationsTabControl(TabFolder tabFolder, JMXManagedObject mbean, MBeanServerConnection mbsc)
    {
        super(tabFolder);
        _mbean = mbean;
        _emb = (ManagedExchange) MBeanServerInvocationHandler.newProxyInstance(mbsc,
                                mbean.getObjectName(), ManagedExchange.class, false);
        _toolkit = new FormToolkit(_tabFolder.getDisplay());
        _form = _toolkit.createScrolledForm(_tabFolder);
        _form.getBody().setLayout(new GridLayout());
        createComposites();
        createWidgets();
    }

    private void createComposites()
    {
        _paramsComposite = _toolkit.createComposite(_form.getBody(), SWT.NONE);
        _paramsComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
        _paramsComposite.setLayout(new GridLayout());
    }

    /**
     * @see TabControl#getControl()
     */
    public Control getControl()
    {
        return _form;
    }

    /**
     * @see TabControl#setFocus()
     */
    public void setFocus()
    {
        _bindingNumberTable.setFocus();
    }

    @Override
    public void refresh(ManagedBean mbean)
    {

        _bindings = null;
        try
        {
            //gather a list of all keys and queues for display and selection
            _bindings = (TabularDataSupport) _emb.bindings();
        }
        catch (Exception e)
        {
            MBeanUtility.handleException(_mbean,e);
        }

        _bindingNumberTableViewer.setInput(_bindings);

        layout();
    }

    public void layout()
    {
        _form.layout(true);
        _form.getBody().layout(true, true);
    }

    private void createWidgets()
    {
        Group bindingsGroup = new Group(_paramsComposite, SWT.SHADOW_NONE);
        bindingsGroup.setBackground(_paramsComposite.getBackground());
        bindingsGroup.setText("Bindings");
        bindingsGroup.setLayout(new GridLayout(2,false));
        GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
        bindingsGroup.setLayoutData(gridData);

        Composite tablesComposite = _toolkit.createComposite(bindingsGroup);
        gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
        gridData.minimumHeight = 250;
        gridData.heightHint = 250;
        tablesComposite.setLayoutData(gridData);
        tablesComposite.setLayout(new GridLayout(2,false));

        //table of bindings for the exchange
        _bindingNumberTable = new Table (tablesComposite, SWT.SINGLE | SWT.SCROLL_LINE | SWT.BORDER | SWT.FULL_SELECTION);
        _bindingNumberTable.setLinesVisible(true);
        _bindingNumberTable.setHeaderVisible(true);
        GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
        data.minimumHeight = 300;
        data.heightHint = 300;
        _bindingNumberTable.setLayoutData(data);

        _bindingNumberTableViewer = new TableViewer(_bindingNumberTable);
        final TableSorter tableSorter = new TableSorter(HDR_BINDING_NUMBER);

        String[] titles = {"Binding Number", "Queue Name"};
        int[] bounds = {135, 175};
        for (int i = 0; i < titles.length; i++)
        {
            final int index = i;
            final TableColumn column = new TableColumn (_bindingNumberTable, SWT.NONE);

            column.setText(titles[i]);
            column.setWidth(bounds[i]);
            column.setResizable(true);

            //Setting the right sorter
            column.addSelectionListener(new SelectionAdapter()
            {
                @Override
                public void widgetSelected(SelectionEvent e)
                {
                    tableSorter.setColumn(index);
                    final TableViewer viewer = _bindingNumberTableViewer;
                    int dir = viewer .getTable().getSortDirection();
                    if (viewer.getTable().getSortColumn() == column)
                    {
                        dir = dir == SWT.UP ? SWT.DOWN : SWT.UP;
                    }
                    else
                    {
                        dir = SWT.UP;
                    }
                    viewer.getTable().setSortDirection(dir);
                    viewer.getTable().setSortColumn(column);
                    viewer.refresh();
                }
            });

        }

        _bindingNumberTableViewer.setContentProvider(new ContentProviderImpl(HDR_BINDING_NUMBER));
        _bindingNumberTableViewer.setLabelProvider(new LabelProviderImpl(HDR_BINDING_NUMBER));
        _bindingNumberTableViewer.setSorter(tableSorter);
        _bindingNumberTable.setSortColumn(_bindingNumberTable.getColumn(0));
        _bindingNumberTable.setSortDirection(SWT.UP);

        //table of header bindings
        _headersTable = new Table (tablesComposite, SWT.SINGLE | SWT.SCROLL_LINE | SWT.BORDER | SWT.FULL_SELECTION);
        _headersTable.setLinesVisible (true);
        _headersTable.setHeaderVisible (true);
        data = new GridData(SWT.FILL, SWT.FILL, true, true);
        data.minimumHeight = 300;
        data.heightHint = 300;
        _headersTable.setLayoutData(data);

        _headersTableViewer = new TableViewer(_headersTable);
        final TableSorter queuesTableSorter = new TableSorter(HDR_QUEUE_BINDINGS);

        titles = new String[]{"Header Bindings"};
        bounds = new int[]{225};
        for (int i = 0; i < titles.length; i++)
        {
            final int index = i;
            final TableColumn column = new TableColumn (_headersTable, SWT.NONE);

            column.setText(titles[i]);
            column.setWidth(bounds[i]);
            column.setResizable(true);

            //Setting the right sorter
            column.addSelectionListener(new SelectionAdapter()
            {
                @Override
                public void widgetSelected(SelectionEvent e)
                {
                	queuesTableSorter.setColumn(index);
                    final TableViewer viewer = _headersTableViewer;
                    int dir = viewer .getTable().getSortDirection();
                    if (viewer.getTable().getSortColumn() == column)
                    {
                        dir = dir == SWT.UP ? SWT.DOWN : SWT.UP;
                    }
                    else
                    {
                        dir = SWT.UP;
                    }
                    viewer.getTable().setSortDirection(dir);
                    viewer.getTable().setSortColumn(column);
                    viewer.refresh();
                }
            });

        }

        _headersTableViewer.setContentProvider(new ContentProviderImpl(HDR_QUEUE_BINDINGS));
        _headersTableViewer.setLabelProvider(new LabelProviderImpl(HDR_QUEUE_BINDINGS));
        _headersTableViewer.setSorter(queuesTableSorter);
        _headersTable.setSortColumn(_headersTable.getColumn(0));
        _headersTable.setSortDirection(SWT.UP);
        _headersTableViewer.setInput(new String[]{"Select a binding to view key-value pairs"});

        _bindingNumberTableViewer.addSelectionChangedListener(new ISelectionChangedListener(){
            public void selectionChanged(SelectionChangedEvent evt)
            {
                int selectionIndex = _bindingNumberTable.getSelectionIndex();

                if (selectionIndex != -1)
                {
                	final CompositeData selectedMsg = (CompositeData)_bindingNumberTable.getItem(selectionIndex).getData();

                	String[] bindings = (String[]) selectedMsg.get(HDR_QUEUE_BINDINGS);
                	_headersTableViewer.setInput(bindings);
                }
                else
                {
                	_headersTableViewer.setInput(new String[]{"Select a binding to view key-value pairs"});
                }
            }
        });

        //listener for double clicking to open the selection mbean
        _bindingNumberTable.addMouseListener(new MouseListener()
        {
            // MouseListener implementation
            public void mouseDoubleClick(MouseEvent event)
            {
                openMBean(_bindingNumberTable);
            }

            public void mouseDown(MouseEvent e){}
            public void mouseUp(MouseEvent e){}
        });

        //Side Buttons
        Composite buttonsComposite = _toolkit.createComposite(bindingsGroup);
        gridData = new GridData(SWT.FILL, SWT.FILL, false, true);
        buttonsComposite.setLayoutData(gridData);
        buttonsComposite.setLayout(new GridLayout());

        final Button createBindingButton = _toolkit.createButton(buttonsComposite, "Create ...", SWT.PUSH);
        createBindingButton.addSelectionListener(new SelectionAdapter()
        {
            public void widgetSelected(SelectionEvent e)
            {
                createNewBinding(createBindingButton.getShell());
            }
        });

    }

    /**
     * Content Provider class for the table viewer
     */
    private static class ContentProviderImpl implements IStructuredContentProvider
    {
    	String type;

    	public ContentProviderImpl(String type)
    	{
    		this.type = type;
    	}

        public void inputChanged(Viewer v, Object oldInput, Object newInput)
        {

        }

        public void dispose()
        {

        }

        public Object[] getElements(Object parent)
        {
        	if(type.equals(HDR_BINDING_NUMBER))
        	{
        		Collection<Object> rowCollection = ((TabularDataSupport) parent).values();

        		return rowCollection.toArray();
        	}
        	else
        	{
        		//we have the list of bindings, return directly
        		return (String[]) parent;
        	}
        }
    }

    /**
     * Label Provider class for the routing key table viewer
     */
    private static class LabelProviderImpl extends LabelProvider implements ITableLabelProvider
    {
    	String type;

    	public LabelProviderImpl(String type)
    	{
    		this.type = type;
    	}

        public String getColumnText(Object element, int columnIndex)
        {
        	if(type.equals(HDR_BINDING_NUMBER)) //binding num and queue name table
        	{
        		switch (columnIndex)
        		{
        			case 0 : // binding number column
        				return String.valueOf(((CompositeDataSupport) element).get(HDR_BINDING_NUMBER));
                    case 1 : // queue name column
                        return (String) ((CompositeDataSupport) element).get(HDR_QUEUE_NAME);
        			default :
        				return "";
        		}
        	}
        	else //binding key-value pair table
        	{
        		switch (columnIndex)
        		{
        			case 0 : //header binding column
        				return String.valueOf(element);
        			default :
        				return "";
        		}
        	}
        }

        public Image getColumnImage(Object element, int columnIndex)
        {
            return null;
        }
    }

    /**
     * Sorter class for the table viewer.
     *
     */
    public static class TableSorter extends ViewerSorter
    {
        private int column;
        private static final int ASCENDING = 0;
        private static final int DESCENDING = 1;

        private int direction = DESCENDING;

    	private String type;

        public TableSorter(String type)
        {
        	this.type = type;
            this.column = 0;
            direction = ASCENDING;
        }

        public void setColumn(int column)
        {
            if (column == this.column)
            {
                // Same column as last sort; toggle the direction
                direction = 1 - direction;
            }
            else
            {
                // New column; do an ascending sort
                this.column = column;
                direction = ASCENDING;
            }
        }

        @Override
        public int compare(Viewer viewer, Object e1, Object e2)
        {
            int comparison = 0;

            if(type.equals(HDR_BINDING_NUMBER)) //binding num and queue name table
            {
                CompositeData binding1 = (CompositeData) e1;
                CompositeData binding2 = (CompositeData) e2;

                switch(column)
                {
                    case 0: // binding number column
                        comparison = ((Integer) binding1.get(HDR_BINDING_NUMBER)).compareTo((Integer) binding2.get(HDR_BINDING_NUMBER));
                        break;
                    case 1: // queue name column
                        comparison = ((String) binding1.get(HDR_QUEUE_NAME)).compareTo((String) binding2.get(HDR_QUEUE_NAME));
                        break;
                    default:
                        comparison = 0;
                }
            }
            else  //binding key-value pair table
            {
                switch(column)
                {
                    case 0: //header binding column
                        comparison = ((String)e1).compareTo((String) e2);
                        break;
                    default:
                        comparison = 0;
                }
            }

            // If descending order, flip the direction
            if(direction == DESCENDING)
            {
                comparison = -comparison;
            }
            return comparison;
        }
    }

    private void createNewBinding(Shell parent)
    {
        final Shell shell = ViewUtility.createModalDialogShell(parent, "Create New Binding");

        Composite queueNameComposite = _toolkit.createComposite(shell, SWT.NONE);
        queueNameComposite.setBackground(shell.getBackground());
        GridData layoutData = new GridData(SWT.CENTER, SWT.TOP, true, false);
        layoutData.minimumWidth = 300;
        queueNameComposite.setLayoutData(layoutData);
        queueNameComposite.setLayout(new GridLayout(2,false));

        _toolkit.createLabel(queueNameComposite,"Queue:").setBackground(shell.getBackground());
        final Combo destinationCombo = new Combo(queueNameComposite,SWT.NONE | SWT.READ_ONLY);
        destinationCombo.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));

        final ScrolledComposite scrolledComposite = new ScrolledComposite(shell, SWT.V_SCROLL);
        scrolledComposite.setExpandHorizontal(true);
        scrolledComposite.setLayout(new GridLayout());
        scrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
        scrolledComposite.setBackground(shell.getBackground());

        final Composite bindingComposite = _toolkit.createComposite(scrolledComposite, SWT.NONE);
        bindingComposite.setBackground(scrolledComposite.getBackground());
        bindingComposite.setLayout(new GridLayout(2,true));
        layoutData = new GridData(SWT.FILL, SWT.TOP, true, false);
        bindingComposite.setLayoutData(layoutData);
        scrolledComposite.setContent(bindingComposite);

        Composite addMoreButtonComp = _toolkit.createComposite(shell);
        addMoreButtonComp.setBackground(shell.getBackground());
        addMoreButtonComp.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, true, true));
        addMoreButtonComp.setLayout(new GridLayout());

        final Button addMoreButton = _toolkit.createButton(addMoreButtonComp, "Add additional field", SWT.PUSH);

        Composite okCancelButtonsComp = _toolkit.createComposite(shell);
        okCancelButtonsComp.setBackground(shell.getBackground());
        okCancelButtonsComp.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, true, true));
        okCancelButtonsComp.setLayout(new GridLayout(2,false));

        Button okButton = _toolkit.createButton(okCancelButtonsComp, "OK", SWT.PUSH);
        okButton.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
        Button cancelButton = _toolkit.createButton(okCancelButtonsComp, "Cancel", SWT.PUSH);
        cancelButton.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));

        List<String> queueList = ApplicationRegistry.getServerRegistry(_mbean).getQueueNames(_mbean.getVirtualHostName());

        if(queueList.size() == 0)
        {
            destinationCombo.setItems(new String[]{"No queues available"});
            okButton.setEnabled(false);
        }
        else
        {
            Collections.sort(queueList);
            destinationCombo.setItems(queueList.toArray(new String[0]));
        }
        destinationCombo.select(0);

        final HashMap<Text, Text> headerBindingHashMap = new HashMap<Text, Text>();

        //add headings
        Label keyLabel = _toolkit.createLabel(bindingComposite,"Key:");
        keyLabel.setBackground(bindingComposite.getBackground());
        keyLabel.setLayoutData(new GridData(SWT.CENTER, SWT.TOP, true, false));

        Label valueLabel = _toolkit.createLabel(bindingComposite,"Value:");
        valueLabel.setBackground(bindingComposite.getBackground());
        valueLabel.setLayoutData(new GridData(SWT.CENTER, SWT.TOP, true, false));

        //add the x-match key by default and offer a comobo to select its value
        final Text xmatchKeyText = new Text(bindingComposite, SWT.BORDER);
        xmatchKeyText.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
        xmatchKeyText.setText("x-match");
        xmatchKeyText.setEditable(false);

        final Combo xmatchValueCombo = new Combo(bindingComposite,SWT.NONE | SWT.READ_ONLY);
        xmatchValueCombo.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
        xmatchValueCombo.setItems(new String[]{"any", "all"});
        xmatchValueCombo.select(0);

        //make some empty key-value fields
        for(int i=0; i < 4; i++)
        {
            Text keyText = new Text(bindingComposite, SWT.BORDER);
            Text valueText = new Text(bindingComposite, SWT.BORDER);
            keyText.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
            valueText.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));

            headerBindingHashMap.put(keyText, valueText);
        }
        bindingComposite.setSize(bindingComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT));

        //allow adding more fields for additional key-value pairs
        addMoreButton.addSelectionListener(new SelectionAdapter()
        {
            public void widgetSelected(SelectionEvent e)
            {
                Text keyText = new Text(bindingComposite, SWT.BORDER);
                Text valueText = new Text(bindingComposite, SWT.BORDER);
                keyText.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
                valueText.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));

                headerBindingHashMap.put(keyText, valueText);

                bindingComposite.setSize(bindingComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
                bindingComposite.layout(true);
                scrolledComposite.layout(true);
            }
        });

        okButton.addSelectionListener(new SelectionAdapter()
        {
            public void widgetSelected(SelectionEvent e)
            {
                String xMatchString = xmatchValueCombo.getText();

                String destQueue = destinationCombo.getItem(destinationCombo.getSelectionIndex()).toString();

                StringBuffer bindingValue = new StringBuffer();

                //insert the x-match key-value pair
                if (xMatchString.equalsIgnoreCase("any"))
                {
                    bindingValue.append("x-match=any");
                }
                else
                {
                    bindingValue.append("x-match=all");
                }

                //insert the other key-value pairs
                for (Text keyText : headerBindingHashMap.keySet())
                {

                    String key = keyText.getText();
                    if(key == null || key.length() == 0)
                    {
                        continue;
                    }

                    Text valueText = headerBindingHashMap.get(keyText);
                    String value = valueText.getText();

                    bindingValue.append(",");
                    bindingValue.append(key + "=");
                    //empty values are permitted, signalling only key-presence is required
                    if(value != null && value.length() > 0)
                    {
                        bindingValue.append(value);
                    }
                }

                shell.dispose();

                try
                {
                    _emb.createNewBinding(destQueue, bindingValue.toString());
                    ViewUtility.operationResultFeedback(null, "Created new Binding", null);
                }
                catch (Exception e4)
                {
                    ViewUtility.operationFailedStatusBarMessage("Error creating new Binding");
                    MBeanUtility.handleException(_mbean, e4);
                }

                refresh(_mbean);
            }
        });

        cancelButton.addSelectionListener(new SelectionAdapter()
        {
            public void widgetSelected(SelectionEvent e)
            {
                shell.dispose();
            }
        });

        shell.setDefaultButton(okButton);
        shell.pack();
        ViewUtility.centerChildInParentShell(parent, shell);

        shell.open();
    }

    private void openMBean(Table table)
    {
        int selectionIndex = table.getSelectionIndex();

        if (selectionIndex == -1)
        {
            return;
        }

        CompositeData bindingResult = (CompositeData) table.getItem(selectionIndex).getData();
        String queueName = (String) bindingResult.get(HDR_QUEUE_NAME);
        ServerRegistry serverRegistry = ApplicationRegistry.getServerRegistry(_mbean);
        ManagedBean selectedMBean = serverRegistry.getQueue(queueName, _mbean.getVirtualHostName());

        if(selectedMBean == null)
        {
            ViewUtility.popupErrorMessage("Error", "Unable to retrieve the selected MBean to open it");
            return;
        }

        IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
        MBeanView view = (MBeanView) window.getActivePage().findView(MBeanView.ID);
        try
        {
            view.openMBean(selectedMBean);
        }
        catch (Exception ex)
        {
            MBeanUtility.handleException(selectedMBean, ex);
        }
    }
}


text:
<!DOCTYPE html>

<meta charset="UTF-8">
<link href="style.css" type="text/css" rel="stylesheet">
<title>PMULUDQ—Multiply Packed Unsigned Doubleword Integers </title>

PMULUDQ—Multiply Packed Unsigned Doubleword Integers

Opcode/Instruction
Op/En
64/32 bit Mode Support
CPUID Feature Flag
Description

0F F4 /r1

PMULUDQ mm1, mm2/m64

RM
V/V
SSE2
Multiply unsigned doubleword integer in mm1 by unsigned doubleword integer in mm2/m64, and store the quadword result in mm1.

66 0F F4 /r

PMULUDQ xmm1, xmm2/m128

RM
V/V
SSE2
Multiply packed unsigned doubleword integers in xmm1 by packed unsigned doubleword integers in xmm2/m128, and store the quadword results in xmm1.

VEX.NDS.128.66.0F.WIG F4 /r

VPMULUDQ xmm1, xmm2, xmm3/m128

RVM
V/V
AVX
Multiply packed unsigned doubleword integers in xmm2 by packed unsigned doubleword integers in xmm3/m128, and store the quadword results in xmm1.

VEX.NDS.256.66.0F.WIG F4 /r

VPMULUDQ ymm1, ymm2, ymm3/m256

RVM
V/V
AVX2
Multiply packed unsigned doubleword integers in ymm2 by packed unsigned doubleword integers in ymm3/m256, and store the quadword results in ymm1.

EVEX.NDS.128.66.0F.W1 F4 /r

VPMULUDQ xmm1 {k1}{z}, xmm2, xmm3/m128/m64bcst

FV
V/V
AVX512VL AVX512F
Multiply packed unsigned doubleword integers in xmm2 by packed unsigned doubleword integers in xmm3/m128/m64bcst, and store the quadword results in xmm1 under writemask k1.

EVEX.NDS.256.66.0F.W1 F4 /r

VPMULUDQ ymm1 {k1}{z}, ymm2, ymm3/m256/m64bcst

FV
V/V
AVX512VL AVX512F
Multiply packed unsigned doubleword integers in ymm2 by packed unsigned doubleword integers in ymm3/m256/m64bcst, and store the quadword results in ymm1 under writemask k1.

EVEX.NDS.512.66.0F.W1 F4 /r

VPMULUDQ zmm1 {k1}{z}, zmm2, zmm3/m512/m64bcst

FV
V/V
AVX512F
Multiply packed unsigned doubleword integers in zmm2 by packed unsigned doubleword integers in zmm3/m512/m64bcst, and store the quadword results in zmm1 under writemask k1.

NOTES:

1. See note in Section 2.4, "AVX and SSE Instruction Exception Specification" in the Intel® 64 and IA-32 Architectures Software Developer's Manual, Volume 2A and Section 22.25.3, "Exception Conditions of Legacy SIMD Instructions Operating on MMX Registers" in the Intel® 64 and IA-32 Architectures Software Developer's Manual, Volume 3A.

Instruction Operand Encoding

Op/En
Operand 1
Operand 2
Operand 3
Operand 4

RM
ModRM:reg (r, w)
ModRM:r/m (r)
NA
NA

RVM
ModRM:reg (w)
VEX.vvvv (r)
ModRM:r/m (r)
NA

FV
ModRM:reg (w)
EVEX.vvvv (r)
ModRM:r/m (r)
NA

Description

Multiplies the first operand (destination operand) by the second operand (source operand) and stores the result in the destination operand.

In 64-bit mode and not encoded with VEX/EVEX, using a REX prefix in the form of REX.R permits this instruction to access additional registers (XMM8-XMM15).

Legacy SSE version 64-bit operand: The source operand can be an unsigned doubleword integer stored in the low doubleword of an MMX technology register or a 64-bit memory location. The destination operand can be an unsigned doubleword integer stored in the low doubleword an MMX technology register. The result is an unsigned

quadword integer stored in the destination an MMX technology register. When a quadword result is too large to be represented in 64 bits (overflow), the result is wrapped around and the low 64 bits are written to the destination element (that is, the carry is ignored).

For 64-bit memory operands, 64 bits are fetched from memory, but only the low doubleword is used in the compu-tation.

128-bit Legacy SSE version: The second source operand is two packed unsigned doubleword integers stored in the first (low) and third doublewords of an XMM register or a 128-bit memory location. For 128-bit memory operands, 128 bits are fetched from memory, but only the first and third doublewords are used in the computation. The first source operand is two packed unsigned doubleword integers stored in the first and third doublewords of an XMM register. The destination contains two packed unsigned quadword integers stored in an XMM register. Bits (VLMAX-1:128) of the corresponding YMM destination register remain unchanged.

VEX.128 encoded version: The second source operand is two packed unsigned doubleword integers stored in the first (low) and third doublewords of an XMM register or a 128-bit memory location. For 128-bit memory operands, 128 bits are fetched from memory, but only the first and third doublewords are used in the computation. The first source operand is two packed unsigned doubleword integers stored in the first and third doublewords of an XMM register. The destination contains two packed unsigned quadword integers stored in an XMM register. Bits (VLMAX-1:128) of the destination YMM register are zeroed.

VEX.256 encoded version: The second source operand is four packed unsigned doubleword integers stored in the first (low), third, fifth and seventh doublewords of a YMM register or a 256-bit memory location. For 256-bit memory operands, 256 bits are fetched from memory, but only the first, third, fifth and seventh doublewords are used in the computation. The first source operand is four packed unsigned doubleword integers stored in the first, third, fifth and seventh doublewords of an YMM register. The destination contains four packed unaligned quadword integers stored in an YMM register.

EVEX encoded version: The input unsigned doubleword integers are taken from the even-numbered elements of the source operands. The first source operand is a ZMM/YMM/XMM registers. The second source operand can be an ZMM/YMM/XMM register, a 512/256/128-bit memory location or a 512/256/128-bit vector broadcasted from a 64-bit memory location. The destination is a ZMM/YMM/XMM register, and updated according to the writemask at 64-bit granularity.

Operation

PMULUDQ (with 64-Bit operands)

    DEST[63:0] ← DEST[31:0] ∗ SRC[31:0];

PMULUDQ (with 128-Bit operands)

    DEST[63:0] ← DEST[31:0] ∗ SRC[31:0];
    DEST[127:64] ← DEST[95:64] ∗ SRC[95:64];

VPMULUDQ (VEX.128 encoded version)

DEST[63:0] (cid:197) SRC1[31:0] * SRC2[31:0]
DEST[127:64] (cid:197) SRC1[95:64] * SRC2[95:64]
DEST[VLMAX-1:128] (cid:197) 0

VPMULUDQ (VEX.256 encoded version)

DEST[63:0] (cid:197) SRC1[31:0] * SRC2[31:0]
DEST[127:64] (cid:197) SRC1[95:64] * SRC2[95:64
DEST[191:128] (cid:197) SRC1[159:128] * SRC2[159:128]
DEST[255:192] (cid:197) SRC1[223:192] * SRC2[223:192]
DEST[VLMAX-1:256] (cid:197) 0

VPMULUDQ (EVEX encoded versions)

(KL, VL) = (2, 128), (4, 256), (8, 512)
FOR j (cid:197) 0 TO KL-1
    i (cid:197) j * 64
    IF k1[j] OR *no writemask* THEN
              IF (EVEX.b = 1) AND (SRC2 *is memory*)
                    THEN DEST[i+63:i] (cid:197) ZeroExtend64( SRC1[i+31:i]) * ZeroExtend64( SRC2[31:0] )
                    ELSE DEST[i+63:i] (cid:197) ZeroExtend64( SRC1[i+31:i]) * ZeroExtend64( SRC2[i+31:i] )
              FI;
         ELSE
              IF *merging-masking*
                                                         ; merging-masking
                    THEN *DEST[i+63:i] remains unchanged*
                    ELSE *zeroing-masking*
                                                              ; zeroing-masking
                         DEST[i+63:i] (cid:197) 0
              FI
    FI;
ENDFOR
DEST[MAX_VL-1:VL] (cid:197) 0

Intel C/C++ Compiler Intrinsic Equivalent

VPMULUDQ __m512i _mm512_mul_epu32(__m512i a, __m512i b);

VPMULUDQ __m512i _mm512_mask_mul_epu32(__m512i s, __mmask8 k, __m512i a, __m512i b);

VPMULUDQ __m512i _mm512_maskz_mul_epu32( __mmask8 k, __m512i a, __m512i b);

VPMULUDQ __m256i _mm256_mask_mul_epu32(__m256i s, __mmask8 k, __m256i a, __m256i b);

VPMULUDQ __m256i _mm256_maskz_mul_epu32( __mmask8 k, __m256i a, __m256i b);

VPMULUDQ __m128i _mm_mask_mul_epu32(__m128i s, __mmask8 k, __m128i a, __m128i b);

VPMULUDQ __m128i _mm_maskz_mul_epu32( __mmask8 k, __m128i a, __m128i b);

PMULUDQ:__m64 _mm_mul_su32 (__m64 a, __m64 b)

(V)PMULUDQ:__m128i _mm_mul_epu32 ( __m128i a, __m128i b)

VPMULUDQ:__m256i _mm256_mul_epu32( __m256i a, __m256i b);

Flags Affected

None.

SIMD Floating-Point Exceptions

None.

Other Exceptions

Non-EVEX-encoded instruction, see Exceptions Type 4.

EVEX-encoded instruction, see Exceptions Type E4.


text:
package org.apache.shardingsphere.authority.provider.natived.model.privilege.database;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.apache.shardingsphere.authority.model.PrivilegeType;

import java.util.Collection;

/**
 * Table privileges.
 */
@RequiredArgsConstructor
@EqualsAndHashCode
@Getter
public final class TablePrivileges {

    private final String tableName;

    private final Collection<PrivilegeType> privileges;

    /**
     * Has privileges.
     *
     * @param privileges privileges
     * @return has privileges or not
     */
    public boolean hasPrivileges(final Collection<PrivilegeType> privileges) {
        return this.privileges.containsAll(privileges);
    }
}


text:
"""decorators -- decorators for owyl behavior trees.

Copyright 2008 David Eyk. All rights reserved.

$Author$\n
$Rev$\n
$Date$
"""

__author__ = "$Author$"[9:-2]
__revision__ = "$Rev$"[6:-2]
__date__ = "$Date$"[7:-2]

import time

import core

__all__ = ['identity', 'repeatUntilFail', 'repeatUntilSucceed',
           'flip', 'repeatAlways', 'limit']

@core.parent_task
def identity(child, **kwargs):
    """Transparent decorator. Pass yielded values from child unchanged.
    """
    result = None
    child = child(**kwargs)
    while result is None:
        result = (yield child)
    yield result

@core.parent_task
def flip(child, **kwargs):
    """NOT decorator. Pass yielded values from child with the boolean flipped.

    Yielded values of "None" are passed unchanged.
    """
    result = None
    child = child(**kwargs)
    while result is None:
        result = (yield child)
    yield not result

@core.parent_task
def repeatAlways(child, **kwargs):
    """Perpetually iterate over the child, regardless of return value.
    """
    while True:
        yield child(**kwargs)

@core.parent_task
def repeatUntilFail(child, **kwargs):
    """Repeatedly iterate over the child until it fails.

    @keyword final_value: Value to return on failure.
    @type final_value: C{True} or C{False}
    """
    final_value = kwargs.pop('final_value', False)
    while True:
        result = (yield child(**kwargs))
        if result is False:
            break
    yield final_value

@core.parent_task
def repeatUntilSucceed(child, **kwargs):
    """Repeatedly iterate over the child until it succeeds.

    @keyword final_value: Value to return on failure.
    @type final_value: C{True} or C{False}
    """
    final_value = kwargs.pop('final_value', False)
    while True:
        result = (yield child(**kwargs))
        if result is True:
            break
    yield final_value

@core.parent_task
def limit(child, **kwargs):
    """Limit the child to only iterate once every period.

    Otherwise, act as an identity decorator.

    @keyword limit_period: how often to run the child, in seconds.
    """
    nowtime = time.time
    last_run = nowtime()
    period = kwargs.get('limit_period', 1.0)
    result = None
    visitor = core.visit(child, **kwargs)
    while True:
        now = nowtime()
        since_last = now - last_run
        if (since_last) <= period:
            yield None
            continue
        last_run = nowtime()
        result = visitor.next()
        yield result


text:
import os
import signal
import sys
import threading
import time
import unittest
from unittest.mock import Mock
from unittest import skip, skipUnless

from curtsies import events
from curtsies.input import Input

class CustomEvent(events.Event):
    pass

class CustomScheduledEvent(events.ScheduledEvent):
    pass

@skipUnless(sys.stdin.isatty(), "stdin must be a tty")
class TestInput(unittest.TestCase):
    def test_create(self):
        Input()

    def test_iter(self):
        inp = Input()
        inp.send = Mock()
        inp.send.return_value = None
        for i, e in zip(range(3), inp):
            self.assertEqual(e, None)
        self.assertEqual(inp.send.call_count, 3)

    def test_send(self):
        inp = Input()
        inp.unprocessed_bytes = [b"a"]
        self.assertEqual(inp.send("nonsensical value"), "a")

    def test_send_nonblocking_no_event(self):
        inp = Input()
        inp.unprocessed_bytes = []
        self.assertEqual(inp.send(0), None)

    def test_nonblocking_read(self):
        inp = Input()
        self.assertEqual(inp._nonblocking_read(), 0)

    def test_send_paste(self):
        inp = Input()
        inp.unprocessed_bytes = []
        inp._wait_for_read_ready_or_timeout = Mock()
        inp._wait_for_read_ready_or_timeout.return_value = (True, None)
        inp._nonblocking_read = Mock()
        n = inp.paste_threshold + 1

        first_time = [True]

        def side_effect():
            if first_time:
                inp.unprocessed_bytes.extend([b"a"] * n)
                first_time.pop()
                return n
            else:
                return None

        inp._nonblocking_read.side_effect = side_effect

        r = inp.send(0)
        self.assertEqual(type(r), events.PasteEvent)
        self.assertEqual(r.events, ["a"] * n)

    def test_event_trigger(self):
        inp = Input()
        f = inp.event_trigger(CustomEvent)
        self.assertEqual(inp.send(0), None)
        f()
        self.assertEqual(type(inp.send(0)), CustomEvent)
        self.assertEqual(inp.send(0), None)

    def test_schedule_event_trigger(self):
        inp = Input()
        f = inp.scheduled_event_trigger(CustomScheduledEvent)
        self.assertEqual(inp.send(0), None)
        f(when=time.time())
        self.assertEqual(type(inp.send(0)), CustomScheduledEvent)
        self.assertEqual(inp.send(0), None)
        f(when=time.time() + 0.01)
        self.assertEqual(inp.send(0), None)
        time.sleep(0.01)
        self.assertEqual(type(inp.send(0)), CustomScheduledEvent)
        self.assertEqual(inp.send(0), None)

    def test_schedule_event_trigger_blocking(self):
        inp = Input()
        f = inp.scheduled_event_trigger(CustomScheduledEvent)
        f(when=time.time() + 0.05)
        self.assertEqual(type(next(inp)), CustomScheduledEvent)

    def test_threadsafe_event_trigger(self):
        inp = Input()
        f = inp.threadsafe_event_trigger(CustomEvent)

        def check_event():
            self.assertEqual(type(inp.send(1)), CustomEvent)
            self.assertEqual(inp.send(0), None)

        t = threading.Thread(target=check_event)
        t.start()
        f()
        t.join()

    def test_interrupting_sigint(self):
        inp = Input(sigint_event=True)

        def send_sigint():
            os.kill(os.getpid(), signal.SIGINT)

        with inp:
            t = threading.Thread(target=send_sigint)
            t.start()
            self.assertEqual(type(inp.send(1)), events.SigIntEvent)
            self.assertEqual(inp.send(0), None)
            t.join()

    def test_create_in_thread_with_sigint_event(self):
        def create():
            inp = Input(sigint_event=True)

        t = threading.Thread(target=create)
        t.start()
        t.join()

    def test_use_in_thread_with_sigint_event(self):
        inp = Input(sigint_event=True)

        def use():
            with inp:
                pass

        t = threading.Thread(target=use)
        t.start()
        t.join()


text:
package org.apache.spark.deploy.master.ui

import java.io.DataOutputStream
import java.net.{HttpURLConnection, URL}
import java.nio.charset.StandardCharsets
import java.util.Date

import scala.collection.mutable.HashMap

import org.mockito.Mockito.{mock, times, verify, when}
import org.scalatest.BeforeAndAfterAll

import org.apache.spark.{SecurityManager, SparkConf, SparkFunSuite}
import org.apache.spark.deploy.DeployMessages.{KillDriverResponse, RequestKillDriver}
import org.apache.spark.deploy.DeployTestUtils._
import org.apache.spark.deploy.master._
import org.apache.spark.rpc.{RpcEndpointRef, RpcEnv}

class MasterWebUISuite extends SparkFunSuite with BeforeAndAfterAll {

  val conf = new SparkConf
  val securityMgr = new SecurityManager(conf)
  val rpcEnv = mock(classOf[RpcEnv])
  val master = mock(classOf[Master])
  val masterEndpointRef = mock(classOf[RpcEndpointRef])
  when(master.securityMgr).thenReturn(securityMgr)
  when(master.conf).thenReturn(conf)
  when(master.rpcEnv).thenReturn(rpcEnv)
  when(master.self).thenReturn(masterEndpointRef)
  val masterWebUI = new MasterWebUI(master, 0)

  override def beforeAll() {
    super.beforeAll()
    masterWebUI.bind()
  }

  override def afterAll() {
    try {
      masterWebUI.stop()
    } finally {
      super.afterAll()
    }
  }

  test("kill application") {
    val appDesc = createAppDesc()
    // use new start date so it isn't filtered by UI
    val activeApp = new ApplicationInfo(
      new Date().getTime, "app-0", appDesc, new Date(), null, Int.MaxValue)

    when(master.idToApp).thenReturn(HashMap[String, ApplicationInfo]((activeApp.id, activeApp)))

    val url = s"http://localhost:${masterWebUI.boundPort}/app/kill/"
    val body = convPostDataToString(Map(("id", activeApp.id), ("terminate", "true")))
    val conn = sendHttpRequest(url, "POST", body)
    conn.getResponseCode

    // Verify the master was called to remove the active app
    verify(master, times(1)).removeApplication(activeApp, ApplicationState.KILLED)
  }

  test("kill driver") {
    val activeDriverId = "driver-0"
    val url = s"http://localhost:${masterWebUI.boundPort}/driver/kill/"
    val body = convPostDataToString(Map(("id", activeDriverId), ("terminate", "true")))
    val conn = sendHttpRequest(url, "POST", body)
    conn.getResponseCode

    // Verify that master was asked to kill driver with the correct id
    verify(masterEndpointRef, times(1)).ask[KillDriverResponse](RequestKillDriver(activeDriverId))
  }

  private def convPostDataToString(data: Map[String, String]): String = {
    (for ((name, value) <- data) yield s"$name=$value").mkString("&")
  }

  /**
   * Send an HTTP request to the given URL using the method and the body specified.
   * Return the connection object.
   */
  private def sendHttpRequest(
      url: String,
      method: String,
      body: String = ""): HttpURLConnection = {
    val conn = new URL(url).openConnection().asInstanceOf[HttpURLConnection]
    conn.setRequestMethod(method)
    if (body.nonEmpty) {
      conn.setDoOutput(true)
      conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
      conn.setRequestProperty("Content-Length", Integer.toString(body.length))
      val out = new DataOutputStream(conn.getOutputStream)
      out.write(body.getBytes(StandardCharsets.UTF_8))
      out.close()
    }
    conn
  }
}


text:
#ifndef __CACHE_HANDLING_H__
#define __CACHE_HANDLING_H__

#include <ti/sysbios/hal/Cache.h>

const xdc_Bool CACHE_BLOCKING=TRUE;
const xdc_Bool CACHE_NONBLOCKING=FALSE;

#endif


text:
using DevExpress.XtraEditors;
using System;
using System.Windows.Forms;
using GlobalResources;
using Visa.BusinessLogic.Managers;

namespace Visa.WinForms.ErrorProvider
{
    public sealed partial class ExceptionHandlerForm : XtraForm
    {
        public ExceptionHandlerForm()
        {
            InitializeComponent();
            FormBorderStyle = FormBorderStyle.FixedSingle;
            if (DesignMode)
                return;
            Text = ResManager.GetString(ResKeys.ExceptionHanler_Title);
            textBox2.Text =
                ResManager.GetString(ResKeys.ExceptionHanler_Text);
        }

        public string StackTrace
        {
            get { return textBox1.Text; }
            set { textBox1.Text = value; }
        }

        public static void ShowException(Exception ex)
        {
            var form = new ExceptionHandlerForm
            {
                StackTrace = ex.Message + ex.StackTrace
            };
            form.ShowDialog();

            var sendMailResult =
               EmailManager.SendErrorMail(ex); //sending mail message
            MessageBox.Show(sendMailResult, "Sending e-mail result:");
        }

        private void simpleButton1_Click(object sender,
            EventArgs e)
        {
            Close();
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Chen & Wei, Journal of Guangxi Agricultural University 12(1): 34 (1993)

#### Original name
Pestalotia siliquastri Thüm.

### Remarks
null


text:
/*
 * QuotesItemProvider.cpp
 *
 *  Created on: Oct 15, 2014
 *      Author: SuhairZain
 */

#include <src/MVC/QuotesItemProvider.h>

#include <bb/cascades/Container>
#include <bb/cascades/controls/labelautosizeproperties.h>

QuotesItem::QuotesItem(Color color)
{
    name = Label::create().
            maxLineCount(2).
            multiline(TRUE);
    //name->autoSize()->setMaxLineCount(3);
    name->textStyle()->setColor(Color::Black);
    name->textStyle()->setFontSize(FontSize::PointValue);
    name->textStyle()->setFontSizeValue(10);
    name->textStyle()->setFontWeight(FontWeight::W100);

    Container *rootC = Container::create().
            //horizontal(HorizontalAlignment::Fill).
            left(6).
            top(6).
            right(6).
            bottom(6).
            preferredWidth(1440).
            background(color).
            add(name);

    setRoot(rootC);
    //setHorizontalAlignment(HorizontalAlignment::Fill);
    setBottomMargin(6);
}

void QuotesItem::activate(bool activate)
{
    // There is no special activate state, select and activated looks the same.
    /*if(activate)
    {
        borderContainer->setVisible(TRUE);
    }
    else
    {
        borderContainer->setVisible(FALSE);
    }*/
    select(activate);
}

void QuotesItem::reset(bool selected, bool activated)
{
    Q_UNUSED(activated);

    // Since items are recycled the reset function is where we have
    // to make sure that item state, defined by the arguments, is correct.
    select(selected);
}

void QuotesItem::select(bool /*select*/)
{
}

void QuotesItem::updateItem(const QString nameString)
{
    name->setText(nameString);
}

VisualNode * QuotesItemProvider::createItem(ListView*/* list*/, const QString &/*type*/)
{
    //We only have one item type so we do not need to check the type variable.
    QuotesItem *myItem = new QuotesItem(itemColor);
    return myItem;
}

void QuotesItemProvider::updateItem(ListView*, bb::cascades::VisualNode *listItem,
        const QString &, const QVariantList &, const QVariant &data)
{
    /*Q_UNUSED(list);
    Q_UNUSED(type);
    Q_UNUSED(indexPath);*/

    // Update the control with correct data.
    QString word = data.toMap()["quote"].toString();
    static_cast<QuotesItem *>(listItem)->updateItem(word);
}


text:
\documentclass[12pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[russian]{babel}
\usepackage[T2A]{fontenc}
\usepackage[top=2cm,right=2cm,left=2cm,bottom=2cm]{geometry}

\begin{document}
\title{Теоретический минимум по оптимизации}
\author{}
\date{}

\maketitle
\thispagestyle{empty}
\vspace{-2cm}
\begin{enumerate}
\item Концепция численных методов оптимизации: скорость сходимости и критерии остановки
\item Градиентный спуск: схема метода, скорость сходимости, теоремы сходимости
\item Правила выбора шага
\item Метод Ньютона: схема метода, скорость сходимости, теоремы сходимости. Концепция квазиньютоновских методов
\item Метод сопряжённых градиентов: схема метода, скорость сходимости, теоремы сходимости. Случаи квадратичной и произвольной функции: чем похожи и чем отличаются схемы метода.
\item Задача линейного программирования: формы записи и их эквивалентность, симплекс-метод и его табличная реализация. Способы выбора начальной точки.
\item Методы проекции градиента и условного градиента: схема метода, скорость сходимости, теоремы сходимости
\item Концепция методов внутренней точки. Барьерные методы. Центральный путь и его свойства.
\item Концепция методов штрафов и модифицированной функции Лагранжа.

\end{enumerate}
\end{document}


text:
package pl.olszak.michal.detector.core.database;

import com.mongodb.WriteResult;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import pl.olszak.michal.detector.model.data.Color;
import pl.olszak.michal.detector.model.data.ColorProbability;
import pl.olszak.michal.detector.model.data.RocDataSet;
import pl.olszak.michal.detector.model.data.RocModel;
import pl.olszak.michal.detector.utils.ColorReduce;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author molszak
 *         created on 30.06.2017.
 */
public class DatabaseFacade {

    private MongoOperations mongo;

    public DatabaseFacade(MongoOperations mongo) {
        this.mongo = mongo;
    }

    private static Criteria createCriteriaColorProbability(Color color, ColorReduce reduce) {
        return new Criteria("color").is(color).and("colorMode").is(reduce.getValue());
    }

    private static Criteria createCriteriaRocModel(ColorReduce reduce) {
        return new Criteria("colorMode").is(reduce.getValue());
    }

    private static Criteria createCriteriaRocModel(String name, ColorReduce colorMode) {
        return new Criteria("name").is(name).and("colorMode").is(colorMode);
    }

    public boolean probabilityExists(Color color, ColorReduce reduce) {
        final Criteria criteria = createCriteriaColorProbability(color, reduce);
        return mongo.exists(new Query(criteria), ColorProbability.class);
    }

    public boolean rocExists(String name, ColorReduce colorMode) {
        final Criteria criteria = createCriteriaRocModel(name, colorMode);
        return mongo.exists(new Query(criteria), RocModel.class);
    }

    public Optional<ColorProbability> retrieve(Color color, ColorReduce reduce) {
        final Criteria criteria = createCriteriaColorProbability(color, reduce);
        ColorProbability probability = mongo.findOne(new Query(criteria), ColorProbability.class);
        return Optional.ofNullable(probability);
    }

    /**
     * Inserts an colorProbability to collection named "probabilityMap",
     * does not care for uniqueness of data, so it's advised to check data using {@link #probabilityExists(Color, ColorReduce)}
     *
     * @param colorProbability probability that should be inserted into database
     */
    public void insert(ColorProbability colorProbability) {
        mongo.insert(colorProbability);
    }

    /**
     * Inserts data set to collection named "roc", does care about uniqueness of name field
     *
     * @param model model to be inserted into collection
     */
    public void insert(RocModel model){
        mongo.insert(model);
    }

    public Optional<RocDataSet> retrieveSingle(String name) {
        RocDataSet set = mongo.findById(name, RocDataSet.class);
        return Optional.ofNullable(set);
    }

    public List<RocDataSet> retrieveAll() {
        List<RocDataSet> dataSets = new ArrayList<>();
        dataSets.addAll(mongo.findAll(RocDataSet.class));
        return dataSets;
    }

    public List<RocDataSet> retrieveByColorReduction(ColorReduce reduce) {
        List<RocDataSet> dataSets = new ArrayList<>();
        final Criteria criteria = createCriteriaRocModel(reduce);
        dataSets.addAll(mongo.find(new Query(criteria), RocDataSet.class));
        return dataSets;
    }

    public boolean removeRoc(String name, ColorReduce colorMode) {
        if (rocExists(name, colorMode)) {
            WriteResult result = mongo.remove(new Query(createCriteriaRocModel(name, colorMode)), RocDataSet.class);
            if (result.getN() == 1) {
                return true;
            }
        }
        return false;
    }

    public boolean probabilityDatabaseExists() {
        return mongo.collectionExists(ColorProbability.class);
    }

}


text:
/**

 The iTunes tagging seems to support any tag field name
 but there are some predefined fields, also known from the QuickTime format

 predefined fields (the ones I know of until now):
 - ©nam : Name of the song/movie (string)
 - ©ART : Name of the artist/performer (string)
 - ©wrt : Name of the writer (string)
 - ©alb : Name of the album (string)
 - ©day : Year (4 bytes, e.g. "2003") (string)
 - ©too : Tool(s) used to create the file (string)
 - ©cmt : Comment (string)
 - ©gen : Custom genre (string)
 - trkn : Tracknumber (8 byte string)
           16 bit: empty
           16 bit: tracknumber
           16 bit: total tracks on album
           16 bit: empty
 - disk : Disknumber (8 byte string)
           16 bit: empty
           16 bit: disknumber
           16 bit: total number of disks
           16 bit: empty
 - gnre : Genre (16 bit genre) (ID3v1 index + 1)
 - cpil : Part of a compilation (1 byte, 1 or 0)
 - tmpo : Tempo in BPM (16 bit)
 - covr : Cover art (xx bytes binary data)
 - ---- : Free form metadata, can have any name and any data

**/

#include "mp4common.h"

bool MP4File::GetMetadataByIndex(u_int32_t index,
                                 const char** ppName,
                                 u_int8_t** ppValue, u_int32_t* pValueSize)
{
    char s[256];

    sprintf(s, "moov.udta.meta.ilst.*[%u].data.metadata", index);
    GetBytesProperty(s, ppValue, pValueSize);

    sprintf(s, "moov.udta.meta.ilst.*[%u]", index);
    MP4Atom* pParent = m_pRootAtom->FindAtom(s);
    *ppName = pParent->GetType();

    /* check for free form tagfield */
    if (memcmp(*ppName, "----", 4) == 0)
    {
        u_int8_t* pV;
        u_int32_t VSize = 0;
        char *pN;

        sprintf(s, "moov.udta.meta.ilst.*[%u].name.metadata", index);
        GetBytesProperty(s, &pV, &VSize);

        pN = (char*)malloc((VSize+1)*sizeof(char));
        memset(pN, 0, (VSize+1)*sizeof(char));
        memcpy(pN, pV, VSize*sizeof(char));

        *ppName = pN;
    }

    return true;
}

bool MP4File::CreateMetadataAtom(const char* name)
{
    char s[256];
    char t[256];

    sprintf(t, "udta.meta.ilst.%s.data", name);
    sprintf(s, "moov.udta.meta.ilst.%s.data", name);
    AddDescendantAtoms("moov", t);
    MP4Atom *pMetaAtom = m_pRootAtom->FindAtom(s);

    if (!pMetaAtom)
        return false;

    /* some fields need special flags set */
    if ((uint8_t)name[0] == 0251)
    {
        pMetaAtom->SetFlags(0x1);
    } else if ((memcmp(name, "cpil", 4) == 0) || (memcmp(name, "tmpo", 4) == 0)) {
        pMetaAtom->SetFlags(0x15);
    }

    MP4Atom *pHdlrAtom = m_pRootAtom->FindAtom("moov.udta.meta.hdlr");
    MP4StringProperty *pStringProperty = NULL;
    MP4BytesProperty *pBytesProperty = NULL;
    ASSERT(pHdlrAtom);

    pHdlrAtom->FindProperty(
        "hdlr.handlerType", (MP4Property**)&pStringProperty);
    ASSERT(pStringProperty);
    pStringProperty->SetValue("mdir");

    u_int8_t val[12];
    memset(val, 0, 12*sizeof(u_int8_t));
    val[0] = 0x61;
    val[1] = 0x70;
    val[2] = 0x70;
    val[3] = 0x6c;
    pHdlrAtom->FindProperty(
        "hdlr.reserved2", (MP4Property**)&pBytesProperty);
    ASSERT(pBytesProperty);
    pBytesProperty->SetReadOnly(false);
    pBytesProperty->SetValue(val, 12);
    pBytesProperty->SetReadOnly(true);

    return true;
}

bool MP4File::SetMetadataName(const char* value)
{
    const char *s = "moov.udta.meta.ilst.\251nam.data";
    MP4BytesProperty *pMetadataProperty = NULL;
    MP4Atom *pMetaAtom = NULL;

    pMetaAtom = m_pRootAtom->FindAtom(s);

    if (!pMetaAtom)
    {
        if (!CreateMetadataAtom("\251nam"))
            return false;

        pMetaAtom = m_pRootAtom->FindAtom(s);
    }

    pMetaAtom->FindProperty("data.metadata", (MP4Property**)&pMetadataProperty);
    ASSERT(pMetadataProperty);

    pMetadataProperty->SetValue((u_int8_t*)value, strlen(value));

    return true;
}

bool MP4File::GetMetadataName(char** value)
{
    unsigned char *val = NULL;
    u_int32_t valSize = 0;
    const char *s = "moov.udta.meta.ilst.\251nam.data.metadata";
    GetBytesProperty(s, (u_int8_t**)&val, &valSize);

    if (valSize > 0)
    {
        *value = (char*)malloc((valSize+1)*sizeof(unsigned char));
        memset(*value, 0, (valSize+1)*sizeof(unsigned char));
        memcpy(*value, val, valSize*sizeof(unsigned char));
        return true;
    } else {
        *value = NULL;
        return false;
    }
}

bool MP4File::SetMetadataWriter(const char* value)
{
    const char *s = "moov.udta.meta.ilst.\251wrt.data";
    MP4BytesProperty *pMetadataProperty = NULL;
    MP4Atom *pMetaAtom = NULL;

    pMetaAtom = m_pRootAtom->FindAtom(s);

    if (!pMetaAtom)
    {
        if (!CreateMetadataAtom("\251wrt"))
            return false;

        pMetaAtom = m_pRootAtom->FindAtom(s);
    }

    pMetaAtom->FindProperty("data.metadata", (MP4Property**)&pMetadataProperty);
    ASSERT(pMetadataProperty);

    pMetadataProperty->SetValue((u_int8_t*)value, strlen(value));

    return true;
}

bool MP4File::GetMetadataWriter(char** value)
{
    unsigned char *val = NULL;
    u_int32_t valSize = 0;
    const char *s = "moov.udta.meta.ilst.\251wrt.data.metadata";
    GetBytesProperty(s, (u_int8_t**)&val, &valSize);

    if (valSize > 0)
    {
        *value = (char*)malloc((valSize+1)*sizeof(unsigned char));
        memset(*value, 0, (valSize+1)*sizeof(unsigned char));
        memcpy(*value, val, valSize*sizeof(unsigned char));
        return true;
    } else {
        *value = NULL;
        return false;
    }
}

bool MP4File::SetMetadataAlbum(const char* value)
{
    const char *s = "moov.udta.meta.ilst.\251alb.data";
    MP4BytesProperty *pMetadataProperty = NULL;
    MP4Atom *pMetaAtom = NULL;

    pMetaAtom = m_pRootAtom->FindAtom(s);

    if (!pMetaAtom)
    {
        if (!CreateMetadataAtom("\251alb"))
            return false;

        pMetaAtom = m_pRootAtom->FindAtom(s);
    }

    pMetaAtom->FindProperty("data.metadata", (MP4Property**)&pMetadataProperty);
    ASSERT(pMetadataProperty);

    pMetadataProperty->SetValue((u_int8_t*)value, strlen(value));

    return true;
}

bool MP4File::GetMetadataAlbum(char** value)
{
    unsigned char *val = NULL;
    u_int32_t valSize = 0;
    const char *s = "moov.udta.meta.ilst.\251alb.data.metadata";
    GetBytesProperty(s, (u_int8_t**)&val, &valSize);

    if (valSize > 0)
    {
        *value = (char*)malloc((valSize+1)*sizeof(unsigned char));
        memset(*value, 0, (valSize+1)*sizeof(unsigned char));
        memcpy(*value, val, valSize*sizeof(unsigned char));
        return true;
    } else {
        *value = NULL;
        return false;
    }
}

bool MP4File::SetMetadataArtist(const char* value)
{
    const char *s = "moov.udta.meta.ilst.\251ART.data";
    MP4BytesProperty *pMetadataProperty = NULL;
    MP4Atom *pMetaAtom = NULL;

    pMetaAtom = m_pRootAtom->FindAtom(s);

    if (!pMetaAtom)
    {
        if (!CreateMetadataAtom("\251ART"))
            return false;

        pMetaAtom = m_pRootAtom->FindAtom(s);
    }

    pMetaAtom->FindProperty("data.metadata", (MP4Property**)&pMetadataProperty);
    ASSERT(pMetadataProperty);

    pMetadataProperty->SetValue((u_int8_t*)value, strlen(value));

    return true;
}

bool MP4File::GetMetadataArtist(char** value)
{
    unsigned char *val = NULL;
    u_int32_t valSize = 0;
    const char *s = "moov.udta.meta.ilst.\251ART.data.metadata";
    GetBytesProperty(s, (u_int8_t**)&val, &valSize);

    if (valSize > 0)
    {
        *value = (char*)malloc((valSize+1)*sizeof(unsigned char));
        memset(*value, 0, (valSize+1)*sizeof(unsigned char));
        memcpy(*value, val, valSize*sizeof(unsigned char));
        return true;
    } else {
        *value = NULL;
        return false;
    }
}

bool MP4File::SetMetadataTool(const char* value)
{
    const char *s = "moov.udta.meta.ilst.\251too.data";
    MP4BytesProperty *pMetadataProperty = NULL;
    MP4Atom *pMetaAtom = NULL;

    pMetaAtom = m_pRootAtom->FindAtom(s);

    if (!pMetaAtom)
    {
        if (!CreateMetadataAtom("\251too"))
            return false;

        pMetaAtom = m_pRootAtom->FindAtom(s);
    }

    pMetaAtom->FindProperty("data.metadata", (MP4Property**)&pMetadataProperty);
    ASSERT(pMetadataProperty);

    pMetadataProperty->SetValue((u_int8_t*)value, strlen(value));

    return true;
}

bool MP4File::GetMetadataTool(char** value)
{
    unsigned char *val = NULL;
    u_int32_t valSize = 0;
    const char *s = "moov.udta.meta.ilst.\251too.data.metadata";
    GetBytesProperty(s, (u_int8_t**)&val, &valSize);

    if (valSize > 0)
    {
        *value = (char*)malloc((valSize+1)*sizeof(unsigned char));
        memset(*value, 0, (valSize+1)*sizeof(unsigned char));
        memcpy(*value, val, valSize*sizeof(unsigned char));
        return true;
    } else {
        *value = NULL;
        return false;
    }
}

bool MP4File::SetMetadataComment(const char* value)
{
    const char *s = "moov.udta.meta.ilst.\251cmt.data";
    MP4BytesProperty *pMetadataProperty = NULL;
    MP4Atom *pMetaAtom = NULL;

    pMetaAtom = m_pRootAtom->FindAtom(s);

    if (!pMetaAtom)
    {
        if (!CreateMetadataAtom("\251cmt"))
            return false;

        pMetaAtom = m_pRootAtom->FindAtom(s);
    }

    pMetaAtom->FindProperty("data.metadata", (MP4Property**)&pMetadataProperty);
    ASSERT(pMetadataProperty);

    pMetadataProperty->SetValue((u_int8_t*)value, strlen(value));

    return true;
}

bool MP4File::GetMetadataComment(char** value)
{
    unsigned char *val = NULL;
    u_int32_t valSize = 0;
    const char *s = "moov.udta.meta.ilst.\251cmt.data.metadata";
    GetBytesProperty(s, (u_int8_t**)&val, &valSize);

    if (valSize > 0)
    {
        *value = (char*)malloc((valSize+1)*sizeof(unsigned char));
        memset(*value, 0, (valSize+1)*sizeof(unsigned char));
        memcpy(*value, val, valSize*sizeof(unsigned char));
        return true;
    } else {
        *value = NULL;
        return false;
    }
}

bool MP4File::SetMetadataYear(const char* value)
{
    const char *s = "moov.udta.meta.ilst.\251day.data";
    MP4BytesProperty *pMetadataProperty = NULL;
    MP4Atom *pMetaAtom = NULL;

    pMetaAtom = m_pRootAtom->FindAtom(s);

    if (!pMetaAtom)
    {
        if (!CreateMetadataAtom("\251day"))
            return false;

        pMetaAtom = m_pRootAtom->FindAtom(s);
    }

    pMetaAtom->FindProperty("data.metadata", (MP4Property**)&pMetadataProperty);
    ASSERT(pMetadataProperty);

    if (strlen(value) < 4)
        return false;

    pMetadataProperty->SetValue((u_int8_t*)value, 4);

    return true;
}

bool MP4File::GetMetadataYear(char** value)
{
    unsigned char *val = NULL;
    u_int32_t valSize = 0;
    const char *s = "moov.udta.meta.ilst.\251day.data.metadata";
    GetBytesProperty(s, (u_int8_t**)&val, &valSize);

    if (valSize > 0)
    {
        *value = (char*)malloc((valSize+1)*sizeof(unsigned char));
        memset(*value, 0, (valSize+1)*sizeof(unsigned char));
        memcpy(*value, val, valSize*sizeof(unsigned char));
        return true;
    } else {
        *value = NULL;
        return false;
    }
}

bool MP4File::SetMetadataTrack(u_int16_t track, u_int16_t totalTracks)
{
    unsigned char t[9];
    const char *s = "moov.udta.meta.ilst.trkn.data";
    MP4BytesProperty *pMetadataProperty = NULL;
    MP4Atom *pMetaAtom = NULL;

    pMetaAtom = m_pRootAtom->FindAtom(s);

    if (!pMetaAtom)
    {
        if (!CreateMetadataAtom("trkn"))
            return false;

        pMetaAtom = m_pRootAtom->FindAtom(s);
    }

    memset(t, 0, 9*sizeof(unsigned char));
    t[2] = (unsigned char)(track>>8)&0xFF;
    t[3] = (unsigned char)(track)&0xFF;
    t[4] = (unsigned char)(totalTracks>>8)&0xFF;
    t[5] = (unsigned char)(totalTracks)&0xFF;

    pMetaAtom->FindProperty("data.metadata", (MP4Property**)&pMetadataProperty);
    ASSERT(pMetadataProperty);

    pMetadataProperty->SetValue((u_int8_t*)t, 8);

    return true;
}

bool MP4File::GetMetadataTrack(u_int16_t* track, u_int16_t* totalTracks)
{
    unsigned char *val = NULL;
    u_int32_t valSize = 0;
    const char *s = "moov.udta.meta.ilst.trkn.data.metadata";
    GetBytesProperty(s, (u_int8_t**)&val, &valSize);

    *track = 0;
    *totalTracks = 0;

    if (valSize != 8)
        return false;

    *track = (u_int16_t)(val[3]);
    *track += (u_int16_t)(val[2]<<8);
    *totalTracks = (u_int16_t)(val[5]);
    *totalTracks += (u_int16_t)(val[4]<<8);

    return true;
}

bool MP4File::SetMetadataDisk(u_int16_t disk, u_int16_t totalDisks)
{
    unsigned char t[9];
    const char *s = "moov.udta.meta.ilst.disk.data";
    MP4BytesProperty *pMetadataProperty = NULL;
    MP4Atom *pMetaAtom = NULL;

    pMetaAtom = m_pRootAtom->FindAtom(s);

    if (!pMetaAtom)
    {
        if (!CreateMetadataAtom("disk"))
            return false;

        pMetaAtom = m_pRootAtom->FindAtom(s);
    }

    memset(t, 0, 9*sizeof(unsigned char));
    t[2] = (unsigned char)(disk>>8)&0xFF;
    t[3] = (unsigned char)(disk)&0xFF;
    t[4] = (unsigned char)(totalDisks>>8)&0xFF;
    t[5] = (unsigned char)(totalDisks)&0xFF;

    pMetaAtom->FindProperty("data.metadata", (MP4Property**)&pMetadataProperty);
    ASSERT(pMetadataProperty);

    pMetadataProperty->SetValue((u_int8_t*)t, 8);

    return true;
}

bool MP4File::GetMetadataDisk(u_int16_t* disk, u_int16_t* totalDisks)
{
    unsigned char *val = NULL;
    u_int32_t valSize = 0;
    const char *s = "moov.udta.meta.ilst.disk.data.metadata";
    GetBytesProperty(s, (u_int8_t**)&val, &valSize);

    *disk = 0;
    *totalDisks = 0;

    if (valSize != 8)
        return false;

    *disk = (u_int16_t)(val[3]);
    *disk += (u_int16_t)(val[2]<<8);
    *totalDisks = (u_int16_t)(val[5]);
    *totalDisks += (u_int16_t)(val[4]<<8);

    return true;
}

static const char* ID3v1GenreList[] = {
    "Blues", "Classic Rock", "Country", "Dance", "Disco", "Funk",
    "Grunge", "Hip-Hop", "Jazz", "Metal", "New Age", "Oldies",
    "Other", "Pop", "R&B", "Rap", "Reggae", "Rock",
    "Techno", "Industrial", "Alternative", "Ska", "Death Metal", "Pranks",
    "Soundtrack", "Euro-Techno", "Ambient", "Trip-Hop", "Vocal", "Jazz+Funk",
    "Fusion", "Trance", "Classical", "Instrumental", "Acid", "House",
    "Game", "Sound Clip", "Gospel", "Noise", "AlternRock", "Bass",
    "Soul", "Punk", "Space", "Meditative", "Instrumental Pop", "Instrumental Rock",
    "Ethnic", "Gothic", "Darkwave", "Techno-Industrial", "Electronic", "Pop-Folk",
    "Eurodance", "Dream", "Southern Rock", "Comedy", "Cult", "Gangsta",
    "Top 40", "Christian Rap", "Pop/Funk", "Jungle", "Native American", "Cabaret",
    "New Wave", "Psychadelic", "Rave", "Showtunes", "Trailer", "Lo-Fi",
    "Tribal", "Acid Punk", "Acid Jazz", "Polka", "Retro", "Musical",
    "Rock & Roll", "Hard Rock", "Folk", "Folk/Rock", "National Folk", "Swing",
    "Fast-Fusion", "Bebob", "Latin", "Revival", "Celtic", "Bluegrass", "Avantgarde",
    "Gothic Rock", "Progressive Rock", "Psychedelic Rock", "Symphonic Rock", "Slow Rock", "Big Band",
    "Chorus", "Easy Listening", "Acoustic", "Humour", "Speech", "Chanson",
    "Opera", "Chamber Music", "Sonata", "Symphony", "Booty Bass", "Primus",
    "Porn Groove", "Satire", "Slow Jam", "Club", "Tango", "Samba",
    "Folklore", "Ballad", "Power Ballad", "Rhythmic Soul", "Freestyle", "Duet",
    "Punk Rock", "Drum Solo", "A capella", "Euro-House", "Dance Hall",
    "Goa", "Drum & Bass", "Club House", "Hardcore", "Terror",
    "Indie", "BritPop", "NegerPunk", "Polsk Punk", "Beat",
    "Christian Gangsta", "Heavy Metal", "Black Metal", "Crossover", "Contemporary C",
    "Christian Rock", "Merengue", "Salsa", "Thrash Metal", "Anime", "JPop",
    "SynthPop",
};

int GenreToString(char** GenreStr, const int genre)
{
  if (genre > 0 &&
      genre <= (int)(sizeof(ID3v1GenreList)/sizeof(*ID3v1GenreList)))
    {
        *GenreStr = (char*)malloc((strlen(ID3v1GenreList[genre-1])+1)*sizeof(char));
        memset(*GenreStr, 0, (strlen(ID3v1GenreList[genre-1])+1)*sizeof(char));
        strcpy(*GenreStr, ID3v1GenreList[genre-1]);
        return 0;
    } else {
        *GenreStr = (char*)malloc(2*sizeof(char));
        memset(*GenreStr, 0, 2*sizeof(char));
        return 1;
    }
}

int StringToGenre(const char* GenreStr)
{
    unsigned int i;

    for (i = 0; i < sizeof(ID3v1GenreList)/sizeof(*ID3v1GenreList); i++)
    {
        if (strcasecmp(GenreStr, ID3v1GenreList[i]) == 0)
            return i+1;
    }
    return 0;
}

bool MP4File::SetMetadataGenre(const char* value)
{
    u_int16_t genreIndex = 0;
    unsigned char t[3];
    MP4BytesProperty *pMetadataProperty = NULL;
    MP4Atom *pMetaAtom = NULL;

    genreIndex = StringToGenre(value);

    if (genreIndex != 0)
    {
        const char *s = "moov.udta.meta.ilst.gnre.data";
        pMetaAtom = m_pRootAtom->FindAtom(s);

        if (!pMetaAtom)
        {
            if (!CreateMetadataAtom("gnre"))
                return false;

            pMetaAtom = m_pRootAtom->FindAtom(s);
        }

        memset(t, 0, 3*sizeof(unsigned char));
        t[0] = (unsigned char)(genreIndex>>8)&0xFF;
        t[1] = (unsigned char)(genreIndex)&0xFF;

        pMetaAtom->FindProperty("data.metadata", (MP4Property**)&pMetadataProperty);
        ASSERT(pMetadataProperty);

        pMetadataProperty->SetValue((u_int8_t*)t, 2);

        return true;
    } else {
        const char *s2 = "moov.udta.meta.ilst.\251gen.data";
        pMetaAtom = m_pRootAtom->FindAtom(s2);

        if (!pMetaAtom)
        {
            if (!CreateMetadataAtom("\251gen"))
                return false;

            pMetaAtom = m_pRootAtom->FindAtom(s2);
        }

        pMetaAtom->FindProperty("data.metadata", (MP4Property**)&pMetadataProperty);
        ASSERT(pMetadataProperty);

        pMetadataProperty->SetValue((u_int8_t*)value, strlen(value));

        return true;
    }

    return false;
}

bool MP4File::GetMetadataGenre(char** value)
{
    u_int16_t genreIndex = 0;
    unsigned char *val = NULL;
    u_int32_t valSize = 0;
    const char *t = "moov.udta.meta.ilst.gnre";
    const char *s = "moov.udta.meta.ilst.gnre.data.metadata";

    MP4Atom *gnre = FindAtom(t);

    if (gnre)
    {
        GetBytesProperty(s, (u_int8_t**)&val, &valSize);

        if (valSize != 2)
            return false;

        genreIndex = (u_int16_t)(val[1]);
        genreIndex += (u_int16_t)(val[0]<<8);

        GenreToString(value, genreIndex);

        return true;
    } else {
        const char *s2 = "moov.udta.meta.ilst.\251gen.data.metadata";

        val = NULL;
        valSize = 0;

        GetBytesProperty(s2, (u_int8_t**)&val, &valSize);

        if (valSize > 0)
        {
            *value = (char*)malloc((valSize+1)*sizeof(unsigned char));
            memset(*value, 0, (valSize+1)*sizeof(unsigned char));
            memcpy(*value, val, valSize*sizeof(unsigned char));
            return true;
        } else {
            *value = NULL;
            return false;
        }
    }

    return false;
}

bool MP4File::SetMetadataTempo(u_int16_t tempo)
{
    unsigned char t[3];
    const char *s = "moov.udta.meta.ilst.tmpo.data";
    MP4BytesProperty *pMetadataProperty = NULL;
    MP4Atom *pMetaAtom = NULL;

    pMetaAtom = m_pRootAtom->FindAtom(s);

    if (!pMetaAtom)
    {
        if (!CreateMetadataAtom("tmpo"))
            return false;

        pMetaAtom = m_pRootAtom->FindAtom(s);
    }

    memset(t, 0, 3*sizeof(unsigned char));
    t[0] = (unsigned char)(tempo>>8)&0xFF;
    t[1] = (unsigned char)(tempo)&0xFF;

    pMetaAtom->FindProperty("data.metadata", (MP4Property**)&pMetadataProperty);
    ASSERT(pMetadataProperty);

    pMetadataProperty->SetValue((u_int8_t*)t, 2);

    return true;
}

bool MP4File::GetMetadataTempo(u_int16_t* tempo)
{
    unsigned char *val = NULL;
    u_int32_t valSize = 0;
    const char *s = "moov.udta.meta.ilst.tmpo.data.metadata";
    GetBytesProperty(s, (u_int8_t**)&val, &valSize);

    *tempo = 0;

    if (valSize != 2)
        return false;

    *tempo = (u_int16_t)(val[1]);
    *tempo += (u_int16_t)(val[0]<<8);

    return true;
}

bool MP4File::SetMetadataCompilation(u_int8_t compilation)
{
    const char *s = "moov.udta.meta.ilst.cpil.data";
    MP4BytesProperty *pMetadataProperty = NULL;
    MP4Atom *pMetaAtom = NULL;

    pMetaAtom = m_pRootAtom->FindAtom(s);

    if (!pMetaAtom)
    {
        if (!CreateMetadataAtom("cpil"))
            return false;

        pMetaAtom = m_pRootAtom->FindAtom(s);
    }

    pMetaAtom->FindProperty("data.metadata", (MP4Property**)&pMetadataProperty);
    ASSERT(pMetadataProperty);

    compilation &= 0x1;
    pMetadataProperty->SetValue((u_int8_t*)&compilation, 1);

    return true;
}

bool MP4File::GetMetadataCompilation(u_int8_t* compilation)
{
    unsigned char *val = NULL;
    u_int32_t valSize = 0;
    const char *s = "moov.udta.meta.ilst.cpil.data.metadata";
    GetBytesProperty(s, (u_int8_t**)&val, &valSize);

    *compilation = 0;

    if (valSize != 1)
        return false;

    *compilation = (u_int16_t)(val[0]);

    return true;
}

bool MP4File::SetMetadataCoverArt(u_int8_t *coverArt, u_int32_t size)
{
    const char *s = "moov.udta.meta.ilst.covr.data";
    MP4BytesProperty *pMetadataProperty = NULL;
    MP4Atom *pMetaAtom = NULL;

    pMetaAtom = m_pRootAtom->FindAtom(s);

    if (!pMetaAtom)
    {
        if (!CreateMetadataAtom("covr"))
            return false;

        pMetaAtom = m_pRootAtom->FindAtom(s);
    }

    pMetaAtom->FindProperty("data.metadata", (MP4Property**)&pMetadataProperty);
    ASSERT(pMetadataProperty);

    pMetadataProperty->SetValue(coverArt, size);

    return true;
}

bool MP4File::GetMetadataCoverArt(u_int8_t **coverArt, u_int32_t *size)
{
    const char *s = "moov.udta.meta.ilst.covr.data.metadata";
    GetBytesProperty(s, coverArt, size);

    if (size == 0)
        return false;

    return true;
}

bool MP4File::SetMetadataFreeForm(char *name, u_int8_t* pValue, u_int32_t valueSize)
{
    MP4Atom *pMetaAtom = NULL;
    MP4BytesProperty *pMetadataProperty = NULL;
    char s[256];
    int i = 0;

    while (1)
    {
        MP4BytesProperty *pMetadataProperty;

        sprintf(s, "moov.udta.meta.ilst.----[%u].name", i);

        MP4Atom *pTagAtom = m_pRootAtom->FindAtom(s);

        if (!pTagAtom)
            break;

        pTagAtom->FindProperty("name.metadata", (MP4Property**)&pMetadataProperty);
        if (pMetadataProperty)
        {
            u_int8_t* pV;
            u_int32_t VSize = 0;

            pMetadataProperty->GetValue(&pV, &VSize);

            if (VSize != 0)
            {
                if (memcmp(pV, name, VSize) == 0)
                {
                    sprintf(s, "moov.udta.meta.ilst.----[%u].data.metadata", i);
                    SetBytesProperty(s, pValue, valueSize);

                    return true;
                }
            }
        }

        i++;
    }

    /* doesn't exist yet, create it */
    char t[256];

    sprintf(t, "udta.meta.ilst.----[%u]", i);
    sprintf(s, "moov.udta.meta.ilst.----[%u].data", i);
    AddDescendantAtoms("moov", t);

    pMetaAtom = m_pRootAtom->FindAtom(s);

    if (!pMetaAtom)
        return false;

    pMetaAtom->SetFlags(0x1);

    MP4Atom *pHdlrAtom = m_pRootAtom->FindAtom("moov.udta.meta.hdlr");
    MP4StringProperty *pStringProperty = NULL;
    MP4BytesProperty *pBytesProperty = NULL;
    ASSERT(pHdlrAtom);

    pHdlrAtom->FindProperty(
        "hdlr.handlerType", (MP4Property**)&pStringProperty);
    ASSERT(pStringProperty);
    pStringProperty->SetValue("mdir");

    u_int8_t val[12];
    memset(val, 0, 12*sizeof(u_int8_t));
    val[0] = 0x61;
    val[1] = 0x70;
    val[2] = 0x70;
    val[3] = 0x6c;
    pHdlrAtom->FindProperty(
        "hdlr.reserved2", (MP4Property**)&pBytesProperty);
    ASSERT(pBytesProperty);
    pBytesProperty->SetReadOnly(false);
    pBytesProperty->SetValue(val, 12);
    pBytesProperty->SetReadOnly(true);

    pMetaAtom = m_pRootAtom->FindAtom(s);
    pMetaAtom->FindProperty("data.metadata", (MP4Property**)&pMetadataProperty);
    ASSERT(pMetadataProperty);
    pMetadataProperty->SetValue(pValue, valueSize);

    sprintf(s, "moov.udta.meta.ilst.----[%u].name", i);
    pMetaAtom = m_pRootAtom->FindAtom(s);
    pMetaAtom->FindProperty("name.metadata", (MP4Property**)&pMetadataProperty);
    ASSERT(pMetadataProperty);
    pMetadataProperty->SetValue((u_int8_t*)name, strlen(name));

    sprintf(s, "moov.udta.meta.ilst.----[%u].mean", i);
    pMetaAtom = m_pRootAtom->FindAtom(s);
    pMetaAtom->FindProperty("mean.metadata", (MP4Property**)&pMetadataProperty);
    ASSERT(pMetadataProperty);
    pMetadataProperty->SetValue((u_int8_t*)"com.apple.iTunes", 16); /* ?? */

    return true;
}

bool MP4File::GetMetadataFreeForm(char *name, u_int8_t** ppValue, u_int32_t *pValueSize)
{
    char s[256];
    int i = 0;

    while (1)
    {
        MP4BytesProperty *pMetadataProperty;

        sprintf(s, "moov.udta.meta.ilst.----[%u].name", i);

        MP4Atom *pTagAtom = m_pRootAtom->FindAtom(s);

        if (!pTagAtom)
            return false;

        pTagAtom->FindProperty("name.metadata", (MP4Property**)&pMetadataProperty);
        if (pMetadataProperty)
        {
            u_int8_t* pV;
            u_int32_t VSize = 0;

            pMetadataProperty->GetValue(&pV, &VSize);

            if (VSize != 0)
            {
                if (memcmp(pV, name, VSize) == 0)
                {
                    sprintf(s, "moov.udta.meta.ilst.----[%u].data.metadata", i);
                    GetBytesProperty(s, ppValue, pValueSize);

                    return true;
                }
            }
        }

        i++;
    }
}

bool MP4File::MetadataDelete()
{
    MP4Atom *pMetaAtom = NULL;
    char s[256];

    sprintf(s, "moov.udta.meta");
    pMetaAtom = m_pRootAtom->FindAtom(s);

    /* if it exists, delete it */
    if (pMetaAtom)
    {
        MP4Atom *pParent = pMetaAtom->GetParentAtom();

        pParent->DeleteChildAtom(pMetaAtom);

        delete pMetaAtom;

        return true;
    }

    return false;
}


text:
package com.gauravbytes.springbeanscope;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Gaurav Rai Mazra
 * Catch me
 */
public class Dictionary {
	private List<String> words;
	public Dictionary() {
		words = new ArrayList<>();
	}

	public void addWord(String word) {
		this.words.add(word);
	}

	public int totalWords() {
		return this.words.size();
	}

	@Override
	public String toString() {
		return words.toString();
	}
}


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Item from './Item';
import { fetchVipCategory, fetchNews, addVipCategory } from'../../App/AppActions';
import { getPageHeader } from'../../App/AppReducer';
import CircularProgress from 'material-ui/CircularProgress';
import styles from '../../../main.css';
import grid from '../../../grid.css';
import { Pagination } from 'react-bootstrap';
import { setCurrentPage } from '../HomeActions';
import { getNewsList, getLoading, getNewsVipList, getCurrentPage, getMaxPage } from '../HomeReducer';

class List extends Component {
  constructor(props) {
    super(props);
    this.state = {
    }
  }

  handleSelect = (eventKey) => {
    this.props.dispatch(setCurrentPage(eventKey));
  };
  render() {
    return (

        <div className={`col-md-12 col-xs-12 ${styles.listHeader}`} style={{ paddingLeft: '0', paddingTop: '0', fontSize: '11pt', fontWeight: 'bold', paddingBottom: '20px' }}>
          {this.props.pageHeader}

          {
            (this.props.newsVipList.length > 0 ) ? (
              this.props.newsVipList.map((info, index) => (
                <div className={grid.itemList} key={`${index}VipCate`}>
                  <Item info={info} />

              ))
            ) : ''
          }
          {
            this.props.newsList.map((info, index) => (
              <div className={grid.itemList} key={`${index}VipCate`}>
                <Item info={info} />

            ))
          }

          <Pagination
            bsSize="small"
            first
            last
            ellipsis
            boundaryLinks
            items={this.props.maxPage}
            maxButtons={5}
            activePage={this.props.currentPage}
            onSelect={this.handleSelect}
            style={{
              display: 'table',
              margin: 'auto'
            }}
          />

    );
  }
}

// Retrieve data from store as props
function mapStateToProps(state) {
  return {
    newsList: getNewsList(state),
    newsVipList: getNewsVipList(state),
    loading: getLoading(state),
    pageHeader: getPageHeader(state),
    currentPage: getCurrentPage(state),
    maxPage: getMaxPage(state),
  };
}

List.propTypes = {
  dispatch: PropTypes.func.isRequired,
  newsList: PropTypes.array.isRequired,
  newsVipList: PropTypes.array.isRequired,
  loading: PropTypes.bool.isRequired,
  pageHeader: PropTypes.string.isRequired,
  currentPage: PropTypes.number.isRequired,
  maxPage: PropTypes.number.isRequired,
};

List.contextTypes = {
  router: PropTypes.object,
};

export default connect(mapStateToProps)(List);


text:
import sys
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
from requests.auth import HTTPBasicAuth

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

CONNECTIONS_HOST = 'https://connections.<company>.com'
CONNECTIONS_USERNAME = '<REPLACE_HERE>'
CONNECTIONS_PASSWORD = '<REPLACE_HERE>'

wiki_id_or_label = 'W34c618febb3c_4a55_81b7_0d5a81dc1954';

xml_data = ''
xml_data += '<entry xmlns="http://www.w3.org/2005/Atom">'
xml_data += '<title type="text">My First Wiki Python</title>'
xml_data += '<content type="text/html">'
xml_data += '<![CDATA[<?xml version="1.0" encoding="UTF-8"?>
'
xml_data += 'Hello World!'
xml_data += '
]]>'
xml_data += '</content>'
xml_data += '<category term="wikipagetag1" />'
xml_data += '<category term="wikipagetag2" />'
xml_data += 'category scheme="tag:ibm.com,2006:td/type" term="page" label="page" />'
xml_data += '</entry>'

xml_data2 = '''
<entry xmlns="http://www.w3.org/2005/Atom">
<title type="text">My First Wiki Python 2</title>
<content type="text/html">
<![CDATA[<?xml version="1.0" encoding="UTF-8"?>

Hello World!

]]>
</content>
<category term="wikipagetag1" />
<category term="wikipagetag2" />
category scheme="tag:ibm.com,2006:td/type" term="page" label="page" />
</entry>
'''

def createWikiPage(wiki_id_or_label, xml_data):

    headers = { 'Content-Type': 'application/atom+xml;charset=UTF-8'}

    url = CONNECTIONS_HOST + '/wikis/basic/api/wiki/' + wiki_id_or_label  + '/feed'
    auth=HTTPBasicAuth(CONNECTIONS_USERNAME, CONNECTIONS_PASSWORD)

    res = requests.post(url=url,headers=headers,auth=auth,verify=False,data=xml_data)
    if (res.status_code != 200):
        print 'doGetToneAnalyze: requests.post -> %s = %s\n' % (res.url, res)
        print res.content
        return None;

    return res.json()

#################### Main Module ###################
print 'Connecting to IBM Connections...\n'

print 'Creating Wiki Page...\n'
createWikiPage(wiki_id_or_label,xml_data)
createWikiPage(wiki_id_or_label,xml_data2)


text:
var path = require('path');
var fs = require('fs');

// Make sure any symlinks in the project folder are resolved:
// https://github.com/facebookincubator/create-react-app/issues/637
var appDirectory = fs.realpathSync(process.cwd());
function resolveApp(relativePath) {
  return path.resolve(appDirectory, relativePath);
}

// We support resolving modules according to `NODE_PATH`.
// This lets you use absolute paths in imports inside large monorepos:
// https://github.com/facebookincubator/create-react-app/issues/253.

// It works similar to `NODE_PATH` in Node itself:
// https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders

// We will export `nodePaths` as an array of absolute paths.
// It will then be used by Webpack configs.
// Jest doesn't need this because it already handles `NODE_PATH` out of the box.
var nodePaths = (process.env.NODE_PATH || '')
  .split(process.platform === 'win32' ? ';' : ':')
  .filter(Boolean)
  .map(resolveApp);

// config after eject: we're in ./utils/
module.exports = {
  appBuild: resolveApp('dist'),
  appPublic: resolveApp('public'),
  appHtml: resolveApp('public/index.html'),
  appIndexJs: resolveApp('src/index.js'),
  appPackageJson: resolveApp('package.json'),
  appSrc: resolveApp('src'),
  yarnLockFile: resolveApp('yarn.lock'),
  testsSetup: resolveApp('src/setupTests.js'),
  appNodeModules: resolveApp('node_modules'),
  ownNodeModules: resolveApp('node_modules'),
  nodePaths: nodePaths
};

function resolveOwn(relativePath) {
  return path.resolve(__dirname, relativePath);
}

// config before eject: we're in ./node_modules/react-scripts/utils/
module.exports = {
  appBuild: resolveApp('dist'),
  appPublic: resolveApp('public'),
  appHtml: resolveApp('public/index.html'),
  appIndexJs: resolveApp('src/index.js'),
  appPackageJson: resolveApp('package.json'),
  appSrc: resolveApp('src'),
  yarnLockFile: resolveApp('yarn.lock'),
  testsSetup: resolveApp('src/setupTests.js'),
  appNodeModules: resolveApp('node_modules'),
  // this is empty with npm3 but node resolution searches higher anyway:
  ownNodeModules: resolveOwn('../node_modules'),
  nodePaths: nodePaths
};


text:
package org.marketcetera.module;

import org.marketcetera.util.misc.ClassVersion;

import java.io.Serializable;
import java.beans.ConstructorProperties;

/* $License$ */
/**
 * Instances of this class describe the state of a module in a data flow.
 *
 * @author anshul@marketcetera.com
 * @version $Id: DataFlowStep.java 16154 2012-07-14 16:34:05Z colin $
 * @since 1.0.0
 */
@ClassVersion("$Id: DataFlowStep.java 16154 2012-07-14 16:34:05Z colin $")  //$NON-NLS-1$
public final class DataFlowStep implements Serializable {
    /**
     * The data request associated with this flow step.
     *
     * @return the data request.
     */
    public StringDataRequest getRequest() {
        return mRequest;
    }

    /**
     * The instance URN of the module in this flow step
     *
     * @return the module URN
     */
    public ModuleURN getModuleURN() {
        return mModuleURN;
    }

    /**
     * If this module is participating as a data emitter
     *
     * @return true if this module is emitting data in this data flow.
     */
    public boolean isEmitter() {
        return mEmitter;
    }

    /**
     * If this module is participating as a data receiver
     *
     * @return true if this module is receiving data in this data flow.
     */
    public boolean isReceiver() {
        return mReceiver;
    }

    /**
     * Number of data objects emitted. This value is valid only if
     * {@link #isEmitter()} is true.
     *
     * @return number of data objects emitted.
     */
    public long getNumEmitted() {
        return mNumEmitted;
    }

    /**
     * Number of data objects received. This value is valid only if
     * {@link #isReceiver()} is true.
     *
     * @return number of data objects received.
     */
    public long getNumReceived() {
        return mNumReceived;
    }

    /**
     * Returns the number of errors encountered on this data flow step
     * when receiving data. This value is valid only if {@link #isReceiver()}
     * is true.
     *
     * Zero, if no errors have been encountered so far.
     *
     * @return the number of errors encountered when receiving data.
     */
    public long getNumReceiveErrors() {
        return mNumReceiveErrors;
    }

    /**
     * Returns a non-null value explaining the last error that was
     * encountered while receiving data in this flow step.
     * This value is valid only if {@link #isReceiver()} is true.
     *
     * @return a non-null value explaining the last error encountered
     * while receiving data. Null, if there have no errors so far.
     */
    public String getLastReceiveError() {
        return mLastReceiveError;
    }

    /**
     * Returns the number of data emit errors encountered by this module
     * when emitting data.
     *
     * This value is valid only if {@link #isEmitter()} is true.
     *
     * @return the number of data emit errors encountered when emitting
     * data. zero, if no errors have been encountered so far.
     *
     * @see DataEmitterSupport#dataEmitError(org.marketcetera.util.log.I18NBoundMessage, boolean)
     */
    public long getNumEmitErrors() {
        return mNumEmitErrors;
    }

    /**
     * Returns the last data emit error encountered by this module.
     *
     * This value is valid only if {@link #isEmitter()} is true.
     *
     * @return the last data emit error encountered by this module, null if
     * no errors have been encountered so far.
     */
    public String getLastEmitError() {
        return mLastEmitError;
    }

    /**
     * Creates an instance.
     *
     * @param inRequest The original data request
     * @param inModuleURN the module instance URN
     * @param inEmitter if this module is emitting data in this data flow
     * @param inReceiver if this module is receiving data in this data flow
     * @param inNumEmitted number of data objects emitted
     * @param inNumReceived number of data objects received
     * @param inNumEmitErrors number of errors encountered when emitting
     * data.
     * @param inNumReceiveErrors number of errors encountered when
     * receiving data
     * @param inLastEmitError last error encountered when emitting data.
     * @param inLastReceiveError last error encountered when receiving data
     */
    @ConstructorProperties({
            "request",          //$NON-NLS-1$
            "moduleURN",        //$NON-NLS-1$
            "emitter",          //$NON-NLS-1$
            "receiver",         //$NON-NLS-1$
            "numEmitted",       //$NON-NLS-1$
            "numReceived",      //$NON-NLS-1$
            "numEmitErrors",    //$NON-NLS-1$
            "numReceiveErrors", //$NON-NLS-1$
            "lastEmitError",    //$NON-NLS-1$
            "lastReceiveError"  //$NON-NLS-1$
            })
    public DataFlowStep(StringDataRequest inRequest,
                        ModuleURN inModuleURN,
                        boolean inEmitter,
                        boolean inReceiver,
                        long inNumEmitted,
                        long inNumReceived,
                        long inNumEmitErrors,
                        long inNumReceiveErrors,
                        String inLastEmitError,
                        String inLastReceiveError) {
        mRequest = inRequest;
        mModuleURN = inModuleURN;
        mEmitter = inEmitter;
        mReceiver = inReceiver;
        mNumEmitted = inNumEmitted;
        mNumReceived = inNumReceived;
        mNumEmitErrors = inNumEmitErrors;
        mNumReceiveErrors = inNumReceiveErrors;
        mLastEmitError = inLastEmitError;
        mLastReceiveError = inLastReceiveError;
    }

    private final StringDataRequest mRequest;
    private final ModuleURN mModuleURN;
    private final boolean mEmitter;
    private final boolean mReceiver;
    private final long mNumEmitted;
    private final long mNumReceived;
    private final long mNumEmitErrors;
    private final long mNumReceiveErrors;
    private final String mLastEmitError;
    private final String mLastReceiveError;
    private static final long serialVersionUID = 2259786776527863195L;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DecouplingDesignPatterns.Patterns
{
    class Composite
    {
    }
}