text:
/**
 * Autogenerated by Thrift Compiler (0.9.0)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
package org.apache.hive.service.cli.thrift;

import java.util.Map;
import java.util.HashMap;
import org.apache.thrift.TEnum;

public enum TOperationType implements org.apache.thrift.TEnum {
  EXECUTE_STATEMENT(0),
  GET_TYPE_INFO(1),
  GET_CATALOGS(2),
  GET_SCHEMAS(3),
  GET_TABLES(4),
  GET_TABLE_TYPES(5),
  GET_COLUMNS(6),
  GET_FUNCTIONS(7),
  UNKNOWN(8);

  private final int value;

  private TOperationType(int value) {
    this.value = value;
  }

  /**
   * Get the integer value of this enum value, as defined in the Thrift IDL.
   */
  public int getValue() {
    return value;
  }

  /**
   * Find a the enum type by its integer value, as defined in the Thrift IDL.
   * @return null if the value is not found.
   */
  public static TOperationType findByValue(int value) {
    switch (value) {
      case 0:
        return EXECUTE_STATEMENT;
      case 1:
        return GET_TYPE_INFO;
      case 2:
        return GET_CATALOGS;
      case 3:
        return GET_SCHEMAS;
      case 4:
        return GET_TABLES;
      case 5:
        return GET_TABLE_TYPES;
      case 6:
        return GET_COLUMNS;
      case 7:
        return GET_FUNCTIONS;
      case 8:
        return UNKNOWN;
      default:
        return null;
    }
  }
}


text:
<?php

namespace Pulpy\Core\Services\PostFile;

use Symfony\Component\Finder\Finder;

use Pulpy\Core\Services\PersistentStorage\PersistentStorageServiceInterface,
    Pulpy\Core\Entity\Post;

class PostFileRepositoryService {

    protected $fs;
    protected $postresolver;
    protected $postpath;
    protected $postfileextension;
    protected $runtimecache;

    public function __construct(PersistentStorageServiceInterface $fs, PostFileResolverService $postresolver, PostFileReaderService $postreader, $postspath, $postfileextension) {
        $this->fs = $fs;
        $this->postresolver = $postresolver;
        $this->postreader = $postreader;
        $this->postspath = rtrim($postspath, '/') . '/';
        $this->postfileextension = ltrim($postfileextension, '.');
        $this->runtimecache = array();
    }

    public function findOneBySlug($slug) {

        $postpath = $this->postresolver->filepathFromSlug($slug);
        $post = $this->postreader->getPost($postpath);
        if($post) {
            return $post;
        }

        # post is not found based on slug
        # We list all posts, and try to find the one with the correct slug (could be defined in it's Yaml Front matter)

        $posts = $this->findAll();
        foreach($posts as $post) {
            if($post->getSlug() === $slug) {

                # It's a match
                return $post;
            }
        }

        return null;
    }

    public function findPrevious(Post $post) {
        $current = null;
        $posts = $this->findAll();

        for($k = 0; $k < count($posts); $k++) {
            if($post->getSlug() === $posts[$k]->getSlug()) {
                $current = $k;
                break;
            }
        }

        if(
            is_null($current) ||
            $current + 1 >= count($posts)
        ) {
            return null;
        }

        return $posts[$current+1];
    }

    public function findNext(Post $post) {

        $current = null;
        $posts = $this->findAll();

        for($k = 0; $k < count($posts); $k++) {
            if($post->getSlug() === $posts[$k]->getSlug()) {
                $current = $k;
                break;
            }
        }

        if(
            is_null($current) ||
            $current - 1 < 0
        ) {
            return null;
        }

        return $posts[$current-1];
    }

    public function findAll() {

        $files = $this->fs->getAll($this->postspath, $this->postfileextension);

        foreach($files as $file) {
            $post = $this->postreader->getPost($file);
            if($post->getStatus() === 'publish') {
                $posts[] = $post;
            }
        }

        usort($posts, function($a, $b) {
            return $a->getDate() < $b->getDate();
        });

        return $posts;
    }
}

redpajama_set_name: RedPajamaGithub


text:
/**
@class Seemple.Object
@module seemple/object
@importance 1
@classdesc ``Seemple.Object`` - класс, который отвечает за данные вида ключ-значение. Его задачей является отделение служебных свойств от данных, которые можно передать на сервер или сохранить в локальном хранилище. Класс наследуется от класса {@link Seemple} и включает все его свойства и методы.

Представьте себе, что вы создаёте класс, включающий свойства ``"a"``, ``"b"`` и ``"c"``. Допустим ``"a"`` и ``"b"`` - свойства которые должны быть отправлены на сервер, а свойство ``"c"`` лишь отвечает за некоторое состояние приложения (например, содержит сумму ``"a"`` и ``"b"``). Свойство ``"c"`` не нужно серверу. Поэтому нам нужно отделить **свойства отвечающие за данные** от свойств, которые таковыми не являются.

Для того, чтоб отделить такие свойства от остальных, можно воспользоваться методом {@link Seemple.Object#addDataKeys}.
```js
this.addDataKeys(['a', 'b']);

this.a = 1;
this.b = 2;
this.c = 3;
```

Если вы заранее не знаете, какие свойства являются данными, можно всегда использовать метод {@link Seemple.Object#setData}, который не только объявляет свойства, отвечающие за данные, но и сразу устанавливает значения.
```js
this.setData({
	a: 1,
	b: 2
});

this.c = 3;
```

После того, как приложение получило информацию о том, что является данными, экземпляр {@link Seemple.Object} можно сконвертировать в обычный объект методом {@link Seemple.Object#toJSON} и передать на сервер или сохранить в локальной БД (например, в ``localStorage``).
```js
// вернет объект { a: 1, b: 2 }
this.toJSON();
```

#### События

При добавлении и изменении свойств, отвечающих за данные генерируется события ``set`` и ``modify``, при удалении - ``remove`` и ``modify``. Т. е. любые изменения данных можно слушать с помощью ``modify``.
```js
this.on('modify', () => {
	alert('Object is modified');
});
```
@param {object} [data] - Данные, входящие в новый экземпляр
@inherits Seemple
@example
Создание экземпляра с двумя свойствами-данными

// то же самое, что и new Seemple.Object().setData({ a: 1, b: 2 });
new Seemple.Object({ a: 1, b: 2 });

@example
Наследование

class MyClass extends Seemple.Object {
	constructor(data) {
		super(data).sayHello();
	}
	sayHello() {
		alert("Hello World!");
	}
}
@example
Наследование при помощи функции {@link Seemple.Class}

const MyClass = Seemple.Class({
	extends: Seemple.Object,
	constructor(data) {
		this.setData(data).sayHello();
	},
	sayHello() {
		alert("Hello World!");
	}
});
@example
Перебор данных, используя цикл for..of

const seempleObject = new Seemple.Object({ a: 1, b: 2 });
for(let item of seempleObject) {
	console.log(item); // 1 .. 2
}
*/


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using nRoute.Navigation.Mapping;

