text:
<?xml version="1.0" encoding="UTF-8"?>
<Form xmlns="http://v8.1c.ru/8.3/xcf/logform" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:dcscor="http://v8.1c.ru/8.1/data-composition-system/core" xmlns:dcsset="http://v8.1c.ru/8.1/data-composition-system/settings" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.12">
	<Title>
		<v8:item>
			<v8:lang>ru</v8:lang>
			<v8:content>Настройка рабочего каталога</v8:content>
		</v8:item>
	</Title>
	<WindowOpeningMode>LockOwnerWindow</WindowOpeningMode>
	<AutoTitle>false</AutoTitle>
	<Customizable>false</Customizable>
	<CommandBarLocation>Bottom</CommandBarLocation>
	<AutoCommandBar name="ФормаКоманднаяПанель" id="-1">
		<HorizontalAlign>Right</HorizontalAlign>
		<ChildItems>
			<Button name="Закрыть" id="21">
				<Type>CommandBarButton</Type>
				<Representation>Text</Representation>
				<DefaultButton>true</DefaultButton>
				<SkipOnInput>false</SkipOnInput>
				<CommandName>Form.StandardCommand.Close</CommandName>
				<ExtendedTooltip name="ЗакрытьРасширеннаяПодсказка" id="28"/>
			</Button>
		</ChildItems>
	</AutoCommandBar>
	<Events>
		<Event name="OnOpen">ПриОткрытии</Event>
		<Event name="OnCreateAtServer">ПриСозданииНаСервере</Event>
	</Events>
	<ChildItems>
		<UsualGroup name="ГруппаРасположение" id="26">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Расположение</v8:content>
				</v8:item>
			</Title>
			<Group>AlwaysHorizontal</Group>
			<Representation>None</Representation>
			<ShowTitle>false</ShowTitle>
			<ExtendedTooltip name="ГруппаРасположениеExtendedTooltip" id="30"/>
			<ChildItems>
				<InputField name="РабочийКаталогПользователя" id="4">
					<DataPath>РабочийКаталогПользователя</DataPath>
					<Title>
						<v8:item>
							<v8:lang>ru</v8:lang>
							<v8:content>Расположение</v8:content>
						</v8:item>
					</Title>
					<FooterHorizontalAlign>Left</FooterHorizontalAlign>
					<Width>48</Width>
					<Wrap>false</Wrap>
					<ChoiceButton>true</ChoiceButton>
					<TextEdit>false</TextEdit>
					<BorderColor>style:BorderColor</BorderColor>
					<ContextMenu name="РабочийКаталогПользователяКонтекстноеМеню" id="5"/>
					<ExtendedTooltip name="РабочийКаталогПользователяExtendedTooltip" id="31"/>
					<Events>
						<Event name="StartChoice">РабочийКаталогПользователяНачалоВыбора</Event>
					</Events>
				</InputField>
				<Button name="ПутьКРабочемуКаталогуПоУмолчанию" id="27">
					<Type>UsualButton</Type>
					<SkipOnInput>false</SkipOnInput>
					<CommandName>Form.Command.ПутьКРабочемуКаталогуПоУмолчанию</CommandName>
					<ExtendedTooltip name="ПутьКРабочемуКаталогуПоУмолчаниюExtendedTooltip" id="32"/>
				</Button>
			</ChildItems>
		</UsualGroup>
		<InputField name="МаксимальныйРазмерЛокальногоКэшаФайлов" id="2">
			<DataPath>МаксимальныйРазмерЛокальногоКэшаФайлов</DataPath>
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Максимальный размер (Мб)</v8:content>
				</v8:item>
			</Title>
			<FooterHorizontalAlign>Left</FooterHorizontalAlign>
			<Wrap>false</Wrap>
			<BorderColor>style:BorderColor</BorderColor>
			<ContextMenu name="МаксимальныйРазмерЛокальногоКэшаФайловКонтекстноеМеню" id="3"/>
			<ExtendedTooltip name="МаксимальныйРазмерЛокальногоКэшаФайловExtendedTooltip" id="33"/>
			<Events>
				<Event name="OnChange">МаксимальныйРазмерЛокальногоКэшаФайловПриИзменении</Event>
			</Events>
		</InputField>
		<CheckBoxField name="УдалятьФайлИзЛокальногоКэшаФайловПриЗавершенииРедактирования" id="16">
			<DataPath>УдалятьФайлИзЛокальногоКэшаФайловПриЗавершенииРедактирования</DataPath>
			<TitleLocation>Right</TitleLocation>
			<CheckBoxType>Auto</CheckBoxType>
			<ContextMenu name="УдалятьФайлИзЛокальногоКэшаФайловПриЗавершенииРедактированияКонтекстноеМеню" id="17"/>
			<ExtendedTooltip name="УдалятьФайлИзЛокальногоКэшаФайловПриЗавершенииРедактированияExtendedTooltip" id="35"/>
			<Events>
				<Event name="OnChange">УдалятьФайлИзЛокальногоКэшаФайловПриЗавершенииРедактированияПриИзменении</Event>
			</Events>
		</CheckBoxField>
		<UsualGroup name="ГруппаПодтверждатьПриУдаленииИзЛокальногоКэшаФайлов" id="41">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Подтверждать при удалении из локального кэша файлов</v8:content>
				</v8:item>
			</Title>
			<Group>AlwaysHorizontal</Group>
			<Representation>None</Representation>
			<ShowTitle>false</ShowTitle>
			<ExtendedTooltip name="ГруппаПодтверждатьПриУдаленииИзЛокальногоКэшаФайловРасширеннаяПодсказка" id="42"/>
			<ChildItems>
				<LabelDecoration name="ДекорацияОтступЗависимыеОпции" id="43">
					<ContextMenu name="ДекорацияОтступЗависимыеОпцииКонтекстноеМеню" id="44"/>
					<ExtendedTooltip name="ДекорацияОтступЗависимыеОпцииРасширеннаяПодсказка" id="45"/>
				</LabelDecoration>
				<CheckBoxField name="ПодтверждатьПриУдаленииИзЛокальногоКэшаФайлов" id="24">
					<DataPath>ПодтверждатьПриУдаленииИзЛокальногоКэшаФайлов</DataPath>
					<Title>
						<v8:item>
							<v8:lang>ru</v8:lang>
							<v8:content>Подтверждать при удалении из рабочего каталога</v8:content>
						</v8:item>
					</Title>
					<TitleLocation>Right</TitleLocation>
					<CheckBoxType>Auto</CheckBoxType>
					<ContextMenu name="ПодтверждатьПриУдаленииИзЛокальногоКэшаФайловКонтекстноеМеню" id="25"/>
					<ExtendedTooltip name="ПодтверждатьПриУдаленииИзЛокальногоКэшаФайловExtendedTooltip" id="34"/>
					<Events>
						<Event name="OnChange">ПодтверждатьПриУдаленииИзЛокальногоКэшаФайловПриИзменении</Event>
					</Events>
				</CheckBoxField>
			</ChildItems>
		</UsualGroup>
		<UsualGroup name="ГруппаТекущееСостояние" id="48">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Текущее состояние:</v8:content>
				</v8:item>
			</Title>
			<Group>AlwaysHorizontal</Group>
			<Representation>NormalSeparation</Representation>
			<ExtendedTooltip name="ГруппаТекущееСостояниеРасширеннаяПодсказка" id="49"/>
			<ChildItems>
				<UsualGroup name="ГруппаФайлов" id="46">
					<Title>
						<v8:item>
							<v8:lang>ru</v8:lang>
							<v8:content>Файлы</v8:content>
						</v8:item>
					</Title>
					<Group>Vertical</Group>
					<Representation>None</Representation>
					<ShowTitle>false</ShowTitle>
					<ExtendedTooltip name="ГруппаФайловРасширеннаяПодсказка" id="47"/>
					<ChildItems>
						<InputField name="КоличествоСуммарное" id="11">
							<DataPath>КоличествоСуммарное</DataPath>
							<ReadOnly>true</ReadOnly>
							<Title>
								<v8:item>
									<v8:lang>ru</v8:lang>
									<v8:content>Файлов</v8:content>
								</v8:item>
							</Title>
							<FooterHorizontalAlign>Left</FooterHorizontalAlign>
							<Wrap>false</Wrap>
							<BorderColor>style:BorderColor</BorderColor>
							<ContextMenu name="КоличествоСуммарноеКонтекстноеМеню" id="12"/>
							<ExtendedTooltip name="КоличествоСуммарноеExtendedTooltip" id="37"/>
						</InputField>
						<Button name="СписокФайлов" id="14">
							<Type>UsualButton</Type>
							<SkipOnInput>false</SkipOnInput>
							<CommandName>Form.Command.СписокФайлов</CommandName>
							<TextColor>style:ButtonTextColor</TextColor>
							<BackColor>style:ButtonBackColor</BackColor>
							<BorderColor>style:BorderColor</BorderColor>
							<ExtendedTooltip name="СписокФайловExtendedTooltip" id="39"/>
						</Button>
					</ChildItems>
				</UsualGroup>
				<UsualGroup name="СейчасВЛокальномКэшеФайлов" id="18">
					<Title>
						<v8:item>
							<v8:lang>ru</v8:lang>
							<v8:content>Общий объем</v8:content>
						</v8:item>
					</Title>
					<Group>Vertical</Group>
					<Representation>None</Representation>
					<ShowTitle>false</ShowTitle>
					<ExtendedTooltip name="СейчасВЛокальномКэшеФайловExtendedTooltip" id="36"/>
					<ChildItems>
						<InputField name="РазмерФайловВРабочемКаталоге" id="9">
							<DataPath>РазмерФайловВРабочемКаталоге</DataPath>
							<ReadOnly>true</ReadOnly>
							<Title>
								<v8:item>
									<v8:lang>ru</v8:lang>
									<v8:content>Общий объем (Мб)</v8:content>
								</v8:item>
							</Title>
							<FooterHorizontalAlign>Left</FooterHorizontalAlign>
							<Wrap>false</Wrap>
							<BorderColor>style:BorderColor</BorderColor>
							<ContextMenu name="РазмерФайловВРабочемКаталогеКонтекстноеМеню" id="10"/>
							<ExtendedTooltip name="РазмерФайловВРабочемКаталогеExtendedTooltip" id="38"/>
						</InputField>
						<Button name="ОчиститьРабочийКаталог" id="13">
							<Type>UsualButton</Type>
							<SkipOnInput>false</SkipOnInput>
							<CommandName>Form.Command.ОчиститьЛокальныйКэшФайлов</CommandName>
							<TextColor>style:ButtonTextColor</TextColor>
							<BackColor>style:ButtonBackColor</BackColor>
							<BorderColor>style:BorderColor</BorderColor>
							<ExtendedTooltip name="ОчиститьРабочийКаталогExtendedTooltip" id="40"/>
						</Button>
					</ChildItems>
				</UsualGroup>
			</ChildItems>
		</UsualGroup>
	</ChildItems>
	<Attributes>
		<Attribute name="МаксимальныйРазмерЛокальногоКэшаФайлов" id="1">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Максимальный размер локального кэша файлов</v8:content>
				</v8:item>
			</Title>
			<Type>
				<v8:Type>xs:decimal</v8:Type>
				<v8:NumberQualifiers>
					<v8:Digits>10</v8:Digits>
					<v8:FractionDigits>0</v8:FractionDigits>
					<v8:AllowedSign>Any</v8:AllowedSign>
				</v8:NumberQualifiers>
			</Type>
		</Attribute>
		<Attribute name="РабочийКаталогПользователя" id="2">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Рабочий каталог пользователя</v8:content>
				</v8:item>
			</Title>
			<Type>
				<v8:Type>xs:string</v8:Type>
				<v8:StringQualifiers>
					<v8:Length>0</v8:Length>
					<v8:AllowedLength>Variable</v8:AllowedLength>
				</v8:StringQualifiers>
			</Type>
		</Attribute>
		<Attribute name="РазмерФайловВРабочемКаталоге" id="3">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Размер</v8:content>
				</v8:item>
			</Title>
			<Type>
				<v8:Type>xs:decimal</v8:Type>
				<v8:NumberQualifiers>
					<v8:Digits>10</v8:Digits>
					<v8:FractionDigits>0</v8:FractionDigits>
					<v8:AllowedSign>Any</v8:AllowedSign>
				</v8:NumberQualifiers>
			</Type>
		</Attribute>
		<Attribute name="КоличествоСуммарное" id="4">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Количество суммарное</v8:content>
				</v8:item>
			</Title>
			<Type>
				<v8:Type>xs:decimal</v8:Type>
				<v8:NumberQualifiers>
					<v8:Digits>10</v8:Digits>
					<v8:FractionDigits>0</v8:FractionDigits>
					<v8:AllowedSign>Any</v8:AllowedSign>
				</v8:NumberQualifiers>
			</Type>
		</Attribute>
		<Attribute name="УдалятьФайлИзЛокальногоКэшаФайловПриЗавершенииРедактирования" id="5">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Удалять файлы при завершении редактирования</v8:content>
				</v8:item>
			</Title>
			<Type>
				<v8:Type>xs:boolean</v8:Type>
			</Type>
		</Attribute>
		<Attribute name="ПодтверждатьПриУдаленииИзЛокальногоКэшаФайлов" id="6">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Подтверждать при удалении из локального кэша файлов</v8:content>
				</v8:item>
			</Title>
			<Type>
				<v8:Type>xs:boolean</v8:Type>
			</Type>
		</Attribute>
	</Attributes>
	<Commands>
		<Command name="ОчиститьЛокальныйКэшФайлов" id="3">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Очистить рабочий каталог</v8:content>
				</v8:item>
			</Title>
			<ToolTip>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Очистить рабочий каталог</v8:content>
				</v8:item>
			</ToolTip>
			<Action>ОчиститьЛокальныйКэшФайлов</Action>
			<Representation>Picture</Representation>
			<CurrentRowUse>DontUse</CurrentRowUse>
		</Command>
		<Command name="СписокФайлов" id="4">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Открыть список файлов...</v8:content>
				</v8:item>
			</Title>
			<ToolTip>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Список файлов</v8:content>
				</v8:item>
			</ToolTip>
			<Action>СписокФайловВыполнить</Action>
			<CurrentRowUse>DontUse</CurrentRowUse>
		</Command>
		<Command name="ПутьКРабочемуКаталогуПоУмолчанию" id="2">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Путь к рабочему каталогу по умолчанию</v8:content>
				</v8:item>
			</Title>
			<ToolTip>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Восстановить значение по умолчанию</v8:content>
				</v8:item>
			</ToolTip>
			<Picture>
				<xr:Ref>CommonPicture.РабочийКаталогПоУмолчанию</xr:Ref>
				<xr:LoadTransparent>false</xr:LoadTransparent>
			</Picture>
			<Action>ПутьКРабочемуКаталогуПоУмолчанию</Action>
			<Representation>Picture</Representation>
			<CurrentRowUse>DontUse</CurrentRowUse>
		</Command>
	</Commands>
