text:
package jp.takke.abc2014sv.ui.fragments;

import it.gmariotti.cardslib.library.internal.Card;
import it.gmariotti.cardslib.library.internal.CardArrayAdapter;
import it.gmariotti.cardslib.library.internal.CardHeader;
import it.gmariotti.cardslib.library.internal.base.BaseCard;
import it.gmariotti.cardslib.library.view.CardListView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import jp.takke.abc2014sv.App;
import jp.takke.abc2014sv.App.Lecture;
import jp.takke.abc2014sv.App.Speaker;
import jp.takke.abc2014sv.MyToolbarListener;
import jp.takke.abc2014sv.R;
import jp.takke.abc2014sv.cards.CustomCard;
import jp.takke.abc2014sv.cards.CustomExpandCard;
import jp.takke.abc2014sv.util.MyLog;
import jp.takke.abc2014sv.util.TPUtil;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupMenu;

/**
 * カンファレンス用Fragment
 */
public class ConferenceFragment extends MyFragment implements MyToolbarListener {

    int mCategoryId = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mCategoryId = mPaneInfo.getCategoryId();

        MyLog.d("ConferenceFragment.onCreate[" + mCategoryId + "]");

        // オプションメニューの存在設定(onOptionsItemSelectedが呼ばれるようにする)
        setHasOptionsMenu(true);

        MyLog.iWithElapsedTime("startupseq[{elapsed}ms] ConferenceFragment.onCreate done [" + mPositionInViewPager + "]", App.sStartedAt);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        MyLog.d("ConferenceFragment.onCreateView[" + mCategoryId + "]");

        return inflater.inflate(R.layout.fragment_list_conference, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initCards();
    }

    @Override
    public void resetTabData() {

        CardListView listView = null;
        final View v = getView();
        if (v != null) {
            listView = (CardListView) v.findViewById(R.id.carddemo_list_expand);
        }

        // スクロール位置保存
        int position = 0;
        int y = 0;
        if (listView!=null){
            position = listView.getFirstVisiblePosition();
            final View child = listView.getChildAt(0);
            if (child != null) {
                y = child.getTop();
            }
        }

        // 再生成
        initCards();

        // スクロール位置復帰
        if (listView!=null) {
            listView.setSelectionFromTop(position, y);
        }

    }

    private void initCards() {

        MyLog.d("ConferenceFragment.initCards[" + mCategoryId + "]");

        // Init an array of Cards
        ArrayList<Card> cards = new ArrayList<Card>();

        if (mCategoryId == 0) {
            // ホーム
            {
                final Lecture pi = new Lecture();
                pi.title = "";
                pi.title += "※講演内容、講演時間は予告無く変更される場合があります。ご了承下さい。";

                final Card card = init_standard_header_with_expandcollapse_button_custom_area(pi);
                cards.add(card);
            }

            //--------------------------------------------------
            // お気に入り登録したデータの表示
            //--------------------------------------------------
            final ArrayList<Lecture> lectures = new ArrayList<App.Lecture>();
            if (App.sConferenceData != null) {

                for (int i=0; i<App.sConferenceData.lectures.size(); i++){

                    final Lecture lecture = App.sConferenceData.lectures.get(i);

                    if (App.sStarMap.containsKey(lecture.getStarKey())) {
                        lectures.add(lecture);
                    }
                }
                if (lectures.size() > 0) {

                    // 枠順、部屋順、開催順にソート
                    Collections.sort(lectures, new Comparator<Lecture>() {

                        @Override
                        public int compare(Lecture lhs, Lecture rhs) {

                            // time_frame
                            final int c0 = lhs.time_frame - rhs.time_frame;
                            if (c0 != 0) {
                                return c0;
                            }

                            // room_id
                            final int c1 = lhs.room_id - rhs.room_id;
                            if (c1 != 0) {
                                return c1;
                            }

                            // start_time
                            if (lhs.start_time != null && rhs.start_time != null) {
                                final int c2 = lhs.start_time.compareTo(rhs.start_time);
                                return c2;
                            }

                            return 0;
                        }
                    });

                    for (Lecture lecture : lectures) {
                        final Card card = init_standard_header_with_expandcollapse_button_custom_area(lecture);
                        cards.add(card);
                    }
                }
            }

            if (lectures.size() == 0 && App.sStarMap.size() == 0) {
                final Lecture pi = new Lecture();
                pi.title = "";

                pi.title += "左側に「ライブ情報」タブがあります。開催前はダミーデータが表示されます。\n"
                         + "このタブにはお気に入りに登録したカンファレンスが表示されます";
                final Card card = init_standard_header_with_expandcollapse_button_custom_area(pi);
                cards.add(card);
            }

        } else {

            if (App.sConferenceData != null) {

                //--------------------------------------------------
                // 会場情報設定
                //--------------------------------------------------
                final Lecture pi = new Lecture();
                switch (mCategoryId) {
                case 1: pi.title = "T0:基調講演/Reborn";            break;
                case 2: pi.title = "T1:デザイン・開発";             break;
                case 3: pi.title = "T2:メーカー・キャリア";         break;
                case 4: pi.title = "T3:コンテンツ・ビジネス";       break;
                case 5: pi.title = "T4:開発";                       break;
                case 6: pi.title = "T5:デバイス";                   break;
                case 7: pi.title = "T6:EffectiveAndroidコラボ開発"; break;
                case 8: pi.title = "T7:LT";                         break;
                case 9: pi.title = "T8:ビジネス・教育";             break;
                }
                // 場所
                pi.speakers.add(new Speaker(getPlace(mCategoryId)));
                {
                    final Card card = init_standard_header_with_expandcollapse_button_custom_area(pi);
                    cards.add(card);
                }

                //--------------------------------------------------
                // 該当カテゴリのカンファレンスデータを追加する
                //--------------------------------------------------
                for (int i=0; i<App.sConferenceData.lectures.size(); i++){

                    final Lecture lecture = App.sConferenceData.lectures.get(i);

                    if (mCategoryId == lecture.category_id) {

                        final Card card = init_standard_header_with_expandcollapse_button_custom_area(lecture);
                        cards.add(card);
                    }
                }
            }
        }

        final CardArrayAdapter mCardArrayAdapter = new CardArrayAdapter(getActivity(), cards);

        final View v = getView();
        if (v != null) {

            final CardListView listView = (CardListView) v.findViewById(R.id.carddemo_list_expand);
            if (listView!=null){
                listView.setAdapter(mCardArrayAdapter);
            }
        }
    }

    private String getPlace(int categoryId) {
        switch (categoryId) {
        case 1: return "秋葉原ダイビル2F";
        case 2: return "秋葉原ダイビル2F";
        case 3: return "秋葉原ダイビル5F 5A";
        case 4: return "秋葉原ダイビル5F 5B";
        case 5: return "秋葉原ダイビル5F 5C";
        case 6: return "UDX 6F タイプ350";
        case 7: return "UDX 6F タイプ120";
        case 8: return "UDX 6F タイプ120";
        case 9: return "UDX 6F タイプ120";
        }
        return "";
    }

    /**
     * This method builds a standard header with a custom expand/collpase
     */
    private Card init_standard_header_with_expandcollapse_button_custom_area(final Lecture lecture) {

        final CustomCard card = new CustomCard(getActivity());

        //--------------------------------------------------
        // ヘッダー
        //--------------------------------------------------
        final CardHeader header = new CardHeader(getActivity());

        String title = "";
//        switch (lecture.time_frame) {
//        case 11:  title += "10:00~"; break;
//        case 12:  title += "11:15~"; break;
//        case 13:  title += "13:15~"; break;
//        case 14:  title += "14:15~"; break;
//        case 15:  title += "15:15~"; break;
//        case 16:  title += "16:15~"; break;
//        }
//        title += " ";

        final Integer starLevel = App.sStarMap.get(lecture.getStarKey());
        if (starLevel != null) {
            switch (starLevel) {
            case 1: title += "★ ";       break;
            case 2: title += "★★ ";     break;
            case 3: title += "★★★ ";   break;
            }
        }

        header.setTitle(title + lecture.title);

        //Set visible the expand/collapse button
//        header.setButtonExpandVisible(true);

        if (lecture.lec_id != null && lecture.lec_id.length() > 0) {

            //--------------------------------------------------
            // メニュー生成
            //--------------------------------------------------

            // Add a popup menu. This method set OverFlow button to visible
            header.setButtonOverflowVisible(true);
            header.setPopupMenuListener(new CardHeader.OnClickCardHeaderPopupMenuListener() {
                @Override
                public void onMenuItemClick(BaseCard card, MenuItem item) {
//                  Toast.makeText(getActivity(), "Click on " + item.getTitle() + "-" + ((Card) card).getCardHeader().getTitle(), Toast.LENGTH_SHORT).show();

                    switch (item.getItemId()) {
                    case 0: // ★★★
                    case 1: // ★★
                    case 2: // ★
                        switch (item.getItemId()) {
                        case 0: // ★★★
                            App.sStarMap.put(lecture.getStarKey(), 3);
                            break;
                        case 1: // ★★
                            App.sStarMap.put(lecture.getStarKey(), 2);
                            break;
                        case 2: // ★
                            App.sStarMap.put(lecture.getStarKey(), 1);
                            break;
                        }
                        getMainActivity().resetAllTabs();
                        getMainActivity().saveStarMap();
                        break;

                    case 3: // ☆
                        // お気に入り削除
                        App.sStarMap.remove(lecture.getStarKey());
                        getMainActivity().resetAllTabs();
                        getMainActivity().saveStarMap();
                        break;

                    case 10: // 共有
                        doShare(lecture);
                        break;

                    case 20: // ブラウザで開く
                        // TODO なんかアンカーのルールがよくわかんないのでカテゴリページを開く
                        getMainActivity().openExternalBrowser(getUrl());
                        break;
                    }

                }
            });

            // Add a PopupMenuPrepareListener to add dynamically a menu entry
            // it is optional.
            header.setPopupMenuPrepareListener(new CardHeader.OnPrepareCardHeaderPopupMenuListener() {
                @SuppressLint("NewApi")
				@Override
                public boolean onPreparePopupMenu(BaseCard card, PopupMenu popupMenu) {
                    popupMenu.getMenu().add(0,  0,  0, "★★★");
                    popupMenu.getMenu().add(0,  1,  1, "★★");
                    popupMenu.getMenu().add(0,  2,  2, "★");
                    popupMenu.getMenu().add(0,  3,  3, "☆");
                    popupMenu.getMenu().add(0, 10, 10, "共有");
                    popupMenu.getMenu().add(0, 20, 20, "ブラウザで開く");

                    //return false; You can use return false to hidden the button and the popup
                    return true;
                }
            });
        }

        //Add Header to card
        card.addCardHeader(header);

        //--------------------------------------------------
        // カード
        //--------------------------------------------------
        String body = lecture.getSpeakersText() + "\n";
        if (lecture.lec_id != null && lecture.lec_id.length() > 0) {
            body += "[" + lecture.lec_id + "] " + lecture.getStartEndText() + "\n";

            if (mCategoryId == 0) {
            	// お気に入りではルーム名、場所も表示する
            	body += lecture.room + " / " + getPlace(lecture.category_id) + "\n";
            } else {
            	body += "\n\n";
            }
        } else {
            body += "\n\n\n";
        }
        card.setTitle(body);

        switch (lecture.time_frame) {
        case 11:
        case 12:
            card.setBackgroundResourceId(R.drawable.card_background_color0);
            break;

        case 13:
            card.setBackgroundResourceId(R.drawable.card_background_color1);
            break;
        case 14:
            card.setBackgroundResourceId(R.drawable.card_background_color2);
            break;
        case 15:
            card.setBackgroundResourceId(R.drawable.card_background_color3);
            break;
        case 16:
            card.setBackgroundResourceId(R.drawable.card_background_color4);
            break;
        case 17:
            card.setBackgroundResourceId(R.drawable.card_background_color5);
            break;

        default:
            card.setBackgroundResourceId(R.drawable.card_background_color6);
            break;
        }

        //--------------------------------------------------
        // Expandカード
        //--------------------------------------------------
        if (lecture.lec_id != null && lecture.lec_id.length() > 0) {
            CustomExpandCard expand = new CustomExpandCard(getActivity(), lecture);

            card.mExpandable = true;

            //Add Expand Area to Card
            card.addCardExpand(expand);
        }

        //Swipe
//        card.setSwipeable(true);

        return card;
    }