namespace EspaceClient.BackOffice.Silverlight.Views.GestionClient.Contact
{
    /// <summary>
    /// Fiche descriptive d'un client PM
    /// </summary>
    [MapNavigationContent("GestionClient/Contact/Details/")]
    [MapNavigationContent("GestionClient/Contact/Details/Fiche/{Id}")]
    public partial class DetailsView : UserControl
    {
        /// <summary>
        /// Initialise une nouvelle instance du contrôle.
        /// </summary>
        public DetailsView()
        {
            InitializeComponent();
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using XenAPI;
using System.Windows.Forms;
using XenAdmin.Dialogs.WarningDialogs;
using XenAdmin.Actions;
using System.Collections.ObjectModel;

namespace XenAdmin.Commands
{
    /// <summary>
    /// Removes the crash-dumps from the selected host.
    /// </summary>
    internal class RemoveHostCrashDumpsCommand : Command
    {
        /// <summary>
        /// Initializes a new instance of this Command. The parameter-less constructor is required if
        /// this Command is to be attached to a ToolStrip menu item or button. It should not be used in any other scenario.
        /// </summary>
        public RemoveHostCrashDumpsCommand()
        {
        }

        public RemoveHostCrashDumpsCommand(IMainWindow mainWindow, IEnumerable<SelectedItem> selection)
            : base(mainWindow, selection)
        {
        }

        public RemoveHostCrashDumpsCommand(IMainWindow mainWindow, Host host)
            : base(mainWindow, host)
        {
        }

        protected override void ExecuteCore(SelectedItemCollection selection)
        {
            Host host = selection[0].HostAncestor;

            DialogResult result = new RemoveCrashDumpsWarningDialog(host).ShowDialog(Parent);

            if (result == DialogResult.OK)
            {
                new DestroyHostCrashDumpAction(host).RunAsync();
            }
        }

        protected override bool CanExecuteCore(SelectedItemCollection selection)
        {
            if (selection.Count == 1)
            {
                Host hostAncestor = selection[0].HostAncestor;
                return hostAncestor != null && hostAncestor.HasCrashDumps;
            }
            return false;
        }

        public override string MenuText
        {
            get
            {
                return Messages.MAINWINDOW_REMOVE_HOST_CRASHDUMPS;
            }
        }

        public override string ContextMenuText
        {
            get
            {
                return Messages.MAINWINDOW_REMOVE_HOST_CRASHDUMPS_CONTEXT_MENU;
            }
        }
    }
}


text:
import {LitElement, html} from "lit";
import UtilsNew from "../../core/utils-new.js";
import "../commons/tool-header.js";

export default class StudyForm extends LitElement {

    constructor() {
        super();
        this._init();
    }

    createRenderRoot() {
        return this;
    }

    static get properties() {
        return {
            project: {
                type: Object
            },
            opencgaSession: {
                type: Object
            },
            config: {
                type: Object
            }
        };
    }

    _init() {
        this._prefix = UtilsNew.randomString(8);
        this.study = {};
    }

    onFieldChange(e) {
        const field = e.detail.param;
        switch (e.detail.param) {
            case "id":
            case "name":
            case "description":
                this.study = {
                    ...this.study,
                    [field]: e.detail.value
                };
                break;
        }
        // Study is not a lit property  #L32,
        // so it's necessary use requestUpdate();
        this.requestUpdate();
        console.log("New Study", this.study);
    }

    getSaveForm(e) {
        console.log(e.detail.param);
    }

    onSave(e) {
        // TODO: Check it's ok ?
        this.opencgaSession.opencgaClient.studies().create(this.study, {project: this.project.fqn})
            .then(res => {
                this.study = {};
                this.requestUpdate();

                this.dispatchEvent(new CustomEvent("sessionUpdateRequest", {
                    detail: {
                    },
                    bubbles: true,
                    composed: true
                }));

                Swal.fire(
                    "New Study",
                    "New Study created correctly.",
                    "success"
                );
            })
            .catch(err => {
                console.error(err);
                params.error(err);
            });
        $("#newStudy").modal("hide"); // TODO: refactor this function.
    }

    onHide() {
        this.dispatchEvent(new CustomEvent("hide", {
            detail: {},
            bubbles: true,
            composed: true
        }));
    }

    getStudyFormConfig() {
        return {
            title: "Edit",
            icon: "fas fa-edit",
            type: "form",
            buttons: {
                show: true,
                cancelText: "Cancel",
                okText: "Save"
            },
            display: {
                style: "margin: 25px 50px 0px 0px",
                // mode: {
                //     type: "modal",
                //     title: "Review Variant",
                //     buttonClass: "btn-link"
                // },
                labelWidth: 3,
                labelAlign: "right",
                defaultValue: "",
                defaultLayout: "horizontal",
            },
            sections: [
                {
                    elements: [
                        {
                            name: "id",
                            field: "id",
                            type: "input-text",
                            display: {
                                placeholder: "Add a short ID...",
                            }
                        },
                        {
                            name: "Name",
                            field: "name",
                            type: "input-text",
                            display: {
                                placeholder: "Study name...",
                            }
                        },
                        {
                            name: "Description",
                            field: "description",
                            type: "input-text",
                            display: {
                                rows: 3,
                                placeholder: "Study description...",
                            }
                        },
                    ]
                }
            ]
        };
    }

    render() {
        return html`
            <data-form  .data=${this.study}
                        .config="${this.getStudyFormConfig()}"
                        @fieldChange="${e => this.onFieldChange(e)}"
                        @clear="${this.onHide}"
                        @submit="${this.onSave}">
            </data-form>
        `;
    }

}

customElements.define("study-form", StudyForm);


text:
import { AxiosError } from 'axios';
import { TimeZones } from 'types/course/admin/course';
import {
  EmailData,
  EmailPostData,
  EmailsData,
  PasswordData,
  PasswordPostData,
  ProfileData,
  ProfilePostData,
} from 'types/users';

import GlobalUsersAPI from 'api/Users';

export type AccountSettingsData = ProfileData & EmailsData & PasswordData;

const PASSWORD_TEMPLATE: PasswordData = {
  currentPassword: '',
  password: '',
  passwordConfirmation: '',
};

/**
 * Fetches profile and emails data, then returns them and an empty password template.
 */
export const fetchAccountSettings = async (): Promise<AccountSettingsData> => {
  const profile = GlobalUsersAPI.users.fetchProfile();
  const emails = GlobalUsersAPI.users.fetchEmails();
  const [profileResponse, emailsResponse] = await Promise.all([
    profile,
    emails,
  ]);

  const profileData = profileResponse.data;
  const emailsData = emailsResponse.data;

  return { ...profileData, ...emailsData, ...PASSWORD_TEMPLATE };
};

export const updateProfile = async (
  data: Partial<ProfileData>,
): Promise<Partial<ProfileData> | undefined> => {
  if (!data.name && !data.timezone) return undefined;

  const adaptedData: ProfilePostData = {
    user: {
      name: data.name,
      time_zone: data.timezone,
    },
  };

  try {
    const response = await GlobalUsersAPI.users.updateProfile(adaptedData);
    return { name: response.data.name, timezone: response.data.timezone };
  } catch (error) {
    if (error instanceof AxiosError) throw error.response?.data?.errors;
    throw error;
  }
};

export const updatePassword = async (
  data: Partial<PasswordData>,
): Promise<PasswordData | undefined> => {
  if (!data.currentPassword && !data.password && !data.passwordConfirmation)
    return undefined;

  const adaptedData: PasswordPostData = {
    user: {
      current_password: data.currentPassword,
      password: data.password,
      password_confirmation: data.passwordConfirmation,
    },
  };

  try {
    await GlobalUsersAPI.users.updatePassword(adaptedData);
    return PASSWORD_TEMPLATE;
  } catch (error) {
    if (error instanceof AxiosError) throw error.response?.data?.errors;
    throw error;
  }
};

/**
 * Updates profile data (except the profile photo) and password, then returns the new
 * updated profile data, along with an empty password template and original `emails`.
 */
export const updateAccountSettings = async (
  data: Partial<AccountSettingsData>,
): Promise<Partial<AccountSettingsData>> => {
  const profileUpdate = updateProfile(data);
  const passwordUpdate = updatePassword(data);

  const responses = await Promise.all([profileUpdate, passwordUpdate]);
  return Object.assign({}, ...responses);
};

export const updateProfilePicture = async (
  file: File,
): Promise<Partial<ProfileData>> => {
  try {
    const response = await GlobalUsersAPI.users.updateProfilePicture(file);
    return { imageUrl: response.data.imageUrl };
  } catch (error) {
    if (error instanceof AxiosError)
      throw new Error(error.response?.data?.errors?.profile_photo);

    throw error;
  }
};

export const fetchTimeZones = async (): Promise<TimeZones> => {
  const response = await GlobalUsersAPI.users.fetchTimeZones();
  return response.data;
};

export const addEmail = async (
  email: EmailData['email'],
): Promise<EmailsData> => {
  const adaptedData: EmailPostData = { user_email: { email } };

  try {
    const response = await GlobalUsersAPI.users.addEmail(adaptedData);
    return response.data;
  } catch (error) {
    if (error instanceof AxiosError) throw error.response?.data?.errors;
    throw error;
  }
};

export const removeEmail = async (id: EmailData['id']): Promise<EmailsData> => {
  try {
    const response = await GlobalUsersAPI.users.removeEmail(id);
    return response.data;
  } catch (error) {
    if (error instanceof AxiosError) throw error.response?.data?.errors;
    throw error;
  }
};

export const setEmailAsPrimary = async (
  url: NonNullable<EmailData['setPrimaryUserEmailPath']>,
): Promise<EmailsData> => {
  try {
    const response = await GlobalUsersAPI.users.setEmailAsPrimary(url);
    return response.data;
  } catch (error) {
    if (error instanceof AxiosError) throw error.response?.data?.errors;
    throw error;
  }
};

export const resendConfirmationEmail = async (
  url: NonNullable<EmailData['confirmationEmailPath']>,
): Promise<void> => {
  try {
    await GlobalUsersAPI.users.resendConfirmationEmail(url);
  } catch (error) {
    if (error instanceof AxiosError) throw error.response?.data?.errors;
    throw error;
  }
};


text:
<?php

/**
 * A protected API call to add a page
 * @uri /menuitem/add
 */
class MenuItemAddResource extends Tonic\Resource {

    /**
     * @method POST
     */
    function add() {

        // get an authuser
        $token = Utilities::ValidateJWTToken(apache_request_headers());

		// check if token is not null
        if($token != NULL){

            parse_str($this->request->data, $request); // parse request

            $name = $request['name'];
            $cssClass = $request['cssClass'];
            $type = $request['type'];
            $url = $request['url'];
            $pageId = $request['pageId'];
            $priority = $request['priority'];
            $siteId = $token->SiteId;
            $lastModifiedBy = $token->UserId;

            $menuItem = MenuItem::Add($name, $cssClass, $type, $url, $pageId, $priority, $siteId, $lastModifiedBy);

            // return a json response
            $response = new Tonic\Response(Tonic\Response::OK);
            $response->contentType = 'application/json';
            $response->body = json_encode($menuItem);

            return $response;

        } else{ // unauthorized access

            return new Tonic\Response(Tonic\Response::UNAUTHORIZED);
        }
    }

}

/**
 * A protected API call to get a list of menu types
 * @uri /menuitem/list/
 */
class MenuItemListResource extends Tonic\Resource {

    /**
     * @method GET
     */
    function get() {

        // get an authuser
        $token = Utilities::ValidateJWTToken(apache_request_headers());

		// check if token is not null
        if($token != NULL){

            parse_str($this->request->data, $request); // parse request

            $type = $request['type'];

            $list = MenuItem::GetMenuItemsForType($authUser->SiteId, $type);

            // return a json response
            $response = new Tonic\Response(Tonic\Response::OK);
            $response->contentType = 'application/json';
            $response->body = json_encode($list);

            return $response;
        }
        else{
            return new Tonic\Response(Tonic\Response::UNAUTHORIZED);
        }
    }
}

/**
 * A protected API call to get a list of menu types
 * @uri /menuitem/list/all
 */
class MenuItemListAllResource extends Tonic\Resource {

    /**
     * @method GET
     */
    function get() {

        // get an authuser
        $token = Utilities::ValidateJWTToken(apache_request_headers());

		// check if token is not null
        if($token != NULL){

            parse_str($this->request->data, $request); // parse request

            $list = MenuItem::GetMenuItems($token->SiteId);

            // return a json response
            $response = new Tonic\Response(Tonic\Response::OK);
            $response->contentType = 'application/json';
            $response->body = json_encode($list);

            return $response;
        }
        else{
            return new Tonic\Response(Tonic\Response::UNAUTHORIZED);
        }
    }
}

/**
 * A protected API call to update the order of a menu
 * @uri /menuitem/save/priorities
 */
class MenuItemSavePrioritiesResource extends Tonic\Resource {

    /**
     * @method POST
     */
    function updateOrder() {

        // get an authuser
        $token = Utilities::ValidateJWTToken(apache_request_headers());

		// check if token is not null
        if($token != NULL){

            parse_str($this->request->data, $request); // parse request

            $json = $request['priorities'];

            $arr = json_decode($json, true);

            // update the order of the menu item
            foreach ($arr as $key => $value){
                MenuItem::EditPriority($key, $value);
            }

            // return a json response
            $response = new Tonic\Response(Tonic\Response::OK);

            return $response;

        } else{ // unauthorized access

            return new Tonic\Response(Tonic\Response::UNAUTHORIZED);
        }
    }

}

/**
 * A protected API call to update the order of a menu
 * @uri /menuitem/toggle/nested
 */
class MenuItemNestedResource extends Tonic\Resource {

    /**
     * @method POST
     */
    function updateIsNested() {

        // get an authuser
        $token = Utilities::ValidateJWTToken(apache_request_headers());

		// check if token is not null
        if($token != NULL){

            parse_str($this->request->data, $request); // parse request

            $menuItemId = $request['menuItemId'];
            $isNested = $request['isNested'];

            $menuItem = MenuItem::EditIsNested($menuItemId, $isNested);

            // return a 200
            return new Tonic\Response(Tonic\Response::OK);

        } else{ // unauthorized access

            return new Tonic\Response(Tonic\Response::UNAUTHORIZED);
        }
    }

}

/**
 * A protected API call to update a menu item
 * @uri /menuitem/edit
 */
class MenuItemEditResource extends Tonic\Resource {

    /**
     * @method POST
     */
    function post() {

        // get an authuser
        $token = Utilities::ValidateJWTToken(apache_request_headers());

		// check if token is not null
        if($token != NULL){

            parse_str($this->request->data, $request); // parse request

			$menuItemId = $request['menuItemId'];
            $name = $request['name'];
            $cssClass = $request['cssClass'];
            $url = $request['url'];
            $pageId = $request['pageId'];

            MenuItem::Edit($menuItemId, $name, $cssClass, $url, $pageId);

            // return a json response
            $response = new Tonic\Response(Tonic\Response::OK);

            return $response;

        } else{ // unauthorized access

            return new Tonic\Response(Tonic\Response::UNAUTHORIZED);
        }
    }

}

/**
 * A protected API call to remove a menu item
 * @uri /menuitem/remove
 */
class MenuItemRemoveResource extends Tonic\Resource {

    /**
     * @method POST
     */
    function post() {

        // get an authuser
        $token = Utilities::ValidateJWTToken(apache_request_headers());

		// check if token is not null
        if($token != NULL){

            parse_str($this->request->data, $request); // parse request

			$menuItemId = $request['menuItemId'];

            MenuItem::Remove($menuItemId);

            return new Tonic\Response(Tonic\Response::OK);
        }
        else{
            return new Tonic\Response(Tonic\Response::UNAUTHORIZED);
        }
    }

}

/**
 * A protected API call to remove a menu item
 * @uri /menuitem/publish
 */
class MenuItemPublishResource extends Tonic\Resource {

    /**
     * @method POST
     */
    function post() {

        // get an authuser
        $token = Utilities::ValidateJWTToken(apache_request_headers());

		// check if token is not null
        if($token != NULL){

            parse_str($this->request->data, $request); // parse request

            Publish::PublishMenuJSON($token->SiteId);

            return new Tonic\Response(Tonic\Response::OK);
        }
        else{
            return new Tonic\Response(Tonic\Response::UNAUTHORIZED);
        }
    }

}

?>


text:
package org.sqsh;

import java.sql.Types;

/**
 * Object that is used to pass parameters to a callable or prepared statement.
 */
public class CallParameter {

    public static final int INPUT = 1;
    public static final int OUTPUT = 2;
    public static final int INOUT = 3;

    private int idx;
    private int dataType;
    private int direction;
    private String value;

    public CallParameter(int idx, int dataType, int direction, String value) {
        this.idx = idx;
        this.dataType = dataType;
        this.direction = direction;
        this.value = value;
    }

    public CallParameter(int idx, String value) {
        this(idx, Types.VARCHAR, INPUT, value);
    }

    public int getIdx() {
        return idx;
    }

    public void setIdx(int idx) {
        this.idx = idx;
    }

    public int getType() {
        return dataType;
    }

    public void setType(int type) {
        this.dataType = type;
    }

    public int getDirection() {
        return direction;
    }

    public void setDirection(int direction) {
        this.direction = direction;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}


text:
<?php
$L['msg777_title'] = 'Registration error';
$L['msg777_body'] = 'This user name already exists!
Please register or log in under your own name!';
$L['msg778_title'] = 'Registration error';
$L['msg778_body'] = 'A user with this email already exists!
Please register or log in under your own name!';
$L['lz_update_ok'] = 'Account has been updated!';

$L['lz_regok_title'] = 'Registration complete.';
$L['lz_regok'] = 'Hello!
You have registered at %1$s. You can enter the site using

 Login: %2$s
 Password: %3$s

or by using your account on the site %4$s.';

$L['cfg_providers']= array('Provider list, separated by commas','Leave blank if you use all available.(Currently supported - google, yandex, mailruapi, mailru, vkontakte, facebook, twitter, loginza, myopenid, webmoney, rambler, flickr, lastfm, verisign, aol, steam, openid)');
$L['cfg_autoreg']= array('Enable Auto Login?','The user is automatically created when during his first login.');
$L['cfg_remember']= array('Remember the user for Auto Login?');
$L['cfg_s_mail']= array('Send a notice of new user registration by email?', 'It only works if email was given. The mail sent to newly registered user contains his username and password.');
$L['cfg_m_group']= array('Users primary group ID at check-in');

$L['lz_ak']  =  "Binding account" ;
$L['lz_profile_provider']  =  "Providers" ;
$L['lz_enter'] = 'You can also log in using';
$L['lz_profile_enter'] = 'You can link your account on this site to an existing account on other sites. And you can go to this site using your account tied. You can only use one account tied.';
$L['lz_profile_save']  ='Your account is tied to your account';

$L['lz_mng_group_4']  ='Register as Freelancer';
$L['lz_mng_group_7']  ='Register as Employer';


text:
dogstatsd-ruby
==============

A client for DogStatsD, an extension of the StatsD metric server for Datadog.

[![Build Status](https://secure.travis-ci.org/DataDog/dogstatsd-ruby.png)](http://travis-ci.org/DataDog/dogstatsd-ruby)

Quick Start Guide
-----------------

First install the library:

    gem install dogstatsd-ruby

Then start instrumenting your code:

``` ruby
# Load the dogstats module.
require 'statsd'

# Create a stats instance.
statsd = Statsd.new('localhost', 8125)

# Increment a counter.
statsd.increment('page.views')

# Record a gauge 50% of the time.
statsd.gauge('users.online', 123, :sample_rate=>0.5)

# Sample a histogram
statsd.histogram('file.upload.size', 1234)

# Time a block of code
statsd.time('page.render') do
  render_page('home.html')
end

# Send several metrics at the same time
# All metrics will be buffered and sent in one packet when the block completes
statsd.batch do |s|
  s.increment('page.views')
  s.gauge('users.online', 123)
end

# Tag a metric.
statsd.histogram('query.time', 10, :tags => ["version:1"])
```

You can also post events to your stream. You can tag them, set priority and even aggregate them with other events.

Aggregation in the stream is made on hostname/event_type/source_type/aggregation_key.

``` ruby
# Post a simple message
statsd.event("There might be a storm tomorrow", "A friend warned me earlier.")

# Cry for help
statsd.event("SO MUCH SNOW", "Started yesterday and it won't stop !!", :alert_type => "error", :tags => ["urgent", "endoftheworld"])
```

Documentation
-------------

Full API documentation is available
[here](http://www.rubydoc.info/github/DataDog/dogstatsd-ruby/master/frames).

Feedback
--------

To suggest a feature, report a bug, or general discussion, head over
[here](http://github.com/DataDog/dogstatsd-ruby/issues/).

[Change Log](CHANGELOG.md)
----------------------------

Credits
-------

dogstatsd-ruby is forked from Rien Henrichs [original Statsd
client](https://github.com/reinh/statsd).

Copyright (c) 2011 Rein Henrichs. See LICENSE.txt for
further details.


text:
[![Build Status][build-badge]][build]
[![Discord][discord-badge]][discord]
[![Support via PayPal][paypal-badge]][paypal]

> Unofficial [wykop.pl][wykop] client for Android, written in Kotlin.

[Przeczytaj w języku polskim.][readme-pl]

## Features

- Browse link feed (Main page, Upcoming, Favorite, Tags)
- Browse entries (MyWykop, Favorite, Hot, Newest, Tags)
- Microblog
- Search entries/links
- Dark theme (gray one and for AMOLEDs)
- Surveys
- Private messages
- Full customization

## Download

You can [download the newest release with built-in update notifier][download-link] or you can get it on Google Play.

[![Google Play Download][google-play-badge]][google-play-download]

## Development

If you want to build your very own version of Wykop Mobilny, copy `credentials.properties.example` to `credentials.properties` and fill it with your API keys. Keep in mind, that application uses API version 2. Version 1 keys are not supported and will not work.

- `apiKey` and `apiSecret` are API keys from Wykop, that shall be obtained [from here][wykop-api] (giving all permissions).
- `googleKey` is an API key for YouTube player. It shall be obtained following [those developers.google.com instructions][youtube-api].

## Changelogs

Usually I report all progress along with changelogs on [#otwartywykopmobilny on Wykop][wykop-tag].

[build-badge]: https://travis-ci.org/feelfreelinux/WykopMobilny.svg?branch=master
[build]: https://travis-ci.org/feelfreelinux/WykopMobilny
[discord-badge]: https://img.shields.io/discord/455024671440633857.svg
[discord]: https://discord.gg/WgQZJD3
[paypal-badge]: https://img.shields.io/badge/Donate-PayPal-green.svg
[paypal]: https://www.paypal.me/WykopMobilny/
[wykop]: https://wykop.pl
[readme-pl]: README.pl.md
[download-link]: https://github.com/feelfreelinux/WykopMobilny/releases/latest
[google-play-badge]: https://play.google.com/intl/en_us/badges/images/badge_new.png
[google-play-download]: https://play.google.com/store/apps/details?id=io.github.feelfreelinux.wykopmobilny
[wykop-api]: https://www.wykop.pl/dla-programistow/nowa-aplikacja/
[youtube-api]: https://developers.google.com/youtube/android/player/register
[wykop-tag]: https://wykop.pl/tag/otwartywykopmobilny


text:
package com.reactivetechnologies.platform.files.io;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.reactivetechnologies.platform.files.FileChunk;
import com.reactivetechnologies.platform.files.dist.AbstractFileChunkHandler;
/**
 * Reads and writes using buffered stream
 */
public class BufferedStreamChunkHandler extends AbstractFileChunkHandler {

  private InputStream iStream;
  private OutputStream oStream;
  private static final Logger log = LoggerFactory.getLogger(BufferedStreamChunkHandler.class);
  /**
   * Write mode.
   * @throws IOException
   */
  public BufferedStreamChunkHandler(String writeDir) throws IOException
  {
    super(writeDir);

  }
  /**
   * Read mode.
   * @param f
   * @param chunkSize
   * @throws IOException
   */
  public BufferedStreamChunkHandler(File f, int chunkSize) throws IOException {
    super(f);
    iStream = new BufferedInputStream(new FileInputStream(file));
    readSize = chunkSize;
    chunks = fileSize % readSize == 0 ? (int) ((fileSize / readSize)) : (int) ((fileSize / readSize) + 1);
    log.info("Reading from source file ["+file+"]. Expected chunks to send- "+chunks);
    if(log.isDebugEnabled())
    {
      debugInitialParams();

    }
  }

  private int chunks;
  @Override
  public void close() throws IOException {
    if (iStream != null) {
      iStream.close();
    }
    if(oStream != null){
      oStream.flush();
      oStream.close();
    }
  }

  private int idx = 0, readSize;
  @Override
  public FileChunk readNext() throws IOException {

    int available = iStream.available();
    if(available != 0)
    {
      byte[] read = new byte[available > readSize ? readSize : available];
      iStream.read(read);
      FileChunk chunk = new FileChunk(fileName, fileSize, creationTime, lastAccessTime, lastModifiedTime);
      chunk.setChunk(read);
      chunk.setOffset(idx++);
      chunk.setSize(chunks);
      log.debug("[readNext] "+chunk);
      return chunk;
    }

    return null;
  }

  @Override
  public void writeNext(FileChunk chunk) throws IOException {
    if(file == null)
    {
      initWriteFile(chunk);
      oStream = new BufferedOutputStream(new FileOutputStream(file, true));
      log.info("Writing to target file ["+file+"]. Expecting chunks to receive- "+chunk.getSize());
      if(log.isDebugEnabled())
      {
        debugInitialParams();

      }
    }

    doAttribCheck(chunk);
    log.debug("[writeNext] "+chunk);
    oStream.write(chunk.getChunk());
    fileSize += chunk.getChunk().length;

    if(fileSize > chunk.getFileSize())
      throw new IOException("File size ["+fileSize+"] greater than expected size ["+chunk.getFileSize()+"]");

  }

}


text:
"""
   Copyright 2017 Mu Chen

   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.
"""

import numpy as np
from scipy.fftpack import fft
from scipy.fftpack import dct
from pydub import AudioSegment

"""
Static util functions that will be used in the app
"""

"""
Compress user input's audio segment by
	1. reducing the number of channels, if possible
	2. reducing the sample rate, if possible
"""
def compress_audio_segment (segment, sample_rate, num_channels):

	# limit the number of channels to be one
	if segment.channels > num_channels:
		segment_out = segment.set_channels (num_channels)

	# limit the segment's frame rate to be 11025
	if segment.frame_rate > sample_rate:
		segment_out = segment_out.set_frame_rate (sample_rate)

	return segment_out

"""
Generate hamming window function with specific length
for FFT's usage
"""
def gen_hamming_window (length):
	alpha = 0.54
	beta = 1 - alpha
	return -beta * np.cos (np.arange (length) * 2 * np.pi / (length - 1)) + alpha

"""
Convert frequency (in hertz) to Mel scale
"""
def toMel (freq):
	return 1125 * np.log (1 + freq / 700.0)

"""
Convert Mel-scale frequency to Hertz frequency
"""
def toHertz (mel):
	return 700 * (np.exp(mel/1125) - 1)

"""
Generate Mel filterbank that convert the linear frequency
resolution obtained in the result of FFT into nonlinear
frequency resolution
Filterbank analysis is a process that simulates how human
ears actually perceive sounds
(http://www.ee.columbia.edu/ln/rosa/doc/HTKBook21/node54.html)
lower and upper are the lower and upper frequencies in hertz
n: number of filterbanks we want to generate
"""
def gen_mel_filters (nfft, sample_rate, n = 26, lower = 300, upper = 8000):
	lower_mel = toMel (lower)
	upper_mel = toMel (upper)
	mel_linspace = np.linspace (lower_mel, upper_mel, n + 2)
	hertz_linspace = toHertz (mel_linspace)

	# round the frequencies to nearest FFT bin to match
	# the frequency resolution
	fft_linspace = np.asarray (np.floor (nfft * hertz_linspace / sample_rate), dtype=np.int32)
	filters = []
	for i in range (n):
		filter = np.zeros (nfft)
		filter[fft_linspace[i]:fft_linspace[i+1] + 1] = np.linspace (0.0, 1.0, fft_linspace[i+1] - fft_linspace[i] + 1)
		filter[fft_linspace[i+1] + 1:fft_linspace[i+2] + 1] = np.linspace (1.0, 0.0, fft_linspace[i+2] - fft_linspace[i+1] + 1)[1:]
		filters.append (filter)

	return filters

"""
Extract MFC coefficients from the given signal data x
Implementation steps:
	1. Take DFT of windowed signal
	2. Calculate the Mel-scaled filterbank energy from the power spectrum obtained in step 1
	3. Take the log of each of the filterbank energy
	4. Take the DCT of the log filterbank energy to obtain the cepstrum coefficients
	(http://practicalcryptography.com/miscellaneous/machine-learning/guide-mel-frequency-cepstral-coefficients-mfccs/)
frame_length and frame_step are in milliseconds
num_coef_kept: number of cepstral coefficients that will be kept in the final step of calculation
nfft: number of fft points
n_filters: number of mel filterbanks that will be used
frame_limit: if greater than zero, only this amount of frames will be processed in x
lower and upper are used as the same lower and upper in gen_mel_filter function declared above
"""
def get_mfccs (x, sample_rate, frame_length = 25, frame_step = 10, num_coef_kept = 13, n_filters = 26, frame_limit = 0, lower = 300, upper = 8000):

	# convert time length of frame length and frame step into
	# array length
	fsize = int (frame_length / 1000.0 * sample_rate)
	fstep = int (frame_step / 1000.0 * sample_rate)

	if frame_limit > 0:
		num_frame = frame_limit
	else:
		# frame limit is not set, process the whole data
		num_frame = (len(x) - fsize) // fstep + 1
	mfccs = np.zeros ((num_frame, num_coef_kept))

	# construct hamming window and mel filterbank beforehand
	hamming_win = gen_hamming_window (fsize)
	mel_filters = gen_mel_filters (fsize, sample_rate, n = n_filters, lower = lower, upper = upper)

	# iterate through each frame and extract its mfcc
	for i in range (num_frame):

		# padding zeros at the end if the last frame goes out of bound
		if i * fstep + fsize > len(x):
			frame = np.zeros (fsize)
			rest_len = len(x) - i * fstep
			frame[:rest_len] = x[i*fstep:]
		else:
			frame = x[i * fstep:i * fstep + fsize]

		# calculate windowed DFT
		f_spectrum = fft (x = hamming_win * frame)

		# convert the complex numbers in the spectrum into their squared magnitudes (power)
		p_spectrum = np.absolute (f_spectrum) ** 2

		# filter the spectrum using mel filterbanks
		mel_energies = np.zeros (len(mel_filters))
		for j in range(len(mel_filters)):
			mel_energies[j] = np.dot (p_spectrum, mel_filters[j])

		# log the energies
		log_mel_energies = np.log (mel_energies + 1e-5)

		# compute DCT of the log energies
		mfcc = dct (log_mel_energies)
		mfccs[i, :] = mfcc[:num_coef_kept]

	return mfccs


text:
<?php

namespace softcommerce\flot;

use yii\web\AssetBundle;

class FlotAxisLabelsAsset extends AssetBundle {
	public $sourcePath = '@vendor/softcommerce/jquery-flot/assets';
	public $js = ['js/plugins/jquery.flot.axislabels.min.js'];

	public $depends = [
		'softcommerce\flot\FlotAsset',
	];
}


text:
clearvars
close all
load aline
ALL_VARIABLES=alinecohortdatajune15.Properties.VariableNames;

%%%%%%%%%%%%%%%%%%%%%%%
%%% SELECT FEATURES %%%
%%%%%%%%%%%%%%%%%%%%%%%

DATA=alinecohortdatajune15(:,[10, 11, 17, 19, 50, 51, 52, 53, 54, 55, 56, 57, 58, 60, 71, 72, 73, 74, 75, 76, 77, 78, 79, 96, 97, 110]);

SELECTED_VARIABLES=DATA.Properties.VariableNames;

%% DEFINE LABELS USING ALINE_FLG

IAC=DATA(find(alinecohortdatajune15.ALINE_FLG==1),:);
NON_IAC=DATA(find(alinecohortdatajune15.ALINE_FLG==0),:);

IAC_out=alinecohortdatajune15(find(alinecohortdatajune15.ALINE_FLG==1),:);
NON_IAC_out=alinecohortdatajune15(find(alinecohortdatajune15.ALINE_FLG==0),:);

IAC_out=IAC_out.DAY_28_FLG;
NON_IAC_out=NON_IAC_out.DAY_28_FLG;
% Vector of the features that are integers (or binary)
vector_int_ft = [2:14,26];
max_ft = ones(1,26);
max_ft([1,3,15:25])=+inf;
min_ft = zeros(1,26);
min_ft([1,3,15:25])=-inf;
min_ft(3)=1;
constraint.int =vector_int_ft;
constraint.max =max_ft;
constraint.min =min_ft;

%%%%%%%%%%%%%%%%%%%%
%%% MISSING DATA %%%
%%%%%%%%%%%%%%%%%%%%

pathh='/home/hugo/Work/MIT_textbook/MIT textbook/missing_data/latex/figures/';

%% check missing data/create tables
% IAC
nr_missing = missing_data(IAC);

% create table with nr of values discarded and percentages
resultados_MISSING=array2table(nr_missing,'VariableNames',{'nr_points_missing' 'perc_missing'}, 'RowNames', SELECTED_VARIABLES);
writetable(resultados_MISSING,'resultados_MISSING_IAC.xls','WriteRowNames',true);
clear nr_missing

% NON IAC
nr_missing = missing_data(NON_IAC);

% create table with nr of values discarded and percentages
resultados_MISSING=array2table(nr_missing,'VariableNames',{'nr_points_missing' 'perc_missing'}, 'RowNames', SELECTED_VARIABLES);
writetable(resultados_MISSING,'resultados_MISSING_IAC.xls','WriteRowNames',true);
clear nr_missing

%% UNTIL HERE IT WAS EQUAL TO THE CODE OF CATIA
%% Remove Missing Data
% IAC
[IAC, IAC_out ] = remove_missing(IAC,IAC_out );
%NON_IAC
[NON_IAC, NON_IAC_out ] = remove_missing(NON_IAC,NON_IAC_out);

%% Normalize data
% IAC
IAC{:,:} = normalize_matrix(IAC{:,:});
%NON_IAC
NON_IAC{:,:} = normalize_matrix(NON_IAC{:,:});

%% Create 5% 10% 20% 40% Missing Data
perc = [0.05, 0.10, 0.20, 0.40];
% IAC and NON_IAC removal
rng(163)
[IAC_05,IAC_10,IAC_20,IAC_40] = create_missing_special(IAC,perc);
%[NON_IAC_05,NON_IAC_10,NON_IAC_20,NON_IAC_40] = create_missing_special(NON_IAC,perc);
% verify that there is no row with all missing data sum(sum(IAC_40') ==26)
% for the sake of simplicity I will just use the 40% IAC for a while
clear IAC_05 IAC_10 IAC_20

%% Reference logistic regression

%% Mean
% seprate decides if the impute function will be applied to each class (=1)
% or to all the data
separate = 1;
inp_case = 'mean';
data_in_new= data_impute(inp_case,IAC_40,IAC_out,separate,constraint);

clear impute_func
%% Median
separate = 1;
inp_case = 'median';
data_in_new= data_impute(inp_case,IAC_40,IAC_out,separate,constraint);

%% Linear regression
separate = 1;
inp_case = 'linear';
data_in_new= data_impute(inp_case,IAC_05,IAC_out,separate,constraint);

%% Quadratic regression
separate = 1;
inp_case = 'quadratic';
data_in_new= data_impute(inp_case,IAC_40,IAC_out,separate,constraint);

%% Hotdeck
separate = 1;
inp_case = 'hotdeck';
data_in_new= data_impute(inp_case,IAC_40,IAC_out,separate,constraint);

%% Logistic regression

% Reference case
b = glmfit(IAC{:,:},IAC_out,'binomial','link','logit');
yfit = round(glmval(b,IAC{:,:},'logit')); % using 0.5 as threshold!

%% Cross validation

for j = 1:num_shuffles
    indices = crossvalind('Kfold',Labels,num_folds);
    for i = 1:num_folds
        test = (indices == i); train = ~test;
        [b,dev,stats] = glmfit(X(train,:),Labels(train),'binomial','logit'); % Logistic regression
        Fit(j,i) = glmval(b,X(test,:),'logit')';
    end
end


text:
import { isArray, isDenseMatrix, isMatrix } from '../../../../utils/is';
import { arraySize } from '../../../../utils/array';
import { format } from '../../../../utils/string';
export function createSolveValidation(_ref) {
  var DenseMatrix = _ref.DenseMatrix;

  /**
   * Validates matrix and column vector b for backward/forward substitution algorithms.
   *
   * @param {Matrix} m            An N x N matrix
   * @param {Array | Matrix} b    A column vector
   * @param {Boolean} copy        Return a copy of vector b
   *
   * @return {DenseMatrix}        Dense column vector b
   */
  return function solveValidation(m, b, copy) {
    // matrix size
    var size = m.size(); // validate matrix dimensions

    if (size.length !== 2) {
      throw new RangeError('Matrix must be two dimensional (size: ' + format(size) + ')');
    } // rows & columns

    var rows = size[0];
    var columns = size[1]; // validate rows & columns

    if (rows !== columns) {
      throw new RangeError('Matrix must be square (size: ' + format(size) + ')');
    } // vars

    var data, i, bdata; // check b is matrix

    if (isMatrix(b)) {
      // matrix size
      var msize = b.size(); // vector

      if (msize.length === 1) {
        // check vector length
        if (msize[0] !== rows) {
          throw new RangeError('Dimension mismatch. Matrix columns must match vector length.');
        } // create data array

        data = []; // matrix data (DenseMatrix)

        bdata = b._data; // loop b data

        for (i = 0; i < rows; i++) {
          // row array
          data[i] = [bdata[i]];
        } // return Dense Matrix

        return new DenseMatrix({
          data: data,
          size: [rows, 1],
          datatype: b._datatype
        });
      } // two dimensions

      if (msize.length === 2) {
        // array must be a column vector
        if (msize[0] !== rows || msize[1] !== 1) {
          throw new RangeError('Dimension mismatch. Matrix columns must match vector length.');
        } // check matrix type

        if (isDenseMatrix(b)) {
          // check a copy is needed
          if (copy) {
            // create data array
            data = []; // matrix data (DenseMatrix)

            bdata = b._data; // loop b data

            for (i = 0; i < rows; i++) {
              // row array
              data[i] = [bdata[i][0]];
            } // return Dense Matrix

            return new DenseMatrix({
              data: data,
              size: [rows, 1],
              datatype: b._datatype
            });
          } // b is already a column vector

          return b;
        } // create data array

        data = [];

        for (i = 0; i < rows; i++) {
          data[i] = [0];
        } // sparse matrix arrays

        var values = b._values;
        var index = b._index;
        var ptr = b._ptr; // loop values in column 0

        for (var k1 = ptr[1], k = ptr[0]; k < k1; k++) {
          // row
          i = index[k]; // add to data

          data[i][0] = values[k];
        } // return Dense Matrix

        return new DenseMatrix({
          data: data,
          size: [rows, 1],
          datatype: b._datatype
        });
      } // throw error

      throw new RangeError('Dimension mismatch. Matrix columns must match vector length.');
    } // check b is array

    if (isArray(b)) {
      // size
      var asize = arraySize(b); // check matrix dimensions, vector

      if (asize.length === 1) {
        // check vector length
        if (asize[0] !== rows) {
          throw new RangeError('Dimension mismatch. Matrix columns must match vector length.');
        } // create data array

        data = []; // loop b

        for (i = 0; i < rows; i++) {
          // row array
          data[i] = [b[i]];
        } // return Dense Matrix

        return new DenseMatrix({
          data: data,
          size: [rows, 1]
        });
      }

      if (asize.length === 2) {
        // array must be a column vector
        if (asize[0] !== rows || asize[1] !== 1) {
          throw new RangeError('Dimension mismatch. Matrix columns must match vector length.');
        } // create data array

        data = []; // loop b data

        for (i = 0; i < rows; i++) {
          // row array
          data[i] = [b[i][0]];
        } // return Dense Matrix

        return new DenseMatrix({
          data: data,
          size: [rows, 1]
        });
      } // throw error

      throw new RangeError('Dimension mismatch. Matrix columns must match vector length.');
    }
  };
}


text:
/**
 * (c) 2014 by Christian Schenk
 **/
package de.schenk.jrtrace.enginex.testclasses;

import de.schenk.jrtrace.annotations.XClass;
import de.schenk.jrtrace.annotations.XClassLoaderPolicy;
import de.schenk.jrtrace.annotations.XLocation;
import de.schenk.jrtrace.annotations.XMethod;
import de.schenk.jrtrace.enginex.testscripts.Test18;

@XClass(classes = "de.schenk.jrtrace.enginex.testscripts.Test18", classloaderpolicy = XClassLoaderPolicy.TARGET)
public class Test18Script {

	@XMethod(location=XLocation.BEFORE_INVOCATION,invokedname="test18sub")
	public void testinstrumentation() {
	  if(Test18.stage==1) Test18.stage=2;
	}
}


text:
<!DOCTYPE html>
<meta charset="utf-8" />
<title>0</title>

Click on kitten to open in 0. Click again to close or use ESC key.

Source: http://placekitten.com/


text:
var parent = require('../../actual/string/small');

module.exports = parent;


text:
import React from 'react'

import styles from './index.less'

export default class Brand extends React.PureComponent {
  render () {
    return (

JoeRay61

make things make sense

    )
  }
}


text:
<!DOCTYPE html>

    <title>substation.README.md)unnamed_14 documentation</title>
    <link rel="stylesheet" type="text/css" href="../../../../../../index.css" />
    <link rel="stylesheet" type="text/css" href="../../../../../../highlight.css" />

            returns

                substation

                |

                :substation.README.md)

If the new keyword is not used, an instance is created and returned.

        This document was generated with
        doczar
        at 3:55pm on 8/14/2015


text:
require 'spec_helper'

describe Rubocop::Cop::Style::SpaceAfterMethodName do
  subject(:cop) { described_class.new }

  it 'registers an offence for def with space before the parenthesis' do
    inspect_source(cop,
                   ['def func (x)',
                    '  a',
                    'end'])
    expect(cop.offences.size).to eq(1)
  end

  it 'registers an offence for defs with space before the parenthesis' do
    inspect_source(cop,
                   ['def self.func (x)',
                    '  a',
                    'end'])
    expect(cop.offences.size).to eq(1)
  end

  it 'accepts a def without arguments' do
    inspect_source(cop,
                   ['def func',
                    '  a',
                    'end'])
    expect(cop.offences).to be_empty
  end

  it 'accepts a defs without arguments' do
    inspect_source(cop,
                   ['def self.func',
                    '  a',
                    'end'])
    expect(cop.offences).to be_empty
  end

  it 'accepts a def with arguments but no parentheses' do
    inspect_source(cop,
                   ['def func x',
                    '  a',
                    'end'])
    expect(cop.offences).to be_empty
  end

  it 'accepts a defs with arguments but no parentheses' do
    inspect_source(cop,
                   ['def self.func x',
                    '  a',
                    'end'])
    expect(cop.offences).to be_empty
  end

  it 'auto-corrects unwanted space' do
    new_source = autocorrect_source(cop, ['def func (x)',
                                          '  a',
                                          'end',
                                          'def self.func (x)',
                                          '  a',
                                          'end'])
    expect(new_source).to eq(['def func(x)',
                              '  a',
                              'end',
                              'def self.func(x)',
                              '  a',
                              'end'].join("\n"))
  end
end


text:
using std::map;
using std::list;

class SimpleHomeAgent : public HomeAgent {
 public:
  // The Home Agent constructor simply takes a transport layer type that it
  // will be using (default -- TCP)
  SimpleHomeAgent(unsigned short listener_port, unsigned short change_port,
                  unsigned short data_port, unsigned short next_port,
                  TransportLayer transmission_type = TCP, Domain domain = NETv4,
                  Protocol protocol = NO_TYPE) {
    transmission_type_ = transmission_type;
    domain_ = domain;
    protocol_ = protocol;

    listener_port_ = listener_port;
    change_port_ = change_port;
    data_port_ = data_port;
    next_port_ = next_port;
  }
  virtual ~SimpleHomeAgent() {}

  // The home agent merely "runs".  We set it up initially, let it run, and it
  // accepts incoming connections, after which it spawns and subsequently kills
  // threads for connections to mobile agents.
  virtual void Run();

  // The home agent has a shutdown method that can be called so that a signal
  // interruption gracefully shuts down the process.  This will close all
  // open connections.
  virtual void ShutDown(const char* format, ...);

 protected:
  // The home agent is responsible for adding and removing virtual tunnels
  // between itself and various mobile agents.  The tunnel will comprise an
  // <IP, outgoing Socket> pair that allows the forwarding of packets onto
  // a roaming client.
  virtual bool AddMobileAgent(unsigned short out_port, int socket);
  virtual bool RemoveMobileAgent(int tunnel);

  // We sometimes get a new connection that tells us how to change a mobile
  // connection
  virtual bool ChangeMobileAgent(int tunnel);

  // The most important thing that a home agent does is to forward packets from
  // an incoming IP address to a specified mobile agent.
  virtual bool ForwardPackets(int tunnel);

  // If the home agent receives packets from the tunnel it must change the
  // from field in the IP address (IP layer) and forward them onto the ultimate
  // recipient.
  virtual bool RelabelPackets(int outbound);

  // First, a home agent must create the socket to listen for new connections
  int CreateSocket(unsigned short port, bool listen = true,
                   bool nonblocking = true, int* ip_address = NULL);

  // The following is a map from incoming ports to IP addresses
  // (virtual tunnels).
  map<int, list<int> > connections_in_;

  // We need to maintain a map of the tunnel sockets to the identities to
  // prevent unauthorized spoofing
  map<int, int> tunnel_identities_;

  // Keep a list of the three main ports
  int listening_socket_;
  int change_socket_;
  int data_socket_;

  // We maintain the highest socket yet opened for use with select().
  int fd_limit_;

  // We represent what type of transport this home agent is using with an enum
  TransportLayer transmission_type_;
  Domain domain_;
  Protocol protocol_;

  // We need to represent what the next available port to delegate out is
  unsigned short next_port_;

  // Finally, we represent what port the home agent takes new connections on,
  // which port it looks for changes in identity, and which port accepts data
  // from mobile nodes.
  unsigned short listener_port_;
  unsigned short change_port_;
  unsigned short data_port_;
};

#endif  // _P2PMIP_HOMEAGENT_SIMPLEHOMEAGENT_H_


text:
from django.core.management import BaseCommand
from django.core.management import call_command
from django.db import connection
import os
import shutil
import re
import tempfile

def delete_line(filename, pattern, stdout):
    pattern_compiled = re.compile(pattern)
    with tempfile.NamedTemporaryFile(mode='w', delete=False) as tmp_file:
        with open(filename) as src_file:
            for line in src_file:
                if pattern_compiled.findall(line):
                    stdout.write('Deleting line in %s' % filename)
                    continue
                tmp_file.write(line)

    # Overwrite the original file with the munged temporary file in a
    # manner preserving file attributes (e.g., permissions).
    shutil.copystat(filename, tmp_file.name)
    shutil.move(tmp_file.name, filename)

class Command(BaseCommand):
    help = "Delete all migrations from one app, reset database and create one new migration"

    def __init__(self, *args, **kwargs):
        self.cursor = connection.cursor()
        return super(Command, self).__init__(*args, **kwargs)

    def add_arguments(self, parser):
        parser.add_argument('apps', nargs='+', type=str)

        # Named (optional) arguments
        parser.add_argument('--cached',
                            action='store_true',
                            dest='cached',
                            default=False,
                            help='Dont delete the migrations files')

    def delete_database_app(self, app):
        self.stdout.write("Deleting APP (%s) in database" % app)
        self.cursor.execute("DELETE from django_migrations WHERE app = %s", [app])

    def delete_files_app(self, app):
        self.stdout.write("Deleting APP (%s) migrations files" % app)
        migrations_dir = os.path.join(app, 'migrations')
        if os.path.exists(migrations_dir):
            shutil.rmtree(os.path.join(app, 'migrations'))

    def delete_dependence_app(self, app):
        self.stdout.write("Deleting dependences in migrations for (%s)" % app)
        for root, dirs, files in os.walk(".", topdown=False):
            for name in dirs:
                if name == 'migrations':
                    migration_dir = os.path.join(root, name)
                    for r, d, f in os.walk(migration_dir):
                        for n in f:
                            file_name = os.path.join(r, n)
                            if '.pyc' in file_name:
                                continue
                            if '.py' in file_name:
                                regex = r'\(\'%s\'' % app
                                delete_line(file_name, regex, self.stdout)

    def handle(self, *args, **options):
        apps = options['apps']
        self.stdout.write("Reseting APP %s" % apps)
        for app in apps:
            self.delete_database_app(app)
            if not options['cached']:
                self.delete_files_app(app)
                self.delete_dependence_app(app)
            self.stdout.write("APP (%s) deleted with success" % app)

        if not options['cached']:
            call_command('makemigrations', *apps)

        for app in apps:
            call_command('migrate', app, '--fake')


text:
<?php

/*
 AntiFlood plugin in Swift Mailer.

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.

 */

//@require 'Swift/Events/SendListener.php';
//@require 'Swift/Events/SendEvent.php';
//@require 'Swift/Plugins/Sleeper.php';

/**
 * Reduces network flooding when sending large amounts of mail.
 * @package Swift
 * @subpackage Plugins
 * @author Chris Corbyn
 */
class Swift_Plugins_AntiFloodPlugin
  implements Swift_Events_SendListener, Swift_Plugins_Sleeper
{

  /**
   * The number of emails to send before restarting Transport.
   * @var int
   * @access private
   */
  private $_threshold;

  /**
   * The number of seconds to sleep for during a restart.
   * @var int
   * @access private
   */
  private $_sleep;

  /**
   * The internal counter.
   * @var int
   * @access private
   */
  private $_counter = 0;

  /**
   * The Sleeper instance for sleeping.
   * @var Swift_Plugins_Sleeper
   * @access private
   */
  private $_sleeper;

  /**
   * Create a new AntiFloodPlugin with $threshold and $sleep time.
   * @param int $threshold
   * @param int $sleep time
   * @param Swift_Plugins_Sleeper $sleeper (not needed really)
   */
  public function __construct($threshold = 99, $sleep = 0,
    Swift_Plugins_Sleeper $sleeper = null)
  {
    $this->setThreshold($threshold);
    $this->setSleepTime($sleep);
    $this->_sleeper = $sleeper;
  }

  /**
   * Set the number of emails to send before restarting.
   * @param int $threshold
   */
  public function setThreshold($threshold)
  {
    $this->_threshold = $threshold;
  }

  /**
   * Get the number of emails to send before restarting.
   * @return int
   */
  public function getThreshold()
  {
    return $this->_threshold;
  }

  /**
   * Set the number of seconds to sleep for during a restart.
   * @param int $sleep time
   */
  public function setSleepTime($sleep)
  {
    $this->_sleep = $sleep;
  }

  /**
   * Get the number of seconds to sleep for during a restart.
   * @return int
   */
  public function getSleepTime()
  {
    return $this->_sleep;
  }

  /**
   * Invoked immediately before the Message is sent.
   * @param Swift_Events_SendEvent $evt
   */
  public function beforeSendPerformed(Swift_Events_SendEvent $evt)
  {
  }

  /**
   * Invoked immediately after the Message is sent.
   * @param Swift_Events_SendEvent $evt
   */
  public function sendPerformed(Swift_Events_SendEvent $evt)
  {
    ++$this->_counter;
    if ($this->_counter >= $this->_threshold)
    {
      $transport = $evt->getTransport();
      $transport->stop();
      if ($this->_sleep)
      {
        $this->sleep($this->_sleep);
      }
      $transport->start();
      $this->_counter = 0;
    }
  }

  /**
   * Sleep for $seconds.
   * @param int $seconds
   */
  public function sleep($seconds)
  {
    if (isset($this->_sleeper))
    {
      $this->_sleeper->sleep($seconds);
    }
    else
    {
      sleep($seconds);
    }
  }

}


text:
namespace planet {

    static void update_last_access_time(shared_ptr<fs_entry> const& entry)
    {
        auto new_inode = entry->inode();
        new_inode.atime = std::chrono::system_clock::now();
        entry->inode(new_inode);
    }

    static void update_last_modified_time(shared_ptr<fs_entry> const& entry)
    {
        auto new_inode = entry->inode();
        new_inode.mtime = std::chrono::system_clock::now();
        entry->inode(new_inode);
    }

    static void update_last_stat_change_time(shared_ptr<fs_entry> const& entry)
    {
        auto new_inode = entry->inode();
        new_inode.ctime = std::chrono::system_clock::now();
        entry->inode(new_inode);
    }

    int core_file_system::getattr(path_type const& path, struct stat& stbuf) const
    {
        if (auto fs_ent = this->get_entry_of(path)) {
            stbuf.st_dev    = fs_ent->inode().dev;
            stbuf.st_mode   = fs_ent->inode().mode;
            stbuf.st_uid    = fs_ent->inode().uid;
            stbuf.st_gid    = fs_ent->inode().gid;
            stbuf.st_nlink  = fs_ent.use_count() - 1;
            stbuf.st_size   = fs_ent->size();
            stbuf.st_atime  = st_inode::to_time_t(fs_ent->inode().atime);
            stbuf.st_mtime  = st_inode::to_time_t(fs_ent->inode().mtime);
            stbuf.st_ctime  = st_inode::to_time_t(fs_ent->inode().ctime);
        } else
            throw_system_error(ENOENT);
        return 0;
    }

    int core_file_system::mknod(path_type const& path, mode_t mode, dev_t device)
    {
        return this->mknod(path, mode, device,
            ops_db_.lock()->get_name_by_path(path, file_type::regular_file)
        );
    }

    int core_file_system::mknod(
        path_type const& path, mode_t mode, dev_t device, string_type const& ops_name)
    {
        if (auto parent_dir = search_dir_entry(*this, path.parent_path())) {
            st_inode new_inode;
            fill_st_inode(new_inode);
            new_inode.dev  = device;
            new_inode.mode = mode | S_IFREG;
            auto fentry =
                parent_dir->add_entry<file_entry>(path.filename().string(), ops_name, new_inode);
            try {
                BOOST_LOG_TRIVIAL(info) << "mknod: Creating " << path << " type=" << ops_name;
                ops_db_.lock()->
                    get_ops(ops_name)->mknod(fentry, path, mode, device);
            } catch (...) {
                parent_dir->remove_entry(path.filename().string());
                throw;
            }
        } else
            throw_system_error(ENOENT);
        return 0;
    }

    int core_file_system::unlink(path_type const& path, bool force)
    {
        int ret = 0;
        if (auto parent_dir = search_dir_entry(*this, path.parent_path())) {
            auto fentry = file_cast(parent_dir->search_entries(path.filename().string()));
            try {
                ret = ops_db_.lock()->get_ops(fentry->ops_name())->rmnod(fentry, path);
            } catch (no_such_ops_type& e) {
                // if no operations found, just unlink a file
                // Possible case: mknod a file, FILE with operation OPS
                //                uninstall the operation, OPS
                //                try to unlink FILE
                BOOST_LOG_TRIVIAL(warning) << __func__ << ": no such operation to unlink: "
                    << e.get_ops_name() << ": just unlink";
            }
            if (ret < 0 && !force)
                return ret;
            parent_dir->remove_entry(path.filename().string());
        } else
            throw_system_error(ENOENT);
        return ret;
    }

    int core_file_system::mkdir(path_type const& path, mode_t mode)
    {
        return this->mkdir(path, mode,
            ops_db_.lock()->get_name_by_path(path, file_type::directory)
        );
    }

    int core_file_system::mkdir(
        path_type const& path, mode_t mode, string_type const& ops_name)
    {
        if (auto parent_dir = search_dir_entry(*this, path.parent_path())) {
            st_inode new_inode;
            fill_st_inode(new_inode);
            new_inode.mode = mode | S_IFDIR;
            auto dir_entry = parent_dir->add_entry<dentry>(path.filename().string(), ops_name, new_inode);
            try {
                BOOST_LOG_TRIVIAL(info) << "mkdir: Creating " << path << " type=" << ops_name;
                ops_db_.lock()->
                    get_ops(ops_name)->mknod(dir_entry, path, mode, 0);
            } catch (...) {
                parent_dir->remove_entry(path.filename().string());
                throw;
            }
        } else
            throw_system_error(ENOENT);
        return 0;
    }

    int core_file_system::rmdir(path_type const& path, bool force)
    {
        int ret = 0;
        if (auto parent_dir = search_dir_entry(*this, path.parent_path())) {
            auto dir_entry = directory_cast(parent_dir->search_entries(path.filename().string()));
            try {
                ret = ops_db_.lock()->get_ops(dir_entry->ops_name())->rmnod(dir_entry, path);
            } catch (no_such_ops_type& e) {
                // if no operations found, just rmdir a directory
                BOOST_LOG_TRIVIAL(warning) << __func__ << ": no such operation to rmdir: "
                    << e.get_ops_name() << ": just rmdir";
            }
            if (ret < 0 && !force)
                return ret;
            parent_dir->remove_entry(path.filename().string());
        } else
            throw_system_error(ENOENT);
        return ret;
    }

    int core_file_system::chmod(path_type const& path, mode_t mode)
    {
        int ret = 0;
        if (auto entry = this->get_entry_of(path)) {
            auto new_inode = entry->inode();
            new_inode.mode = mode;
            new_inode.ctime = std::chrono::system_clock::now();
            entry->inode(new_inode);
        } else
            ret = -ENOENT;
        return ret;
    }

    int core_file_system::chown(path_type const& path, uid_t uid, gid_t gid)
    {
        int ret = 0;
        if (auto entry = this->get_entry_of(path)) {
            auto new_inode = entry->inode();
            new_inode.uid = uid;
            new_inode.gid = gid;
            new_inode.ctime = std::chrono::system_clock::now();
            entry->inode(new_inode);
        } else
            ret = -ENOENT;
        return ret;
    }

    int core_file_system::truncate(path_type const& path, off_t offset)
    {
        int ret = 0;
        if (auto entry = this->get_entry_of(path))
            planet::file_cast(entry)->data().resize(offset);
        else
            ret = -ENOENT;
        return ret;
    }

    int core_file_system::utimens(path_type const& path, struct timespec const tv[2])
    {
        int ret = 0;
        namespace ch = std::chrono;
        if (auto entry = this->get_entry_of(path)) {
            ch::nanoseconds nano_access(tv[0].tv_nsec), nano_mod(tv[1].tv_nsec);
            ch::seconds sec_access(tv[0].tv_sec), sec_mod(tv[1].tv_sec);
            planet::st_inode new_inode = entry->inode();
            new_inode.atime = decltype(new_inode.atime)
                (ch::duration_cast<decltype(new_inode.atime)::duration>(nano_access + sec_access));
            new_inode.mtime = decltype(new_inode.atime)
                (ch::duration_cast<decltype(new_inode.atime)::duration>(nano_mod + sec_mod));
            entry->inode(new_inode);
        } else
            ret = -ENOENT;
        return ret;
    }

    std::vector<std::string> core_file_system::readdir(path_type const& path) const
    {
        std::vector<std::string> store;
        if (auto dir_ent = search_dir_entry(*this, path))
            for (auto entry : dir_ent->entries())
                store.push_back(entry->name());
        else
            throw_system_error(ENOENT);
        return store;
    }

    handle_t core_file_system::open(path_type const& path)
    {
        handle_t new_handle;
        if (auto entry = get_entry_of(path)) {
            if (entry->type() != file_type::regular_file)
                throw_system_error(EISDIR);
            auto fentry = file_cast(entry);
            new_handle = open_handles_.register_op(
                ops_db_.lock()->get_ops(fentry->ops_name())->create_op(shared_from_this()),
                fentry
            );
            try {
                auto& op_tuple = open_handles_.get_op_entry(new_handle);
                int open_ret = std::get<0>(op_tuple)->open(std::get<1>(op_tuple), path);
                if (open_ret < 0)
                    throw_system_error(-open_ret);
                update_last_access_time(fentry);
            } catch (...) {
                open_handles_.unregister_op(new_handle);
                throw;
            }
        } else
            throw_system_error(ENOENT);
        return new_handle;
    }

    int core_file_system::read(handle_t handle, char *buf, size_t size, off_t offset)
    {
        auto&& op_tuple = open_handles_.get_op_entry(handle);
        int ret = std::get<0>(op_tuple)->read(
            std::get<1>(op_tuple), buf, size, offset
        );
        update_last_access_time(std::get<1>(op_tuple));
        return ret;
    }

    int core_file_system::write(handle_t handle, char const *buf, size_t size, off_t offset)
    {
        auto&& op_tuple = open_handles_.get_op_entry(handle);
        int ret = std::get<0>(op_tuple)->write(
            std::get<1>(op_tuple), buf, size, offset
        );
        update_last_access_time(std::get<1>(op_tuple));
        update_last_modified_time(std::get<1>(op_tuple));
        return ret;
    }

    int core_file_system::close(handle_t handle)
    {
        auto&& op_tuple = open_handles_.get_op_entry(handle);
        raii_wrapper raii([this, handle] {
            raii_wrapper raii([this,handle] {
                this->open_handles_.unregister_op(handle);
            });
            this->poller_.unregister(handle);
        });
        int ret = std::get<0>(op_tuple)->release(std::get<1>(op_tuple));
        return ret;
    }

    int core_file_system::poll(handle_t handle, pollmask_t& pollmask)
    {
        auto&& op_tuple = open_handles_.get_op_entry(handle);
        return std::get<0>(op_tuple)->poll(pollmask);
    }

    int core_file_system::poll(
        path_type const& path, struct fuse_file_info *fi, struct fuse_pollhandle *ph, unsigned *reventsp
    )
    {
        auto handle = get_handle_from(*fi);
        std::call_once(invoke_poller_once_, [this]() {
            this->poller_.poll(this->shared_from_this());
        });

        if (ph) {
            BOOST_LOG_TRIVIAL(trace) << __func__ << ": handle=" << handle << " adding new handle";
            poller_.register_new(handle, ph);
        }

        *reventsp |= poller_.get_status(handle);
        BOOST_LOG_TRIVIAL(trace) << __func__ << ": handle=" << handle << " polled=" << *reventsp;
        return 0;

    }

    void core_file_system::install_ops(priority p, shared_ptr<fs_ops_type> ops)
    {
        BOOST_LOG_TRIVIAL(info) << "Installing ops: " << ops->name();
        raii_wrapper raii([this, ops] {
            if (std::uncaught_exception())
                this->ops_db_.lock()->unregister_ops(ops->name());
        });
        ops_db_.lock()->register_ops(p, ops);
        int ret = ops->install(this->shared_from_this());
        if (ret < 0)
            throw_system_error(-ret, ops->name() + ": registering ops failed");
    }

    void core_file_system::uninstall_ops(string_type const& name)
    {
        BOOST_LOG_TRIVIAL(info) << "Uninstalling ops: " << name;
        raii_wrapper finalize([this, name]() {
            ops_db_.lock()->unregister_ops(name);
        });
        ops_db_.lock()->get_ops(name)->uninstall(this->shared_from_this());
    }

    void core_file_system::install_module(priority p, string_type const& mod_name)
    {
        this->install_ops(p, make_shared<module_ops_type>(mod_name));
    }

    void core_file_system::install_module(
        priority p, string_type const& mod_name, std::vector<string_type> const& paths)
    {
        this->install_ops(p, make_shared<module_ops_type>(mod_name, paths));
    }

    void core_file_system::uninstall_module(string_type const& mod_name)
    {
        BOOST_LOG_TRIVIAL(info) << "Uninstalling module: " << mod_name;
        this->uninstall_ops(mod_name);
    }

    shared_ptr<fs_entry> core_file_system::get_entry_of(path_type const& path) const
    {
        return (path == "/" ? root : get_entry_of(root, path));
    }

    shared_ptr<fs_entry> core_file_system::get_entry_of(shared_ptr<dentry> root, path_type const& path)
    {
        if (path.empty() || path.is_relative() || !root)
            throw std::runtime_error{"detect null parent dir or relative path"};
        string_type p = path.string();
        auto pos = p.find_first_of('/', 1);
        if (pos == std::string::npos)
            return root->search_entries(p.substr(1));
        // Get parent directory from filename
        auto dir_entry = root->search_entries(p.substr(1, pos - 1));
        return (!dir_entry || dir_entry->type() != file_type::directory) ? detail::shared_null_ptr
            : get_entry_of(directory_cast(dir_entry), "/" + p.substr(pos + 1));
    }

    void core_file_system::uninstal_all()
    {
        auto db = ops_db_.lock();
        for (auto&& info : db->info()) {
            try {
                db->get_ops(std::get<0>(info))->uninstall(this->shared_from_this());
            } catch (std::exception& e) {
                BOOST_LOG_TRIVIAL(warning) << __func__ << ": " << e.what();
            }
        }
    }

    ops_type_db& core_file_system::get_ops_db()
    {
        auto db = ops_db_.lock();
        if (!db)
            throw std::runtime_error("get_ops_db(): ops_db_ not available");
        return *db;
    }

    ops_type_db const& core_file_system::get_ops_db() const
    {
        auto db = ops_db_.lock();
        if (!db)
            throw std::runtime_error("get_ops_db(): ops_db_ not available");
        return *db;
    }

}   // namespace planet


text:
#include <rtthread.h>
#include <lwip/api.h>

#define TCP_ECHO_PORT   7

void tcpecho_entry(void *parameter)
{
	struct netconn *conn, *newconn;
	err_t err;

	/* Create a new connection identifier. */
	conn = netconn_new(NETCONN_TCP);

	/* Bind connection to well known port number 7. */
	netconn_bind(conn, NULL, TCP_ECHO_PORT);

	/* Tell connection to go into listening mode. */
	netconn_listen(conn);

	while(1)
	{
		/* Grab new connection. */
		err = netconn_accept(conn, &newconn);
		/* Process the new connection. */
		if(err == ERR_OK)
		{
			struct netbuf *buf;
			void *data;
			u16_t len;
			char deal = 1;

			while(deal && netconn_recv(newconn, &buf) == ERR_OK)
			{
				do
				{
					netbuf_data(buf, &data, &len);
					err = netconn_write(newconn, data, len, NETCONN_COPY);
					if(err != ERR_OK)
					{
						rt_kprintf("tcpecho send failed\n");
						deal = 0;
						break;
					}
				}
				while(netbuf_next(buf) >= 0);
				netbuf_delete(buf);
			}
			/* Close connection and discard connection identifier. */
			netconn_delete(newconn);
		}
	}
    rt_thread_delete(NULL);
}

static rt_thread_t echo_tid = RT_NULL;
void tcpecho(void)
{
    if (echo_tid == RT_NULL)
    {
        echo_tid = rt_thread_create("echo",
			tcpecho_entry, RT_NULL,
            4096, 30, 20);
        if (echo_tid != RT_NULL)
            rt_thread_startup(echo_tid);
    }
    else
    {
        rt_thread_delete(echo_tid); /* delete thread */
        echo_tid = RT_NULL;
    }
}

#ifdef RT_USING_FINSH
#include <finsh.h>
FINSH_FUNCTION_EXPORT(tcpecho, startup or stop TCP echo server);
MSH_CMD_EXPORT(tcpecho, startup or stop TCP echo server);
#endif


text:
// @formatter:off

package com.microsoft.alm.teamfoundation.workitemtracking.webapi.models;

import java.util.ArrayList;

/**
 */
public class ProvisioningResult {

    private ArrayList<String> provisioningImportEvents;

    public ArrayList<String> getProvisioningImportEvents() {
        return provisioningImportEvents;
    }

    public void setProvisioningImportEvents(final ArrayList<String> provisioningImportEvents) {
        this.provisioningImportEvents = provisioningImportEvents;
    }
}


text:
/*
  This is the main navigator shown for devices. This component chooses the correct page to set based upon the data
  it is getting (shows loading page if the user/device/stream are not ready).

  The component also performs further routing based upon the hash. This is because react-router does not
  support both normal and hash-based routing at the same time.
  All child pages are located in ./pages. This component can be throught of as an extension to the main app routing
  done in App.js, with additional querying for the user/device/stream we want to view.

  It also queries the user/device/stream-specific state from redux, so further children can just use the state without worrying
  about which user/device/stream it belongs to.
*/

import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";

import { getDeviceState } from "./reducers/device";
import connectStorage from "./connectStorage";

import Error from "./components/Error";
import Loading from "./components/Loading";

import DeviceView from "./pages/DeviceView";
import DeviceEdit from "./pages/DeviceEdit";
import StreamCreate from "./pages/StreamCreate";

import { setTitle } from "./util";

function setDeviceTitle(user, device) {
  setTitle(user == null || device == null ? "" : user.name + "/" + device.name);
}

class Device extends Component {
  static propTypes = {
    user: PropTypes.object,
    device: PropTypes.object,
    streamarray: PropTypes.object,
    error: PropTypes.object,
    location: PropTypes.object.isRequired,
    state: PropTypes.object
  };
  componentDidMount() {
    setDeviceTitle(this.props.user, this.props.device);
  }
  componentWillReceiveProps(newProps) {
    if (
      newProps.user !== this.props.user ||
      newProps.device !== this.props.device
    ) {
      setDeviceTitle(newProps.user, newProps.device);
    }
  }

  render() {
    if (this.props.error != null) {
      return <Error err={this.props.error} />;
    }
    if (
      this.props.user == null ||
      this.props.device == null ||
      this.props.streamarray == null
    ) {
      // Currently querying
      return <Loading />;
    }

    // React router does not allow using hash routing, so we route by hash here
    switch (this.props.location.hash) {
      case "#create":
        return (
          <StreamCreate
            user={this.props.user}
            device={this.props.device}
            state={this.props.state.create}
            datatype=""
          />
        );
      case "#edit":
        return (
          <DeviceEdit
            user={this.props.user}
            device={this.props.device}
            state={this.props.state.edit}
          />
        );
    }

    // Custom rating routing
    if (this.props.location.hash.startsWith("#create/")) {
      // The hash is to create the specific datatype.
      let datatype = this.props.location.hash.substring(8);
      return (
        <StreamCreate
          user={this.props.user}
          device={this.props.device}
          state={this.props.state.create}
          datatype={datatype}
        />
      );
    }

    return (
      <DeviceView
        user={this.props.user}
        device={this.props.device}
        state={this.props.state.view}
        streamarray={this.props.streamarray}
      />
    );
  }
}

export default connectStorage(
  connect((store, props) => ({
    state: getDeviceState(
      props.user != null && props.device != null
        ? props.user.name + "/" + props.device.name
        : "",
      store
    )
  }))(Device),
  false,
  true
);


text:
from subprocess import check_output, CalledProcessError
from functools import lru_cache
import os.path

@lru_cache(maxsize=1)
def root():
    ''' returns the absolute path of the repository root '''
    try:
        base = check_output(['git', 'rev-parse', '--show-toplevel'])
    except CalledProcessError:
        raise IOError('Current working directory is not a git repository')
    return base.decode('utf-8').strip()

def abspath(relpath):
    ''' returns the absolute path for a path given relative to the root of
    the git repository
    '''
    return os.path.join(root(), relpath)


text:
'''
               Simimple Model Railway Automation
               Hall-effect Sensor Support Module

Author : Peter Wallen
Created : 21/1/13
Version 1.0

This code encapulates hardware associated with sensors used to detect the location of trains.

The hardware supported comprises of :
 One or more Microchip MCP23017 16-Bit I/O Expanders acting as sensor controllers.
 Each sensor controller can be connected to a maximum of 16 hall-effect sensors.

 This module requires python-smbus
'''

import smbus
import time

bus = 0

def i2Cbus_open():
  '''
    This function must be called once by the automation script to open the I2C bus between
    the Rpi and the sensor controller(s).

  '''
  global bus
  try:
    bus = smbus.SMBus(0)
  except EnvironmentError as e:
    print e
    raise RuntimeError("Unable to open I2C bus")

def config(address):
  '''
  This function must be called once by the automation script for each sensor controller.
  The address of the controller is determined by the A10,A1,A2 pins on the MCP23017 chip.
  eg. If A0,A1 and A2 are LOW then the address should be 0x20.

  For information about configuring the sensor controller see the Microchip MCP23017 datasheet.
  For eaxample to connect sensors to GPA0 - GPA7, use GPB0 - GPB7 to drive LED indicators and
  enable interupts to allow the last sensor triggered to be stored in the interupt capture register,
  configure as follows:
  bus.write_byte_data(address,IODIRA,0xff)  # set all ports in bank A to input
  bus.write_byte_data(address,IODIRB,0x00)  # set all ports in bank B to output
  bus.write_byte_data(address,GPPUA,0xff)   # enable pullup resistors for bank A
  bus.write_byte_data(address,GPINTENA,0xff) # enable interupts on port A
  '''
  global bus

  # MCP23017 register constants
  IODIRA =  0x00
  IODIRB =  0x01
  GPINTENA = 0X04
  GPINTENB = 0x05
  GPPUA  =  0x0c
  GPPUB  =  0x0d
  INTCAPA=  0x10
  INTCAPB=  0x11
  GPIOA  =  0x12
  GPIOB  =  0x13

  bus.write_byte_data(address,IODIRA,0xff)  # set all ports in bank A to input
  bus.write_byte_data(address,IODIRB,0x00)  # set all ports in bank B to output
  bus.write_byte_data(address,GPPUA,0xff)   # enable pullup resistors for bank A
  bus.write_byte_data(address,GPINTENA,0xff) # enable interupts on port A

class Sensor(object):
  '''
    The class describing a sensor object.
    A sensor object is associate with each train detection sensor.
  '''
  def __init__(self,address,bank,port):
    '''
     The class constructor is called with the following parameters:
     address : the address of the sensor controller on the I2C bus eg. 0X20
     bank : the register group the sensor is connected to: 'A'  for GPA0 - GPA7 and 'B' for GPB0 - GPB7
     port : the port on the sensor controller the sensor is connected to (1 - 8).
            NB. port 1 corresponds to pin GPx0 and port 8 corresponds to pin GPx7
            where x = A or B
    '''
    global bus
    mask_table = [0x00,0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80]
    if bus == 0 :
      raise RuntimeError("I2C bus has not been opened")
    self.address = address
    self.port = 0
    if bank == "A" :
      self.iodir = 0x00
      self.gpinten = 0x04
      self.gppu = 0x0c
      self.intcap = 0x10
      self.gpio = 0x12
    elif bank == "B" :
      self.iodir = 0x01
      self.gpinten = 0x05
      self.gppu = 0x0d
      self.intcap = 0x11
      self.gpio = 0x13
    else :
      raise RuntimeError("Invalid bank must be A or B")
    if port > 8 or port < 1 :
      raise RuntimeError("Invalid port must be between 1 and 8")
    else :
      self.port |= mask_table[port]

  def wait(self) :
    '''
    This method will poll the interupt capture registor for the sensor until its triggered.
    In addition, it will control a status LED connected to the corresponding port on bank A.
    '''
    x = bus.read_byte_data(self.address,self.intcap)

    # switch off indicator for appropriate port
    status  = bus.read_byte_data(self.address,0x13)
    status &= self.port
    bus.write_byte_data(self.address,0x13,status)

    while (x & self.port) :
      x = bus.read_byte_data(self.address,self.intcap)
      time.sleep(1)

    # switch on indicator for appropriate port
    status  = bus.read_byte_data(self.address,0x13)
    status |= self.port
    bus.write_byte_data(self.address,0x13,status)


text:
@implementation AQGLViewPixelFormat

+ (AQGLViewPixelFormat *) doubleBuffered
{
    static NSOpenGLPixelFormatAttribute attrs[] =
    {
        NSOpenGLPFADoubleBuffer,
        NSOpenGLPFAAccelerated,
        NSOpenGLPFANoRecovery,
        NSOpenGLPFAColorSize, 24,
        NSOpenGLPFAAlphaSize, 8,
        0
    };

    NSOpenGLPixelFormat * nsFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes: attrs];
    [nsFormat autorelease];

    return ( [[[self alloc] initWithNSFormat: nsFormat] autorelease] );
}

- (id) initWithNSFormat: (NSOpenGLPixelFormat *) nsFormat
{
    if ( [super init] == nil )
        return ( nil );

    _nsFormat = [nsFormat retain];

    return ( self );
}

- (void) dealloc
{
    [_nsFormat release];
    [super dealloc];
}

- (CGLPixelFormatObj) CGLPixelFormat
{
    return ( [_nsFormat CGLPixelFormatObj] );
}

- (NSOpenGLPixelFormat *) NSFormat
{
    return ( _nsFormat );
}

@end


text:
Test.assertEquals(greaterThanLessThan(Number(null), 0, 1), true);
Test.assertEquals(greaterThanLessThan(700000000001, 700000000002, -1), false);
Test.assertEquals(greaterThanLessThan(-9, -8, 7), true);
Test.assertEquals(greaterThanLessThan(-9, -8, -7), false);


text:
use kernel::prelude::*;
use kernel::lib::mem::aref::ArefBorrow;
use kernel::vfs::node;

const ERROR_SHORTCHAIN: node::IoError = node::IoError::Unknown("Cluster chain terminated early");

pub type FilesystemInner = super::FilesystemInner;

pub struct FileNode
{
	fs: ArefBorrow<FilesystemInner>,
	//parent_dir: u32,
	first_cluster: u32,
	size: u32,
}

impl FileNode
{
	pub fn new_boxed(fs: ArefBorrow<FilesystemInner>, _parent: u32, first_cluster: u32, size: u32) -> Box<FileNode> {
		Box::new(FileNode {
			fs: fs,
			//parent_dir: parent,
			first_cluster: first_cluster,
			size: size,
			})
	}
}
impl node::NodeBase for FileNode {
	fn get_id(&self) -> node::InodeId {
		todo!("FileNode::get_id")
	}
}
impl node::File for FileNode {
	fn size(&self) -> u64 {
		self.size as u64
	}
	fn truncate(&self, newsize: u64) -> node::Result<u64> {
		todo!("FileNode::truncate({:#x})", newsize);
	}
	fn clear(&self, ofs: u64, size: u64) -> node::Result<()> {
		todo!("FileNode::clear({:#x}+{:#x}", ofs, size);
	}
	fn read(&self, ofs: u64, buf: &mut [u8]) -> node::Result<usize> {
		// Sanity check and bound parameters
		if ofs >= self.size as u64 {
			// out of range
			return Err( node::IoError::OutOfRange );
		}
		let maxread = (self.size as u64 - ofs) as usize;
		let buf = if buf.len() > maxread { &mut buf[..maxread] } else { buf };
		let read_length = buf.len();

		// Seek to correct position in the cluster chain
		let mut clusters = super::ClusterList::chained(self.fs.reborrow(), self.first_cluster)
			.skip( (ofs/self.fs.cluster_size as u64) as usize);
		let ofs = (ofs % self.fs.cluster_size as u64) as usize;

		// First incomplete cluster
		let chunks = if ofs != 0 {
				let cluster = match clusters.next()
					{
					Some(v) => v,
					None => return Err( ERROR_SHORTCHAIN ),
					};
				let short_count = ::core::cmp::min(self.fs.cluster_size-ofs, buf.len());
				let c = try!(self.fs.load_cluster(cluster));
				let n = buf[..short_count].clone_from_slice( &c[ofs..] );
				assert_eq!(n, short_count);

				buf[short_count..].chunks_mut(self.fs.cluster_size)
			}
			else {
				buf.chunks_mut(self.fs.cluster_size)
			};

		// The rest of the clusters
		for dst in chunks
		{
			let cluster = match clusters.next()
				{
				Some(v) => v,
				None => return Err(ERROR_SHORTCHAIN),
				};
			if dst.len() == self.fs.cluster_size {
				// Read directly
				try!(self.fs.read_cluster(cluster, dst));
			}
			else {
				// Bounce (could leave the bouncing up to read_cluster I guess...)
				let c = try!(self.fs.load_cluster(cluster));
				let n = dst.clone_from_slice( &c );
				assert_eq!(n, dst.len());
			}
		}

		Ok( read_length )
	}
	/// Write data to the file, can only grow the file if ofs==size
	fn write(&self, ofs: u64, buf: &mut [u8]) -> node::Result<usize> {
		todo!("FileNode::write({:#x}, {:p})", ofs, ::kernel::lib::SlicePtr(buf));
	}
}


text:
package com.sishuok.es.common.repository;

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

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.NoRepositoryBean;

import com.sishuok.es.common.entity.search.Searchable;

/**
 *

 * 抽象DAO层基类 提供一些简便方法

 * 具体使用请参考测试用例:{@see com.sishuok.es.common.repository.UserRepository}
 *

 * 想要使用该接口需要在spring配置文件的jpa:repositories中添加
 * factory-class="com.sishuok.es.common.repository.support.SimpleBaseRepositoryFactoryBean"
 *

 *

 * 泛型 : M 表示实体类型;ID表示主键类型
 *

 * User: Zhang Kaitao
 *

 * Date: 13-1-12 下午4:46
 *

 * Version: 1.0
 */
@NoRepositoryBean
public interface BaseRepository<M, ID extends Serializable> extends JpaRepository<M, ID> {

	/**
	 * 根据主键删除
	 *
	 * @param ids
	 */
	public void delete(ID[] ids);

	/*
	* (non-Javadoc)
	* @see org.springframework.data.repository.CrudRepository#findAll()
	*/
	List<M> findAll();

	/*
	 * (non-Javadoc)
	 * @see org.springframework.data.repository.PagingAndSortingRepository#findAll(org.springframework.data.domain.Sort)
	 */
	List<M> findAll(Sort sort);

	/**
	 * Returns a {@link Page} of entities meeting the paging restriction provided in the {@code Pageable} object.
	 *
	 * @param pageable
	 * @return a page of entities
	 */
	Page<M> findAll(Pageable pageable);

	/**
	 * 根据条件查询所有 条件 + 分页 + 排序
	 *
	 * @param searchable
	 * @return
	 */
	public Page<M> findAll(Searchable searchable);

	/**
	 * 根据条件统计所有记录数
	 *
	 * @param searchable
	 * @return
	 */
	public long count(Searchable searchable);

	/**
	 * 对象联查
	 * @param spec
	 * @return
	 */
	public List<M> findAll(Specification<M> spec);

	/**
	 * 对象联查
	 * @param spec
	 * @param pageable
	 * @return
	 */
	public Page<M> findAll(Specification<M> spec, Pageable pageable);

	/**
	 * 对象联查
	 * @param spec
	 * @param sort
	 * @return
	 */
	public List<M> findAll(Specification<M> spec, Sort sort);

	/**
	 * 对象联查
	 * @param spec
	 * @return
	 */
	public long count(Specification<M> spec);

}


text:
namespace doppia {

/// helper class that provides access to an image where
/// every row is 16 bytes memory aligned
class AlignedImage
{

public:
    typedef Eigen::aligned_allocator<boost::uint8_t> aligned_uint8_allocator;
    typedef boost::multi_array< boost::uint8_t, 2, aligned_uint8_allocator> data_t;
    typedef boost::gil::rgb8_view_t view_t;
    typedef boost::gil::rgb8c_view_t const_view_t;
    typedef view_t::point_t point_t;

    AlignedImage();
    AlignedImage(const point_t dimensions);
    AlignedImage(const size_t width, const size_t height);

    ~AlignedImage();

    bool empty() const;

    void resize(const point_t dimensions);
    void resize(const size_t width, const size_t height);

    const point_t &dimensions() const;

    data_t &get_multi_array();
    const data_t &get_multi_array() const;

    const view_t &get_view();
    const const_view_t &get_view() const;

protected:

    data_t data;
    view_t image_view;
    const_view_t image_const_view;
};

} // end of namespace doppia

#endif // ALIGNEDIMAGE_HPP