</Form>


text:
package Windows;

import java.awt.*;
import javax.swing.*;
import com.csvreader.CsvReader;
import OcGraduateSystemClasses.*;
import SystemDataManagementClasses.*;

import java.awt.Font;
import java.awt.event.*;
import java.io.FileNotFoundException;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;

//	TODO - need to add error handling
// 	1. cancel selection - if needed!

public class CourseListJPanel extends JPanel {

	JScrollPane scrollpane;
	DefaultListModel <Course> listModel;
	JList list_courses;
	JLabel lblListOfAvailable;
	JButton btn_addNewCourse;
	JButton btn_viewCourseDetails;
	JButton btn_editCourseInfo;
	JButton btn_deleteCourse;
	JButton btn_coursesListToMain;

	/**
	 * Create the panel.
	 */
	public CourseListJPanel(JFrame currentFrame, University university) {
		setBounds(new Rectangle(0, 0, 700, 650));
		setLayout(null);

		// title label
		lblListOfAvailable = new JLabel("List of Available Courses");
		lblListOfAvailable.setFont(new Font("Lucida Grande", Font.PLAIN, 18));
		lblListOfAvailable.setBounds(50, 20, 300, 25);
		add(lblListOfAvailable);

		// Add button - it leads to a new course creation page
		btn_addNewCourse = new JButton("Add");
		btn_addNewCourse.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				currentFrame.getContentPane().removeAll();
				currentFrame.getContentPane().add(new AddCourseJPanel(currentFrame, university));
				currentFrame.revalidate();
			}
		});
		btn_addNewCourse.setBounds(500, 50, 100, 30);
		add(btn_addNewCourse);

		// View button - it lets you view details about a selected course
		btn_viewCourseDetails = new JButton("View");
		btn_viewCourseDetails.setEnabled(false);
		btn_viewCourseDetails.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				// TODO - get the selected course and send it to the view JPanel
				// the work here is done, we have a selected course, just need to work on the edit page
				Course selectedCourse = (Course) list_courses.getSelectedValue();
				currentFrame.getContentPane().removeAll();
				currentFrame.getContentPane().add(new CourseDetailsJPanel(currentFrame, selectedCourse, university));
				currentFrame.revalidate();
			}
		});
		btn_viewCourseDetails.setBounds(500, 100, 100, 30);
		add(btn_viewCourseDetails);

		// Edit button - it takes you to a course edit page
		btn_editCourseInfo = new JButton("Edit");
		btn_editCourseInfo.setEnabled(false);
		btn_editCourseInfo.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				// TODO
				// get the selected course and pass its information to the edit page
				// this is partially done - just need to add more fields on the edit page
				// it is going to look exactly like the add course page with pre-filled fields

				Course selectedCourse = (Course) list_courses.getSelectedValue();
				currentFrame.getContentPane().removeAll();
				currentFrame.getContentPane().add(new EditCourseJPanel(currentFrame, university, selectedCourse));
				currentFrame.revalidate();
			}
		});
		btn_editCourseInfo.setBounds(500, 150, 100, 30);
		add(btn_editCourseInfo);

		// Delete button - it deletes the selected course from the list
		btn_deleteCourse = new JButton("Delete");
		btn_deleteCourse.setEnabled(false);
		btn_deleteCourse.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				// TODO - almost done - just add error handling code
				// get the selected course and deleted if from the list

				Course selectedCourse = (Course) list_courses.getSelectedValue();
				university.removeCourse(selectedCourse);
				listModel.removeElement(selectedCourse);
			}
		});

		btn_deleteCourse.setBounds(500, 200, 100, 30);
		add(btn_deleteCourse);

		// Back button from the list of courses back to main
		btn_coursesListToMain = new JButton("< Back");
		btn_coursesListToMain.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				currentFrame.getContentPane().removeAll();
				currentFrame.getContentPane().add(new MainJPanel(university));
				currentFrame.revalidate();
			}
		});
		btn_coursesListToMain.setBounds(500, 250, 100, 30);
		add(btn_coursesListToMain);

		// get the list of courses and create a list model for them
		// the JList needs to be added to the scroll pane to give it the scrolling ability
		listModel = new DefaultListModel<>();
		for (Course course : university.getCourses())
			listModel.addElement(course);
		list_courses = new JList(listModel);
		list_courses.addListSelectionListener(new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent e) {

				// allow view, edit and delete only when there is a selected item
				if (list_courses.getSelectedValue() != null)
				{
					btn_viewCourseDetails.setEnabled(true);
					btn_editCourseInfo.setEnabled(true);
					btn_deleteCourse.setEnabled(true);

				}
				else
				{
					btn_viewCourseDetails.setEnabled(false);
					btn_editCourseInfo.setEnabled(false);
					btn_deleteCourse.setEnabled(false);
				}
			}
		});

		scrollpane = new JScrollPane(list_courses);
		scrollpane.setBounds(50, 50, 400, 500);
		add(scrollpane);
	}
}

redpajama_set_name: RedPajamaGithub


text:
if ENV['COVERAGE'] == 'true'
  require 'simplecov'
  require 'coveralls'

  SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[
    SimpleCov::Formatter::HTMLFormatter,
    Coveralls::SimpleCov::Formatter
  ]

  SimpleCov.start do
    command_name 'spec:unit'

    add_filter 'config'
    add_filter 'spec'
  end
end

require 'reference'

require 'awesome_print'


text:
package org.uberfire.ext.editor.commons.service.restrictor;

import org.uberfire.backend.vfs.Path;
import org.uberfire.ext.editor.commons.service.restriction.PathOperationRestriction;

/**
 * Represents a restrictor to a path operation (copy, delete or rename).
 */
public interface PathOperationRestrictor {

    /**
     * Checks if there is a restriction to execute a operation on this path.
     * @param path Path to be checked.
     * @return The restriction to execute the operation, or null if there is not one.
     */
    PathOperationRestriction hasRestriction(Path path);
}