    protected void doShare(Lecture lecture) {

        String text = "";

        text += " ";
        text += "[" + lecture.lec_id + "]";
        text += lecture.title;
        text += "(" + getPlace(lecture.category_id) + ")";
//      text += " " + lecture.url;
        // URLデータが不正なのでルーム別のページにする
        text += " " + getUrl();
        text += " #abc2014s";

        TPUtil.doShareAsText(getActivity(), text, null);
    }

    /**
     * ViewPager 内でアクティブになった際の通知
     */
    public void onActivatedOnViewPager() {

        MyLog.d("ConferenceFragment.onActivatedOnViewPager[" + mCategoryId + "]");
    }

    @Override
    public boolean isLoading() {
        return false;
    }

    @Override
    public String getUrl() {

        switch (mCategoryId) {
        case 1: return "http://www.android-group.jp/conference/abc2014s/conference/keynote/";   // 基調講演/Reborn
        case 2: return "http://www.android-group.jp/conference/abc2014s/conference/design/";    // デザイン・開発
        case 3: return "http://www.android-group.jp/conference/abc2014s/conference/maker/";     // メーカー・キャリア
        case 4: return "http://www.android-group.jp/conference/abc2014s/conference/content/";   // コンテンツ・ビジネス
        case 5: return "http://www.android-group.jp/conference/abc2014s/conference/dev/";       // 開発
        case 6: return "http://www.android-group.jp/conference/abc2014s/conference/device/";    // デバイス
        case 7: return "http://www.android-group.jp/conference/abc2014s/conference/effective/"; // EffectiveAndroidコラボ開発
        case 8: return "http://www.android-group.jp/conference/abc2014s/conference/lt/";        // LT
        case 9: return "http://www.android-group.jp/conference/abc2014s/conference/business/";  // ビジネス・教育
        }

        return "http://www.android-group.jp/conference/abc2014s/";
    }

}


text:
<!DOCTYPE html>
<html ng-app="grabs">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="Pragma" content="no-cache">
        <meta http-equiv="Expires" content="-1">
        <meta name="googlebot" content="noarchive">
        <meta name="Revisit-After" content="1 days">
        <meta name="robots" content="index,follow">
        <base href="/">
        <link rel="shortcut icon" href="img/grabs/favicon.ico">

        <!-- Directive - pageTitle -->
        <title></title>

        <!-- Development or Live Mode Styles -->
        <% if (development) { %>
            <% cssFiles.forEach(function (href) { %>
                <link rel="stylesheet" type="text/css" href="<%= href %>">
            <% }) %>
        <% } else { %>
            <link rel="stylesheet" type="text/css" href="css/app.min.<%= hash %>.css">
        <% } %>
    </head>
    <body>

        <!-- Main Content -->
        <div ng-view></div>

        <!-- Development or Live Mode Scripts -->
        <% if (development) { %>
            <% jsFiles.forEach(function (src) { %>
                <script type="text/javascript" src="<%= src %>"></script>
            <% }) %>
            <script src="http://localhost:35729/livereload.js"></script>
        <% } else { %>
            <script type="text/javascript" src="js/app.min.<%= hash %>.js"></script>
        <% } %>
    </body>
</html>

redpajama_set_name: RedPajamaGithub


text:
layout: post
lang: ru
ref: serious_training_endurance_athlets_rob_sleamaker_ray_browning_sheet
title: "Google таблица для составления плана по книге Серьезные тренировки для спортсменов на выносливость, Роб Слимейкер"
comments: true
tags: [sport, ski]
redirect_from: "/posts/ru/2019-03-01-serious_training_endurance_athlets_rob_sleamaker_google_sheet/"
---
![](/images/2019-03-02_15-49-22.png){:.post-title}

