text:
This command line tool enables merging yaml files into one single file. For the operation to work, the yaml files must follow the same source path.
For example, the following command allows the tool to merge the component configurations residing under the `/prow/cluster/components` path and place the resulting target file under `/prow/cluster/starter.yaml`.
```bash
go run main.go -path /prow/cluster/components -target /prow/cluster/starter.yaml
```

>**NOTE**:  If the `starter.yaml` file does not already exist under a given path, it will be created.

## Usage

For security reasons, the dry-run mode is the default one.
To run it, use:
```bash
go run main.go -path /path/to/components/folder -target /path/to/target/file
```

To turn the dry-run mode off, use:
```bash
go run main.go -path /path/to/components/folder -target /path/to/target/file -dryRun=false
```

### Flags

See the list of available flags:

| Name                      | Required | Description                                                                                |
| :------------------------ | :------: | :--------------------------------------------------------------------------------------------------- |
| **--path**                |   Yes    | Path to the folder containing the yaml files to merge.
| **--target**              |   Yes    | Path of the file which includes the content of the merged files.
| **--dryRun**              |    No    | The boolean value that controls the dry-run mode. Its default value is `true`.

redpajama_set_name: RedPajamaGithub


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Fl. ital. crypt. (Genoa), Hymeniales 456 (1916)

#### Original name
Cantharellus edulis Sacc., 1916

### Remarks
null


text:
#if !defined(SPIRIT_NO_CASE_SEPT_16_2014_0912PM)
#define SPIRIT_NO_CASE_SEPT_16_2014_0912PM

#include <boost/spirit/home/x3/support/context.hpp>
#include <boost/spirit/home/x3/support/unused.hpp>
#include <boost/spirit/home/x3/support/no_case.hpp>
#include <boost/spirit/home/x3/core/parser.hpp>

namespace boost { namespace spirit { namespace x3
{
    // propagate no_case information through the context
    template <typename Subject>
    struct no_case_directive : unary_parser<Subject, no_case_directive<Subject>>
    {
        typedef unary_parser<Subject, no_case_directive<Subject> > base_type;
        static bool const is_pass_through_unary = true;
        static bool const handles_container = Subject::handles_container;

        no_case_directive(Subject const& subject)
          : base_type(subject) {}

        template <typename Iterator, typename Context
          , typename RContext, typename Attribute>
        bool parse(Iterator& first, Iterator const& last
          , Context const& context, RContext& rcontext, Attribute& attr) const
        {
            return this->subject.parse(
                first, last
              , make_context<no_case_tag>(no_case_compare_, context)
              , rcontext
              , attr);
        }
    };

    struct no_case_gen
    {
        template <typename Subject>
        no_case_directive<typename extension::as_parser<Subject>::value_type>
        operator[](Subject const& subject) const
        {
            return { as_parser(subject) };
        }
    };

    auto const no_case = no_case_gen{};
}}}

#endif


text:
<!doctype html>

  <title>core-header-panel</title>

  <link rel="import" href="core-header-panel.html">

  <core-header-panel>

standard

  </core-header-panel>

  <core-header-panel mode="seamed">

seamed

  </core-header-panel>

  <core-header-panel mode="waterfall">

waterfall

  </core-header-panel>

  <core-header-panel mode="waterfall-tall">

waterfall-tall

  </core-header-panel>

  <core-header-panel mode="waterfall-tall" tallClass="medium-tall">

waterfall-tall (tallClass: medium-tall)

  </core-header-panel>

  <core-header-panel mode="scroll">

scroll

  </core-header-panel>

  <core-header-panel mode="cover">

cover

  </core-header-panel>


text:
#

import logging

__author__ = 'elip'

logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

def get_logger(name):
    logger = logging.getLogger(name)
    logger.level = logging.DEBUG
    return logger


text:
import operator
import argparse
import progressbar
import json
from spacy.en import English

def getModalAnswer(answers):
	candidates = {}
	for i in xrange(10):
		candidates[answers[i]['answer']] = 1

	for i in xrange(10):
		candidates[answers[i]['answer']] += 1

	return max(candidates.iteritems(), key=operator.itemgetter(1))[0]

def getAllAnswer(answers):
	answer_list = []
	for i in xrange(10):
		answer_list.append(answers[i]['answer'])

	return ';'.join(answer_list)

def main():
	parser = argparse.ArgumentParser()
	parser.add_argument('-split', type=str, default='train',
		help='Specify which part of the dataset you want to dump to text. Your options are: train, val, test, test-dev')
	parser.add_argument('-answers', type=str, default='modal',
		help='Specify if you want to dump just the most frequent answer for each questions (modal), or all the answers (all)')
	args = parser.parse_args()

	nlp = English() #used for conting number of tokens

	if args.split == 'train':
		annFile = '../data/mscoco_train2014_annotations.json'
		quesFile = '../data/OpenEnded_mscoco_train2014_questions.json'
		questions_file = open('../data/preprocessed/questions_train2014.txt', 'w')
		questions_id_file = open('../data/preprocessed/questions_id_train2014.txt', 'w')
		questions_lengths_file = open('../data/preprocessed/questions_lengths_train2014.txt', 'w')
		if args.answers == 'modal':
			answers_file = open('../data/preprocessed/answers_train2014_modal.txt', 'w')
		elif args.answers == 'all':
			answers_file = open('../data/preprocessed/answers_train2014_all.txt', 'w')
		coco_image_id = open('../data/preprocessed/images_train2014.txt', 'w')
		data_split = 'training data'
	elif args.split == 'val':
		annFile = '../data/mscoco_val2014_annotations.json'
		quesFile = '../data/OpenEnded_mscoco_val2014_questions.json'
		questions_file = open('../data/preprocessed/questions_val2014.txt', 'w')
		questions_id_file = open('../data/preprocessed/questions_id_val2014.txt', 'w')
		questions_lengths_file = open('../data/preprocessed/questions_lengths_val2014.txt', 'w')
		if args.answers == 'modal':
			answers_file = open('../data/preprocessed/answers_val2014_modal.txt', 'w')
		elif args.answers == 'all':
			answers_file = open('../data/preprocessed/answers_val2014_all.txt', 'w')
		coco_image_id = open('../data/preprocessed/images_val2014_all.txt', 'w')
		data_split = 'validation data'
	elif args.split == 'test-dev':
		quesFile = '../data/OpenEnded_mscoco_test-dev2015_questions.json'
		questions_file = open('../data/preprocessed/questions_test-dev2015.txt', 'w')
		questions_id_file = open('../data/preprocessed/questions_id_test-dev2015.txt', 'w')
		questions_lengths_file = open('../data/preprocessed/questions_lengths_test-dev2015.txt', 'w')
		coco_image_id = open('../data/preprocessed/images_test-dev2015.txt', 'w')
		data_split = 'test-dev data'
	elif args.split == 'test':
		quesFile = '../data/OpenEnded_mscoco_test2015_questions.json'
		questions_file = open('../data/preprocessed/questions_test2015.txt', 'w')
		questions_id_file = open('../data/preprocessed/questions_id_test2015.txt', 'w')
		questions_lengths_file = open('../data/preprocessed/questions_lengths_test2015.txt', 'w')
		coco_image_id = open('../data/preprocessed/images_test2015.txt', 'w')
		data_split = 'test data'
	else:
		raise RuntimeError('Incorrect split. Your choices are:\ntrain\nval\ntest-dev\ntest')

	#initialize VQA api for QA annotations
	#vqa=VQA(annFile, quesFile)
	questions = json.load(open(quesFile, 'r'))
	ques = questions['questions']
	if args.split == 'train' or args.split == 'val':
		qa = json.load(open(annFile, 'r'))
		qa = qa['annotations']

	pbar = progressbar.ProgressBar()
	print 'Dumping questions, answers, questionIDs, imageIDs, and questions lengths to text files...'
	for i, q in pbar(zip(xrange(len(ques)),ques)):
		questions_file.write((q['question'] + '\n').encode('utf8'))
		questions_lengths_file.write((str(len(nlp(q['question'])))+ '\n').encode('utf8'))
		questions_id_file.write((str(q['question_id']) + '\n').encode('utf8'))
		coco_image_id.write((str(q['image_id']) + '\n').encode('utf8'))
		if args.split == 'train' or args.split == 'val':
			if args.answers == 'modal':
				answers_file.write(getModalAnswer(qa[i]['answers']).encode('utf8'))
			elif args.answers == 'all':
				answers_file.write(getAllAnswer(qa[i]['answers']).encode('utf8'))
			answers_file.write('\n'.encode('utf8'))

	print 'completed dumping', data_split

if __name__ == "__main__":
	main()


text:
<?php
/**
 * Checks for admin credential and loads appropriate javascript/css files to allow editable
 * components admin from a frontend context
 *
 * @package    sfDoctrineEditableContent
 * @subpackage filter
 * @author     Nicolas Perriault <nperriault@gmail.com>
 */
class sfEditableComponentAdminFilter extends sfFilter
{
  /**
   * This filter will check if the current connected user has the configured credential in
   * order to load the admin javascript and css files
   *
   * @param sfFilterChain $filterChain A sfFilterChain instance
   */
  public function execute($filterChain)
  {
    if ($this->isFirstCall())
    {
      // load plugin assets if
      //   1) The credential was specified and the user has it
      //   2) No credential was specified, but the user is at least authenticated
      $credential = sfConfig::get('app_sfDoctrineEditableComponentPlugin_admin_credential', 'editable_content_admin');
      if (
        ($credential && $this->context->getUser()->hasCredential($credential))
        || ($credential === false && $this->context->getUser()->isAuthenticated()))
      {
        $this->addPluginAssets();
      }
    }

    $filterChain->execute();
  }