text:
class RemoveSrcThumbIdFromSrcImages < ActiveRecord::Migration[4.2]
  def up
    remove_column :src_images, :src_thumb_id
  end

  def down
    add_column :src_images, :src_thumb_id, :integer
  end
end


text:
require 'compass/core/generated_version'

module Compass
  module Core
    unless defined?(::Compass::Core::VERSION)
      def self.scope(file)
        File.expand_path(File.join(File.dirname(__FILE__), "..", "..", "..", file))
      end

      VERSION = File.read(scope("VERSION")).strip
    end
  end
end


text:
require 'spec_helper'

describe "FacebookRailsStarterkit" do
end


text:
import { IViewlet } from 'vs/workbench/common/viewlet';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import Event from 'vs/base/common/event';
import { TPromise } from 'vs/base/common/winjs.base';
import { IPager } from 'vs/base/common/paging';
import { IQueryOptions, IExtensionManifest, LocalExtensionType } from 'vs/platform/extensionManagement/common/extensionManagement';

export const VIEWLET_ID = 'workbench.view.extensions';

export interface IExtensionsViewlet extends IViewlet {
	search(text: string): void;
}

export enum ExtensionState {
	Installing,
	Installed,
	Uninstalling,
	Uninstalled
}

export interface IExtension {
	type: LocalExtensionType;
	state: ExtensionState;
	name: string;
	displayName: string;
	id: string;
	publisher: string;
	publisherDisplayName: string;
	version: string;
	latestVersion: string;
	description: string;
	url: string;
	iconUrl: string;
	iconUrlFallback: string;
	licenseUrl: string;
	installCount: number;
	rating: number;
	ratingCount: number;
	outdated: boolean;
	disabledGlobally: boolean;
	disabledForWorkspace: boolean;
	dependencies: string[];
	telemetryData: any;
	getManifest(): TPromise<IExtensionManifest>;
	getReadme(): TPromise<string>;
	getChangelog(): TPromise<string>;
}

export interface IExtensionDependencies {
	dependencies: IExtensionDependencies[];
	hasDependencies: boolean;
	identifier: string;
	extension: IExtension;
	dependent: IExtensionDependencies;
}

export const SERVICE_ID = 'extensionsWorkbenchService';

export const IExtensionsWorkbenchService = createDecorator<IExtensionsWorkbenchService>(SERVICE_ID);

export interface IExtensionsWorkbenchService {
	_serviceBrand: any;
	onChange: Event<void>;
	local: IExtension[];
	isAutoUpdateEnabled: boolean;
	queryLocal(): TPromise<IExtension[]>;
	queryGallery(options?: IQueryOptions): TPromise<IPager<IExtension>>;
	canInstall(extension: IExtension): boolean;
	install(vsix: string): TPromise<void>;
	install(extension: IExtension, promptToInstallDependencies?: boolean): TPromise<void>;
	uninstall(extension: IExtension): TPromise<void>;
	setEnablement(extension: IExtension, enable: boolean, workspace?: boolean): TPromise<void>;
	loadDependencies(extension: IExtension): TPromise<IExtensionDependencies>;
	open(extension: IExtension, sideByside?: boolean): TPromise<any>;
	checkForUpdates(): TPromise<void>;
	setAutoUpdate(autoUpdate: boolean): TPromise<void>;
}

export const ConfigurationKey = 'extensions';

export interface IExtensionsConfiguration {
	autoUpdate: boolean;
	ignoreRecommendations: boolean;
}


text:
FROM aweiker/elixir-build:1.4.0-19.1.0
MAINTAINER Nick Cronquist <nick@ncronquist.com>

ENV PATH=/opt/listerlyify/node_modules/.bin:$PATH

RUN mkdir -p /opt/listerlyify
WORKDIR /opt/listerlyify

ADD ./mix.exs /opt/listerlyify/mix.exs
ADD ./mix.lock /opt/listerlyify/mix.lock
ADD ./package.json /opt/listerlyify/package.json
ADD ./brunch-config.js /opt/listerlyify/brunch-config.js
ADD ./node_modules/ /opt/concur/receipt_service/node_modules/
ADD ./run-install /opt/listerlyify/run-install
ADD ./run-service /opt/listerlyify/run-service

RUN chmod 550 /opt/listerlyify/run-install /opt/listerlyify/run-service

COPY docker-entrypoint.sh /opt/entrypoint.sh
ENTRYPOINT ["/opt/entrypoint.sh"]

EXPOSE 4000

ENTRYPOINT ["/opt/entrypoint.sh"]
CMD ["/usr/bin/mix", "phoenix.server"]


text:
package com.example.xmc.hao;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by xmc on 2017/7/10.
 */

public class Fragment4 extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view =inflater.inflate(R.layout.fragment4,container,false);
        return view;
    }
}


text:
package org.sistemafinanciero.util;

import java.security.Principal;

import javax.annotation.Resource;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.inject.Named;

import org.keycloak.KeycloakPrincipal;
import org.keycloak.KeycloakSecurityContext;

@Named
@Stateless
public class UsuarioSession {

	@Resource
	private SessionContext context;

	public boolean haveSession() {
		Principal principal = context.getCallerPrincipal();
		String name = principal.getName();
		return name == null;
	}

	public String getUsername() {
		KeycloakPrincipal p = (KeycloakPrincipal) context.getCallerPrincipal();
		KeycloakSecurityContext kcSecurityContext = p.getKeycloakSecurityContext();
		String username = kcSecurityContext.getToken().getPreferredUsername();
		return username;
	}

}


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

namespace BeeHive.Azure.Tests.Integration
{
    public class AzureCollectionStoreTests
    {
        private const string ConnectionString = "UseDevelopmentStorage=true;";

        [Fact]
        public void CanStoreAndRetrieve()
        {
            var store = new AzureCollectionStore<TestCollectionEntity>(ConnectionString);
            var id = Guid.NewGuid().ToString("N");
            store.InsertAsync(new TestCollectionEntity()
            {
                Id = id
            }).Wait();

            Assert.True(store.ExistsAsync(id).Result);

            var t = store.GetAsync(id).Result;
            Assert.Equal(id, t.Id);
        }

        [Fact]
        public void CanStoreAndRemoved()
        {
            var store = new AzureCollectionStore<TestCollectionEntity>(ConnectionString);
            var id = Guid.NewGuid().ToString("N");
            var t = new TestCollectionEntity()
            {
                Id = id
            };
            store.InsertAsync(t).Wait();

            store.DeleteAsync(t).Wait();

            Assert.False(store.ExistsAsync(id).Result);
            Assert.Throws<AggregateException>(() => store.GetAsync(id).Result);
        }

        [Fact]
        public void CanBeUpdated()
        {
            var store = new AzureCollectionStore<TestCollectionEntity>(ConnectionString);
            var id = Guid.NewGuid().ToString("N");
            var t = new TestCollectionEntity()
            {
                Id = id,
                Name = "Tommy Shooter"
            };
            store.InsertAsync(t).Wait();
            t.Name = "The Fall";
            store.UpsertAsync(t).Wait();

            var t2 = store.GetAsync(id).Result;
            Assert.Equal("The Fall", t2.Name);
        }

        [Fact]
        public void CannotBeInsertedTwice()
        {
            var store = new AzureCollectionStore<TestCollectionEntity>(ConnectionString);
            var id = Guid.NewGuid().ToString("N");
            var t = new TestCollectionEntity()
            {
                Id = id,
                Name = "Tommy Shooter"
            };
            store.InsertAsync(t).Wait();
            Assert.Throws<AggregateException>(() => store.InsertAsync(t).Wait());
        }

        [Fact]
        public void CanBeUpdatedForConcurrencyAware()
        {
            var store = new AzureCollectionStore<TestCollectionEntityConcurrencyAware>(ConnectionString);
            var id = Guid.NewGuid().ToString("N");
            var t = new TestCollectionEntityConcurrencyAware()
            {
                Id = id,
                Name = "Tommy Shooter",
                ETag = "\"1234\"",
                LastModified = DateTimeOffset.UtcNow
            };
            store.InsertAsync(t).Wait();
            t.Name = "The Fall";
            store.UpsertAsync(t).Wait();

            var t2 = store.GetAsync(id).Result;
            Assert.Equal("The Fall", t2.Name);
        }

        [Fact]
        public void ETagsProvidedWillBeUsedAndStored()
        {
            var store = new AzureCollectionStore<TestCollectionEntityConcurrencyAware>(ConnectionString);
            var id = Guid.NewGuid().ToString("N");
            var t = new TestCollectionEntityConcurrencyAware()
            {
                Id = id,
                Name = "Tommy Shooter",
                ETag = "\"1234\"",
                LastModified = DateTimeOffset.UtcNow.AddHours(1)
            };
            store.InsertAsync(t).Wait();
            var entity = store.GetAsync(id).Result;
            Assert.Equal(t.ETag, entity.ETag);
        }

        [Fact]
        public void CannotBeUpdatedForConcurrencyAwareWhenETagInConflict()
        {
            var store = new AzureCollectionStore<TestCollectionEntityConcurrencyAware>(ConnectionString);
            var id = Guid.NewGuid().ToString("N");
            var t = new TestCollectionEntityConcurrencyAware()
            {
                Id = id,
                Name = "Tommy Shooter",
                ETag = "\"1234\"",
                LastModified = DateTimeOffset.UtcNow

            };
            store.InsertAsync(t).Wait();

            t.Name = "The Fall";
            t.ETag = "\"8998\"";

            Assert.Throws<AggregateException>(() => store.UpsertAsync(t).Wait());
        }

        [Fact]
        public void CannotBeDeletedForConcurrencyAwareWhenETagInConflict()
        {
            var store = new AzureCollectionStore<TestCollectionEntityConcurrencyAware>(ConnectionString);
            var id = Guid.NewGuid().ToString("N");
            var t = new TestCollectionEntityConcurrencyAware()
            {
                Id = id,
                Name = "Tommy Shooter",
                ETag = "1234",
                LastModified = DateTimeOffset.UtcNow
            };
            store.InsertAsync(t).Wait();

            t.Name = "The Fall";
            t.ETag = "4567";

            Assert.Throws<AggregateException>(() => store.DeleteAsync(t).Wait());
        }

    }

    public class TestCollectionEntity : IHaveIdentity
    {
        public string Id { get; set; }
        public string Name { get; set; }
    }

    public class TestCollectionEntityConcurrencyAware : IHaveIdentity, IConcurrencyAware
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public DateTimeOffset? LastModified { get; set; }
        public string ETag { get; set; }
    }

}