В этой статье описан Google sheet для составления тренировочных планов по методике из книги:
* [Роб Слимейкер, Рэй Браунинг Серьезные тренировки для спортсменов на выносливость](https://www.ozon.ru/context/detail/id/142772738/)
* [Rob Sleamaker, Ray Browning Serious Training for Endurance Athletes 2nd](https://www.amazon.com/Serious-Training-Endurance-Athletes-2nd/dp/0873226445)

Краткое описание упражнений можно прочитать в статье
 [Серьезные тренировки..](/posts/ru/serious_training_endurance_athlets_rob_sleamaker_ray_browning.html).

## Как настроить план под вас

Google documents таблица с шаблоном плана публично доступна:
[Training plan google sheet](https://docs.google.com/spreadsheets/d/1GcrX_6qRqsKnWwP0Ya3QMR7ztyWaiKZsMRE6p0xxe0E)

Чтобы составить свой план вам нужно:
* Указать в ячейке `C4` дату его начала
* Указать в ячейке `A2` количество часов в году, которое вы можете выделить
на тренировки.
* Если вам необходимо, чтобы план завершился раньше - например, к дате
соревнования, удалить лишние недели из каких-то фаз.
Старайтесь не удалять первую неделю
цикла, а если вам это надо, то потом поправьте  фомулу расчета коэффициента
в `B6`.
При удалении столбцов google sheet
предупредит вас о коррекции защищенного диапазона ячеек. вы можете
проигнорировать это предупреждение.

Если вы рассчитываете количество часов в году как число часов в неделю,
умноженное на число недель, то учтите, что объем тренировок чуть больше в интенсивной
фазе.

Поэтому, если вы не можете тратить на тренировки столько времени, как
требует интенсивная фаза, укажите на год чуть меньшее число часов.

Тогда в интенсивной фазе вы будете использовать
все возможное для вас время, а на базовой фазе - чуть меньше.

## Планирование

* Проставить распределение по видам тренировок на все недели.
Я делаю это частично автоматически. Например, я выделяю в базовой фазе три,
а в интенсивной два дня под силовые тренировки, и формулой распределяю
между ними время равномерно. Кроме того, то что не распределено по понедельник-пятницу
у меня равномерно распределяется по субботе и воскресенью.
За счет этого я составляю план на полгода очень быстро.
* Обратите внимание,  что нельзя редактировать в плане воскресенье.
Оно автоматически планируется как остаток того, что вы не разнесли на
другие дни. Это ускоряет планирование и страхует вас от ошибок.
Если вам все-таи надо поправить и сумму за неделю (например, вы решили
полностью отдохнуть три дня перед соревнованием), то корректируйте коэффициент
недели в `6`й строке, или коэффициент соответствующего вида тренировок в строках
`7-14`. В `6`й строке заполнены все колонки, но все, кроме первой, имеют
одинаковый цвет фона и шрифта, чтобы в глазах не рябило от одинаковых
цифр.

## Локализация на другие языки

Я сделал локализацию надписей в таблице.
Вручную на русский и английский, а для прочих языков используется
автоматический переводчик google.

Таблица использует язык, который
указывается в `File - Spreadsheet settings`.

К сожалению, я не нашел, как обновлять ячейки при смене языка,
поэтому я их обновляю при открытии таблицы. Технически это происходит
за счет записи случайного числа в ячейку `B4` - цвет шрифта в ней
совпадает с цветом фона, поэтому ее содержимое незаметно.

## Корректировки

Конечно, жизнь не предсказуема, для того и план чтобы периодически его
корректировать.

Но одну корректировку я делаю всегда. В шаблоне используются коэффициенты
из книги.
Но в своих планах я ставлю большие коэффициенты силовой подготовке на базовом
периоде - время на этой фазе есть в избытке, а силовую тренировку я считаю
важной для поддержания здоровья. Мне вовсе не хочется выгладеть так,
как чемпионы марафонов - тощие, без видимых мускулов.

## Ведение журнала

Когда вы заполняете журнал - строки "факт", внизу показывается процент
выполнения плана. Для воскресенья серым цветом показывается, сколько
осталось не выполнено. Серые цифры (рассчитанные формулой) не учитываются
при расчете процента выполнения плана. Как только вы введете поверх них
свои фактические цифры, они будут показаны черным цветом и будут учитываться
в расчете процента выполнения плана.

В итоге у вас будет что-то вроде этого:

![](/images/endurance_example.png){:.post-title}


text:
.. blogpost::
    :title: A quoi sert ce module ?
    :keywords: module
    :date: 2015-23-11
    :categories: python

    Ce module contient du code développé spécifiquement pour des projets
    ou des événements comme un hackathon. Il s'agit d'une
    documentation et de bouts codes dédiés.
    Il contient également des données, le plus souvent
    cryptées et seulement accessibles avec le mot de passe adéquat.
    Français et anglais sont utilisés.


text:
nclude<iostream>
using namespace std;

// Utility function to find minimum of three numbers
int min(int x, int y, int z)
{
    return min(min(x, y), z);
}

int editDistDP(string str1, string str2, int m, int n)
{
    // Create a table to store results of subproblems
    int dp[m+1][n+1];

    // Fill d[][] in bottom up manner
    for (int i=0; i<=m; i++)
    {
        for (int j=0; j<=n; j++)
        {
            // If first string is empty, only option is to
            // isnert all characters of second string
            if (i==0)
                dp[i][j] = j;  // Min. operations = j

            // If second string is empty, only option is to
            // remove all characters of second string
            else if (j==0)
                dp[i][j] = i; // Min. operations = i

            // If last characters are same, ignore last char
            // and recur for remaining string
            else if (str1[i-1] == str2[j-1])
                dp[i][j] = dp[i-1][j-1];

            // If last character are different, consider all
            // possibilities and find minimum
            else
                dp[i][j] = 1 + min(dp[i][j-1],  // Insert
                                   dp[i-1][j],  // Remove
                                   dp[i-1][j-1]); // Replace
        }
    }

    return dp[m][n];
}

// Driver program
int main()
{
    // your code goes here
    string str1 = "sunday";
    string str2 = "saturday";

    cout << editDistDP(str1, str2, str1.length(), str2.length());

    return 0;
}


text:
from __future__ import print_function
import os, sys
import numpy as np
import copy
import types

from getch import getch

def import_file(filename):
    path = os.path.dirname(filename)
    if not path in sys.path:
        sys.path.append(path)
    name = os.path.splitext(os.path.basename(filename))[0]
    mod = __import__(name)
    return mod

def assert_(condition):
    if not condition:
        raise ValueError('assertion failed!')

def pause(msg=None):
    """
    Prints the line number and waits for a keypress.

    If you press:
    "q" ............. it will call sys.exit()
    any other key ... it will continue execution of the program

    This is useful for debugging.
    """
    f = sys._getframe(1)
    ff = f.f_code
    if (msg):
        print('%s, %d: %s(), %d: %s' % (ff.co_filename, ff.co_firstlineno,
                                        ff.co_name, f.f_lineno, msg))
    else:
        print('%s, %d: %s(), %d' % (ff.co_filename, ff.co_firstlineno,
                                    ff.co_name, f.f_lineno))
    spause()

def spause(msg=None):
    """
    Waits for a keypress.

    If you press:
    "q" ............. it will call sys.exit()
    any other key ... it will continue execution of the program

    This is useful for debugging. This function is called from pause().
    """
    if (msg):
        print(msg)
    sys.stdout.flush()
    ch = getch()
    if ch == 'q':
        sys.exit()

def ordered_iteritems(adict):
    keys = list(adict.keys())
    order = np.argsort(keys)
    for ii in order:
        key = keys[ii]
        yield key, adict[key]

def dict_from_keys_init(keys, seq_class=None):

    if seq_class is None:
        return {}.fromkeys(keys)

    out = {}
    for key in keys:
        out[key] = seq_class()
    return out

_dashes = '-'*50

class Object(object):
    traits = {}

    @staticmethod
    def objects_from_dict(*args, **kwargs):

        kws = copy.copy(kwargs)

        level = kws.pop('level', 0)
        flag = kws.pop('flag')

        # For level 0 only...
        constructor = kws.pop('constructor', Object)

        out = []
        for arg in args:
            if type(arg) == dict:
                if flag[level]:
                    arg.update(kws)
                    aux = constructor(**arg)
                    iterator = aux.__dict__
                else:
                    aux = iterator = arg

                for key, val in iterator.items():
                    if (type(val) == dict) and (key != 'traits'):
                        try:
                            flag[level+1]
                        except:
                            flag = flag + (0,)
                        val2 = Object.objects_from_dict(val, level=level+1,
                                                        flag=flag)

                        if flag[level]:
                            aux.__dict__[key] = val2
                        else:
                            aux[key] = val2

                out.append(aux)
            else:
                out.append(arg)

        if len(out) == 1:
            out = out[0]

        return out

    def __init__(self, **kwargs):
        if kwargs:
            self.__dict__.update(kwargs)
            self.traits = copy.copy(self.__class__.traits)
            self.set_default_traits(kwargs.keys())

    def set_default_traits(self, keys):
        self.traits.update({}.fromkeys(keys))

    def init_trait(self, name, value, format=None):
        setattr(self, name, value)
        self.traits[name] = format

    def get_dict(self):
        aux = copy.copy(self.__dict__)
        aux.pop('traits')
        return aux

    def get(self, key, default=None, msg_if_none=None):
        """
        A dict-like get().
        """
        out = getattr(self, key, default)

        if (out is None) and (msg_if_none is not None):
            raise ValueError(msg_if_none)

        return out

    def get_not_none(self, key, default):
        val = self.get(key, default)
        if val is None:
            if default is None:
                msg = 'both attribute "%s" and default value are None!' % key
                raise ValueError(msg)

            else:
                val = default

        return val

    def __str__(self):
        return self._format()

    def __repr__(self):
        if hasattr(self, 'name'):
            return "%s:%s" % (self.__class__.__name__, self.name)
        else:
            return object.__repr__(self)

    def copy(self, deep=False):
        if deep:
            return copy.deepcopy(self)
        else:
            return copy(self)

    def _format(self, mode='print', header=True):
        if header:
            if mode != 'report':
                msg = ['%s' % object.__str__(self)]
            elif mode == 'report':
                msg = [_dashes, self.__repr__(), _dashes]
        else:
            msg = []

        keys = list(self.traits.keys())
        order = np.argsort(keys)
        for ii in order:
            key = keys[ii]
            if (key == 'name') and (mode == 'report'): continue

            val = self.traits[key]

            not_set = False
            if isinstance(val, tuple):
                tr = val[1]
                try:
                    attr = tr(getattr(self, key))
                except:
                    attr = '<not set>'
                    not_set = True
                    val = '%s'
                else:
                    val = val[0]
            elif isinstance(val, types.FunctionType):
                attr = val(self)
                val = None
            else:
                try:
                    attr = getattr(self, key)
                except:
                    attr = '<not set>'
                    not_set = True

            if not_set and (mode == 'set_only'): continue

            if issubclass(attr.__class__, Object):
                sattr = repr(attr)
                attr = '%s: %s' % (key, sattr)
            else:
                if val is None:
                    attr = '%s: %s' % (key, attr)
                else:
                    attr = ('%s: ' % key) + (val % attr)

            msg.append(attr)

        return '\n'.join(msg)

    def fd_open(self, filename):
        if isinstance(filename, file):
            fd = filename
        else:
            fd = open(filename, 'w')

        self._fd = fd
        self._filename = filename

        return fd

    def fd_close(self):
        if self._fd is not self._filename:
            self._fd.close()

    def report(self, filename, header=True):
        fd = self.fd_open(filename)
        fd.write(self._format(mode='report', header=header))
        fd.write('\n')
        self.fd_close()

class Config(Object):

    @staticmethod
    def from_file(filename, required=None, optional=None, defaults=None):
        conf_mod = import_file(filename)

        if 'define' in conf_mod.__dict__:
            define_dict = conf_mod.__dict__['define']()
        else:
            define_dict = conf_mod.__dict__

        return Config.from_conf(define_dict, required, optional, defaults)

    @staticmethod
    def from_conf(conf, required=None, optional=None, defaults=None):
        if required is None:
            required = []

        if optional is None:
            optional = [key for key in conf.keys() if key[:7] == 'options']

        if defaults is None:
            defaults = {}

        valid = {}
        for kw in required:
            try:
                val = conf[kw]
            except KeyError:
                raise ValueError('missing keyword "%s"!' % kw)
            valid[kw] = val

        for kw in optional:
            valid[kw] = conf.get(kw, None)

        for group_key, group in valid.items():
            for key, val in defaults.items():
                if key not in group:
                    group[key] = val

        return Config(**valid)

    def override(self, options, can_override):
        for group_key, group in self.__dict__.items():
            for key, val in group.items():
                if key in can_override:
                    group[key] = getattr(options, key)

class Output(Object):
    """Factory class providing output (print) functions.

    Example:

    >>> output = Output('sfepy:')
    >>> output(1, 2, 3, 'hello')
    >>> output.prefix = 'my_cool_app:'
    >>> output(1, 2, 3, 'hello')
    """
    traits = {
        'prefix' : None,
        'output_function' : None,
        'level' : None,
    }

    def __init__(self, prefix, filename=None, combined=False, **kwargs):
        Object.__init__(self, **kwargs)

        self.prefix = prefix

        self.set_output(filename, combined)

    def __call__(self, *argc, **argv):
        self.output_function(*argc, **argv)

    def set_output(self, filename=None, combined=False, append=False):
        """Set the output function - all SfePy printing is accomplished by
        it. If filename is None, output is to screen only, otherwise it is to
        the specified file, moreover, if combined is True, both the ways are
        used.

        Arguments:
                filename - print into this file
                combined - print both on screen and into a file
                append - append to an existing file instead of overwriting it
        """
        self.level = 0
        def output_screen(*argc, **argv):
            format = '%s' + ' %s' * (len(argc) - 1)
            msg =  format % argc

            if msg.startswith('...'):
                self.level -= 1

            print(self._prefix + ('  ' * self.level) + msg)

            if msg.endswith('...'):
                self.level += 1

        def output_file(*argc, **argv):
            format = '%s' + ' %s' * (len(argc) - 1)
            msg =  format % argc

            if msg.startswith('...'):
                self.level -= 1

            fd = open(filename, 'a')
            print(self._prefix + ('  ' * self.level) + msg, file=fd)
            fd.close()

            if msg.endswith('...'):
                self.level += 1

        def output_combined(*argc, **argv):
            output_screen(*argc, **argv)
            output_file(*argc, **argv)

        if filename is None:
            self.output_function = output_screen

        else:
            if not append:
                fd = open(filename, 'w')
                fd.close()

            if combined:
                self.output_function = output_combined
            else:
                self.output_function = output_file

    def get_output_function(self):
        return self.output_function

    def set_output_prefix(self, prefix):
        assert_(isinstance(prefix, str))
        if len(prefix) > 0:
            prefix += ' '
        self._prefix = prefix

    def get_output_prefix(self):
        return self._prefix[:-1]
    prefix = property(get_output_prefix, set_output_prefix)

output = Output('elfpy:')


text:
package com.timgroup.statsd;

import static java.lang.Long.valueOf;
import static junit.framework.Assert.assertTrue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.startsWith;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Test;

public final class NonBlockingStatsDClientTest {

    private static final int STATSD_SERVER_PORT = 17254;

    private final NonBlockingStatsDClient client = new NonBlockingStatsDClient("my.prefix", "localhost", STATSD_SERVER_PORT);
    private final DummyStatsDServer server = new DummyStatsDServer(STATSD_SERVER_PORT);

    @After
    public void stop() throws Exception {
        client.stop();
        server.stop();
    }

    @Test(timeout=5000L) public void
    sends_counter_value_to_statsd() throws Exception {
        client.count("mycount", Long.MAX_VALUE);
        server.waitForMessage();

        assertThat(server.messagesReceived(), contains("my.prefix.mycount:9223372036854775807|c"));
    }

    @Test(timeout=5000L) public void
    sends_counter_value_with_rate_to_statsd() throws Exception {
        client.count("mycount", Long.MAX_VALUE, 0.00024);
        server.waitForMessage();

        assertThat(server.messagesReceived(), contains("my.prefix.mycount:9223372036854775807|c|@0.00024"));
    }

    @Test(timeout=5000L) public void
    sends_counter_increment_to_statsd() throws Exception {
        client.incrementCounter("myinc");
        server.waitForMessage();

        assertThat(server.messagesReceived(), contains("my.prefix.myinc:1|c"));
    }

    @Test(timeout=5000L) public void
    sends_counter_decrement_to_statsd() throws Exception {
        client.decrementCounter("mydec");
        server.waitForMessage();

        assertThat(server.messagesReceived(), contains("my.prefix.mydec:-1|c"));
    }

    @Test(timeout=5000L) public void
    sends_gauge_to_statsd() throws Exception {
        client.recordGaugeValue("mygauge", Long.MAX_VALUE);
        server.waitForMessage();

        assertThat(server.messagesReceived(), contains("my.prefix.mygauge:9223372036854775807|g"));
    }

    @Test(timeout=5000L) public void
    sends_fractional_gauge_to_statsd() throws Exception {
        client.recordGaugeValue("mygauge", 423.123456789d);
        server.waitForMessage();

        assertThat(server.messagesReceived(), contains("my.prefix.mygauge:423.123456789|g"));
    }

    @Test(timeout=5000L) public void
    sends_large_fractional_gauge_to_statsd() throws Exception {
        client.recordGaugeValue("mygauge", 423423423.9d);
        server.waitForMessage();

        assertThat(server.messagesReceived(), contains("my.prefix.mygauge:423423423.9|g"));
    }

    @Test(timeout=5000L) public void
    sends_zero_gauge_to_statsd() throws Exception {
        client.recordGaugeValue("mygauge", 0L);
        server.waitForMessage();

        assertThat(server.messagesReceived(), contains("my.prefix.mygauge:0|g"));
    }

    @Test(timeout=5000L) public void
    sends_negagive_gauge_to_statsd_by_resetting_to_zero_first() throws Exception {
        client.recordGaugeValue("mygauge", -423L);
        server.waitForMessage();

        assertThat(server.messagesReceived(), contains("my.prefix.mygauge:0|g\nmy.prefix.mygauge:-423|g"));
    }

    @Test(timeout=5000L) public void
    sends_gauge_positive_delta_to_statsd() throws Exception {
        client.recordGaugeDelta("mygauge", 423L);
        server.waitForMessage();

        assertThat(server.messagesReceived(), contains("my.prefix.mygauge:+423|g"));
    }

    @Test(timeout=5000L) public void
    sends_gauge_negative_delta_to_statsd() throws Exception {
        client.recordGaugeDelta("mygauge", -423L);
        server.waitForMessage();

        assertThat(server.messagesReceived(), contains("my.prefix.mygauge:-423|g"));
    }

    @Test(timeout=5000L) public void
    sends_gauge_zero_delta_to_statsd() throws Exception {
        client.recordGaugeDelta("mygauge", 0L);
        server.waitForMessage();

        assertThat(server.messagesReceived(), contains("my.prefix.mygauge:+0|g"));
    }

    @Test(timeout=5000L) public void
    sends_set_to_statsd() throws Exception {
        client.recordSetEvent("myset", "test");
        server.waitForMessage();

        assertThat(server.messagesReceived(), contains("my.prefix.myset:test|s"));
    }

    @Test(timeout=5000L) public void
    sends_timer_to_statsd() throws Exception {
        client.recordExecutionTime("mytime", 123L);
        server.waitForMessage();

        assertThat(server.messagesReceived(), contains("my.prefix.mytime:123|ms"));
    }

    @Test(timeout=5000L) public void
    sends_timer_with_rate_to_statsd() throws Exception {
        client.recordExecutionTime("mytime", 123L, 0.000123);
        server.waitForMessage();

        assertThat(server.messagesReceived(), contains("my.prefix.mytime:123|ms|@0.000123"));
    }

    @Test(timeout=5000L) public void
    sends_timer_to_statsd_based_on_specified_start_time_to_now() throws Exception {
        final long startTime = System.currentTimeMillis() - 1000L;

        final long beforeCompletionTime = System.currentTimeMillis();
        client.recordExecutionTimeToNow("mytime", startTime);
        final long afterCompletionTime = System.currentTimeMillis();

        server.waitForMessage();

        long maxExpectedValue = afterCompletionTime - startTime;
        long minExpectedValue = beforeCompletionTime - startTime;
        final String messageReceived = server.messagesReceived().get(0);
        final Matcher resultMatcher = Pattern.compile(".*:(\\d+)\\|ms").matcher(messageReceived);
        assertTrue(messageReceived, resultMatcher.matches());
        assertThat(valueOf(resultMatcher.group(1)), Matchers.greaterThanOrEqualTo(minExpectedValue));
        assertThat(valueOf(resultMatcher.group(1)), Matchers.lessThanOrEqualTo(maxExpectedValue));
    }

    @Test(timeout=5000L) public void
    sends_timer_of_zero_to_statsd_based_on_specified_start_time_in_the_future() throws Exception {
        client.recordExecutionTimeToNow("mytime", System.currentTimeMillis() + 100000L);
        server.waitForMessage();

        assertThat(server.messagesReceived(), contains("my.prefix.mytime:0|ms"));
    }

    @Test(timeout=5000L) public void
    allows_empty_prefix() {
        final NonBlockingStatsDClient emptyPrefixClient = new NonBlockingStatsDClient(" ", "localhost", STATSD_SERVER_PORT);
        try {
            emptyPrefixClient.count("mycount", 24L);
            server.waitForMessage();
        } finally {
            emptyPrefixClient.stop();
        }
        assertThat(server.messagesReceived(), contains(startsWith("mycount:")));
    }

    @Test(timeout=5000L) public void
    allows_null_prefix() {
        final NonBlockingStatsDClient nullPrefixClient = new NonBlockingStatsDClient(null, "localhost", STATSD_SERVER_PORT);
        try {
            nullPrefixClient.count("mycount", 24L);
            server.waitForMessage();
        } finally {
            nullPrefixClient.stop();
        }
        assertThat(server.messagesReceived(), contains(startsWith("mycount:")));
    }

    private static final class DummyStatsDServer {
        private final List<String> messagesReceived = new ArrayList<String>();
        private final DatagramSocket server;

        public DummyStatsDServer(int port) {
            try {
                server = new DatagramSocket(port);
            } catch (SocketException e) {
                throw new IllegalStateException(e);
            }
            new Thread(new Runnable() {
                @Override public void run() {
                    try {
                        final DatagramPacket packet = new DatagramPacket(new byte[256], 256);
                        server.receive(packet);
                        messagesReceived.add(new String(packet.getData(), Charset.forName("UTF-8")).trim());
                    } catch (Exception e) { }
                }
            }).start();
        }

        public void stop() {
            server.close();
        }

        public void waitForMessage() {
            while (messagesReceived.isEmpty()) {
                try {
                    Thread.sleep(50L);
                } catch (InterruptedException e) {}
            }
        }

        public List<String> messagesReceived() {
            return new ArrayList<String>(messagesReceived);
        }
    }
}


text:
class RedoActionCommand < ActiveRecord::Base
  belongs_to :master_tree
  belongs_to :action_command

  def self.redo_actions(master_tree_id)
    self.where(master_tree_id: master_tree_id).order("id desc").limit(Gnite::Config.undo_limit)
  end

  def self.redo(master_tree_id, session_id)
    redo_actions = self.where(master_tree_id: master_tree_id).order("id desc").limit(1)
    action = redo_actions.empty? ? nil : redo_actions[0].action_command
    ActionCommand.schedule_actions(action, session_id) if action
    action
  end
end


text:
((function() {

    function Waitfor(exports) {

        var status = {};
        exports._status = status;

        exports.serial = function(callback) {
            var id = new Date().getTime();
            var running = false;
            var queue = [];
            var error = undefined;
            return function waitFor() {
                function runOrQueueWorker(name, args) {
                    if (running === false) {
                        runWorker(name, args);
                    }
                    else {
                        queue.push(function() {
                            runWorker(name, args);
                        });
                    }
                }
                function runWorker(name, args) {
                    running = true;
                    var worker = args.pop();
                    args.push(function(cont) {
                        status[id][name] = "done";
                        if (cont === false) {
                            queue = [];
                            running = false;
                            callback(error);
                        } else
                        if(typeof cont === "undefined" || cont === true || cont === null) {
                            if (queue.length > 0) {
                                queue.shift()();
                            } else {
                                running = false;
                                if(callback) callback(error);
                            }
                        } else {
                            error = cont;
                            if (callback) {
                                callback(error);
                                callback = false;
                            }
                        }
                    });
                    if (!status[id]) {
                        status[id] = {};
                    }
                    status[id][name] = "pending";
                    exports.setImmediate(function() {
                        try {
                            worker.apply(null, args);
                        } catch(err) {
                            args[args.length-1](err);
                        }
                    });
                }
                var args = Array.prototype.slice.call(arguments);
                if (args.length === 0) {
                    if (running === false && callback) {
                        callback(error);
                    }
                } else
                if (args.length === 1 && typeof args[0] === "string") {
                    return function waitFor() {
                        runOrQueueWorker(args[0], Array.prototype.slice.call(arguments));
                    }
                } else {
                    runOrQueueWorker(new Date().getTime(), args);
                }
            };
        }

        exports.parallel = function(callback) {
            var id = new Date().getTime();
            var c = 0;
            var error = undefined;
            return function waitFor() {
                function runWorker(name, args) {
                    var worker = args.pop();
                    args.push(function(err) {
                        if (err) {
                            error = err;
                            if (typeof error === "object") {
                                if (!error.stack) error.stack = new Error(error.message + " (occurred somewhere prior to this stack)").stack;
                            } else {
                                error = new Error(JSON.stringify(error) + " (occurred somewhere prior to this stack)");
                            }
                        }
                        c -= 1;
                        status[id][name] = "done";
                        if (c === 0 && callback) {
                            callback(error);
                            callback = false;
                        } else
                        if (error && callback) {
                            callback(error);
                            callback = false;
                        }
                    });
                    c += 1;
                    if (!status[id]) {
                        status[id] = {};
                    }
                    status[id][name] = "pending";
                    exports.setImmediate(function() {
                        try {
                            worker.apply(null, args);
                        } catch(err) {
                            args[args.length-1](err);
                        }
                    });
                }
                var args = Array.prototype.slice.call(arguments);
                if (args.length === 0) {
                    if (c === 0 && callback) {
                        callback(error);
                    }
                } else
                if (args.length === 1 && typeof args[0] === "string") {
                    return function waitFor() {
                        runWorker(args[0], Array.prototype.slice.call(arguments));
                    }
                } else {
                    runWorker(new Date().getTime(), args);
                }
            };
        }
    }

    // Check for AMD
    if (typeof define === "function") {
        define(function() {
            var exports = {
                setImmediate: function(callback) {
                    return setTimeout(callback, 0);
                }
            };
            Waitfor(exports);
            return exports;
        });
    } else
    // Assume NodeJS
    if (typeof exports === "object") {
        require("setimmediate");
        exports.setImmediate = setImmediate;
        Waitfor(exports);
    }

})());


text:
<?php

namespace Symfony\Bridge\Doctrine\Form\ChoiceList;

use Symfony\Component\Form\Exception\UnexpectedTypeException;
use Doctrine\ORM\QueryBuilder;
use Doctrine\DBAL\Connection;
use Doctrine\Common\Persistence\ObjectManager;

/**
 * Loads entities using a {@link QueryBuilder} instance.
 *
 * @author Benjamin Eberlei <kontakt@beberlei.de>
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class ORMQueryBuilderLoader implements EntityLoaderInterface
{
    /**
     * Contains the query builder that builds the query for fetching the
     * entities.
     *
     * This property should only be accessed through queryBuilder.
     *
     * @var QueryBuilder
     */
    private $queryBuilder;

    /**
     * Construct an ORM Query Builder Loader.
     *
     * @param QueryBuilder|\Closure $queryBuilder The query builder or a closure
     *                                            for creating the query builder.
     *                                            Passing a closure is
     *                                            deprecated and will not be
     *                                            supported anymore as of
     *                                            Symfony 3.0.
     * @param ObjectManager         $manager      Deprecated
     * @param string                $class        Deprecated
     *
     * @throws UnexpectedTypeException
     */
    public function __construct($queryBuilder, $manager = null, $class = null)
    {
        // If a query builder was passed, it must be a closure or QueryBuilder
        // instance
        if (!($queryBuilder instanceof QueryBuilder || $queryBuilder instanceof \Closure)) {
            throw new UnexpectedTypeException($queryBuilder, 'Doctrine\ORM\QueryBuilder or \Closure');
        }

        if ($queryBuilder instanceof \Closure) {
            @trigger_error('Passing a QueryBuilder closure to '.__CLASS__.'::__construct() is deprecated since version 2.7 and will be removed in 3.0.', E_USER_DEPRECATED);

            if (!$manager instanceof ObjectManager) {
                throw new UnexpectedTypeException($manager, 'Doctrine\Common\Persistence\ObjectManager');
            }

            @trigger_error('Passing an EntityManager to '.__CLASS__.'::__construct() is deprecated since version 2.7 and will be removed in 3.0.', E_USER_DEPRECATED);
            @trigger_error('Passing a class to '.__CLASS__.'::__construct() is deprecated since version 2.7 and will be removed in 3.0.', E_USER_DEPRECATED);

            $queryBuilder = $queryBuilder($manager->getRepository($class));

            if (!$queryBuilder instanceof QueryBuilder) {
                throw new UnexpectedTypeException($queryBuilder, 'Doctrine\ORM\QueryBuilder');
            }
        }

        $this->queryBuilder = $queryBuilder;
    }

    /**
     * {@inheritdoc}
     */
    public function getEntities()
    {
        return $this->queryBuilder->getQuery()->execute();
    }

    /**
     * {@inheritdoc}
     */
    public function getEntitiesByIds($identifier, array $values)
    {
        $qb = clone $this->queryBuilder;
        $alias = current($qb->getRootAliases());
        $parameter = 'ORMQueryBuilderLoader_getEntitiesByIds_'.$identifier;
        $parameter = str_replace('.', '_', $parameter);
        $where = $qb->expr()->in($alias.'.'.$identifier, ':'.$parameter);

        // Guess type
        $entity = current($qb->getRootEntities());
        $metadata = $qb->getEntityManager()->getClassMetadata($entity);
        if (in_array($metadata->getTypeOfField($identifier), array('integer', 'bigint', 'smallint'))) {
            $parameterType = Connection::PARAM_INT_ARRAY;

            // Filter out non-integer values (e.g. ""). If we don't, some
            // databases such as PostgreSQL fail.
            $values = array_values(array_filter($values, function ($v) {
                return (string) $v === (string) (int) $v || ctype_digit($v);
            }));
        } elseif (in_array($metadata->getTypeOfField($identifier), array('uuid', 'guid'))) {
            $parameterType = Connection::PARAM_STR_ARRAY;

            // Like above, but we just filter out empty strings.
            $values = array_values(array_filter($values, function ($v) {
                return '' !== (string) $v;
            }));
        } else {
            $parameterType = Connection::PARAM_STR_ARRAY;
        }
        if (!$values) {
            return array();
        }

        return $qb->andWhere($where)
                  ->getQuery()
                  ->setParameter($parameter, $values, $parameterType)
                  ->getResult();
    }
}


text:
package pl.java.borowiec.controller.photo;

import java.io.File;
import java.io.IOException;
import java.security.Principal;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author Sławomir Borowiec
 * Module name : personalBlogCore
 * Creating time :  11-04-2013 17:04:49

 */
@Controller
@RequestMapping("/photo")
public class ServerPhotoController {
	private static final Logger logger = LoggerFactory.getLogger(ServerPhotoController.class);

	@Resource
	private org.springframework.core.io.Resource anonymousImg;

	@RequestMapping(value = "/{login}", method = RequestMethod.GET,headers = "Accept=image/jpeg, image/jpg, image/png, image/gif")
	public @ResponseBody
	byte[] getPhoto(@PathVariable("login") String login, Principal principal) throws IllegalAccessException, IOException {
	//	User user =userService.getUserByLogin(login);
		logger.info("Serve {} photo ", login);

		byte[] userPhotoBytes =null;// user.getPhoto();

		if (userPhotoBytes == null) {
			userPhotoBytes = new byte[(int) anonymousImg.contentLength()];
			anonymousImg.getInputStream().read(userPhotoBytes);
		}

		return userPhotoBytes;
	}

	@RequestMapping(value = "/temp/{fileName}/{ext}", method = RequestMethod.GET)
	public @ResponseBody
	byte[] getTempPhoto(@PathVariable("fileName") String fileName, @PathVariable("ext") String extension, Principal principal) throws IllegalAccessException,
			IOException {
		// 'jpeg', 'jpg', 'gif', 'png'
		if (!(extension.toLowerCase().trim().equals("jpeg") || extension.toLowerCase().trim().equals("jpg") || extension.toLowerCase().trim().equals("gif") || extension
				.toLowerCase().trim().equals("png"))) {
			return null;
		}
		String tmpDir = System.getProperty("java.io.tmpdir");
		if (!tmpDir.endsWith("//")) {
			tmpDir += "//";
		}
		File tempFile = new File(tmpDir + fileName + "." + extension);
		return FileUtils.readFileToByteArray(tempFile);
	}
}


text:
title: Weak Goodstein sequence
localeTitle: تسلسل ضعيف Goodstein
---
## المشكلة 396: تتابع ضعيف Goodstein

هذا هو كعب. [ساعد مجتمعنا على توسيعه](https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/project-euler/problem-396-weak-goodstein-sequence/index.md) .

[سيساعدك دليل النمط السريع هذا على ضمان قبول طلب السحب](https://github.com/freecodecamp/guides/blob/master/README.md) .


text:
package lila.swiss

import lila.common.LightUser
import lila.rating.PerfType
import lila.user.User

case class SwissPlayer(
    id: SwissPlayer.Id, // swissId:userId
    swissId: Swiss.Id,
    userId: User.ID,
    rating: Int,
    provisional: Boolean,
    points: Swiss.Points,
    tieBreak: Swiss.TieBreak,
    performance: Option[Swiss.Performance],
    score: Swiss.Score,
    absent: Boolean,
    byes: Set[SwissRound.Number] // byes granted by the pairing system - the player was here
) {
  def is(uid: User.ID): Boolean       = uid == userId
  def is(user: User): Boolean         = is(user.id)
  def is(other: SwissPlayer): Boolean = is(other.userId)
  def present                         = !absent

  def recomputeScore =
    copy(
      score = Swiss.makeScore(points, tieBreak, performance | Swiss.Performance(rating.toFloat))
    )
}

object SwissPlayer {

  case class Id(value: String) extends AnyVal with StringValue

  def makeId(swissId: Swiss.Id, userId: User.ID) = Id(s"$swissId:$userId")

  private[swiss] def make(
      swissId: Swiss.Id,
      user: User,
      perf: PerfType
  ): SwissPlayer =
    new SwissPlayer(
      id = makeId(swissId, user.id),
      swissId = swissId,
      userId = user.id,
      rating = user.perfs(perf).intRating,
      provisional = user.perfs(perf).provisional,
      points = Swiss.Points(0),
      tieBreak = Swiss.TieBreak(0),
      performance = none,
      score = Swiss.Score(0),
      absent = false,
      byes = Set.empty
    ).recomputeScore

  case class WithRank(player: SwissPlayer, rank: Int) {
    def is(other: WithRank)       = player is other.player
    def withUser(user: LightUser) = WithUserAndRank(player, user, rank)
    override def toString         = s"$rank. ${player.userId}[${player.rating}]"
  }

  case class WithUser(player: SwissPlayer, user: LightUser)

  case class WithUserAndRank(player: SwissPlayer, user: LightUser, rank: Int)

  sealed private[swiss] trait Viewish {
    val player: SwissPlayer
    val rank: Int
    val user: lila.common.LightUser
    val sheet: SwissSheet
  }

  private[swiss] case class View(
      player: SwissPlayer,
      rank: Int,
      user: lila.common.LightUser,
      pairings: Map[SwissRound.Number, SwissPairing],
      sheet: SwissSheet
  ) extends Viewish

  private[swiss] case class ViewExt(
      player: SwissPlayer,
      rank: Int,
      user: lila.common.LightUser,
      pairings: Map[SwissRound.Number, SwissPairing.View],
      sheet: SwissSheet
  ) extends Viewish

  type PlayerMap = Map[User.ID, SwissPlayer]

  def toMap(players: List[SwissPlayer]): PlayerMap =
    players.view.map(p => p.userId -> p).toMap

  object Fields {
    val id          = "_id"
    val swissId     = "s"
    val userId      = "u"
    val rating      = "r"
    val provisional = "pr"
    val points      = "p"
    val tieBreak    = "t"
    val performance = "e"
    val score       = "c"
    val absent      = "a"
    val byes        = "b"
  }
  def fields[A](f: Fields.type => A): A = f(Fields)
}


text:
<?php

class Mage_Sales_Model_Order_Invoice_Total_Cost extends Mage_Sales_Model_Order_Invoice_Total_Abstract
{
    /**
     * Collect total cost of invoiced items
     *
     * @param Mage_Sales_Model_Order_Invoice $invoice
     * @return Mage_Sales_Model_Order_Invoice_Total_Cost
     */
    public function collect(Mage_Sales_Model_Order_Invoice $invoice)
    {
        $baseInvoiceTotalCost = 0;
        foreach ($invoice->getAllItems() as $item) {
            if (!$item->getHasChildren()){
                $baseInvoiceTotalCost += $item->getBaseCost()*$item->getQty();
            }
        }
        $invoice->setBaseCost($baseInvoiceTotalCost);
        return $this;
    }
}


text:
#ifndef __Technique_H__
#define __Technique_H__

#include "OgrePrerequisites.h"
#include "OgreCommon.h"
#include "OgrePass.h"
#include "OgreRenderSystemCapabilities.h"
#include "OgreUserObjectBindings.h"

namespace Ogre {
    /** \addtogroup Core
    *  @{
    */
    /** \addtogroup Materials
    *  @{
    */
    /** Class representing an approach to rendering this particular Material.
    @remarks
        Ogre will attempt to use the best technique supported by the active hardware,
        unless you specifically request a lower detail technique (say for distant
        rendering).
    */
    class _OgreExport Technique : public TechniqueAlloc
    {
    protected:
        /// Illumination pass state type
        enum IlluminationPassesState
        {
            IPS_COMPILE_DISABLED = -1,
            IPS_NOT_COMPILED = 0,
            IPS_COMPILED = 1
        };

        typedef vector<Pass*>::type Passes;
        /// List of primary passes
        Passes mPasses;
        /// List of derived passes, categorised into IlluminationStage (ordered)
        IlluminationPassList mIlluminationPasses;
        // Raw pointer since we don't want child to stop parent's destruction
        Material* mParent;
        bool mIsSupported;
        IlluminationPassesState mIlluminationPassesCompilationPhase;
        /// LOD level
        unsigned short mLodIndex;
        /** Scheme index, derived from scheme name but the names are held on
            MaterialManager, for speed an index is used here.
        */
        unsigned short mSchemeIndex;
        /// Optional name for the technique
        String mName;

        /// Internal method for clearing illumination pass list
        void clearIlluminationPasses(void);
        /// Internal method - check for manually assigned illumination passes
        bool checkManuallyOrganisedIlluminationPasses();

        /** When casting shadow, if not using default Ogre shadow casting material, or
        * nor using fixed function casting, mShadowCasterMaterial let you customize per material
        * shadow caster behavior
        */
        MaterialPtr mShadowCasterMaterial;
        /** When casting shadow, if not using default Ogre shadow casting material, or
        * nor using fixed function casting, mShadowCasterMaterial let you customize per material
        * shadow caster behavior.There only material name is stored so that it can be loaded once all file parsed in a resource group.
        */
        String mShadowCasterMaterialName;

        // User objects binding.
        UserObjectBindings  mUserObjectBindings;

    public:
        /** Directive used to manually control technique support based on the
            inclusion or exclusion of some factor.
        */
        enum IncludeOrExclude
        {
            /// Inclusive - only support if present
            INCLUDE = 0,
            /// Exclusive - do not support if present
            EXCLUDE = 1
        };
        /// Rule controlling whether technique is deemed supported based on GPU vendor
        struct GPUVendorRule
        {
            GPUVendor vendor;
            IncludeOrExclude includeOrExclude;
            GPUVendorRule()
                : vendor(GPU_UNKNOWN), includeOrExclude(EXCLUDE) {}
            GPUVendorRule(GPUVendor v, IncludeOrExclude ie)
                : vendor(v), includeOrExclude(ie) {}
        };
        /// Rule controlling whether technique is deemed supported based on GPU device name
        struct GPUDeviceNameRule
        {
            String devicePattern;
            IncludeOrExclude includeOrExclude;
            bool caseSensitive;
            GPUDeviceNameRule()
                : includeOrExclude(EXCLUDE), caseSensitive(false) {}
            GPUDeviceNameRule(const String& pattern, IncludeOrExclude ie, bool caseSen)
                : devicePattern(pattern), includeOrExclude(ie), caseSensitive(caseSen) {}
        };
        typedef vector<GPUVendorRule>::type GPUVendorRuleList;
        typedef vector<GPUDeviceNameRule>::type GPUDeviceNameRuleList;
    protected:
        GPUVendorRuleList mGPUVendorRules;
        GPUDeviceNameRuleList mGPUDeviceNameRules;
    public:
        /// Constructor
        Technique(Material* parent);
        /// Copy constructor
        Technique(Material* parent, const Technique& oth);
        ~Technique();
        /** Indicates if this technique is supported by the current graphics card.
        @remarks
            This will only be correct after the Technique has been compiled, which is
            usually done from Material::compile.
        */
        bool isSupported(void) const;
        /** Internal compilation method; see Material::compile.
        @return Any information explaining problems with the compile.
        */
        String _compile(bool autoManageTextureUnits);
        /// Internal method for checking GPU vendor / device rules
        bool checkGPURules(StringStream& errors);
        /// Internal method for checking hardware support
        bool checkHardwareSupport(bool autoManageTextureUnits, StringStream& compileErrors);
        /** Internal method for splitting the passes into illumination passes. */
        void _compileIlluminationPasses(void);
        size_t calculateSize(void) const;

        /** Creates a new Pass for this Technique.
        @remarks
            A Pass is a single rendering pass, i.e. a single draw of the given material.
            Note that if you create a pass without a fragment program, during compilation of the
            material the pass may be split into multiple passes if the graphics card cannot
            handle the number of texture units requested. For passes with fragment programs, however,
            the number of passes you create will never be altered, so you have to make sure
            that you create an alternative fallback Technique for if a card does not have
            enough facilities for what you're asking for.
        */
        Pass* createPass(void);
        /** Retrieves the Pass with the given index. */
        Pass* getPass(unsigned short index);
        /** Retrieves the Pass matching name.
            Returns 0 if name match is not found.
        */
        Pass* getPass(const String& name);
        /** Retrieves the number of passes. */
        unsigned short getNumPasses(void) const;
        /** Removes the Pass with the given index. */
        void removePass(unsigned short index);
        /** Removes all Passes from this Technique. */
        void removeAllPasses(void);
        /** Move a pass from source index to destination index.
            If successful then returns true.
        */
        bool movePass(const unsigned short sourceIndex, const unsigned short destinationIndex);
        typedef VectorIterator<Passes> PassIterator;
        /** Gets an iterator over the passes in this Technique. */
        const PassIterator getPassIterator(void);
        typedef VectorIterator<IlluminationPassList> IlluminationPassIterator;
        /** Gets an iterator over the illumination-stage categorised passes. */
        const IlluminationPassIterator getIlluminationPassIterator(void);
        /// Gets the parent Material
        Material* getParent(void) const { return mParent; }

        /** Overloaded operator to copy on Technique to another. */
        Technique& operator=(const Technique& rhs);

        /// Gets the resource group of the ultimate parent Material
        const String& getResourceGroup(void) const;

        /** Returns true if this Technique involves transparency.
        @remarks
            This basically boils down to whether the first pass
            has a scene blending factor. Even if the other passes
            do not, the base colour, including parts of the original
            scene, may be used for blending, therefore we have to treat
            the whole Technique as transparent.
        */
        bool isTransparent(void) const;

        /** Returns true if this Technique has transparent sorting enabled.
        @remarks
            This basically boils down to whether the first pass
            has transparent sorting enabled or not
        */
        bool isTransparentSortingEnabled(void) const;

        /** Returns true if this Technique has transparent sorting forced.
        @remarks
            This basically boils down to whether the first pass
            has transparent sorting forced or not
        */
        bool isTransparentSortingForced(void) const;

        /** Internal prepare method, derived from call to Material::prepare. */
        void _prepare(void);
        /** Internal unprepare method, derived from call to Material::unprepare. */
        void _unprepare(void);
        /** Internal load method, derived from call to Material::load. */
        void _load(void);
        /** Internal unload method, derived from call to Material::unload. */
        void _unload(void);

        /// Is this loaded?
        bool isLoaded(void) const;

        /** Tells the technique that it needs recompilation. */
        void _notifyNeedsRecompile(void);

        /** return this material specific  shadow casting specific material
        */
        Ogre::MaterialPtr getShadowCasterMaterial() const;
        /** set this material specific  shadow casting specific material
        */
        void setShadowCasterMaterial(Ogre::MaterialPtr val);
        /** set this material specific  shadow casting specific material
        */
        void setShadowCasterMaterial(const Ogre::String &name);

        // -------------------------------------------------------------------------------
        // The following methods are to make migration from previous versions simpler
        // and to make code easier to write when dealing with simple materials
        // They set the properties which have been moved to Pass for all Techniques and all Passes

        /** Sets the point size properties for every Pass in this Technique.
        @note
            This property actually exists on the Pass class. For simplicity, this method allows
            you to set these properties for every current Pass within this Technique. If
            you need more precision, retrieve the Pass instance and set the
            property there.
        @see Pass::setPointSize
        */
        void setPointSize(Real ps);

        /** Sets the ambient colour reflectance properties for every Pass in every Technique.
        @note
            This property actually exists on the Pass class. For simplicity, this method allows
            you to set these properties for every current Pass within this Technique. If
            you need more precision, retrieve the Pass instance and set the
            property there.
        @see Pass::setAmbient
        */
        void setAmbient(Real red, Real green, Real blue);

        /** Sets the ambient colour reflectance properties for every Pass in every Technique.
        @note
            This property actually exists on the Pass class. For simplicity, this method allows
            you to set these properties for every current Pass within this Technique. If
            you need more precision, retrieve the Pass instance and set the
            property there.
        @see Pass::setAmbient
        */
        void setAmbient(const ColourValue& ambient);

        /** Sets the diffuse colour reflectance properties of every Pass in every Technique.
        @note
            This property actually exists on the Pass class. For simplicity, this method allows
            you to set these properties for every current Pass within this Technique. If
            you need more precision, retrieve the Pass instance and set the
            property there.
        @see Pass::setDiffuse
        */
        void setDiffuse(Real red, Real green, Real blue, Real alpha);

        /** Sets the diffuse colour reflectance properties of every Pass in every Technique.
        @note
            This property actually exists on the Pass class. For simplicity, this method allows
            you to set these properties for every current Pass within this Technique. If
            you need more precision, retrieve the Pass instance and set the
            property there.
        @see Pass::setDiffuse
        */
        void setDiffuse(const ColourValue& diffuse);

        /** Sets the specular colour reflectance properties of every Pass in every Technique.
        @note
            This property actually exists on the Pass class. For simplicity, this method allows
            you to set these properties for every current Pass within this Technique. If
            you need more precision, retrieve the Pass instance and set the
            property there.
        @see Pass::setSpecular
        */
        void setSpecular(Real red, Real green, Real blue, Real alpha);

        /** Sets the specular colour reflectance properties of every Pass in every Technique.
        @note
            This property actually exists on the Pass class. For simplicity, this method allows
            you to set these properties for every current Pass within this Technique. If
            you need more precision, retrieve the Pass instance and set the
            property there.
        @see Pass::setSpecular
        */
        void setSpecular(const ColourValue& specular);

        /** Sets the shininess properties of every Pass in every Technique.
        @note
            This property actually exists on the Pass class. For simplicity, this method allows
            you to set these properties for every current Pass within this Technique. If
            you need more precision, retrieve the Pass instance and set the
            property there.
        @see Pass::setShininess
        */
        void setShininess(Real val);

        /** Sets the amount of self-illumination of every Pass in every Technique.
        @note
            This property actually exists on the Pass class. For simplicity, this method allows
            you to set these properties for every current Pass within this Technique. If
            you need more precision, retrieve the Pass instance and set the
            property there.
        @see Pass::setSelfIllumination
        */
        void setSelfIllumination(Real red, Real green, Real blue);

        /** Sets the amount of self-illumination of every Pass in every Technique.
        @note
            This property actually exists on the Pass class. For simplicity, this method allows
            you to set these properties for every current Pass within this Technique. If
            you need more precision, retrieve the Pass instance and set the
            property there.
        @see Pass::setSelfIllumination
        */
        void setSelfIllumination(const ColourValue& selfIllum);

        /** Sets whether or not each Pass renders with depth-buffer checking on or not.
        @note
            This property actually exists on the Pass class. For simplicity, this method allows
            you to set these properties for every current Pass within this Technique. If
            you need more precision, retrieve the Pass instance and set the
            property there.
        @see Pass::setDepthCheckEnabled
        */
        void setDepthCheckEnabled(bool enabled);

        /** Sets whether or not each Pass renders with depth-buffer writing on or not.
        @note
            This property actually exists on the Pass class. For simplicity, this method allows
            you to set these properties for every current Pass within this Technique. If
            you need more precision, retrieve the Pass instance and set the
            property there.
        @see Pass::setDepthWriteEnabled
        */
        void setDepthWriteEnabled(bool enabled);

        /** Sets the function used to compare depth values when depth checking is on.
        @note
            This property actually exists on the Pass class. For simplicity, this method allows
            you to set these properties for every current Pass within this Technique. If
            you need more precision, retrieve the Pass instance and set the
            property there.
        @see Pass::setDepthFunction
        */
        void setDepthFunction( CompareFunction func );

        /** Sets whether or not colour buffer writing is enabled for each Pass.
        @note
            This property actually exists on the Pass class. For simplicity, this method allows
            you to set these properties for every current Pass within this Technique. If
            you need more precision, retrieve the Pass instance and set the
            property there.
        @see Pass::setColourWriteEnabled
        */
        void setColourWriteEnabled(bool enabled);

        /** Sets the culling mode for each pass  based on the 'vertex winding'.
        @note
            This property actually exists on the Pass class. For simplicity, this method allows
            you to set these properties for every current Pass within this Technique. If
            you need more precision, retrieve the Pass instance and set the
            property there.
        @see Pass::setCullingMode
        */
        void setCullingMode( CullingMode mode );

        /** Sets the manual culling mode, performed by CPU rather than hardware.
        @note
            This property actually exists on the Pass class. For simplicity, this method allows
            you to set these properties for every current Pass within this Technique. If
            you need more precision, retrieve the Pass instance and set the
            property there.
        @see Pass::setManualCullingMode
        */
        void setManualCullingMode( ManualCullingMode mode );

        /** Sets whether or not dynamic lighting is enabled for every Pass.
        @note
            This property actually exists on the Pass class. For simplicity, this method allows
            you to set these properties for every current Pass within this Technique. If
            you need more precision, retrieve the Pass instance and set the
            property there.
        @see Pass::setLightingEnabled
        */
        void setLightingEnabled(bool enabled);

        /** Sets the type of light shading required
        @note
            This property actually exists on the Pass class. For simplicity, this method allows
            you to set these properties for every current Pass within this Technique. If
            you need more precision, retrieve the Pass instance and set the
            property there.
        @see Pass::setShadingMode
        */
        void setShadingMode( ShadeOptions mode );

        /** Sets the fogging mode applied to each pass.
        @note
            This property actually exists on the Pass class. For simplicity, this method allows
            you to set these properties for every current Pass within this Technique. If
            you need more precision, retrieve the Pass instance and set the
            property there.
        @see Pass::setFog
        */
        void setFog(
            bool overrideScene,
            FogMode mode = FOG_NONE,
            const ColourValue& colour = ColourValue::White,
            Real expDensity = 0.001, Real linearStart = 0.0, Real linearEnd = 1.0 );

        /** Sets the depth bias to be used for each Pass.
        @note
            This property actually exists on the Pass class. For simplicity, this method allows
            you to set these properties for every current Pass within this Technique. If
            you need more precision, retrieve the Pass instance and set the
            property there.
        @see Pass::setDepthBias
        */
        void setDepthBias(float constantBias, float slopeScaleBias);

        /** Set texture filtering for every texture unit in every Pass
        @note
            This property actually exists on the TextureUnitState class
            For simplicity, this method allows you to set these properties for
            every current TeextureUnitState, If you need more precision, retrieve the
            Pass and TextureUnitState instances and set the property there.
        @see TextureUnitState::setTextureFiltering
        */
        void setTextureFiltering(TextureFilterOptions filterType);
        /** Sets the anisotropy level to be used for all textures.
        @note
            This property has been moved to the TextureUnitState class, which is accessible via the
            Technique and Pass. For simplicity, this method allows you to set these properties for
            every current TeextureUnitState, If you need more precision, retrieve the Technique,
            Pass and TextureUnitState instances and set the property there.
        @see TextureUnitState::setTextureAnisotropy
        */
        void setTextureAnisotropy(unsigned int maxAniso);

        /** Sets the kind of blending every pass has with the existing contents of the scene.
        @note
            This property actually exists on the Pass class. For simplicity, this method allows
            you to set these properties for every current Pass within this Technique. If
            you need more precision, retrieve the Pass instance and set the
            property there.
        @see Pass::setSceneBlending
        */
        void setSceneBlending( const SceneBlendType sbt );

        /** Sets the kind of blending every pass has with the existing contents of the scene, using individual factors both color and alpha channels
        @note
            This property actually exists on the Pass class. For simplicity, this method allows
            you to set these properties for every current Pass within this Technique. If
            you need more precision, retrieve the Pass instance and set the
            property there.
        @see Pass::setSeparateSceneBlending
        */
        void setSeparateSceneBlending( const SceneBlendType sbt, const SceneBlendType sbta );

        /** Allows very fine control of blending every Pass with the existing contents of the scene.
        @note
            This property actually exists on the Pass class. For simplicity, this method allows
            you to set these properties for every current Pass within this Technique. If
            you need more precision, retrieve the Pass instance and set the
            property there.
        @see Pass::setSceneBlending
        */
        void setSceneBlending( const SceneBlendFactor sourceFactor, const SceneBlendFactor destFactor);

        /** Allows very fine control of blending every Pass with the existing contents of the scene, using individual factors both color and alpha channels
        @note
            This property actually exists on the Pass class. For simplicity, this method allows
            you to set these properties for every current Pass within this Technique. If
            you need more precision, retrieve the Pass instance and set the
            property there.
        @see Pass::setSeparateSceneBlending
        */
        void setSeparateSceneBlending( const SceneBlendFactor sourceFactor, const SceneBlendFactor destFactor, const SceneBlendFactor sourceFactorAlpha, const SceneBlendFactor destFactorAlpha);

        /** Assigns a level-of-detail (LOD) index to this Technique.
        @remarks
            As noted previously, as well as providing fallback support for various
            graphics cards, multiple Technique objects can also be used to implement
            material LOD, where the detail of the material diminishes with distance to
            save rendering power.
        @par
            By default, all Techniques have a LOD index of 0, which means they are the highest
            level of detail. Increasing LOD indexes are lower levels of detail. You can
            assign more than one Technique to the same LOD index, meaning that the best
            Technique that is supported at that LOD index is used.
        @par
            You should not leave gaps in the LOD sequence; Ogre will allow you to do this
            and will continue to function as if the LODs were sequential, but it will
            confuse matters.
        */
        void setLodIndex(unsigned short index);
        /** Gets the level-of-detail index assigned to this Technique. */
        unsigned short getLodIndex(void) const { return mLodIndex; }

        /** Set the 'scheme name' for this technique.
        @remarks
            Material schemes are used to control top-level switching from one
            set of techniques to another. For example, you might use this to
            define 'high', 'medium' and 'low' complexity levels on materials
            to allow a user to pick a performance / quality ratio. Another
            possibility is that you have a fully HDR-enabled pipeline for top
            machines, rendering all objects using unclamped shaders, and a
            simpler pipeline for others; this can be implemented using
            schemes.
        @par
            Every technique belongs to a scheme - if you don't specify one, the
            Technique belongs to the scheme called 'Default', which is also the
            scheme used to render by default. The active scheme is set one of
            two ways - either by calling Viewport::setMaterialScheme, or
            by manually calling MaterialManager::setActiveScheme.
        */
        void setSchemeName(const String& schemeName);
        /** Returns the scheme to which this technique is assigned.
            @see Technique::setSchemeName
        */
        const String& getSchemeName(void) const;

        /// Internal method for getting the scheme index
        unsigned short _getSchemeIndex(void) const;

        /** Is depth writing going to occur on this technique? */
        bool isDepthWriteEnabled(void) const;

        /** Is depth checking going to occur on this technique? */
        bool isDepthCheckEnabled(void) const;

        /** Exists colour writing disabled pass on this technique? */
        bool hasColourWriteDisabled(void) const;

        /** Set the name of the technique.
        @remarks
        The use of technique name is optional.  Its useful in material scripts where a material could inherit
        from another material and only want to modify a particular technique.
        */
        void setName(const String& name);
        /// Gets the name of the technique
        const String& getName(void) const { return mName; }

        /** Applies texture names to Texture Unit State with matching texture name aliases.
            All passes, and Texture Unit States within the technique are checked.
            If matching texture aliases are found then true is returned.

        @param
            aliasList is a map container of texture alias, texture name pairs
        @param
            apply set true to apply the texture aliases else just test to see if texture alias matches are found.
        @return
            True if matching texture aliases were found in the Technique.
        */
        bool applyTextureAliases(const AliasTextureNamePairList& aliasList, const bool apply = true) const;

        /** Add a rule which manually influences the support for this technique based
            on a GPU vendor.
        @remarks
            You can use this facility to manually control whether a technique is
            considered supported, based on a GPU vendor. You can add inclusive
            or exclusive rules, and you can add as many of each as you like. If
            at least one inclusive rule is added, a technique is considered
            unsupported if it does not match any of those inclusive rules. If exclusive rules are
            added, the technique is considered unsupported if it matches any of
            those inclusive rules.
        @note
            Any rule for the same vendor will be removed before adding this one.
        @param vendor The GPU vendor
        @param includeOrExclude Whether this is an inclusive or exclusive rule
        */
        void addGPUVendorRule(GPUVendor vendor, IncludeOrExclude includeOrExclude);
        /** Add a rule which manually influences the support for this technique based
            on a GPU vendor.
        @remarks
            You can use this facility to manually control whether a technique is
            considered supported, based on a GPU vendor. You can add inclusive
            or exclusive rules, and you can add as many of each as you like. If
            at least one inclusive rule is added, a technique is considered
            unsupported if it does not match any of those inclusive rules. If exclusive rules are
            added, the technique is considered unsupported if it matches any of
            those inclusive rules.
        @note
            Any rule for the same vendor will be removed before adding this one.
        */
        void addGPUVendorRule(const GPUVendorRule& rule);
        /** Removes a matching vendor rule.
        @see addGPUVendorRule
        */
        void removeGPUVendorRule(GPUVendor vendor);
        typedef ConstVectorIterator<GPUVendorRuleList> GPUVendorRuleIterator;
        /// Get an iterator over the currently registered vendor rules.
        GPUVendorRuleIterator getGPUVendorRuleIterator() const;

        /** Add a rule which manually influences the support for this technique based
            on a pattern that matches a GPU device name (e.g. '*8800*').
        @remarks
            You can use this facility to manually control whether a technique is
            considered supported, based on a GPU device name pattern. You can add inclusive
            or exclusive rules, and you can add as many of each as you like. If
            at least one inclusive rule is added, a technique is considered
            unsupported if it does not match any of those inclusive rules. If exclusive rules are
            added, the technique is considered unsupported if it matches any of
            those inclusive rules. The pattern you supply can include wildcard
            characters ('*') if you only want to match part of the device name.
        @note
            Any rule for the same device pattern will be removed before adding this one.
        @param devicePattern The GPU vendor
        @param includeOrExclude Whether this is an inclusive or exclusive rule
        @param caseSensitive Whether the match is case sensitive or not
        */
        void addGPUDeviceNameRule(const String& devicePattern, IncludeOrExclude includeOrExclude, bool caseSensitive = false);
        /** Add a rule which manually influences the support for this technique based
            on a pattern that matches a GPU device name (e.g. '*8800*').
        @remarks
            You can use this facility to manually control whether a technique is
            considered supported, based on a GPU device name pattern. You can add inclusive
            or exclusive rules, and you can add as many of each as you like. If
            at least one inclusive rule is added, a technique is considered
            unsupported if it does not match any of those inclusive rules. If exclusive rules are
            added, the technique is considered unsupported if it matches any of
            those inclusive rules. The pattern you supply can include wildcard
            characters ('*') if you only want to match part of the device name.
        @note
            Any rule for the same device pattern will be removed before adding this one.
        */
        void addGPUDeviceNameRule(const GPUDeviceNameRule& rule);
        /** Removes a matching device name rule.
        @see addGPUDeviceNameRule
        */
        void removeGPUDeviceNameRule(const String& devicePattern);
        typedef ConstVectorIterator<GPUDeviceNameRuleList> GPUDeviceNameRuleIterator;
        /// Get an iterator over the currently registered device name rules.
        GPUDeviceNameRuleIterator getGPUDeviceNameRuleIterator() const;

        /** Return an instance of user objects binding associated with this class.
        You can use it to associate one or more custom objects with this class instance.
        @see UserObjectBindings::setUserAny.
        */
        UserObjectBindings& getUserObjectBindings() { return mUserObjectBindings; }

        /** Return an instance of user objects binding associated with this class.
        You can use it to associate one or more custom objects with this class instance.
        @see UserObjectBindings::setUserAny.
        */
        const UserObjectBindings& getUserObjectBindings() const { return mUserObjectBindings; }

    };

    /** @} */
    /** @} */

}
#endif