  /**
   * Adds required or configured assets files to current response object, plus the admin
   * javascript and stylesheet files (mandatory)
   *
   */
  protected function addPluginAssets()
  {
    $response = $this->context->getResponse();

    $pluginWebRoot = sfConfig::get('app_sfDoctrineEditableComponentPlugin_assets_web_root', '');

    // JQuery
    if (true === sfConfig::get('app_sfDoctrineEditableComponentPlugin_load_jquery'))
    {
      $response->addJavascript(sprintf('%s/js/jquery-1.4.2.min.js', $pluginWebRoot), 'last');
    }

    // Facebox
    if (true === sfConfig::get('app_sfDoctrineEditableComponentPlugin_load_facebox'))
    {
      $response->addJavascript(sprintf('%s/facebox/facebox.js', $pluginWebRoot), 'last');
      $response->addStylesheet(sprintf('%s/facebox/facebox.css', $pluginWebRoot), 'last');
    }

    // CKEditor
    if (true === sfConfig::get('app_sfDoctrineEditableComponentPlugin_load_ckeditor'))
    {
      $response->addJavascript(sprintf('%s/ckeditor/ckeditor.js', $pluginWebRoot), 'last');
    }

    // The admin javascript file is handled by symfony
    $response->addJavascript($this->context->getController()->genUrl('@editable_component_admin_js'), 'last');

    // The admin css file is handled by symfony
    $response->addStylesheet($this->context->getController()->genUrl('@editable_component_admin_css'), 'first');
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Tic-Tac-Toe</string>
    <string name="settings">Settings</string>
    <string name="dummy_content">DUMMY\nCONTENT</string>
    <string name="start">PLAY</string>
    <string name="prefs_category_one">Category One</string>
    <string name="prefs_summ_category_one">Summ Category One</string>
    <string name="prefs_category_two">Category Two</string>
    <string name="prefs_summ_category_two">Summ Category Two</string>
    <string name="custom_game_settings">Custom Game Settings?</string>
    <string name="custom_game_settings_summ">If Custom Settings mode is disabled then Computer Mode(Second Player) is on by default with playing grid of size 5x5!</string>
    <string name="computer_mode_message">Check mark this option if you want to play against computer, uncheck it otherwise!</string>
    <string name="computer_mode_title">Want to play against computer?</string>
    <string name="game_grid_size">Grid Size(NxN)</string>
    <string name="select_size_NxN">Select Playing Grid Size(3x3, 4x4, 5x5, 6x6 or 7x7).</string>
    <string name="default_grid_size">5</string>
    <string name="action_settings">Settings</string>

    <!-- Reset Dialog Message Strings. -->
    <string name="reset_game_dialog_title">Reset Game?</string>
    <string name="reset_game_dialog_message">This will reset the Game to initial state!</string>
    <string name="reset_game_dialog_confirm">Confirm</string>
    <string name="reset_game_dialog_cancel">Cancel</string>

    <string name="grid_size_select">Select Grid Size(NxN)</string>
</resources>


text:
namespace Aspose.Tasks.Examples.CSharp
{
    using System.Collections.Generic;
    using System.IO;
    using NUnit.Framework;
    using Saving;
    using Visualization;

    [TestFixture]
    public class ExFontSavingArgs : ApiExampleBase
    {
        // ExStart
        // ExFor: FontSavingArgs
        // ExFor: HtmlSaveOptions.ExportCss
        // ExFor: HtmlSaveOptions.ExportFonts
        // ExFor: HtmlSaveOptions.ExportImages
        // ExFor: HtmlSaveOptions.FontFaceTypes
        // ExFor: FontFaceType
        // ExSummary: Shows how to work with font saving args.

        [Test] // ExSkip
        public void ResourcePrefixForNestedResourcesExample()
        {
            var project = new Project(DataDir + "Project1.mpp");
            var options = ResourcePrefixForNestedResources.GetSaveOptions(1);
            project.Save(OutDir + "document_out.html", options);
        }

        private class ResourcePrefixForNestedResources : ICssSavingCallback, IFontSavingCallback, IImageSavingCallback
        {
            public void CssSaving(CssSavingArgs args)
            {
                if (!Directory.Exists(OutDir + "css/"))
                {
                    Directory.CreateDirectory(OutDir + "css/");
                }

                var stream = new FileStream(OutDir + "css/" + args.FileName, FileMode.Create);
                args.Stream = stream;
                args.KeepStreamOpen = false;
                args.Uri = OutDir + "css/" + args.FileName;
            }

            public void FontSaving(FontSavingArgs args)
            {
                if (!Directory.Exists(OutDir + "fonts/"))
                {
                    Directory.CreateDirectory(OutDir + "fonts/");
                }

                var stream = new FileStream(OutDir + "fonts/" + args.FileName, FileMode.Create);
                args.Stream = stream;
                args.KeepStreamOpen = false;
                args.Uri = OutDir + "fonts/" + args.FileName;
            }

            public void ImageSaving(ImageSavingArgs args)
            {
                if (!Directory.Exists(OutDir + "resources/"))
                {
                    Directory.CreateDirectory(OutDir + "resources/");
                }

                if (!Directory.Exists(OutDir + "resources/nestedResources/"))
                {
                    Directory.CreateDirectory(OutDir + "resources/nestedResources/");
                }

                if (args.FileName.EndsWith("png"))
                {
                    var stream1 = new FileStream(OutDir + "resources/nestedResources/" + args.FileName, FileMode.Create);
                    args.Stream = stream1;
                    args.KeepStreamOpen = false;
                    args.Uri = OutDir + "resources/" + args.FileName;

                    // args.NestedUri = dataDir + "nestedResources/" + args.FileName;
                }
                else
                {
                    var stream2 = new FileStream(OutDir + "resources/" + args.FileName, FileMode.Create);
                    args.Stream = stream2;
                    args.KeepStreamOpen = false;
                    args.Uri = OutDir + "resources/" + args.FileName;
                }
            }

            public static HtmlSaveOptions GetSaveOptions(int pageNumber)
            {
                var options = new HtmlSaveOptions
                                  {
                                      Pages = new List<int>(),
                                      IncludeProjectNameInPageHeader = false,
                                      IncludeProjectNameInTitle = false,
                                      PageSize = PageSize.A3,
                                      Timescale = Timescale.ThirdsOfMonths,
                                      ReduceFooterGap = true,
                                      FontFaceTypes = FontFaceType.Ttf,
                                      ExportCss = ResourceExportType.AsFile,
                                      ExportFonts = ResourceExportType.AsFile,
                                      ExportImages = ResourceExportType.AsFile
                                  };

                var program = new ResourcePrefixForNestedResources();
                options.FontSavingCallback = program;
                options.CssSavingCallback = program;
                options.ImageSavingCallback = program;

                options.Pages.Clear();
                options.Pages.Add(pageNumber);

                if (!Directory.Exists(DataDir + "fonts"))
                {
                    Directory.CreateDirectory(DataDir + "fonts");
                }

                if (!Directory.Exists(DataDir + "resources"))
                {
                    Directory.CreateDirectory(DataDir + "resources");
                }

                if (!Directory.Exists(DataDir + "nestedResources"))
                {
                    Directory.CreateDirectory(DataDir + "resources/nestedResources");
                }

                if (!Directory.Exists(DataDir + "css"))
                {
                    Directory.CreateDirectory(DataDir + "css");
                }

                return options;
            }
        }

        // ExEnd
    }
}


text:
using System.Linq;

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace DominikStiller.VertretungsplanServer.Helper
{
    public class ResponseCachingHelper
    {
        readonly HttpContext context;

        public ResponseCachingHelper(IHttpContextAccessor context)
        {
            this.context = context.HttpContext;
        }

        /// <returns>The appropriate response or null to indicate that the client does not possess the most recent version of the document</returns>
        public IActionResult UseETag(string tag)
        {
            var quotedTag = "\"" + tag + "\"";
            context.Response.Headers["ETag"] = quotedTag;

            var ifNoneMatch = context.Request.Headers["If-None-Match"];
            if (ifNoneMatch.Count > 0 && ifNoneMatch.Contains(quotedTag))
            {
                return new StatusCodeResult(StatusCodes.Status304NotModified);
            }

            return null;
        }
    }
}


text:
namespace W3SavegameEditor.Core.Savegame.Variables
{
    public class OpVariable : TypedVariable
    {
        public override string ToString()
        {
            return "OP " + base.ToString();
        }
    }
}


text:
URL

    <input type="text" class="form-control code-block" ng-model="provider.url" style="border-radius:2px;">

    Method
    <select class="form-control app-select" style="border-radius:2px" ng-model="provider.method">
        <option value="GET">GET</option>
        <option value="POST">POST</option>
    </select>

Params

    <textarea type="text" class="form-control code-block" ng-model="provider.params" style="border-radius:2px;" http-provider-params></textarea>

Body

    <textarea type="text" class="form-control code-block" ng-model="provider.body" style="border-radius:2px;" http-provider-body></textarea>

Normalizer

    <textarea type="text" class="form-control code-block" ng-model="provider.normalizer" style="border-radius:2px;"></textarea>

Aggregator

    <select class="form-control app-select" ng-model="provider.aggregator" style="border-radius:2px" ng-options="aggr for aggr in aggregators"></select>


text:
layout: post
title: "Tiny Outfits"
date: 2007-11-27 18:42:57
---
This evening I spent some time going through some of the clothes that Baby T will wear when he is born. Most were given to us and a few came from some shopping I did in France. Everything is just so cute! And I am sure that seeing the little outfits on Baby T will make them even cuter! Guess that's all I have to say for now.....just feeling excited.


text:
package com.glacier.modules.sys.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;

import com.glacier.modules.sys.domain.UserRole;

/**
 *
 *
 * @author glacier
 * @since
2017-03-29

 * @version 1.0.0
 */
@Repository("userRoleRepository")
public interface UserRoleRepository
		extends JpaRepository<UserRole, String>, JpaSpecificationExecutor<UserRole>, CommonDao {

}


text:
"""jsonp transport"""
import asyncio
import re
from urllib.parse import unquote_plus

from aiohttp import web, hdrs

from .base import StreamingTransport
from .utils import session_cookie, cors_headers
from ..protocol import dumps, loads, ENCODING

class JSONPolling(StreamingTransport):

    check_callback = re.compile('^[a-zA-Z0-9_\.]+$')
    callback = ''

    def send(self, text):
        blob = ('/**/%s(%s);\r\n' % (self.callback, dumps(text))).encode(ENCODING)
        self.response.write(blob)
        return True

    @asyncio.coroutine
    def process(self):
        session = self.session
        request = self.request
        meth = request.method

        if request.method == hdrs.METH_GET:

            callback = self.callback = request.GET.get('c')
            if not callback:
                yield from self.session._remote_closed()
                return web.HTTPInternalServerError(
                    body=b'"callback" parameter required')

            elif not self.check_callback.match(callback):
                yield from self.session._remote_closed()
                return web.HTTPBadRequest(
                    body=b'invalid "callback" parameter')

            headers = list(
                ((hdrs.CONTENT_TYPE,
                  'application/javascript; charset=UTF-8'),
                 (hdrs.CACHE_CONTROL,
                  'no-store, no-cache, must-revalidate, max-age=0')) +
                session_cookie(request) +
                cors_headers(request.headers))

            resp = self.response = web.StreamResponse(headers=headers)
            resp.start(request)

            yield from self.handle_session()
            return resp

        elif request.method == hdrs.METH_POST:
            data = yield from request.read()

            ctype = request.content_type.lower()
            if ctype == 'application/x-www-form-urlencoded':
                if not data.startswith(b'd='):
                    return web.HTTPInternalServerError(body=b'Payload expected.')

                data = unquote_plus(data[2:].decode(ENCODING))
            else:
                data = data.decode(ENCODING)

            if not data:
                return web.HTTPInternalServerError(body=b'Payload expected.')

            try:
                messages = loads(data)
            except:
                return web.HTTPInternalServerError(body=b'Broken JSON encoding.')

            yield from session._remote_messages(messages)
            return web.Response(
                body=b'ok',
                headers=((hdrs.CONTENT_TYPE,
                          'text/plain; charset=UTF-8'),
                         (hdrs.CACHE_CONTROL,
                          'no-store, no-cache, must-revalidate, max-age=0')) +
                session_cookie(request))

        else:
            return web.HTTPBadRequest(
                text="No support for such method: %s" % meth)


text:
/**
    websocketprotocol.h

    Websocket protocol constants see https://tools.ietf.org/html/rfc6455

    @author Bertrand Martel
    @version 1.0
*/
#ifndef WEBSOCKETPROTOCOL_H
#define WEBSOCKETPROTOCOL_H

/** FIN_FRAME mask */
#define WEBSOCKET_PROTOCOL_FIN 0b10000000

/** RSV_FRAME mask */
#define WEBSOCKET_PROTOCOL_RSV 0b01110000

/** OPCODE_FRAME mask */
#define WEBSOCKET_PROTOCOL_OPCODE 0b00001111

/** MASK_FRAME mask */
#define WEBSOCKET_PROTOCOL_MASK 0b10000000

/** PAYLOAD_LENGTH mask */
#define WEBSOCKET_PROTOCOL_PAYLOAD_LENGTH  0b01111111

/** static size for 2 byte data payload */
#define WEBSOCKET_PROTOCOL_PAYLOAD_SIZE_2BYTES 2

/** static size for 8 bytes data payload */
#define WEBSOCKET_PROTOCOL_PAYLOAD_SIZE_8BYTES 8

/** mask key size is always 4 (only when mask is enabled) */
#define WEBSOCKET_PROTOCOL_MASK_KEY_SIZE 4

/**
 * if payload size < payload_size_limit1 payload_length_frame is actual
 * payload length value || if payload size > payload_size_limit1 payload
 * length value is following two byte after PAYLOAD_LENGTH_FRAME
 */
#define WEBSOCKET_PROTOCOL_PAYLOAD_SIZE_LIMIT1 126

/**
 * if payload size is PAYLOAD_SIZE_LIMIT2 following 8 bytes are actual
 * paylad length value
 */
#define WEBSOCKET_PROTOCOL_PAYLOAD_SIZE_LIMIT2 127

#endif // WEBSOCKETPROTOCOL_H


text:
/**
 * Created by gsemerdjiev on 21.7.2016 г..
 */

export abstract class AbstractData {

	protected _parent:AbstractData;

	[key:string]:any;

	constructor(parent?:AbstractData) {
		this._parent = parent;
	}

	public getParent():AbstractData{
		return this._parent;
	}

	public setParent(parent:AbstractData):void{
		this._parent = parent;
	}
}


text:
package com.chuangfeng.pdnl.live.adapter;

import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chuangfeng.pdnl.R;
import com.chuangfeng.pdnl.live.mvp.model.bean.LiveListItemBean;

import java.util.List;

/**
 * Created by chuangfeng on 2017/4/11.
 * 直播房间列表的Adapter
 */

public class LiveListAdapter extends BaseQuickAdapter<LiveListItemBean> {
    public LiveListAdapter(List<LiveListItemBean> data) {
        super(R.layout.item_live_list_layout, data);
    }

    @Override
    protected void convert(BaseViewHolder viewHolder, LiveListItemBean bean) {
        viewHolder.setText(R.id.live_tv_roomname, bean.getLive_title())//房间名称
                .setText(R.id.live_tv_nickname, bean.getLive_nickname())//主播昵称
                .setText(R.id.live_tv_online, String.valueOf(bean.getLive_online()))//在线人数
                .setOnClickListener(R.id.live_cardview, new OnItemChildClickListener());//添加子Item点击监听,在UI中实现回调接口
        Glide.with(mContext)//直播房间截图
                .load(bean.getLive_img())
                .crossFade()
                .centerCrop()
                .into((ImageView) viewHolder.getView(R.id.live_iv_roomsrc));
        Glide.with(mContext)//主播头像
                .load(bean.getLive_userimg())
                .crossFade()
                .centerCrop()
                .placeholder(R.drawable.ic_avatar_default)
                .into((ImageView) viewHolder.getView(R.id.live_iv_avatar));
    }
}


text:
import sys
from setuptools import setup, find_packages

classifiers = [
    "Development Status :: 4 - Beta",
    "Intended Audience :: Developers",
    "License :: OSI Approved :: Apache Software License",
    "Programming Language :: Python",
    "Programming Language :: Python :: 2.6",
    "Programming Language :: Python :: 2.7",
    "Programming Language :: Python :: 3.2",
    "Programming Language :: Python :: 3.3",
    "Programming Language :: Python :: 3.4",
    "Programming Language :: Python :: 3.5",
    "Topic :: Database",
    "Topic :: Software Development",
    "Topic :: Software Development :: Testing",
]

install_requires = ['testing.common.database >= 1.1.0', 'pg8000 >= 1.10']
if sys.version_info < (2, 7):
    install_requires.append('unittest2')

setup(
    name='testing.postgresql',
    version='1.3.0',
    description='automatically setups a postgresql instance in a temporary '
                'directory, and destroys it after testing',
    long_description=open('README.rst').read(),
    classifiers=classifiers,
    keywords=[],
    author='Takeshi Komiya',
    author_email='i.tkomiya at gmail.com',
    url='https://github.com/tk0miya/testing.postgresql',
    license='Apache License 2.0',
    packages=find_packages('src'),
    package_dir={'': 'src'},
    package_data={'': ['buildout.cfg']},
    include_package_data=True,
    install_requires=install_requires,
    extras_require=dict(
        testing=[
            'nose',
            'psycopg2',
            'SQLAlchemy',
        ],
    ),
    test_suite='nose.collector',
    namespace_packages=['testing'],
)


text:
package org.spongepowered.api.event;

import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.function.Supplier;

/**
 * Provides an interface into the system managing the cause and contextual
 * information for events being thrown. This allows plugins to attach more
 * contextual information to events which may be triggered from their api
 * interactions.
 *
 *
For example a plugin may wish to push a player into the cause stack before
 * spawning an entity to expose to any plugin listening for SpawnEntityEvents
 * that the player is the reason that the entity was spawned.

 *
 *
This system will automatically handle associating a plugin with actions
 * performed inside of event listeners, command executors, and scheduled
 * tasks.

 */
public interface CauseStackManager {

    /**
     * Gets the current {@link Cause} object from the current cause stack.
     *
     * @return A cause of the current stack.
     */
    Cause currentCause();

    /**
     * Gets an {@link EventContext} object on the current contextual
     * information.
     *
     * @return The current event context
     */
    EventContext currentContext();

    /**
     * Pushes an object to the current cause stack which will associate it with
     * all events through from api actions until it is popped off again.
     *
     * @param obj The object to push to the stack
     * @return The cause stack manager, for chaining
     */
    CauseStackManager pushCause(Object obj);

    /**
     * Pops the most recently pushed cause object off of the stack and returns
     * it.
     *
     * @return The last pushed object
     */
    Object popCause();

    /**
     * Pops the most recently n pushed cause objects off of the stack.
     *
     * @param n The number of causes to pop
     */
    void popCauses(int n);

    /**
     * Retrieves but does not remove the most recently pushed cause object.
     *
     * @return The last pushed object
     */
    Object peekCause();

    /**
     * Pushes a frame of the current cause stack and context state.
     *
     * @return A handle for the frame which must be passed back to pop the frame
     *         from the stack
     */
    StackFrame pushCauseFrame();

    /**
     * Replaces the current cause stack and context with the cause frame at the
     * top of the frame stack.
     *
     *
The frame handle is required to ensure that frames are popped of in
     * order and are not left in the stack. If an attempt is made to pop a frame
     * which is not the head of the frame stack then an error will be thrown as
     * this indicates that a frame was not popped properly.

     *
     * @param handle The frame handle to pop
     */
    void popCauseFrame(StackFrame handle);

    /**
     * Adds the given object to the current context under the given key.
     *
     * @param key The context key
     * @param value The object
     * @param <T> The type of the value stored with the event context key
     * @return The cause stack manager, for chaining
     * @see EventContextKeys
     */
    <T> CauseStackManager addContext(EventContextKey<T> key, T value);

    /**
     * Adds the given object to the current context under the given key.
     *
     * @param key The context key
     * @param value The object
     * @param <T> The type of the value stored with the event context key
     * @return The cause stack manager, for chaining
     * @see EventContextKeys
     */
    default <T> CauseStackManager addContext(EventContextKey<T> key, Supplier<? extends T> value) {
        return this.addContext(key, value.get());
    }

    /**
     * Adds the given object to the current context under the given key.
     *
     * @param key The context key
     * @param value The object
     * @param <T> The type of the value stored with the event context key
     * @return The cause stack manager, for chaining
     * @see EventContextKeys
     */
    default <T> CauseStackManager addContext(Supplier<EventContextKey<T>> key, T value) {
        return this.addContext(key.get(), value);
    }

    /**
     * Adds the given object to the current context under the given key.
     *
     * @param key The context key
     * @param value The object
     * @param <T> The type of the value stored with the event context key
     * @return The cause stack manager, for chaining
     * @see EventContextKeys
     */
    default <T> CauseStackManager addContext(Supplier<EventContextKey<T>> key, Supplier<? extends T> value) {
        return this.addContext(key.get(), value.get());
    }

    /**
     * Gets the context value with the given key.
     *
     * @param key The context key
     * @param <T> The type of the value stored with the event context key
     * @return The context object, if present
     */
    <T> Optional<T> context(EventContextKey<T> key);

    /**
     * Gets the context value with the given key.
     *
     * @param key The context key
     * @param <T> The type of the value stored with the event context key
     * @return The context object, if present
     */
    default <T> Optional<T> context(Supplier<EventContextKey<T>> key) {
        return this.context(key.get());
    }

    /**
     * Gets the context value with the given key.
     *
     *
If the key is not available, {@link NoSuchElementException} will be
     * thrown.

     *
     * @param key The context key
     * @param <T> The type of the value stored with the event context key
     * @return The context object, if present
     */
    default <T> T requireContext(EventContextKey<T> key) {
        final Optional<T> optional = this.context(key);
        if (optional.isPresent()) {
            return optional.get();
        }
        throw new NoSuchElementException(String.format("Could not retrieve value for key '%s'", key.toString()));
    }

    /**
     * Gets the context value with the given key.
     *
     *
If the key is not available, {@link NoSuchElementException} will be
     * thrown.

     *
     * @param key The context key
     * @param <T> The type of the value stored with the event context key
     * @return The context object, if present
     */
    default <T> T requireContext(Supplier<EventContextKey<T>> key) {
        final Optional<T> optional = this.context(key.get());
        if (optional.isPresent()) {
            return optional.get();
        }
        throw new NoSuchElementException(String.format("Could not retrieve value for key '%s'", key.get().toString()));
    }

    /**
     * Removes the given context key from the current context.
     *
     * @param key The key to clear
     * @param <T> The type of the value stored with the event context key
     * @return The existing context value, if it was present
     * @see EventContextKeys
     */
    <T> Optional<T> removeContext(EventContextKey<T> key);

    /**
     * Removes the given context key from the current context.
     *
     * @param key The key to clear
     * @param <T> The type of the value stored with the event context key
     * @return The existing context value, if it was present
     * @see EventContextKeys
     */
    default <T> Optional<T> removeContext(Supplier<EventContextKey<T>> key) {
        return this.removeContext(key.get());
    }

    interface StackFrame extends AutoCloseable {

        /**
         * Gets the current {@link Cause} object from the current cause stack.
         *
         * @return A cause of the current stack.
         * @see CauseStackManager#currentCause()
         */
        Cause currentCause();

        /**
         * Gets an {@link EventContext} object on the current contextual
         * information.
         *
         * @return The current event context
         * @see CauseStackManager#currentContext()
         */
        EventContext currentContext();

        /**
         * Pushes an object to the current cause stack which will associate
         * it with all events through from api actions until it is
         * popped off again.
         *
         * @param obj The object to push to the stack
         * @return The stack frame, for chaining
         * @see CauseStackManager#pushCause(Object)
         */
        StackFrame pushCause(Object obj);

        /**
         * Pops the most recently pushed cause object off of the stack and
         * returns it.
         *
         * @return The last pushed object
         * @see CauseStackManager#popCause()
         */
        Object popCause();

        /**
         * Adds the given object to the current context under the given key.
         *
         * @param key The context key
         * @param value The object
         * @param <T> The type of value key
         * @return The stack frame, for chaining
         * @see EventContextKeys
         * @see CauseStackManager#addContext(EventContextKey, Object)
         */
        <T> StackFrame addContext(EventContextKey<T> key, T value);

        /**
         * Adds the given object to the current context under the given key.
         *
         * @param key The context key
         * @param value The object
         * @param <T> The type of value key
         * @return The stack frame, for chaining
         * @see EventContextKeys
         * @see CauseStackManager#addContext(EventContextKey, Object)
         */
        default <T> StackFrame addContext(EventContextKey<T> key, Supplier<? extends T> value) {
            return this.addContext(key, value.get());
        }

        /**
         * Adds the given object to the current context under the given key.
         *
         * @param key The context key
         * @param value The object
         * @param <T> The type of value key
         * @return The stack frame, for chaining
         * @see EventContextKeys
         * @see CauseStackManager#addContext(EventContextKey, Object)
         */
        default <T> StackFrame addContext(Supplier<EventContextKey<T>> key, T value) {
            return this.addContext(key.get(), value);
        }

        /**
         * Adds the given object to the current context under the given key.
         *
         * @param key The context key
         * @param value The object
         * @param <T> The type of value key
         * @return The stack frame, for chaining
         * @see EventContextKeys
         * @see CauseStackManager#addContext(EventContextKey, Object)
         */
        default <T> StackFrame addContext(Supplier<EventContextKey<T>> key, Supplier<? extends T> value) {
            return this.addContext(key.get(), value.get());
        }

        /**
         * Removes the given context key from the current context.
         *
         * @param key The key to clear
         * @param <T> The type of value key
         * @return The existing context value, if it was present
         * @see EventContextKeys
         * @see CauseStackManager#removeContext(EventContextKey)
         */
        <T> Optional<T> removeContext(EventContextKey<T> key);

        /**
         * Removes the given context key from the current context.
         *
         * @param key The key to clear
         * @param <T> The type of value key
         * @return The existing context value, if it was present
         * @see EventContextKeys
         * @see CauseStackManager#removeContext(EventContextKey)
         */
        default <T> Optional<T> removeContext(Supplier<EventContextKey<T>> key) {
            return this.removeContext(key.get());
        }

        @Override
        void close();

    }
}


text:
package ru.alttiri.examples.spliterator.logicbig;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class IteratorForEachRemainingExample {

    public static void main (String[] args) {
        List<String> list = Arrays.asList("Apple", "Banana", "Orange");
        Iterator<String> i = list.iterator();
        i.next();
        i.forEachRemaining(System.out::println);
    }
}


text:
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace DevOps.Portal.Domain.Teamcity
{
    public class VcsRoot : TeamCityComponent
    {
        public string VcsName { get; set; }

        public Project Project { get; set; }

        public VcsProperites Properties { get; set; }
    }
}


text:
\RequirePackage[l2tabu, orthodox]{nag}
\RequirePackage{silence}
\WarningFilter{fmtcount}{\ordinal already defined use \FCordinal instead}
\documentclass[english, french]{beamer}
\input{preamble/packages}
\input{preamble/math_basics}
\input{preamble/math_mine}
\input{preamble/redac}
\input{preamble/draw}
\input{preamble/acronyms}
\input{preamble/uml}
\input{preamble/refAPIcmds}

\setbeamertemplate{headline}[singleline]
\setbeamertemplate{footline}[onlypage]

\title{CDI}
\subtitle{}
\subject{Dependency injection}
\keywords{Java EE}
\author{Olivier Cailloux}
\institute[LAMSADE]{LAMSADE, Université Paris-Dauphine}
\date{Version du \today}

\begin{document}
\bibliographystyle{apalike}

\begin{frame}[plain]
	\tikz[remember picture,overlay]{
		\path (current page.south west) node[anchor=south west, inner sep=0] {
			\includegraphics[height=1cm]{LAMSADE95.jpg}
		};
		\path (current page.south) ++ (0, 1mm) node[anchor=south, inner sep=0] {
			\includegraphics[height=9mm]{Dauphine.jpg}
		};
		\path (current page.south east) node[anchor=south east, inner sep=0] {
			\includegraphics[height=1cm]{PSL.png}
		};
	}
   \titlepage
\end{frame}
\addtocounter{framenumber}{-1}

\section{Utilité de l'injection}
\begin{frame}
	\frametitle{Utilité de l'injection}
	CDI ? \pause Context Dependency \emph{Injection}\pause
	\begin{itemize}
		\item Votre classe dépend d'une autre classe
		\item L'autre classe lui rend un service
		\begin{itemize}
			\item Exemple : fournit l'accès à une BD
			\item Autres exemples ? \pause
			\item Fournit sérialisation en JSON
			\item Effectue des calculs
		\end{itemize}
		\item CDI permet d'éviter de coder la dépendance en dur
		\item Permet remplacement facile de la dépendance
		\item Permet d'y accéder même si instance créée automatiquement (exemple ? \pause Servlet !)
		\item Permet (et requiert) gestion du cycle de vie par le conteneur
	\end{itemize}
\end{frame}

\section{Vue d'ensemble}
\begin{frame}
	\frametitle{Vue d'ensemble}
	\begin{itemize}
		\item Bean géré (\emph{managed bean}) : classe dont le cycle de vie des instances peut être géré par le conteneur (y compris ressources)
		\item Pour ce faire, préciser sa portée contextuelle (\emph{contextual scope}) : \jeeref[@]{javax.enterprise.context/RequestScoped} ; \jeeref[@]{javax.enterprise.context/SessionScoped} ; \jeeref[@]{javax.enterprise.context/ConversationScoped} ; \jeeref[@]{javax.enterprise.context/ApplicationScoped}…
		\item Conteneur crée \emph{instance contextuelle} à la demande
		\item Instance contextuelle détruite à la fin de son scope
		\item Injection : \jeeref[@]{javax.inject/Inject} sur champ {\tiny ou méthode ou constructeur}
	\end{itemize}
\end{frame}

\section{Portée contextuelle}
\begin{frame}
	\frametitle{Portées contextuelles}
	\begin{itemize}
		\item \texttt{@RequestScoped} : détruit après traitement de la requête
		\item \texttt{@SessionScoped} : référence liée à la session HTTP ; détruit avec la session
		\item \texttt{@ApplicationScoped} : créé au besoin, un par application
		\item \texttt{@ConversationScoped} : gestion manuelle de la conversation
		\item \jeeref[@]{javax.enterprise.context/Dependent} : pas un normal scope ; scope lié à la destination de l'injection
		\item Session et conversation-scoped : implémenter \jseref{java.io/Serializable}
	\end{itemize}
\end{frame}

\begin{frame}
	\frametitle{Exemple portée Application : Programmation}
	\begin{itemize}
		\item Bean géré \texttt{ASMB}, annoté \texttt{@ApplicationScoped}
		\item Servlet \texttt{MyServlet}
		\item Servlet injecte une instance de \texttt{ASMB}
	\end{itemize}
\end{frame}

\begin{frame}
	\frametitle{Exemple portée Application : Comportement}
	Supposé : application vient d'être déployée
	\begin{itemize}
		\item Première requête R1 entrante, vers \texttt{MyServlet}
		\item \pause Conteneur doit créer instance \texttt{s1} de \texttt{MyServlet} pour traitement R1
		\item \pause Conteneur doit injecter dans \texttt{s1} une instance de \texttt{ASMB}
		\item \pause Conteneur crée une instance \texttt{b1} de \texttt{ASMB}
		\item \pause Conteneur injecte \texttt{b1} dans \texttt{s1}
		\item En parallèle : requête R2 vers \texttt{ASMB}
		\item \pause Conteneur doit créer instance \texttt{s2} de \texttt{MyServlet} pour traitement R2
		\item \pause Conteneur injecte \texttt{b1} dans \texttt{s2}
	\end{itemize}
\end{frame}

\begin{frame}
	\frametitle{Exemple portée Requête : Programmation}
	\begin{itemize}
		\item Bean géré \texttt{RSMB}, annoté \texttt{@RequestScoped}
		\item Servlet \texttt{MyServlet}
		\item Servlet injecte une instance de \texttt{RSMB}
	\end{itemize}
\end{frame}

\begin{frame}
	\frametitle{Exemple portée Requête : Comportement}
	Supposé : application vient d'être déployée
	\begin{itemize}
		\item Première requête R1 entrante, vers \texttt{MyServlet}
		\item \pause Conteneur doit créer instance \texttt{s1} de \texttt{MyServlet} pour traitement R1
		\item \pause Conteneur doit injecter dans \texttt{s1} une instance de \texttt{RSMB}
		\item \pause Conteneur crée une instance \texttt{b1} de \texttt{RSMB}
		\item \pause Conteneur injecte \texttt{b1} dans \texttt{s1}
		\item En parallèle : requête R2 vers \texttt{RSMB}
		\item \pause Conteneur doit créer instance \texttt{s2} de \texttt{MyServlet} pour traitement R2
		\item \pause Conteneur crée une instance \texttt{b2} de \texttt{RSMB}
		\item \pause Conteneur injecte \texttt{b2} dans \texttt{s2}
	\end{itemize}
\end{frame}

\section{Divers}
\begin{frame}
	\frametitle{Divers}
	\begin{itemize}
		\item \jeeref[@]{javax.transaction/Transactional} démarcation automatique de transaction
		\item On peut injecter : managed beans et Java EE Resources
		\item Ressource : bean représentant référence vers environnement composant (\jeeref[@]{javax.ejb/EJB}, \jeeref[@]{javax.annotation/Resource}, {\tiny @WebServiceRef, slmt scope \texttt{@Dependent} standard})
	\end{itemize}
	\begin{block}{Tests}
		\begin{itemize}
			\item Comment faciliter les tests unitaires (par exemple) ? \pause
			\item Ajouter des méthodes \texttt{setTruc(Truc)}, visibilité package
			\item Test sans CDI : initialiser la classe avec \texttt{new}
		\end{itemize}
	\end{block}
\end{frame}

\appendix
\section{Suppléments techniques}
\begin{frame}
	\frametitle{Objets gestionnaires de contexte}
	\begin{itemize}
		\item Le conteneur utilise un objet gestionnaire de contexte (\emph{context object}) pour chaque contexte
		\item Exemple : quatre gestionnaires de contexte si le conteneur gère actuellement une application, une session, deux requêtes
		\item Chaque objet gestionnaire de contexte associe un type de bean à maximum une instance contextuelle
		\item Exemple : l'objet gestionnaire du contexte \og{}Session 1\fg{} associe le type \texttt{SayHelloService} à zéro instance
		\item Le gestionnaire du contexte crée une instance contextuelle de \texttt{SayHelloService} à la demande d'un servlet servant \og{}Session 1\fg{}
		\item Le gestionnaire du contexte sert \emph{la même} instance à un autre servlet servant la même session
		\item À la destruction de la session, le gestionnaire du contexte détruit l'instance
	\end{itemize}
\end{frame}

\begin{frame}
	\frametitle{Conversations}
	\begin{itemize}
		\item \texttt{@ConversationScoped} : gestion manuelle de la conversation
		\item \jeeref{javax.enterprise.context/Conversation} : objet \texttt{@RequestScoped} (donc injectable) pour démarrer et terminer une conversation
		\item Une conversation a un identifiant unique
		\item Joindre une conversation : envoyer paramètre de requête \texttt{cid}
		\item Voir application \href{https://github.com/oliviercailloux/samples/tree/master/JavaEE-Inject-Servlets-Conversation}{JavaEE-Inject-Servlets-Conversation}
	\end{itemize}
\end{frame}

\begin{frame}
	\frametitle{Portées et EJB}
	\begin{itemize}
		\item Stateless session bean doit avoir portée \texttt{@Dependent}
		\item Singleton doit avoir \texttt{@ApplicationScoped} {\tiny ou \texttt{@Dependent}}
		\item Stateful : tout est permis
	\end{itemize}
\end{frame}

\begin{frame}
	\frametitle{Portées et concurrence}
	\begin{itemize}
		\item Le développeur doit protéger les objets dans un contexte contre les accès concurrents
		\item Sauf \texttt{ConversationScoped}, garanti par le conteneur actif pour une requête à la fois
	\end{itemize}
\end{frame}

\begin{frame}
	\frametitle{Désambiguation et production}
	Comment préciser quelle classe injecter ?
	\begin{itemize}
		\item Un bean a des \emph{qualifieurs} : annotations spécialisant un type
		\item Qualifieur : type annotation annoté \jseref[@]{java.lang.annotation/Retention} \jseref{java.lang.annotation/RetentionPolicy\#RUNTIME} et \jeeref[@]{javax.inject/Qualifier}
		\item Préciser \texttt{@Inject @Qualifieur Type truc;}
		\item {\tiny Qualifieurs prédéfinis : \jeeref[@]{javax.enterprise.inject/Default} (tout type sans qualifieur {\tiny ou slmt \jeeref[@]{javax.inject/Named}}), \jeeref[@]{javax.enterprise.inject/Any} (tout {\tiny sauf \jeeref[@]{javax.enterprise.inject/New}})}
	\end{itemize}
	\begin{block}{Producteurs}
		\begin{itemize}
			\item Méthode \jeeref[@]{javax.enterprise.inject/Produces} : produit une instance à la demande
			\item Méthode peut aussi être annotée d'un scope et de qualifieurs (s'appliquent au produit)
		\end{itemize}
	\end{block}
\end{frame}

\section{Exercices}
\begin{frame}[allowframebreaks]
	\frametitle{Exercices}
	\begin{itemize}
		\item Programmer un bean \texttt{@RequestScoped}
		\item L'injecter et l'utiliser dans un servlet {\tiny ou autre objet avec portée requête}
		\item Programmer un bean \texttt{@RequestScoped} avec un état (un simple compteur, par exemple, qui s'incrémente lors de chaque utilisation)
		\item Observer son comportement lors de l'utilisation dans un servlet
		\item Rendre votre bean \texttt{@ApplicationScoped} ; observer ce que ça change
		\item Rendre votre bean \texttt{@SessionScoped} ; observer ce que ça change
		\item[*] Simuler un traitement long (\texttt{\jseref{java.lang/Thread}.sleep}) dans le bean CDI. Avec deux navigateurs différents, envoyer deux GET simultanées. On souhaite qu'elles soient traitées en parallèle (la deuxième n'attend pas la fin de la première avant de s'exécuter). Comment annoter le bean CDI pour ce faire ? Quelle différence prévoyez-vous par exemple entre \texttt{@ApplicationScoped} et \texttt{@RequestScoped} ?
		\item[*] Pour le vérifier, modifiez le comportement de votre bean CDI. Il possède maintenant un compteur \texttt{i}. Il incrémente \texttt{i} en entrée d'appel, puis il renvoie la valeur de \texttt{i} à l'appelant, puis il décrémente \texttt{i}. Le bean renverra-t-il toujours la valeur d'initialisation de \texttt{i} + 1, lors d'appels parallèles de clients web différents ? Prédire son comportement en fonction de la portée CDI qui vous lui affectez. Réfléchir aux avantages de différents choix. Pour vérifier vos prédictions, utiliser \texttt{Thread.sleep} judicieusement.
		\item Programmer un SLSB (stateless session bean), l'injecter avec \jeeref[@]{javax.ejb/EJB} : quelles différences avec un bean \texttt{@RequestScoped} ? Et quelles différences avec d'autres portées ?
	\end{itemize}
\end{frame}

\section{Licence}
\begin{frame}
	\frametitle{Licence}
	Cette présentation, et le code LaTeX associé, sont sous \href{https://opensource.org/licenses/MIT}{licence MIT}. Vous êtes libres de réutiliser des éléments de cette présentation, sous réserve de citer l'auteur.

	Le travail réutilisé est à attribuer à \href{http://www.lamsade.dauphine.fr/~ocailloux/}{Olivier Cailloux}, Université Paris-Dauphine.
\end{frame}
\end{document}

\begin{frame}
	\frametitle{}
	\begin{itemize}
		\item
	\end{itemize}
	\begin{block}{}

	\end{block}
\end{frame}

\section{Bibliographie}
\begin{frame}[allowframebreaks]
	\frametitle{Bibliographie}
	\def\newblock{\hskip .11em plus .33em minus .07em}
% 	\bibliography{zotero}
\end{frame}

\section{Autres}
\begin{frame}
	\frametitle{}
	\begin{itemize}
		\item
	\end{itemize}
	\begin{block}{}

	\end{block}
\end{frame}
\end{document}


text:
$context.section('Basic');
//= require menu-basic
$context.section('Underlined');
//= require menu-underlined
$context.section('Tabular');
//= require menu-tabs
$context.section('Secondary');
//= require menu-secondary
$context.section('Dropdown');
//= require menu-dropdown
$context.section('Submenu');
//= require menu-submenu
$context.section('Context');
//= require menu-context
$context.section('Vertical');
//= require menu-vertical
$context.section('Vertical icons');
//= require menu-vertical-icons
$context.section('Group');
//= require menu-groups
$context.section('Nested');
//= require menu-nested


text:
#include <iostream>
#include <cstring>
#include <cassert>

#include "hadoop/Pipes.hh"
#include "hadoop/TemplateFactory.hh"

void host_to_network(uint32_t x, std::string& str) {
    str[0] = x >> 24;
    str[1] = x >> 16;
    str[2] = x >>  8;
    str[3] = x >>  0;
}

uint32_t network_to_host(const void* from) {
    uint8_t* network = (uint8_t*)(from);
    return uint32_t(network[0]) << 24 |
           uint32_t(network[1]) << 16 |
           uint32_t(network[2]) <<  8 |
           uint32_t(network[3]) <<  0;
}

// assert url_list_header.length() > 4 Bytes
const std::string url_list_header = "     ";
const std::string delimiter = "ABCDEF";

/* Mapper input format:
   Key = ...
   Value = URL\t(PR, URL_list)
   PR is 4-Byte floating point defined in IEEE 754
   RUL is a 4-Byte unsigned integer in big-endian
*/
class PageRankMapper: public HadoopPipes::Mapper {
public:
    PageRankMapper(HadoopPipes::TaskContext& /* context */) { }

    void map(HadoopPipes::MapContext& context) {
        std::string input_value = context.getInputValue();

        size_t offset = 0;

        // URL
        uint32_t URL = network_to_host(input_value.data() + offset);
        offset += sizeof(URL);

        // tab
        char space = *(char*)(input_value.data() + offset);
        offset += sizeof(space);
        if (space != '\t') return;

        // initial PR
        float pr = *(float*)(input_value.data() + offset);
        offset += sizeof(pr);

        // construct emit key
        std::string emit_key(sizeof(URL), 0);
        host_to_network(URL, emit_key);

        // emit url_list
        context.emit(emit_key, url_list_header + std::string(input_value.data() + offset, input_value.length() - offset));

        size_t url_list_size = (input_value.length() - offset) / sizeof(uint32_t);

        // compute new pr
        float new_pr = pr / url_list_size;

        // construct emit value
        std::string emit_value(sizeof(new_pr), 0);
        memcpy(&emit_value[0], &new_pr, sizeof(new_pr));

        // URL list
        while (offset + sizeof(uint32_t) <= input_value.length()) {
            // construct emit key (url)
            emit_key[0] = input_value[offset++];
            emit_key[1] = input_value[offset++];
            emit_key[2] = input_value[offset++];
            emit_key[3] = input_value[offset++];

            context.emit(emit_key, emit_value);
        }
    }
};

/* Reducer input format:
   Key = URL
   Value = 4-Byte floating point defined in IEEE 754
        or url list header + URL_list
   RUL is a 4-Byte unsigned integer in big-endian
*/
class PageRankReducer: public HadoopPipes::Reducer {
public:
    PageRankReducer(HadoopPipes::TaskContext& /* context */) { }

    void reduce(HadoopPipes::ReduceContext& context) {
        constexpr float d = 0.85f;

        uint32_t URL = network_to_host(context.getInputKey().data());

        std::string input_value;
        std::string url_list;

        float pr = 0.0f;

        while (context.nextValue()) {
            input_value = context.getInputValue();

            // url list
            if (input_value.length() >= url_list_header.length())
                url_list = input_value.substr(url_list_header.length());
            else {
                assert(input_value.length() == 4);
                pr += *(float*)(input_value.data());
            }
        }

        pr = 1.0f - d + d * pr;

        // construct emit key
        std::string emit_key(sizeof(URL), 0);
        host_to_network(URL, emit_key);

        // and emit value
        std::string emit_value(sizeof(pr), 0);
        emit_value += url_list;
        emit_value += delimiter;
        memcpy(&emit_value[0], &pr, sizeof(pr));

        context.emit(emit_key, emit_value);
    }
};

int main(int, char**) {
    return HadoopPipes::runTask(HadoopPipes::TemplateFactory<PageRankMapper, PageRankReducer>());
}


text:
MYCALLPATHNAME=$0
MYCALLNAME=`basename $MYCALLPATHNAME`
MYCALLNAME=${MYCALLNAME%.sh}
MYCALLPATH=`dirname $MYCALLPATHNAME`

MYBOOTSTRAPFILE=$(getPathToBootstrapDir.sh)/bootstrap-03_03_001.sh
. ${MYBOOTSTRAPFILE}
if [ $? -ne 0 ];then
	echo "ERROR:Missing bootstrap file:configuration: ${MYBOOTSTRAPFILE}">&2
	exit 1
fi
setUTALMbash 1 $*
#
###
#
. $(getPathToLib.sh libutalmfileobjects.sh)
. $(getPathToLib.sh libutalmrefpersistency.sh)
TROOT=$(getUpperTreePathMatch $PWD tests 0)
refDataInit $TROOT

refDataStore input-data-min.txt
fref=$(refDataStorePath input-data-min.txt)

$(getPathToBin.sh)/strip-bash.sh DROPLINES -o ${fref%input-data-min.txt} input-data.txt
assertRefDataWithExit $LINENO $BASH_SOURCE input-data-min.txt "$(cat ref-data.txt)"

## \endcond


text:
This is a statement by Philippe Leite that grants permission to
relicense its copyrights in the libzmq C++ library (ZeroMQ) under the
Mozilla Public License v2 (MPLv2) or any other Open Source Initiative
approved license chosen by the current ZeroMQ BDFL (Benevolent
Dictator for Life).

A portion of the commits made by the Github handle "philippeleite", with
commit author "Philippe Leite <philippe.leite@gmail.com>", are
copyright of Philippe Leite.  This document hereby grants the libzmq
project team to relicense libzmq, including all past, present and
future contributions of the author listed above.

Philippe Leite
2019/06/10


text:
layout: posts_by_category
category: docker-yobi
permalink: /categories/docker-yobi/
---


text:
function getListTimeRecord() {

    if(!localStorage.getItem("#01"))
        localStorage.setItem("#01", "00:00");
    if(!localStorage.getItem("#02"))
        localStorage.setItem("#02", "00:00");
    if(!localStorage.getItem("#03"))
        localStorage.setItem("#03", "00:00");
    if(!localStorage.getItem("#04"))
        localStorage.setItem("#04", "00:00");
    if(!localStorage.getItem("#05"))
        localStorage.setItem("#05", "00:00");
    if(!localStorage.getItem("#06"))
        localStorage.setItem("#06", "00:00");

    let timeRecords = document.querySelectorAll(".time_record");

    timeRecords.forEach(function(item, i, timeRecords) {
        item.innerHTML = localStorage.getItem("#0" + (i + 1))
    })
}

function getTimeRecord(level) {
    if(localStorage.getItem(level)) {
        let str = localStorage.getItem(level);
        let sec = parseInt(str.substring(0, 3)) * 60 + parseInt(str.substring(3))
        return sec;
    } else {
        return null;
    }
}

function getCurrentTime() {
    let str = document.getElementById("timer").innerHTML;
    let arrCurrentTime = {}

    arrCurrentTime = {
        strTime : str,
        sec : parseInt(str.substring(0, 3)) * 60 + parseInt(str.substring(3))
    }
    return arrCurrentTime;
}

function isNewRecord(level, arrCurrentTime) {
    let oldTime = getTimeRecord(level);
    let newTime = arrCurrentTime.sec;
    if(oldTime == 0 || newTime < oldTime) {
        localStorage.setItem(level, arrCurrentTime.strTime);
        getListTimeRecord();
        return true;
    }
    return false;
}


text:
**[Download RC Version](https://github.com/dmunozgaete/Angular-Gale-Material/releases/tag/v1.0.0-rc.1) |**
**[Guide](https://angular-gale.azurewebsites.net) |**
**[C# API](https://gale.azurewebsites.net) |**
**[Report Issues](#report-an-issue)**

---

Angular Gale Material is a set of components design for support the UX created with
the Angular-Material Project (Only Web Environment)

**Note:** *Angular-Gale-Material is under active development. As such, while this library is well-tested, the API may change. Consider using it in production applications only if you're comfortable following a changelog and updating your usage accordingly.*

## Get Started

**(1)** Get Angular-Gale-Material in one of the following ways:
 - [download the release](https://github.com/dmunozgaete/Angular-Gale-Material/releases/tag/v1.0.0-rc.1)
 - or via **[Bower](http://bower.io/)**: by running `$ bower install angular-gale-material --save` from your console

**(2)** Include `angular-gale-material.js` (or `angular-gale-material.min.js`) in your `index.html`

**(3)** Add `gale-material` to your main module's list of dependencies

When you're done, your setup should look similar to the following:

```html
<!doctype html>
<html ng-app="myApp">
<head>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angular-material/0.11.2/angular-material.min.js"></script>
    <script src="bower_components/angular-gale-material/angular-gale-material.min.js"></script>
    <script>
        var myApp = angular.module('myApp', ['gale-material']);
    </script>
    ...
</head>
<body>
    ...
</body>
</html>
```

**Note:** if you want the unstable version use: `$ bower install dmunozgaete/angular-gale-material#master --save` from your console

# Report an Issue

Help us make Angular-Gale better! If you think you might have found a bug, or some other weirdness, start by making sure
it hasn't already been reported. You can [search through existing issues](https://github.com/dmunozgaete/Angular-Gale-Material/issues?q=is%3Aopen+is%3Aissue)
to see if someone's reported one similar to yours.

If not, then [create a plunkr](http://bit.ly/UIR-Plunk) that demonstrates the problem (try to use as little code
as possible: the more minimalist, the faster we can debug it).

Next, [create a new issue](https://github.com/dmunozgaete/Angular-Gale-Material/issues/new) that briefly explains the problem,
and provides a bit of background as to the circumstances that triggered it. Don't forget to include the link to
that plunkr you created!

Issues only! |
-------------|
Please keep in mind that the issue tracker is for *issues*. Please do *not* post an issue if you need help or support.

# Contribute

**(1)** See the **[Developing](#developing)** section below, to get the development version of Angular-Gale up and running on your local machine.

**(2)** Check out the [roadmap](https://github.com/dmunozgaete/Angular-Gale-Material/milestones) to see where the project is headed, and if your feature idea fits with where we're headed.

**(4)** Finally, commit some code and open a pull request. Code & commits should abide by the following rules:

*Always*
- Commits should represent one logical change each; if a feature goes through multiple iterations, squash your commits down to one
- Changes should always respect the coding style of the project

## Resources

- [Angular Gale Doc's](http://angular-gale.azurewebsites.net/)
- [Framework API](http://gale.azurewebsites.net/)
- [Grupo Valentys](http://www.valentys.com)

## Developing

```bash
 npm install & bower install
 grunt compile
```


text:
$:.unshift File.dirname(__FILE__) # For use/testing when no gem is installed

# core
require 'fileutils'
require 'time'
require 'ostruct'
require 'date'
require 'rexml/document'

#stdlib
require 'timeout'
require 'singleton'
require 'uri'
require 'socket'

#third party
require 'rubygems'
require 'net/ssh'
require 'net/scp'
require 'open4'
require 'json'
require 'ERB'
require 'tree'

#project internals
require 'ext/string'

require 'fcs/lazy_reader'
require 'fcs/multi_tree'
require 'fcs/fcs_entity'
require 'fcs/asset'
require 'fcs/client'
require 'fcs/device'
require 'fcs/element'
require 'fcs/factory'
require 'fcs/file'
require 'fcs/project'

module FinalCutServer
  class << self
    attr_accessor :debug
  end

  self.debug = false

end


text:
package io.emeraldpay.etherjar.rpc.ws;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.emeraldpay.etherjar.rpc.RpcResponseError;
import io.emeraldpay.etherjar.rpc.json.BlockJson;
import io.emeraldpay.etherjar.rpc.RequestJson;
import io.emeraldpay.etherjar.rpc.json.TransactionRefJson;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.util.*;

/**
 * Ethereum Websocket subscription call
 *
 * @author Igor Artamonov
 */
public abstract class Subscription<T> {

    private List params;

    private List<SubscriptionListener<T>> listeners = new ArrayList<>();
    private Channel channel;
    private String id;

    protected Subscription(List params) {
        this.params = params;
    }

    public void addListener(SubscriptionListener<T> listener) {
        listeners.add(listener);
    }

    public void start(Channel channel, ObjectMapper objectMapper, Integer requestId) throws JsonProcessingException {
        this.channel = channel;
        RequestJson<Integer> json = new RequestJson<>("eth_subscribe", params, requestId);
        channel.write(new TextWebSocketFrame(objectMapper.writeValueAsString(json)));
        channel.flush();
    }

    public void stop(ObjectMapper objectMapper, Integer requestId) throws JsonProcessingException {
        RequestJson<Integer> json = new RequestJson<>("eth_unsubscribe", Collections.singletonList(id), requestId);
        channel.write(new TextWebSocketFrame(objectMapper.writeValueAsString(json)));
        channel.flush();
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getId() {
        return id;
    }

    public abstract void onReceive(SubscriptionJson json);

    public void onReceive(T data) {
        for (SubscriptionListener<T> listener: listeners) {
            try {
                listener.onData(data);
            } catch (Exception e) { }
        }
    }

    /**
     * Called on socket close
     *
     * @param error error if closed as a result of error
     */
    public void onClose(RpcResponseError error) {
        if (error != null) {
            System.err.println("Socket closed with " + error.getMessage());
        }
    }

    public static class Block extends Subscription<BlockJson<TransactionRefJson>> {

        private static final List PARAMS = Arrays.asList(
            "newHeads"
        );

        protected Block() {
            super(PARAMS);
        }

        @Override
        public void onReceive(SubscriptionJson json) {
            BlockJson<TransactionRefJson> blockJson = json.getBlockResult();
            onReceive(blockJson);
        }
    }

}


text:
/**
 */
package gluemodel.CIM.IEC61970.ControlArea.impl;

import gluemodel.CIM.IEC61970.ControlArea.*;

import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EDataType;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;

import org.eclipse.emf.ecore.impl.EFactoryImpl;

import org.eclipse.emf.ecore.plugin.EcorePlugin;

/**
 * <!-- begin-user-doc -->
 * An implementation of the model <b>Factory</b>.
 * <!-- end-user-doc -->
 * @generated
 */
public class ControlAreaFactoryImpl extends EFactoryImpl implements ControlAreaFactory {
	/**
	 * Creates the default factory implementation.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public static ControlAreaFactory init() {
		try {
			ControlAreaFactory theControlAreaFactory = (ControlAreaFactory)EPackage.Registry.INSTANCE.getEFactory(ControlAreaPackage.eNS_URI);
			if (theControlAreaFactory != null) {
				return theControlAreaFactory;
			}
		}
		catch (Exception exception) {
			EcorePlugin.INSTANCE.log(exception);
		}
		return new ControlAreaFactoryImpl();
	}

	/**
	 * Creates an instance of the factory.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public ControlAreaFactoryImpl() {
		super();
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	public EObject create(EClass eClass) {
		switch (eClass.getClassifierID()) {
			case ControlAreaPackage.CONTROL_AREA: return createControlArea();
			case ControlAreaPackage.ALT_GENERATING_UNIT_MEAS: return createAltGeneratingUnitMeas();
			case ControlAreaPackage.TIE_FLOW: return createTieFlow();
			case ControlAreaPackage.CONTROL_AREA_GENERATING_UNIT: return createControlAreaGeneratingUnit();
			case ControlAreaPackage.ALT_TIE_MEAS: return createAltTieMeas();
			default:
				throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier");
		}
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	public Object createFromString(EDataType eDataType, String initialValue) {
		switch (eDataType.getClassifierID()) {
			case ControlAreaPackage.CONTROL_AREA_TYPE_KIND:
				return createControlAreaTypeKindFromString(eDataType, initialValue);
			default:
				throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier");
		}
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	public String convertToString(EDataType eDataType, Object instanceValue) {
		switch (eDataType.getClassifierID()) {
			case ControlAreaPackage.CONTROL_AREA_TYPE_KIND:
				return convertControlAreaTypeKindToString(eDataType, instanceValue);
			default:
				throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier");
		}
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public ControlArea createControlArea() {
		ControlAreaImpl controlArea = new ControlAreaImpl();
		return controlArea;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public AltGeneratingUnitMeas createAltGeneratingUnitMeas() {
		AltGeneratingUnitMeasImpl altGeneratingUnitMeas = new AltGeneratingUnitMeasImpl();
		return altGeneratingUnitMeas;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public TieFlow createTieFlow() {
		TieFlowImpl tieFlow = new TieFlowImpl();
		return tieFlow;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public ControlAreaGeneratingUnit createControlAreaGeneratingUnit() {
		ControlAreaGeneratingUnitImpl controlAreaGeneratingUnit = new ControlAreaGeneratingUnitImpl();
		return controlAreaGeneratingUnit;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public AltTieMeas createAltTieMeas() {
		AltTieMeasImpl altTieMeas = new AltTieMeasImpl();
		return altTieMeas;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public ControlAreaTypeKind createControlAreaTypeKindFromString(EDataType eDataType, String initialValue) {
		ControlAreaTypeKind result = ControlAreaTypeKind.get(initialValue);
		if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'");
		return result;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public String convertControlAreaTypeKindToString(EDataType eDataType, Object instanceValue) {
		return instanceValue == null ? null : instanceValue.toString();
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public ControlAreaPackage getControlAreaPackage() {
		return (ControlAreaPackage)getEPackage();
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @deprecated
	 * @generated
	 */
	@Deprecated
	public static ControlAreaPackage getPackage() {
		return ControlAreaPackage.eINSTANCE;
	}

} //ControlAreaFactoryImpl


text:
import React from 'react'
import Todo from '../Todo'
import { connect } from 'cerebral/react'
import {signal} from 'cerebral/tags'
import isAllChecked from '../../computed/isAllChecked'
import visibleTodosRefs from '../../computed/visibleTodosRefs'

export default connect({
  isAllChecked: isAllChecked,
  todoRefs: visibleTodosRefs,
  toggleAllChanged: signal`app.toggleAllChanged`
},
  function List ({ isAllChecked, todoRefs, toggleAllChanged }) {
    return (

        <input
          className='toggle-all'
          type='checkbox'
          checked={isAllChecked}
          onChange={() => toggleAllChanged()} />

          Mark all as complete

          {todoRefs.map(ref => <Todo key={ref} todoRef={ref} />)}

    )
  }
)


text:
package tech.alexontest.poftutor.pageblocks;

import com.google.inject.Inject;
import org.apache.commons.lang3.tuple.Pair;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import tech.alexanderontest.guicefactory.infrastructure.pagefactory.AbstractDefinedBlock;

import java.util.List;
import java.util.stream.Collectors;

public class ArchivesWidgetBlockDesktop extends AbstractDefinedBlock implements ArchivesWidgetBlock {
    @FindBy(css = ".widget_archive")
    private WebElement rootElement;

    @FindBy(css = ".widget-title")
    private WebElement title;

    @FindBy(tagName = "a")
    private List<WebElement> months;

    @Inject
    protected ArchivesWidgetBlockDesktop(final WebDriver webDriver) {
        super(webDriver);
    }

    @Override
    public String getTitle() {
        return title.getText();
    }

    @Override
    public List<Pair<String, String>> getMonths() {
        return months.stream()
                .map(e -> Pair.of(e.getText(), e.getAttribute("href")))
                .collect(Collectors.toList());
    }
}


text:
using namespace std;

namespace chrono
{
namespace fea
{

//////////////////////////////////////////////////////////////////////////////
////  ChContactTriangleXYZ

ChContactTriangleXYZ::ChContactTriangleXYZ() {
        this->collision_model = new collision::ChModelBullet;
        this->collision_model->SetContactable(this);
}

ChContactTriangleXYZ::ChContactTriangleXYZ(ChSharedPtr<ChNodeFEAxyz> n1, ChSharedPtr<ChNodeFEAxyz> n2, ChSharedPtr<ChNodeFEAxyz> n3, ChContactSurface* acontainer) {
        mnode1 = n1;
        mnode1 = n2;
        mnode1 = n3;
        container = acontainer;

        this->collision_model = new collision::ChModelBullet;
        this->collision_model->SetContactable(this);
}

ChSharedPtr<ChMaterialSurfaceBase>& ChContactTriangleXYZ::GetMaterialSurfaceBase()
{
    return container->GetMaterialSurfaceBase();
}

ChPhysicsItem* ChContactTriangleXYZ::GetPhysicsItem()
{
    return (ChPhysicsItem*)container->GetMesh();
}

//////////////////////////////////////////////////////////////////////////////
////  ChContactSurfaceMesh

void ChContactSurfaceMesh::AddFacesFromBoundary(double sphere_swept) {

    std::vector< std::array<ChNodeFEAxyz*,3> > triangles;
    std::vector< std::array<ChSharedPtr<ChNodeFEAxyz>,3> > triangles_ptrs;

    ///
    /// Case1. Outer skin boundary of meshes of TETRAHEDRONS:
    ///

    std::multimap< std::array<ChNodeFEAxyz*, 3> , ChFaceTetra_4> face_map;

    for (unsigned int ie= 0; ie< this->mmesh->GetNelements(); ++ie) {
        if (ChSharedPtr<ChElementTetra_4> mtetra = mmesh->GetElement(ie).DynamicCastTo<ChElementTetra_4>()) {
            for (int nface = 0; nface<4; ++nface) {
                ChFaceTetra_4 mface(mtetra, nface);
                std::array<ChNodeFEAxyz*, 3> mface_key = {mface.GetNodeN(0).get_ptr(), mface.GetNodeN(1).get_ptr(), mface.GetNodeN(2).get_ptr()};
                std::sort(mface_key.begin(), mface_key.end());
                face_map.insert( {mface_key, mface} );
            }
        }
    }
    for (unsigned int ie= 0; ie< this->mmesh->GetNelements(); ++ie) {
        if (ChSharedPtr<ChElementTetra_4> mtetra = mmesh->GetElement(ie).DynamicCastTo<ChElementTetra_4>()) {
            for (int nface = 0; nface<4; ++nface) {
                ChFaceTetra_4 mface(mtetra, nface);
                std::array<ChNodeFEAxyz*, 3> mface_key = {mface.GetNodeN(0).get_ptr(), mface.GetNodeN(1).get_ptr(), mface.GetNodeN(2).get_ptr()};
                std::sort(mface_key.begin(), mface_key.end());
                if (face_map.count(mface_key) == 1) {
                    // Found a face that is not shared.. so it is a boundary face.
                    triangles.push_back( {mface.GetNodeN(0).get_ptr(), mface.GetNodeN(1).get_ptr(), mface.GetNodeN(2).get_ptr()} );
                    triangles_ptrs.push_back( {mface.GetNodeN(0), mface.GetNodeN(1), mface.GetNodeN(2)} );
                }
            }
        }
    }

    ///
    /// Case2. skin of ANCF SHELLS:
    ///
    for (unsigned int ie= 0; ie< this->mmesh->GetNelements(); ++ie) {
        if (ChSharedPtr<ChElementShellANCF> mshell = mmesh->GetElement(ie).DynamicCastTo<ChElementShellANCF>()) {
            ChSharedPtr<ChNodeFEAxyz> nA = mshell->GetNodeA();
            ChSharedPtr<ChNodeFEAxyz> nB = mshell->GetNodeB();
            ChSharedPtr<ChNodeFEAxyz> nC = mshell->GetNodeC();
            ChSharedPtr<ChNodeFEAxyz> nD = mshell->GetNodeD();
            std::array<ChNodeFEAxyz*,3> tri1 = {nA.get_ptr(),nB.get_ptr(),nC.get_ptr()};
            std::array<ChNodeFEAxyz*,3> tri2 = {nA.get_ptr(),nC.get_ptr(),nD.get_ptr()};
            std::array<ChSharedPtr<ChNodeFEAxyz>,3> tri1_ptrs = {nA,nB,nC};
            std::array<ChSharedPtr<ChNodeFEAxyz>,3> tri2_ptrs = {nA,nC,nD};
            triangles.push_back( tri1 );
            triangles.push_back( tri2 );
            triangles_ptrs.push_back( tri1_ptrs );
            triangles_ptrs.push_back( tri2_ptrs );
        }
    }

    // Compute triangles connectivity

    std::multimap< std::pair<ChNodeFEAxyz*, ChNodeFEAxyz*>, int> edge_map;

    for (int it = 0; it<  triangles.size(); ++it) {
        // edges = pairs of vertexes indexes
        std::pair<ChNodeFEAxyz*, ChNodeFEAxyz*> medgeA( triangles[it][0],  triangles[it][1]);
        std::pair<ChNodeFEAxyz*, ChNodeFEAxyz*> medgeB( triangles[it][1],  triangles[it][2]);
        std::pair<ChNodeFEAxyz*, ChNodeFEAxyz*> medgeC( triangles[it][2],  triangles[it][0]);
        // vertex indexes in edges: always in increasing order to avoid ambiguous duplicated edges
        if (medgeA.first>medgeA.second)
            medgeA = std::pair<ChNodeFEAxyz*, ChNodeFEAxyz*>(medgeA.second, medgeA.first);
        if (medgeB.first>medgeB.second)
            medgeB = std::pair<ChNodeFEAxyz*, ChNodeFEAxyz*>(medgeB.second, medgeB.first);
        if (medgeC.first>medgeC.second)
            medgeC = std::pair<ChNodeFEAxyz*, ChNodeFEAxyz*>(medgeC.second, medgeC.first);
        edge_map.insert( { medgeA , it} );
        edge_map.insert( { medgeB , it} );
        edge_map.insert( { medgeC , it} );
    }

    // Create a map of neighbouring triangles, vector of:
    // [Ti TieA TieB TieC]
    std::vector<std::array<int, 4>> tri_map;
    tri_map.resize(triangles.size());

    for (int it = 0; it< triangles.size(); ++it) {
        tri_map[it][0]=it;
        tri_map[it][1]=-1; // default no neighbour
        tri_map[it][2]=-1; // default no neighbour
        tri_map[it][3]=-1; // default no neighbour
        // edges = pairs of vertexes indexes
        std::pair<ChNodeFEAxyz*, ChNodeFEAxyz*> medgeA( triangles[it][0],  triangles[it][1]);
        std::pair<ChNodeFEAxyz*, ChNodeFEAxyz*> medgeB( triangles[it][1],  triangles[it][2]);
        std::pair<ChNodeFEAxyz*, ChNodeFEAxyz*> medgeC( triangles[it][2],  triangles[it][0]);
        // vertex indexes in edges: always in increasing order to avoid ambiguous duplicated edges
        if (medgeA.first>medgeA.second)
            medgeA = std::pair<ChNodeFEAxyz*, ChNodeFEAxyz*>(medgeA.second, medgeA.first);
        if (medgeB.first>medgeB.second)
            medgeB = std::pair<ChNodeFEAxyz*, ChNodeFEAxyz*>(medgeB.second, medgeB.first);
        if (medgeC.first>medgeC.second)
            medgeC = std::pair<ChNodeFEAxyz*, ChNodeFEAxyz*>(medgeC.second, medgeC.first);
        auto retA = edge_map.equal_range(medgeA);
        for (auto fedge=retA.first; fedge!=retA.second; ++fedge) {
            if (fedge->second != it) {
                tri_map[it][1]=fedge->second;
                break;
            }
        }
        auto retB = edge_map.equal_range(medgeB);
        for (auto fedge=retB.first; fedge!=retB.second; ++fedge) {
            if (fedge->second != it) {
                tri_map[it][2]=fedge->second;
                break;
            }
        }
        auto retC = edge_map.equal_range(medgeC);
        for (auto fedge=retC.first; fedge!=retC.second; ++fedge) {
            if (fedge->second != it) {
                tri_map[it][3]=fedge->second;
                break;
            }
        }
    }

    std::map<std::pair<ChNodeFEAxyz*,ChNodeFEAxyz*>, std::pair<int,int>> winged_edges;
    bool allow_single_wing = true;

    for ( auto aedge = edge_map.begin(); aedge != edge_map.end(); ++aedge ) {
        auto ret = edge_map.equal_range(aedge->first);
        int nt=0;
        std::pair<ChNodeFEAxyz*,ChNodeFEAxyz*> wingedge;
        std::pair<int,int> wingtri;
        wingtri.first = -1;
        wingtri.second = -1;
        for (auto fedge=ret.first; fedge!=ret.second; ++fedge) {
            if (fedge->second == -1)
                break;
            wingedge.first = fedge->first.first;
            wingedge.second= fedge->first.second;
            if (nt==0)
                wingtri.first  = fedge->second;
            if (nt==1)
                wingtri.second = fedge->second;
            ++nt;
            if (nt==2)
                break;
        }
        if ((nt==2) || ((nt==1) && allow_single_wing) ) {
            winged_edges.insert(std::pair<std::pair<ChNodeFEAxyz*,ChNodeFEAxyz*>, std::pair<int,int>>(wingedge,wingtri)); // ok found winged edge!
            aedge->second = -1; // deactivate this way otherwise found again by sister
        }
    }

    //
    // Now create triangles with collision models:
    //

    std::set<ChNodeFEAxyz*> added_vertexes;

    // iterate on triangles
    for (int it = 0; it < triangles.size(); ++it) {
        // edges = pairs of vertexes indexes
        std::pair<ChNodeFEAxyz*, ChNodeFEAxyz*> medgeA( triangles[it][0],  triangles[it][1]);
        std::pair<ChNodeFEAxyz*, ChNodeFEAxyz*> medgeB( triangles[it][1],  triangles[it][2]);
        std::pair<ChNodeFEAxyz*, ChNodeFEAxyz*> medgeC( triangles[it][2],  triangles[it][0]);
        // vertex indexes in edges: always in increasing order to avoid ambiguous duplicated edges
        if (medgeA.first>medgeA.second)
            medgeA = std::pair<ChNodeFEAxyz*, ChNodeFEAxyz*>(medgeA.second, medgeA.first);
        if (medgeB.first>medgeB.second)
            medgeB = std::pair<ChNodeFEAxyz*, ChNodeFEAxyz*>(medgeB.second, medgeB.first);
        if (medgeC.first>medgeC.second)
            medgeC = std::pair<ChNodeFEAxyz*, ChNodeFEAxyz*>(medgeC.second, medgeC.first);
        auto wingedgeA = winged_edges.find(medgeA);
        auto wingedgeB = winged_edges.find(medgeB);
        auto wingedgeC = winged_edges.find(medgeC);

        ChNodeFEAxyz* i_wingvertex_A = 0;
        ChNodeFEAxyz* i_wingvertex_B = 0;
        ChNodeFEAxyz* i_wingvertex_C = 0;

        if (tri_map[it][1] != -1) {
            i_wingvertex_A = triangles[tri_map[it][1]][0];
            if (triangles[tri_map[it][1]][1] != wingedgeA->first.first && triangles[tri_map[it][1]][1] != wingedgeA->first.second)
                i_wingvertex_A = triangles[tri_map[it][1]][1];
            if (triangles[tri_map[it][1]][2] != wingedgeA->first.first && triangles[tri_map[it][1]][2] != wingedgeA->first.second)
                i_wingvertex_A = triangles[tri_map[it][1]][2];
        }

        if (tri_map[it][2] != -1) {
            i_wingvertex_B =triangles[tri_map[it][2]][0];
            if (triangles[tri_map[it][2]][1] != wingedgeB->first.first && triangles[tri_map[it][2]][1] != wingedgeB->first.second)
                i_wingvertex_B = triangles[tri_map[it][2]][1];
            if (triangles[tri_map[it][2]][2] != wingedgeB->first.first && triangles[tri_map[it][2]][2] != wingedgeB->first.second)
                i_wingvertex_B = triangles[tri_map[it][2]][2];
        }

        if (tri_map[it][3] != -1) {
            i_wingvertex_C = triangles[tri_map[it][3]][0];
            if (triangles[tri_map[it][3]][1] != wingedgeC->first.first && triangles[tri_map[it][3]][1] != wingedgeC->first.second)
                i_wingvertex_C = triangles[tri_map[it][3]][1];
            if (triangles[tri_map[it][3]][2] != wingedgeC->first.first && triangles[tri_map[it][3]][2] != wingedgeC->first.second)
                i_wingvertex_C = triangles[tri_map[it][3]][2];
        }

        ChSharedPtr<ChContactTriangleXYZ> contact_triangle (new ChContactTriangleXYZ);
        contact_triangle->SetNode1(triangles_ptrs[it][0]);
        contact_triangle->SetNode2(triangles_ptrs[it][1]);
        contact_triangle->SetNode3(triangles_ptrs[it][2]);
        this->vfaces.push_back(contact_triangle);
        contact_triangle->SetContactSurface(this);

        contact_triangle->GetCollisionModel()->ClearModel();
        ((collision::ChModelBullet*)contact_triangle->GetCollisionModel())->AddTriangleProxy(
                                &triangles[it][0]->pos,
                                &triangles[it][1]->pos,
                                &triangles[it][2]->pos,
                                // if no wing vertex (ie. 'free' edge), point to opposite vertex, ie vertex in triangle not belonging to edge
                                wingedgeA->second.second != -1 ? &i_wingvertex_A->pos : &triangles[it][2]->pos,
                                wingedgeB->second.second != -1 ? &i_wingvertex_B->pos : &triangles[it][0]->pos,
                                wingedgeC->second.second != -1 ? &i_wingvertex_C->pos : &triangles[it][1]->pos,
                                (added_vertexes.find(triangles[it][0]) == added_vertexes.end()),
                                (added_vertexes.find(triangles[it][1]) == added_vertexes.end()),
                                (added_vertexes.find(triangles[it][2]) == added_vertexes.end()),
                                // are edges owned by this triangle? (if not, they belong to a neighbouring triangle)
                                wingedgeA->second.first != -1,
                                wingedgeB->second.first != -1,
                                wingedgeC->second.first != -1,
                                sphere_swept);
        contact_triangle->GetCollisionModel()->BuildModel();

        // Mark added vertexes
        added_vertexes.insert( triangles[it][0] );
        added_vertexes.insert( triangles[it][1] );
        added_vertexes.insert( triangles[it][2] );
        // Mark added edges, setting to -1 the 'ti' id of 1st triangle in winged edge {{vi,vj}{ti,tj}}
        wingedgeA->second.first = -1;
        wingedgeB->second.first = -1;
        wingedgeC->second.first = -1;
    }

}

void ChContactSurfaceMesh::SurfaceSyncCollisionModels() {
    for (unsigned int j = 0; j < vfaces.size(); j++) {
        this->vfaces[j]->GetCollisionModel()->SyncPosition();
    }
}

void ChContactSurfaceMesh::SurfaceAddCollisionModelsToSystem(ChSystem* msys) {
    assert(msys);
    SurfaceSyncCollisionModels();
    for (unsigned int j = 0; j < vfaces.size(); j++) {
        msys->GetCollisionSystem()->Add(this->vfaces[j]->GetCollisionModel());
    }
}

void ChContactSurfaceMesh::SurfaceRemoveCollisionModelsFromSystem(ChSystem* msys) {
    assert(msys);
    for (unsigned int j = 0; j < vfaces.size(); j++) {
        msys->GetCollisionSystem()->Remove(this->vfaces[j]->GetCollisionModel());
    }
}

} // END_OF_NAMESPACE____
} // END_OF_NAMESPACE____


text:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Store } from '@ngrx/store';
import { TranslateService } from '@ngx-translate/core';
import { Config, IsoLanguage } from '../../core/index';
import { IAppState } from '../../ngrx';
import { SetLanguageResponse } from '../multilingual.interfaces';

@Injectable()
export class MultilingualService {
  // default supported languages
  // see app.module.ts for example of how to provide different value
  public static SUPPORTED_LANGUAGES: IsoLanguage[] = [
    { code: 'en', name: 'English', nativeName: 'English' },
  ];

  constructor(private translate: TranslateService,
              private store: Store<IAppState>,
              private http: HttpClient) {

    // this language will be used as a fallback when a translation isn't found in the current language
    translate.setDefaultLang('en');

    // subscribe to changes
    store.select('i18n').subscribe(state => {
      // for unit tests
      if (!state) {
        state = {
          lang: 'en',
        };
      }
      // update ng2-translate which will cause translations to occur wherever the TranslatePipe is used in the view
      this.translate.use(state.lang);
    });
  }

  public languageChanged(language: string) {
    return this.http.put<SetLanguageResponse>(`${Config.API_URL}/language`, { language: language });
  }
}


text:
/**
 * @flow
 */

import React from 'react';
import ReactDOM from 'react-dom';
import { remote } from 'electron';

import RootApp from './ui/RootApp';

const rootNode = document.getElementById('app');
const commandLineArgs = remote.getCurrentWindow().commandLineArgs;

ReactDOM.render(<RootApp segment={window.analytics} commandLineArgs={commandLineArgs} />, rootNode);

window.addEventListener('beforeunload', () => {
  ReactDOM.unmountComponentAtNode(rootNode);
});


text:
import { isFunction, isString } from 'inferno-shared';
import { EMPTY_OBJ } from '../utils/common';

function triggerEventListener(props, methodName, e) {
  if (props[methodName]) {
    const listener = props[methodName];

    if (listener.event) {
      listener.event(listener.data, e);
    } else {
      listener(e);
    }
  } else {
    const nativeListenerName = methodName.toLowerCase();

    if (props[nativeListenerName]) {
      props[nativeListenerName](e);
    }
  }
}

export function createWrappedFunction(methodName: string | string[], applyValue?: Function): Function {
  const fnMethod = function (e) {
    const vNode = this.$V;
    // If vNode is gone by the time event fires, no-op
    if (!vNode) {
      return;
    }
    const props = vNode.props || EMPTY_OBJ;
    const dom = vNode.dom;

    if (isString(methodName)) {
      triggerEventListener(props, methodName, e);
    } else {
      for (let i = 0; i < methodName.length; ++i) {
        triggerEventListener(props, methodName[i], e);
      }
    }

    if (isFunction(applyValue)) {
      const newVNode = this.$V;
      const newProps = newVNode.props || EMPTY_OBJ;

      applyValue(newProps, dom, false, newVNode);
    }
  };

  Object.defineProperty(fnMethod, 'wrapped', {
    configurable: false,
    enumerable: false,
    value: true,
    writable: false
  });

  return fnMethod;
}


text:
namespace Virtuoso{

///the SimpleLog is just a Virtuoso::BaseLog that uses a single ostream for all write operations.
///the default c-tor uses cout by default, but can be changed later.
class SimpleLog:public BaseLog{

    std::ostream* os;
public:
    //default to cout
    SimpleLog()
    :os(&std::cout)
    {
    }

    //construct with a particular stream
    SimpleLog(std::ostream& str):os(&str){
    }

    ///overwrite the stream
    void  setStream(std::ostream& str){
        os = &str;
    }

    inline virtual std::ostream& status(){
        return *os;
    }

    inline virtual std::ostream& error(){
        return *os;
    }

    inline virtual std::ostream& echo(){
        return *os;
    }

    inline virtual std::ostream& warning(){
        return *os;
    }

};

}
#endif // SIMPLELOG_H_INCLUDED


text:
title: The One Remote Person
tags: team, meetings, remote
cover_image: https://source.unsplash.com/IwLV8c2XwVw/1400x900
---
Often consultants bring a fantasy of co-located teams to their clients. This is a fantasy because companies have been using remote workforces for the entirety of my career, so thinking that will change is silly.  In this particular article, I want to focus on one tiny aspect of a fairly standard setup—a single remote worker with a significant time difference.

## Are They on the Team?

As it turns out, there is a bit of a trickiness in making this one remote person feel like they are part of the team. Often there is a bit of a paradox that is built-in as well.

How do we make them part of the team but not exhaust them or their hours if they're a contractor (As they often are)?

I think it is natural to want the benefits of them being part of the team in terms of cohesion and some form of seamlessness in how work flows. How we exactly accomplish that is where we go next.

## Talk To Everyone

Yep, there's the simple answer. I've done this with multiple clients over the years, but most of the time, nobody made explicit how this arrangement is exactly going to work.

The remote person doesn't know what they should and shouldn't be a part of and feels isolated. The core group feels strange leaving them out but assumes this is what is preferred.

Both sides fumble around, not knowing how to work together.

So I have a conversation with each group independently. I find out what the desired working conditions are for each.

Now, almost always, the core group and leadership are comfortable with whatever keeps people effective without going over their hours if they're a contractor.

The contractor is almost always comfortable with just getting some information about the significant decisions and having a voice.

## Formalize the Agreement

It's one thing to have a few conversations behind closed doors and reach a conclusion, but the final step is to make the agreement explicit with everyone.

Recently, for example, I did this with a client, and in a meeting with everyone, I told everyone what we decided.

There was a sigh of relief, and a few people were surprised that their assumptions were wrong about how the contractor wanted to be involved.

Formalizing the agreement doesn't have to be more complex than just informing everyone as to the specifics—most of the time, that includes someone telling the remote person about the decision.

## Better Teams No Matter Where

This is a tiny little article, but I've seen this configuration too many times to ignore. Also, great teams happen when everyone knows what everyone else is bringing to the table.

A few quick conversations might be all it takes to remove the fumbling around a single remote worker who only wanted to remain informed of key decisions.


text:
/**
 * @author Jon Carey
 * @author Dan Nuffer
 */

#include "OW_config.h"
#include "OW_StringStream.hpp"

namespace OW_NAMESPACE
{

///////////////////////////////////////////////////////////////////////////////
OStringStreamBuf::OStringStreamBuf(size_t size)
	: BaseStreamBuffer(size, "out"), m_buf(size)
{
}
///////////////////////////////////////////////////////////////////////////////
OStringStreamBuf::~OStringStreamBuf()
{
}
///////////////////////////////////////////////////////////////////////////////
String OStringStreamBuf::toString() const
{
	return m_buf.toString();
}
///////////////////////////////////////////////////////////////////////////////
String OStringStreamBuf::releaseString()
{
	return m_buf.releaseString();
}
///////////////////////////////////////////////////////////////////////////////
size_t OStringStreamBuf::length() const
{
	return m_buf.length();
}
///////////////////////////////////////////////////////////////////////////////
const char* OStringStreamBuf::c_str() const
{
	return m_buf.c_str();
}
///////////////////////////////////////////////////////////////////////////////
void OStringStreamBuf::reset()
{
	m_buf.reset();
}
///////////////////////////////////////////////////////////////////////////////
int OStringStreamBuf::buffer_to_device(const char *c, int n)
{
	m_buf.append(c, n);
	return 0;
}
///////////////////////////////////////////////////////////////////////////////
OStringStreamBase::OStringStreamBase(size_t sz)
	: m_buf(sz)
{
}
///////////////////////////////////////////////////////////////////////////////
OStringStream::OStringStream(size_t size)
	: OStringStreamBase(size)
	, std::basic_ostream<char, std::char_traits<char> >(&m_buf)
{
}
///////////////////////////////////////////////////////////////////////////////
OStringStream::~OStringStream()
{
}
///////////////////////////////////////////////////////////////////////////////
OStringStream::OStringStream(const OStringStream& ostr)
#if !defined(__GNUC__) || __GNUC__ > 2
	: std::basic_ios<char>()
#else
	: std::ios() // gcc 2.95.x broken library.
#endif
	, OStringStreamBase(ostr.length())
	, std::basic_ostream<char, std::char_traits<char> >(&m_buf)
{
	*this << ostr.toString();
}
///////////////////////////////////////////////////////////////////////////////
OStringStream& OStringStream::operator=(const OStringStream& ostr)
{
	if ( &ostr != this )
	{
		this->reset();
		*this << ostr.toString();
	}
	return *this;
}

///////////////////////////////////////////////////////////////////////////////
String OStringStream::toString() const
{
	m_buf.sync();
	return m_buf.toString();
}
///////////////////////////////////////////////////////////////////////////////
String OStringStream::releaseString()
{
	m_buf.sync();
	return m_buf.releaseString();
}
///////////////////////////////////////////////////////////////////////////////
size_t OStringStream::length() const
{
	m_buf.sync();
	return m_buf.length();
}
///////////////////////////////////////////////////////////////////////////////
const char* OStringStream::c_str() const
{
	m_buf.sync();
	return m_buf.c_str();
}
///////////////////////////////////////////////////////////////////////////////
void OStringStream::reset()
{
	m_buf.reset();
}

} // end namespace OW_NAMESPACE