text:
class AddStatusToTicket < ActiveRecord::Migration
  def change
    add_column :tickets, :status, :string
  end
end


text:
export default {
    test: /\.html$/,
    loader: 'html-loader',
};


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_drink_data"
            android:icon="@drawable/ic_heart"
            android:title="数据中心" />
        <item
            android:id="@+id/nav_user_data"
            android:icon="@drawable/ic_settings"
            android:title="个人中心" />
        <item
            android:id="@+id/nav_rank"
            android:icon="@drawable/ic_location"
            android:title="饮水排行" />

        <item
            android:id="@+id/nav_step"
            android:icon="@drawable/ic_tast"
            android:title="今日步数" />
        <item
            android:id="@+id/nav_weather"
            android:icon="@drawable/ic_cloud"
            android:title="今日天气"/>
        <item
            android:id="@+id/nav_cup"
            android:icon="@drawable/ic_water"
            android:title="我的水杯" />
        <item
            android:id="@+id/nav_exit"
            android:icon="@drawable/ic_power"
            android:title="退出应用"/>
    </group>
</menu>


text:
require 'securerandom'

#normal user
#customer address
customer_address = Address.create name: 'Max Mustermann', street: 'Musterstraße 11', postcode: '12345', city: 'Musterhausen'
customer_user = User.new email: 'test@example.com', password: 'test', password_confirmation: 'test'
customer_user.addresses << customer_address
customer_user.confirmation_sent_at = Time.now
customer_user.save! validate: false

#admin user
admin_user = User.new email: 'admin@example.com', password: 'test', password_confirmation: 'test', admin: true
admin_user.confirmation_sent_at = Time.now
admin_user.save! validate: false

#shop
shop_address = Address.create name: 'Best Pizza Around', street: 'Musterweg 11', postcode: '12345', city: 'Musterhausen'
shop_user = User.new email: 'shop@example.com', password: 'test', password_confirmation: 'test'
shop_user.confirmation_sent_at = Time.now
shop_user.save! validate: false
shop = Shop.create user: shop_user, address: shop_address

#product-category
product_category = ProductCategory.create name: 'Pizzas', shop: shop

#product
product = Product.create name: 'Pizza Salami', description: 'Best salami pizza around', price: '9.99', product_category: product_category

#order
order = Order.create uuid: SecureRandom.uuid, shop: shop, user: customer_user, address: customer_address
sub_order = SubOrder.create nickname: 'flower-pot', order: order, comment: 'Cut please!'
item = Item.create sub_order: sub_order, product: product, quantity: 1, price: '9.99'


text:
#include "stdafx.h"

#include "PHDynamicData.h"
#include "Physics.h"
#include "ExtendedGeom.h"
#include "../xrEngine/cl_intersect.h"
#include "tri-colliderKNoOPC\__aabb_tri.h"

#include "phaicharacter.h"
#include "../xrengine/device.h"

#ifdef DEBUG
//#	include "../xrEngine/StatGraph.h"
#include "debug_output.h"
//#	include "level.h"
//#	include "debug_renderer.h"
#endif

CPHAICharacter::CPHAICharacter() { m_forced_physics_control = false; }
void CPHAICharacter::Create(dVector3 sizes) {
    inherited::Create(sizes);

    m_forced_physics_control = false; //.
}
bool CPHAICharacter::TryPosition(Fvector pos, bool exact_state) {
    if (!b_exist)
        return false;
    if (m_forced_physics_control || JumpState())
        return false; // b_was_on_object||b_on_object||
    if (DoCollideObj())
        return false;
    Fvector current_pos;
    GetPosition(current_pos);
    Fvector cur_vel;
    GetVelocity(cur_vel);

    Fvector displace;
    displace.sub(pos, current_pos);
    float disp_mag = displace.magnitude();

    if (fis_zero(disp_mag) || fis_zero(inl_ph_world().Device().fTimeDelta))
        return true;
    const u32 max_steps = 15;
    const float fmax_steps = float(max_steps);
    float fsteps_num = 1.f;
    u32 steps_num = 1;
    float disp_pstep = FootRadius();
    float rest = 0.f;

    float parts = disp_mag / disp_pstep;
    fsteps_num = floor(parts);
    steps_num = iFloor(parts);
    if (steps_num > max_steps) {
        steps_num = max_steps;
        fsteps_num = fmax_steps;
        disp_pstep = disp_mag / fsteps_num;
    }
    rest = disp_mag - fsteps_num * disp_pstep;

    Fvector vel;
    vel.mul(displace, disp_pstep / fixed_step / disp_mag);
    bool ret = true;
    int save_gm = dBodyGetGravityMode(m_body);
    dBodySetGravityMode(m_body, 0);
    for (u32 i = 0; steps_num > i; ++i) {
        SetVelocity(vel);
        Enable();
        if (!step_single(fixed_step)) {
            SetVelocity(cur_vel);
            ret = false;
            break;
        }
    }

    vel.mul(displace, rest / fixed_step / disp_mag);
    SetVelocity(vel);
    Enable();
    ret = step_single(fixed_step);

    dBodySetGravityMode(m_body, save_gm);
    SetVelocity(cur_vel);
    Fvector pos_new;
    GetPosition(pos_new);

#if 0
	Fvector	dif;dif .sub( pos, pos_new );
	float	dif_m = dif.magnitude();
	if(ret&&dif_m>EPS_L)
	{
		Msg("dif vec %f,%f,%f \n",dif.x,dif.y,dif.z);
		Msg("dif mag %f \n",dif_m);
	}
#endif

    SetPosition(pos_new);
    m_last_move.sub(pos_new, current_pos).mul(1.f / inl_ph_world().Device().fTimeDelta);
    m_body_interpolation.UpdatePositions();
    m_body_interpolation.UpdatePositions();
    if (ret)
        Disable();
    m_collision_damage_info.m_contact_velocity = 0.f;
    return ret;
}
/*
void CPHAICharacter::		SetPosition	(const Fvector &pos)
{
        //m_vDesiredPosition.set(pos);
        inherited::SetPosition(pos);

}
*/
/*
void CPHAICharacter::BringToDesired(float time,float velocity,float force)
{
        Fvector pos,move;
        GetPosition(pos);

        move.sub(m_vDesiredPosition,pos);
        move.y=0.f;
        float dist=move.magnitude();

        float vel;
        if(dist>EPS_L*100.f)
        {
                vel=dist/time;
                move.mul(1.f/dist);
        }
        else if(dist>EPS_L*10.f)
        {
                vel=dist*dist*dist;
                move.mul(1.f/dist);
        }
        else
        {
                vel=0.f;
                move.set(0,0,0);
        }

        if(vel>velocity)//&&velocity>EPS_L
                vel=velocity;

        if(velocity<EPS_L/fixed_step)
        {
                vel=0.f;
                move.set(0,0,0);
        }

        SetMaximumVelocity(vel);

        SetAcceleration(move);
}

*/

void CPHAICharacter::Jump(const Fvector& jump_velocity) {
    b_jump = true;
    m_jump_accel.set(jump_velocity);
}
void CPHAICharacter::ValidateWalkOn() {
    // if(b_on_object)
    //	ValidateWalkOnObject();
    // else
    //	 b_clamb_jump=true;
    inherited::ValidateWalkOn();
}
void CPHAICharacter::InitContact(dContact* c, bool& do_collide, u16 material_idx_1,
                                 u16 material_idx_2) {
    SGameMtl* material_1 = GMLibrary().GetMaterialByIdx(material_idx_1);
    SGameMtl* material_2 = GMLibrary().GetMaterialByIdx(material_idx_2);
    if ((material_1 && material_1->Flags.test(SGameMtl::flActorObstacle)) ||
        (material_2 && material_2->Flags.test(SGameMtl::flActorObstacle)))
        do_collide = true;
    inherited::InitContact(c, do_collide, material_idx_1, material_idx_2);
    if (is_control || b_lose_control || b_jumping)
        c->surface.mu = 0.00f;
    dxGeomUserData* D1 = retrieveGeomUserData(c->geom.g1);
    dxGeomUserData* D2 = retrieveGeomUserData(c->geom.g2);
    if (D1 && D2 && D1->ph_object && D2->ph_object && D1->ph_object->CastType() == tpCharacter &&
        D2->ph_object->CastType() == tpCharacter) {
        b_on_object = true;
        b_valide_wall_contact = false;
    }
#ifdef DEBUG
    if (debug_output().ph_dbg_draw_mask().test(phDbgNeverUseAiPhMove))
        do_collide = false;
#endif
}
/*
EEnvironment CPHAICharacter::CheckInvironment()
{

        return inherited::CheckInvironment();
}
*/
#ifdef DEBUG
void CPHAICharacter::OnRender() {
    inherited::OnRender();
#if 0
	if(!b_exist) return;

	Fvector pos;
	GetDesiredPosition(pos);
	pos.y+=m_radius;

	Fvector scale;
	scale.set(0.35f,0.35f,0.35f);
	Fmatrix M;
	M.identity();
	M.scale(scale);
	M.c.set(pos);

	Level().debug_renderer().draw_ellipse(M, 0xffffffff);
#endif
}
#endif


text:
package springfox.documentation.spring.web.readers.parameter;

import com.fasterxml.classmate.ResolvedType;
import org.springframework.core.MethodParameter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.service.ResolvedMethodParameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.ParameterBuilderPlugin;
import springfox.documentation.spi.service.contexts.OperationContext;
import springfox.documentation.spi.service.contexts.ParameterContext;

import java.lang.annotation.Annotation;

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ParameterTypeReader implements ParameterBuilderPlugin {

    @Override
    public void apply(ParameterContext context) {
        context.parameterBuilder().parameterType(findParameterType(context));
    }

    @Override
    public boolean supports(DocumentationType delimiter) {
        return true;
    }

    public static String findParameterType(ParameterContext parameterContext) {
        MethodParameter methodParameter = parameterContext.methodParameter();
        ResolvedMethodParameter resolvedMethodParameter = parameterContext.resolvedMethodParameter();
        ResolvedType parameterType = resolvedMethodParameter.getResolvedParameterType();
        parameterType = parameterContext.alternateFor(parameterType);

        //Multi-part file trumps any other annotations
        if (MultipartFile.class.isAssignableFrom(parameterType.getErasedType())) {
            return "form";
        }
        Annotation[] methodAnnotations = methodParameter.getParameterAnnotations();
        for (Annotation annotation : methodAnnotations) {
            if (annotation instanceof PathVariable) {
                return "path";
            } else if (annotation instanceof ModelAttribute) {
                return "body";
            } else if (annotation instanceof RequestBody) {
                return "body";
            } else if (annotation instanceof RequestParam) {
                return queryOrForm(parameterContext.getOperationContext());
            } else if (annotation instanceof RequestHeader) {
                return "header";
            } else if (annotation instanceof RequestPart) {
                return "form";
            }
        }
        return "body";
    }

    private static String queryOrForm(OperationContext context) {
        if (context.consumes().contains(MediaType.APPLICATION_FORM_URLENCODED) && context.httpMethod() == HttpMethod
                .POST) {
            return "form";
        }
        return "query";
    }
}


text:
@interface ZKDescribeSoftphoneScreenPopOption()
@property (strong,nonatomic) NSString  *matchType__v;
@property (strong,nonatomic) NSString  *screenPopData__v;
@property (strong,nonatomic) NSString  *screenPopType__v;
@end

@implementation ZKDescribeSoftphoneScreenPopOption

+(void)load {
    [self registerType:self xmlName:@"DescribeSoftphoneScreenPopOption"];
}

+(ZKComplexTypeInfo *)wsdlSchema {
   static ZKComplexTypeInfo *wsdlSchema;
   static dispatch_once_t onceToken;
   dispatch_once(&onceToken, ^{
       wsdlSchema = [[ZKComplexTypeInfo alloc] initWithType:@"DescribeSoftphoneScreenPopOption" parent:nil
                    fields:@[
                        [[ZKComplexTypeFieldInfo alloc] initWithElementName:@"matchType" propertyName:@"matchType" optional:NO nillable:NO],
                        [[ZKComplexTypeFieldInfo alloc] initWithElementName:@"screenPopData" propertyName:@"screenPopData" optional:NO nillable:NO],
                        [[ZKComplexTypeFieldInfo alloc] initWithElementName:@"screenPopType" propertyName:@"screenPopType" optional:NO nillable:NO],

                    ]];
   });
   return wsdlSchema;
}

-(NSString *)matchType {
    if ((fields__set[0] & 0x1) == 0) {
        self.matchType__v = [self string:@"matchType"];
        fields__set[0] |= 0x1;
    }
    return self.matchType__v;
}

-(void)setMatchType:(NSString *)v {
    self.matchType__v = v;
    fields__set[0] |= 0x1;
}

-(NSString *)screenPopData {
    if ((fields__set[0] & 0x2) == 0) {
        self.screenPopData__v = [self string:@"screenPopData"];
        fields__set[0] |= 0x2;
    }
    return self.screenPopData__v;
}

-(void)setScreenPopData:(NSString *)v {
    self.screenPopData__v = v;
    fields__set[0] |= 0x2;
}

-(NSString *)screenPopType {
    if ((fields__set[0] & 0x4) == 0) {
        self.screenPopType__v = [self string:@"screenPopType"];
        fields__set[0] |= 0x4;
    }
    return self.screenPopType__v;
}

-(void)setScreenPopType:(NSString *)v {
    self.screenPopType__v = v;
    fields__set[0] |= 0x4;
}

-(void)serializeTo:(ZKXmlWriter *)env elemName:(NSString *)elemName {
	[env startElement:elemName];
	[env addElement:@"matchType"     elemValue:self.matchType     nillable:NO  optional:NO];
	[env addElement:@"screenPopData" elemValue:self.screenPopData nillable:NO  optional:NO];
	[env addElement:@"screenPopType" elemValue:self.screenPopType nillable:NO  optional:NO];
	[env endElement:elemName];
}
@end


text:
#include "crypto_aead.h"
#include "Keyakv2.h"

int crypto_aead_encrypt(
    unsigned char *c,unsigned long long *clen,
    const unsigned char *m,unsigned long long mlen,
    const unsigned char *ad,unsigned long long adlen,
    const unsigned char *nsec,
    const unsigned char *npub,
    const unsigned char *k
    )
{
    OceanKeyak_Instance instance;

    OceanKeyak_Initialize( &instance, k, 16, npub, 150, 0, 0, 0, 0 );
    OceanKeyak_Wrap( &instance, m, c, (size_t)mlen, ad, (size_t)adlen, c+mlen, 0, 0 );
    *clen = mlen + 16;
    return 0;
}

int crypto_aead_decrypt(
    unsigned char *m,unsigned long long *mlen,
    unsigned char *nsec,
    const unsigned char *c,unsigned long long clen,
    const unsigned char *ad,unsigned long long adlen,
    const unsigned char *npub,
    const unsigned char *k
    )
{
    OceanKeyak_Instance instance;
    unsigned long long mlen_;

    if (clen < 16)
        return -1;
    OceanKeyak_Initialize( &instance, k, 16, npub, 150, 0, 0, 1, 0 );
    mlen_ = clen - 16;
    *mlen = mlen_;
    if ( OceanKeyak_Wrap( &instance, c, m, (size_t)mlen_, ad, (size_t)adlen, (unsigned char*)c+mlen_, 1, 0 ) == 1 )
        return 0;
    return -1;
}


text:
import 'babel-polyfill';
import 'source-map-support/register';

global.Promise = require('bluebird');

import 'app-module-path/register';

import 'server';


text:
#ifndef IEEE802154_NL_H
#define IEEE802154_NL_H

struct net_device;
struct ieee802154_addr;

/**
 * ieee802154_nl_assoc_indic - Notify userland of an association request.
 * @dev: The network device on which this association request was
 *       received.
 * @addr: The address of the device requesting association.
 * @cap: The capability information field from the device.
 *
 * This informs a userland coordinator of a device requesting to
 * associate with the PAN controlled by the coordinator.
 *
 * Note: This is in section 7.3.1 of the IEEE 802.15.4-2006 document.
 */
int ieee802154_nl_assoc_indic(struct net_device *dev,
		struct ieee802154_addr *addr, u8 cap);

/**
 * ieee802154_nl_assoc_confirm - Notify userland of association.
 * @dev: The device which has completed association.
 * @short_addr: The short address assigned to the device.
 * @status: The status of the association.
 *
 * Inform userland of the result of an association request. If the
 * association request included asking the coordinator to allocate
 * a short address then it is returned in @short_addr.
 *
 * Note: This is in section 7.3.2 of the IEEE 802.15.4 document.
 */
int ieee802154_nl_assoc_confirm(struct net_device *dev,
		u16 short_addr, u8 status);

/**
 * ieee802154_nl_disassoc_indic - Notify userland of disassociation.
 * @dev: The device on which disassociation was indicated.
 * @addr: The device which is disassociating.
 * @reason: The reason for the disassociation.
 *
 * Inform userland that a device has disassociated from the network.
 *
 * Note: This is in section 7.3.3 of the IEEE 802.15.4 document.
 */
int ieee802154_nl_disassoc_indic(struct net_device *dev,
		struct ieee802154_addr *addr, u8 reason);

/**
 * ieee802154_nl_disassoc_confirm - Notify userland of disassociation
 * completion.
 * @dev: The device on which disassociation was ordered.
 * @status: The result of the disassociation.
 *
 * Inform userland of the result of requesting that a device
 * disassociate, or the result of requesting that we disassociate from
 * a PAN managed by another coordinator.
 *
 * Note: This is in section 7.1.4.3 of the IEEE 802.15.4 document.
 */
int ieee802154_nl_disassoc_confirm(struct net_device *dev,
		u8 status);

/**
 * ieee802154_nl_scan_confirm - Notify userland of completion of scan.
 * @dev: The device which was instructed to scan.
 * @status: The status of the scan operation.
 * @scan_type: What type of scan was performed.
 * @unscanned: Any channels that the device was unable to scan.
 * @edl: The energy levels (if a passive scan).
 *
 *
 * Note: This is in section 7.1.11 of the IEEE 802.15.4 document.
 * Note: This API does not permit the return of an active scan result.
 */
int ieee802154_nl_scan_confirm(struct net_device *dev,
		u8 status, u8 scan_type, u32 unscanned, u8 page,
		u8 *edl/*, struct list_head *pan_desc_list */);

/**
 * ieee802154_nl_beacon_indic - Notify userland of a received beacon.
 * @dev: The device on which a beacon was received.
 * @panid: The PAN of the coordinator.
 * @coord_addr: The short address of the coordinator on that PAN.
 *
 * Note: This is in section 7.1.5 of the IEEE 802.15.4 document.
 * Note: This API does not provide extended information such as what
 * channel the PAN is on or what the LQI of the beacon frame was on
 * receipt.
 * Note: This API cannot indicate a beacon frame for a coordinator
 *       operating in long addressing mode.
 */
int ieee802154_nl_beacon_indic(struct net_device *dev, u16 panid,
		u16 coord_addr);

/**
 * ieee802154_nl_start_confirm - Notify userland of completion of start.
 * @dev: The device which was instructed to scan.
 * @status: The status of the scan operation.
 *
 * Note: This is in section 7.1.14 of the IEEE 802.15.4 document.
 */
int ieee802154_nl_start_confirm(struct net_device *dev, u8 status);

#endif


text:
import numbers
import warnings
from itertools import product
from numbers import Integral
from operator import getitem

import numpy as np

from .core import (
    normalize_chunks,
    Array,
    slices_from_chunks,
    asarray,
    broadcast_shapes,
    broadcast_to,
)
from .creation import arange
from ..base import tokenize
from ..highlevelgraph import HighLevelGraph
from ..utils import ignoring, random_state_data, derived_from, skip_doctest

def doc_wraps(func):
    """ Copy docstring from one function to another """
    warnings.warn(
        "dask.array.random.doc_wraps is deprecated and will be removed in a future version",
        FutureWarning,
    )

    def _(func2):
        if func.__doc__ is not None:
            func2.__doc__ = skip_doctest(func.__doc__)
        return func2

    return _

class RandomState(object):
    """
    Mersenne Twister pseudo-random number generator

    This object contains state to deterministically generate pseudo-random
    numbers from a variety of probability distributions.  It is identical to
    ``np.random.RandomState`` except that all functions also take a ``chunks=``
    keyword argument.

    Parameters
    ----------
    seed: Number
        Object to pass to RandomState to serve as deterministic seed
    RandomState: Callable[seed] -> RandomState
        A callable that, when provided with a ``seed`` keyword provides an
        object that operates identically to ``np.random.RandomState`` (the
        default).  This might also be a function that returns a
        ``randomgen.RandomState``, ``mkl_random``, or
        ``cupy.random.RandomState`` object.

    Examples
    --------
    >>> import dask.array as da
    >>> state = da.random.RandomState(1234)  # a seed
    >>> x = state.normal(10, 0.1, size=3, chunks=(2,))
    >>> x.compute()
    array([10.01867852, 10.04812289,  9.89649746])

    See Also
    --------
    np.random.RandomState
    """

    def __init__(self, seed=None, RandomState=None):
        self._numpy_state = np.random.RandomState(seed)
        self._RandomState = RandomState

    def seed(self, seed=None):
        self._numpy_state.seed(seed)

    def _wrap(
        self, funcname, *args, size=None, chunks="auto", extra_chunks=(), **kwargs
    ):
        """ Wrap numpy random function to produce dask.array random function

        extra_chunks should be a chunks tuple to append to the end of chunks
        """
        if size is not None and not isinstance(size, (tuple, list)):
            size = (size,)

        args_shapes = {ar.shape for ar in args if isinstance(ar, (Array, np.ndarray))}
        args_shapes.union(
            {ar.shape for ar in kwargs.values() if isinstance(ar, (Array, np.ndarray))}
        )

        shapes = list(args_shapes)
        if size is not None:
            shapes.extend([size])
        # broadcast to the final size(shape)
        size = broadcast_shapes(*shapes)
        chunks = normalize_chunks(
            chunks,
            size,  # ideally would use dtype here
            dtype=kwargs.get("dtype", np.float64),
        )
        slices = slices_from_chunks(chunks)

        def _broadcast_any(ar, shape, chunks):
            if isinstance(ar, Array):
                return broadcast_to(ar, shape).rechunk(chunks)
            if isinstance(ar, np.ndarray):
                return np.ascontiguousarray(np.broadcast_to(ar, shape))

        # Broadcast all arguments, get tiny versions as well
        # Start adding the relevant bits to the graph
        dsk = {}
        dsks = []
        lookup = {}
        small_args = []
        dependencies = []
        for i, ar in enumerate(args):
            if isinstance(ar, (np.ndarray, Array)):
                res = _broadcast_any(ar, size, chunks)
                if isinstance(res, Array):
                    dependencies.append(res)
                    dsks.append(res.dask)
                    lookup[i] = res.name
                elif isinstance(res, np.ndarray):
                    name = "array-{}".format(tokenize(res))
                    lookup[i] = name
                    dsk[name] = res
                small_args.append(ar[tuple(0 for _ in ar.shape)])
            else:
                small_args.append(ar)

        small_kwargs = {}
        for key, ar in kwargs.items():
            if isinstance(ar, (np.ndarray, Array)):
                res = _broadcast_any(ar, size, chunks)
                if isinstance(res, Array):
                    dependencies.append(res)
                    dsks.append(res.dask)
                    lookup[key] = res.name
                elif isinstance(res, np.ndarray):
                    name = "array-{}".format(tokenize(res))
                    lookup[key] = name
                    dsk[name] = res
                small_kwargs[key] = ar[tuple(0 for _ in ar.shape)]
            else:
                small_kwargs[key] = ar

        sizes = list(product(*chunks))
        seeds = random_state_data(len(sizes), self._numpy_state)
        token = tokenize(seeds, size, chunks, args, kwargs)
        name = "{0}-{1}".format(funcname, token)

        keys = product(
            [name], *([range(len(bd)) for bd in chunks] + [[0]] * len(extra_chunks))
        )
        blocks = product(*[range(len(bd)) for bd in chunks])

        vals = []
        for seed, size, slc, block in zip(seeds, sizes, slices, blocks):
            arg = []
            for i, ar in enumerate(args):
                if i not in lookup:
                    arg.append(ar)
                else:
                    if isinstance(ar, Array):
                        dependencies.append(ar)
                        arg.append((lookup[i],) + block)
                    else:  # np.ndarray
                        arg.append((getitem, lookup[i], slc))
            kwrg = {}
            for k, ar in kwargs.items():
                if k not in lookup:
                    kwrg[k] = ar
                else:
                    if isinstance(ar, Array):
                        dependencies.append(ar)
                        kwrg[k] = (lookup[k],) + block
                    else:  # np.ndarray
                        kwrg[k] = (getitem, lookup[k], slc)
            vals.append(
                (_apply_random, self._RandomState, funcname, seed, size, arg, kwrg)
            )

        meta = _apply_random(
            self._RandomState,
            funcname,
            seed,
            (0,) * len(size),
            small_args,
            small_kwargs,
        )

        dsk.update(dict(zip(keys, vals)))

        graph = HighLevelGraph.from_collections(name, dsk, dependencies=dependencies)
        return Array(graph, name, chunks + extra_chunks, meta=meta)

    @derived_from(np.random.RandomState, skipblocks=1)
    def beta(self, a, b, size=None, chunks="auto", **kwargs):
        return self._wrap("beta", a, b, size=size, chunks=chunks, **kwargs)

    @derived_from(np.random.RandomState, skipblocks=1)
    def binomial(self, n, p, size=None, chunks="auto", **kwargs):
        return self._wrap("binomial", n, p, size=size, chunks=chunks, **kwargs)

    @derived_from(np.random.RandomState, skipblocks=1)
    def chisquare(self, df, size=None, chunks="auto", **kwargs):
        return self._wrap("chisquare", df, size=size, chunks=chunks, **kwargs)

    with ignoring(AttributeError):

        @derived_from(np.random.RandomState, skipblocks=1)
        def choice(self, a, size=None, replace=True, p=None, chunks="auto"):
            dependencies = []
            # Normalize and validate `a`
            if isinstance(a, Integral):
                # On windows the output dtype differs if p is provided or
                # absent, see https://github.com/numpy/numpy/issues/9867
                dummy_p = np.array([1]) if p is not None else p
                dtype = np.random.choice(1, size=(), p=dummy_p).dtype
                len_a = a
                if a < 0:
                    raise ValueError("a must be greater than 0")
            else:
                a = asarray(a)
                a = a.rechunk(a.shape)
                dtype = a.dtype
                if a.ndim != 1:
                    raise ValueError("a must be one dimensional")
                len_a = len(a)
                dependencies.append(a)
                a = a.__dask_keys__()[0]

            # Normalize and validate `p`
            if p is not None:
                if not isinstance(p, Array):
                    # If p is not a dask array, first check the sum is close
                    # to 1 before converting.
                    p = np.asarray(p)
                    if not np.isclose(p.sum(), 1, rtol=1e-7, atol=0):
                        raise ValueError("probabilities do not sum to 1")
                    p = asarray(p)
                else:
                    p = p.rechunk(p.shape)

                if p.ndim != 1:
                    raise ValueError("p must be one dimensional")
                if len(p) != len_a:
                    raise ValueError("a and p must have the same size")

                dependencies.append(p)
                p = p.__dask_keys__()[0]

            if size is None:
                size = ()
            elif not isinstance(size, (tuple, list)):
                size = (size,)

            chunks = normalize_chunks(chunks, size, dtype=np.float64)
            if not replace and len(chunks[0]) > 1:
                err_msg = (
                    "replace=False is not currently supported for "
                    "dask.array.choice with multi-chunk output "
                    "arrays"
                )
                raise NotImplementedError(err_msg)
            sizes = list(product(*chunks))
            state_data = random_state_data(len(sizes), self._numpy_state)

            name = "da.random.choice-%s" % tokenize(
                state_data, size, chunks, a, replace, p
            )
            keys = product([name], *(range(len(bd)) for bd in chunks))
            dsk = {
                k: (_choice, state, a, size, replace, p)
                for k, state, size in zip(keys, state_data, sizes)
            }

            graph = HighLevelGraph.from_collections(
                name, dsk, dependencies=dependencies
            )
            return Array(graph, name, chunks, dtype=dtype)

    # @derived_from(np.random.RandomState, skipblocks=1)
    # def dirichlet(self, alpha, size=None, chunks="auto"):

    @derived_from(np.random.RandomState, skipblocks=1)
    def exponential(self, scale=1.0, size=None, chunks="auto", **kwargs):
        return self._wrap("exponential", scale, size=size, chunks=chunks, **kwargs)

    @derived_from(np.random.RandomState, skipblocks=1)
    def f(self, dfnum, dfden, size=None, chunks="auto", **kwargs):
        return self._wrap("f", dfnum, dfden, size=size, chunks=chunks, **kwargs)

    @derived_from(np.random.RandomState, skipblocks=1)
    def gamma(self, shape, scale=1.0, size=None, chunks="auto", **kwargs):
        return self._wrap("gamma", shape, scale, size=size, chunks=chunks, **kwargs)

    @derived_from(np.random.RandomState, skipblocks=1)
    def geometric(self, p, size=None, chunks="auto", **kwargs):
        return self._wrap("geometric", p, size=size, chunks=chunks, **kwargs)

    @derived_from(np.random.RandomState, skipblocks=1)
    def gumbel(self, loc=0.0, scale=1.0, size=None, chunks="auto", **kwargs):
        return self._wrap("gumbel", loc, scale, size=size, chunks=chunks, **kwargs)

    @derived_from(np.random.RandomState, skipblocks=1)
    def hypergeometric(self, ngood, nbad, nsample, size=None, chunks="auto", **kwargs):
        return self._wrap(
            "hypergeometric", ngood, nbad, nsample, size=size, chunks=chunks, **kwargs
        )

    @derived_from(np.random.RandomState, skipblocks=1)
    def laplace(self, loc=0.0, scale=1.0, size=None, chunks="auto", **kwargs):
        return self._wrap("laplace", loc, scale, size=size, chunks=chunks, **kwargs)

    @derived_from(np.random.RandomState, skipblocks=1)
    def logistic(self, loc=0.0, scale=1.0, size=None, chunks="auto", **kwargs):
        return self._wrap("logistic", loc, scale, size=size, chunks=chunks, **kwargs)

    @derived_from(np.random.RandomState, skipblocks=1)
    def lognormal(self, mean=0.0, sigma=1.0, size=None, chunks="auto", **kwargs):
        return self._wrap("lognormal", mean, sigma, size=size, chunks=chunks, **kwargs)

    @derived_from(np.random.RandomState, skipblocks=1)
    def logseries(self, p, size=None, chunks="auto", **kwargs):
        return self._wrap("logseries", p, size=size, chunks=chunks, **kwargs)

    @derived_from(np.random.RandomState, skipblocks=1)
    def multinomial(self, n, pvals, size=None, chunks="auto", **kwargs):
        return self._wrap(
            "multinomial",
            n,
            pvals,
            size=size,
            chunks=chunks,
            extra_chunks=((len(pvals),),),
        )

    @derived_from(np.random.RandomState, skipblocks=1)
    def negative_binomial(self, n, p, size=None, chunks="auto", **kwargs):
        return self._wrap("negative_binomial", n, p, size=size, chunks=chunks, **kwargs)

    @derived_from(np.random.RandomState, skipblocks=1)
    def noncentral_chisquare(self, df, nonc, size=None, chunks="auto", **kwargs):
        return self._wrap(
            "noncentral_chisquare", df, nonc, size=size, chunks=chunks, **kwargs
        )

    @derived_from(np.random.RandomState, skipblocks=1)
    def noncentral_f(self, dfnum, dfden, nonc, size=None, chunks="auto", **kwargs):
        return self._wrap(
            "noncentral_f", dfnum, dfden, nonc, size=size, chunks=chunks, **kwargs
        )

    @derived_from(np.random.RandomState, skipblocks=1)
    def normal(self, loc=0.0, scale=1.0, size=None, chunks="auto", **kwargs):
        return self._wrap("normal", loc, scale, size=size, chunks=chunks, **kwargs)

    @derived_from(np.random.RandomState, skipblocks=1)
    def pareto(self, a, size=None, chunks="auto", **kwargs):
        return self._wrap("pareto", a, size=size, chunks=chunks, **kwargs)

    @derived_from(np.random.RandomState, skipblocks=1)
    def permutation(self, x):
        from .slicing import shuffle_slice

        if isinstance(x, numbers.Number):
            x = arange(x, chunks="auto")

        index = np.arange(len(x))
        self._numpy_state.shuffle(index)
        return shuffle_slice(x, index)

    @derived_from(np.random.RandomState, skipblocks=1)
    def poisson(self, lam=1.0, size=None, chunks="auto", **kwargs):
        return self._wrap("poisson", lam, size=size, chunks=chunks, **kwargs)

    @derived_from(np.random.RandomState, skipblocks=1)
    def power(self, a, size=None, chunks="auto", **kwargs):
        return self._wrap("power", a, size=size, chunks=chunks, **kwargs)

    @derived_from(np.random.RandomState, skipblocks=1)
    def randint(self, low, high=None, size=None, chunks="auto", dtype="l", **kwargs):
        return self._wrap(
            "randint", low, high, size=size, chunks=chunks, dtype=dtype, **kwargs
        )

    @derived_from(np.random.RandomState, skipblocks=1)
    def random_integers(self, low, high=None, size=None, chunks="auto", **kwargs):
        return self._wrap(
            "random_integers", low, high, size=size, chunks=chunks, **kwargs
        )

    @derived_from(np.random.RandomState, skipblocks=1)
    def random_sample(self, size=None, chunks="auto", **kwargs):
        return self._wrap("random_sample", size=size, chunks=chunks, **kwargs)

    random = random_sample

    @derived_from(np.random.RandomState, skipblocks=1)
    def rayleigh(self, scale=1.0, size=None, chunks="auto", **kwargs):
        return self._wrap("rayleigh", scale, size=size, chunks=chunks, **kwargs)

    @derived_from(np.random.RandomState, skipblocks=1)
    def standard_cauchy(self, size=None, chunks="auto", **kwargs):
        return self._wrap("standard_cauchy", size=size, chunks=chunks, **kwargs)

    @derived_from(np.random.RandomState, skipblocks=1)
    def standard_exponential(self, size=None, chunks="auto", **kwargs):
        return self._wrap("standard_exponential", size=size, chunks=chunks, **kwargs)

    @derived_from(np.random.RandomState, skipblocks=1)
    def standard_gamma(self, shape, size=None, chunks="auto", **kwargs):
        return self._wrap("standard_gamma", shape, size=size, chunks=chunks, **kwargs)

    @derived_from(np.random.RandomState, skipblocks=1)
    def standard_normal(self, size=None, chunks="auto", **kwargs):
        return self._wrap("standard_normal", size=size, chunks=chunks, **kwargs)

    @derived_from(np.random.RandomState, skipblocks=1)
    def standard_t(self, df, size=None, chunks="auto", **kwargs):
        return self._wrap("standard_t", df, size=size, chunks=chunks, **kwargs)

    @derived_from(np.random.RandomState, skipblocks=1)
    def tomaxint(self, size=None, chunks="auto", **kwargs):
        return self._wrap("tomaxint", size=size, chunks=chunks, **kwargs)

    @derived_from(np.random.RandomState, skipblocks=1)
    def triangular(self, left, mode, right, size=None, chunks="auto", **kwargs):
        return self._wrap(
            "triangular", left, mode, right, size=size, chunks=chunks, **kwargs
        )

    @derived_from(np.random.RandomState, skipblocks=1)
    def uniform(self, low=0.0, high=1.0, size=None, chunks="auto", **kwargs):
        return self._wrap("uniform", low, high, size=size, chunks=chunks, **kwargs)

    @derived_from(np.random.RandomState, skipblocks=1)
    def vonmises(self, mu, kappa, size=None, chunks="auto", **kwargs):
        return self._wrap("vonmises", mu, kappa, size=size, chunks=chunks, **kwargs)

    @derived_from(np.random.RandomState, skipblocks=1)
    def wald(self, mean, scale, size=None, chunks="auto", **kwargs):
        return self._wrap("wald", mean, scale, size=size, chunks=chunks, **kwargs)

    @derived_from(np.random.RandomState, skipblocks=1)
    def weibull(self, a, size=None, chunks="auto", **kwargs):
        return self._wrap("weibull", a, size=size, chunks=chunks, **kwargs)

    @derived_from(np.random.RandomState, skipblocks=1)
    def zipf(self, a, size=None, chunks="auto", **kwargs):
        return self._wrap("zipf", a, size=size, chunks=chunks, **kwargs)

def _choice(state_data, a, size, replace, p):
    state = np.random.RandomState(state_data)
    return state.choice(a, size=size, replace=replace, p=p)

def _apply_random(RandomState, funcname, state_data, size, args, kwargs):
    """Apply RandomState method with seed"""
    if RandomState is None:
        RandomState = np.random.RandomState
    state = RandomState(state_data)
    func = getattr(state, funcname)
    return func(*args, size=size, **kwargs)

_state = RandomState()

seed = _state.seed

beta = _state.beta
binomial = _state.binomial
chisquare = _state.chisquare
if hasattr(_state, "choice"):
    choice = _state.choice
exponential = _state.exponential
f = _state.f
gamma = _state.gamma
geometric = _state.geometric
gumbel = _state.gumbel
hypergeometric = _state.hypergeometric
laplace = _state.laplace
logistic = _state.logistic
lognormal = _state.lognormal
logseries = _state.logseries
multinomial = _state.multinomial
negative_binomial = _state.negative_binomial
noncentral_chisquare = _state.noncentral_chisquare
noncentral_f = _state.noncentral_f
normal = _state.normal
pareto = _state.pareto
permutation = _state.permutation
poisson = _state.poisson
power = _state.power
rayleigh = _state.rayleigh
random_sample = _state.random_sample
random = random_sample
randint = _state.randint
random_integers = _state.random_integers
triangular = _state.triangular
uniform = _state.uniform
vonmises = _state.vonmises
wald = _state.wald
weibull = _state.weibull
zipf = _state.zipf

"""
Standard distributions
"""

standard_cauchy = _state.standard_cauchy
standard_exponential = _state.standard_exponential
standard_gamma = _state.standard_gamma
standard_normal = _state.standard_normal
standard_t = _state.standard_t


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Ann. bot. fenn. 40(3): 216 (2003)

#### Original name
Clitocybe bresadolana var. dryadum Bon

### Remarks
null


text:
==================================
Rule set ``@PHP56Migration:risky``
==================================

Rules to improve code for PHP 5.6 compatibility. This set contains rules that are risky.

Rules
-----

- `pow_to_exponentiation <./../rules/alias/pow_to_exponentiation.rst>`_


text:
//
// Copyright (c) Microsoft and contributors.  All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//

var assert = require('assert');

var fs = require('fs');
var path = require("path");
var util = require('util');

// Test includes
var testutil = require('../../util/util');

// Lib includes
var azureutil = testutil.libRequire('common/lib/util/util');
var azure = testutil.libRequire('azure');

var SharedAccessSignature = azure.SharedAccessSignature;
var BlobService = azure.BlobService;
var ServiceClient = azure.ServiceClient;
var Constants = azure.Constants;
var HttpConstants = Constants.HttpConstants;
var BlobConstants = Constants.BlobConstants;

var blobService;
var containerNames = [];
var containerNamesPrefix = 'cont';
var blobNames = [];
var blobNamesPrefix = 'blob';

var mockServerClient;
var currentTestName;

suite('blobservice-longrunning-tests', function () {
  setup(function (done) {
    blobService = azure.createBlobService(ServiceClient.DEVSTORE_STORAGE_ACCOUNT, ServiceClient.DEVSTORE_STORAGE_ACCESS_KEY, ServiceClient.DEVSTORE_BLOB_HOST);

    done();
  });

  teardown(function (done) {
    var deleteFiles = function () {
      // delete test files
      var list = fs.readdirSync('./');
      list.forEach(function (file) {
        if (file.indexOf('.test') !== -1) {
          fs.unlinkSync(file);
        }
      });

      done();
    };

    // delete blob containers
    blobService.listContainers(function (listError, containers) {
      if (containers && containers.length > 0) {
        var containerCount = 0;
        containers.forEach(function (container) {
          blobService.deleteContainer(container.name, function () {
            containerCount++;
            if (containerCount === containers.length) {
              // clean up
              deleteFiles();
            }
          });
        });
      }
      else {
        // clean up
        deleteFiles();
      }
    });
  });

  test('GetBlobToStream', function (done) {
    var containerName = testutil.generateId(containerNamesPrefix, containerNames);
    var blobName = testutil.generateId(blobNamesPrefix, blobNames);
    var fileNameTarget = testutil.generateId('getBlobFile') + '.test';
    var blobText = 'Hello World';

    blobService.createContainer(containerName, function (createError1, container1) {
      assert.equal(createError1, null);
      assert.notEqual(container1, null);

      blobService.createBlockBlobFromText(containerName, blobName, blobText, function (error1) {
        assert.equal(error1, null);

        blobService.getBlobToFile(containerName, blobName, fileNameTarget, function (error2) {
          assert.equal(error2, null);

          path.exists(fileNameTarget, function (exists) {
            assert.equal(exists, true);

            var fileText = fs.readFileSync(fileNameTarget);
            assert.equal(blobText, fileText);
            done();
          });
        });
      });
    });
  });

  test('SmallUploadBlobFromFile', function (done) {
    var containerName = testutil.generateId(containerNamesPrefix, containerNames);
    var blobName = testutil.generateId(blobNamesPrefix, blobNames);
    var fileNameSource = testutil.generateId('getBlobFile') + '.test';
    var blobText = 'Hello World';

    fs.writeFile(fileNameSource, blobText, function () {
      blobService.createContainer(containerName, function (createError1, container1, createResponse1) {
        assert.equal(createError1, null);
        assert.notEqual(container1, null);
        assert.ok(createResponse1.isSuccessful);
        assert.equal(createResponse1.statusCode, HttpConstants.HttpResponseCodes.Created);

        var blobOptions = { contentType: 'text' };
        blobService.createBlockBlobFromFile(containerName, blobName, fileNameSource, blobOptions, function (uploadError, blobResponse, uploadResponse) {
          assert.equal(uploadError, null);
          assert.notEqual(blobResponse, null);
          assert.ok(uploadResponse.isSuccessful);

          blobService.getBlobToText(containerName, blobName, function (downloadErr, blobTextResponse) {
            assert.equal(downloadErr, null);
            assert.equal(blobTextResponse, blobText);

            blobService.getBlobProperties(containerName, blobName, function (getBlobPropertiesErr, blobGetResponse) {
              assert.equal(getBlobPropertiesErr, null);
              assert.notEqual(blobGetResponse, null);
              if (blobGetResponse) {
                assert.equal(blobOptions.contentType, blobGetResponse.contentType);
              }

              done();
            });
          });
        });
      });
    });
  });

  test('AnalyzeStream', function (done) {
    var containerName = testutil.generateId(containerNamesPrefix, containerNames);
    var blobName = testutil.generateId(blobNamesPrefix, blobNames);
    var fileNameSource = testutil.generateId('getBlobFile') + '.test';
    var blobText = 'Hello World';

    fs.writeFile(fileNameSource, blobText, function () {
      blobService.createContainer(containerName, function (createError1, container1, createResponse1) {
        assert.equal(createError1, null);
        assert.notEqual(container1, null);
        assert.ok(createResponse1.isSuccessful);
        assert.equal(createResponse1.statusCode, HttpConstants.HttpResponseCodes.Created);

        blobService.createBlockBlobFromFile(containerName, blobName, fileNameSource, { setBlobContentMD5: true }, function (uploadError, blobResponse, uploadResponse) {
          assert.equal(uploadError, null);
          assert.notEqual(blobResponse, null);
          assert.ok(uploadResponse.isSuccessful);

          blobService.getBlobToText(containerName, blobName, function (downloadErr, blobTextResponse) {
            assert.equal(downloadErr, null);
            assert.equal(blobTextResponse, blobText);

            done();
          });
        });
      });
    });
  });

  test('InvalidMD5SmallFile', function (done) {
    var containerName = testutil.generateId(containerNamesPrefix, containerNames);
    var blobName = testutil.generateId(blobNamesPrefix, blobNames);
    var fileNames = [];
    var fileNameSource = testutil.generateId('getBlobFile', fileNames) + '.test';
    var fileNameTarget = testutil.generateId('getBlobFile', fileNames) + '.test';
    var blobText = 'Hello World';

    fs.writeFile(fileNameSource, blobText, function () {
      blobService.createContainer(containerName, function (createError1, container1, createResponse1) {
        assert.equal(createError1, null);
        assert.notEqual(container1, null);
        assert.ok(createResponse1.isSuccessful);
        assert.equal(createResponse1.statusCode, HttpConstants.HttpResponseCodes.Created);

        blobService.createBlockBlobFromFile(containerName, blobName, fileNameSource, { setBlobContentMD5: true }, function (uploadError, blobResponse, uploadResponse) {
          assert.equal(uploadError, null);
          assert.notEqual(blobResponse, null);
          assert.ok(uploadResponse.isSuccessful);

          // Just retrieving works fine
          blobService.getBlobToFile(containerName, blobName, fileNameTarget, function (downloadErr1) {
            assert.equal(downloadErr1, null);

            // replace contentMD5 by a messed up one
            var blobOptions = { contentMD5: 'fake' };
            blobService.setBlobProperties(containerName, blobName, blobOptions, function (setPropErr) {
              assert.equal(setPropErr, null);

              blobService.getBlobToFile(containerName, blobName, fileNameTarget, function (downloadErr2) {
                assert.notEqual(downloadErr2, null);
                assert.equal(downloadErr2, 'Blob data corrupted (integrity check failed), Expected value is fake, retrieved sQqNsWTgdUEFt6mb5y4/5Q==');

                done();
              });
            });
          });
        });
      });
    });
  });

  test('SharedAccess', function (done) {
    var containerName = testutil.generateId(containerNamesPrefix, containerNames);
    var blobName = testutil.generateId(blobNamesPrefix, blobNames);
    var blobText = 'text';

    var sharedBlobClient = azure.createBlobService();
    var sharedAccessSignature = new SharedAccessSignature(sharedBlobClient.storageAccount, sharedBlobClient.storageAccessKey);
    sharedBlobClient.authenticationProvider = sharedAccessSignature;

    var managementBlobClient = azure.createBlobService();

    managementBlobClient.createContainer(containerName, function (createError, container1, createResponse) {
      assert.equal(createError, null);
      assert.notEqual(container1, null);
      assert.ok(createResponse.isSuccessful);

      var currentDate = new Date();
      var futureDate = new Date(currentDate);
      futureDate.setMinutes(currentDate.getMinutes() + 5);

      var sharedAccessPolicy = {
        AccessPolicy: {
          Expiry: futureDate,
          Permissions: BlobConstants.SharedAccessPermissions.WRITE
        }
      };

      // Get shared access Url valid for the next 5 minutes
      var sharedAccessCredentials = managementBlobClient.generateSharedAccessSignature(
        containerName,
        null,
        sharedAccessPolicy);

      sharedAccessSignature.permissionSet = [sharedAccessCredentials];

      // Writing the blob should be possible
      sharedBlobClient.createBlockBlobFromText(containerName, blobName, blobText, function (putError, blob, putResponse) {
        assert.equal(putError, null);
        assert.ok(putResponse.isSuccessful);

        // Make sure its not possible to get the blob since only write permission was given
        sharedBlobClient.getBlobToText(containerName, blobName, function (getError, content, blockBlob, getResponse) {
          assert.equal(getError.code, Constants.StorageErrorCodeStrings.RESOURCE_NOT_FOUND);
          assert.equal(content, null);
          assert.equal(blockBlob, null);
          assert.notEqual(getResponse, null);
          if (getResponse) {
            assert.equal(getResponse.isSuccessful, false);
          }

          done();
        });
      });
    });
  });
});

function repeat(s, n) {
  var ret = "";
  for (var i = 0; i < n; i++) {
    ret += s;
  }
  return ret;
}


text:
title: Version 2.20.0 released
categories:
  - news
tags:
  - release
description: >
  Version 2.20.0 of this project has been released.
excerpt: >
  Release highlights: New git lb alias, Go 1.14.2, Java 8u252 & 11.0.7...
read_time: no
date: 2020-04-27T21:19:32+01:00
modified: 2020-04-27T21:19:32+01:00
---

## Release highlights

* [#677](https://github.com/gantsign/development-environment/pull/677):
  Updated Go lang to 1.14.2
* [#678](https://github.com/gantsign/development-environment/pull/678):
  Updated Java 8 to 8u252
* [#679](https://github.com/gantsign/development-environment/pull/679):
  Updated Java 11 to 11.0.7
* [#682](https://github.com/gantsign/development-environment/pull/682):
  Add git lb alias to view recent branches

## Full change list

For a full list of changes view the
[release notes](https://github.com/gantsign/development-environment/releases/tag/2.20.0).

## Upgrade procedure

To upgrade follow the
[upgrade documentation]({{ '/docs/upgrade/' | relative_url }}).


text:
#include <aws/proton/model/UpdateAccountSettingsRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Proton::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

UpdateAccountSettingsRequest::UpdateAccountSettingsRequest() :
    m_pipelineServiceRoleArnHasBeenSet(false)
{
}

Aws::String UpdateAccountSettingsRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_pipelineServiceRoleArnHasBeenSet)
  {
   payload.WithString("pipelineServiceRoleArn", m_pipelineServiceRoleArn);

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection UpdateAccountSettingsRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AwsProton20200720.UpdateAccountSettings"));
  return headers;

}


text:
import paths from '../config/paths.json'
import { argv as argv } from 'yargs'
import webpack from 'webpack'
import CommonsChunkPlugin from '../node_modules/webpack/lib/optimize/CommonsChunkPlugin'
let theSourcemap

// Create plugins array
const plugins = [
  new CommonsChunkPlugin('commons.js'),
  new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery'
  })
]

// Add Uglify task to plugins array if there is a production flag
// If not production, generate sourcemap
if (argv.production) {
  plugins.push(new webpack.optimize.UglifyJsPlugin())
  theSourcemap = ''
}
else {
  theSourcemap = 'source-map'
}

module.exports = {
  entry: {
    home: './' + paths.js + 'app-home',
    blog: './' + paths.js + 'app-blog'
  },
  output: {
    path: './' + paths.buildAssets + 'js/',
    filename: '[name].bundle.js',
    chunkFilename: '[id].chunk.js',
    publicPath: '/assets/js/'
  },
  devtool: theSourcemap,
  plugins: plugins,
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel',
        query: {
          presets: ['es2015']
        }
      }
    ]
  }
}


text: Ansible module for installing Bareos Director, Storage, File Daemon and REAR.


text:
"""Mock UI tests."""

def test_something_ui():
    pass


text:
class AddPermaIdToFileUsages < ActiveRecord::Migration[5.2]
  def up
    add_column :pageflow_file_usages, :file_perma_id, :integer, after: 'file_id'
    add_index :pageflow_file_usages,
              [:revision_id, :file_type, :file_perma_id],
              name: 'index_pageflow_file_usages_on_revision_and_file'
    execute('UPDATE pageflow_file_usages SET file_perma_id = file_id;')
  end

  def down
    remove_column :pageflow_file_usages, :file_perma_id
  end
end