text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.SessionState;
using Newtonsoft.Json.Linq;
using RestSharp;
using System.Web;
using Maestrano.Configuration;

namespace Maestrano.Sso
{
    public class Session
    {
        private Configuration.Sso ssoConfiguration;
        public string Uid { get; set; }
        public string GroupUid { get; set; }
        public DateTime Recheck { get; set; }
        public string SessionToken { get; set; }
        public HttpSessionStateBase HttpSession { get; set; }

        /// <summary>
        /// Initialize the Session
        /// </summary>
        /// <returns></returns>
        public Session(Preset preset, HttpSessionState httpSessionObj = null) : this(preset.Sso, new HttpSessionStateWrapper(httpSessionObj))
        {
        }

        /// <summary>
        /// Initialize the Session
        /// </summary>
        /// <returns></returns>
        public Session(Preset preset, HttpSessionState httpSessionObj, User user) : this(preset.Sso, new HttpSessionStateWrapper(httpSessionObj), user)
        {
        }

        /// <summary>
        /// Initialize the Session
        /// </summary>
        /// <returns></returns>
        public Session(Configuration.Sso ssoConfiguration, HttpSessionState httpSessionObj = null) : this(ssoConfiguration, new HttpSessionStateWrapper(httpSessionObj))
        {
        }

        /// <summary>
        /// Initialize the Session
        /// </summary>
        /// <returns></returns>
        public Session(Configuration.Sso ssoConfiguration, HttpSessionState httpSessionObj, User user) : this(ssoConfiguration, new HttpSessionStateWrapper(httpSessionObj), user)
        {
        }

        /// <summary>
        /// Initialize the Session
        /// </summary>
        /// <returns></returns>
        public Session(Configuration.Sso ssoConfiguration, HttpSessionStateBase httpSessionObj = null)
        {
            this.ssoConfiguration = ssoConfiguration;
            HttpSession = httpSessionObj;
            if (HttpSession != null && HttpSession[ssoConfiguration.Marketplace] != null)
            {
                var enc = System.Text.Encoding.UTF8;
                JObject sessionObject = new JObject();
                try
                {
                    string decryptedMnoSession = enc.GetString(Convert.FromBase64String(HttpSession[ssoConfiguration.Marketplace].ToString()));
                    sessionObject = JObject.Parse(decryptedMnoSession);
                }
                catch (Exception) { }

                // Assign attributes
                Uid = sessionObject.Value<String>("uid");
                GroupUid = sessionObject.Value<String>("group_uid");
                SessionToken = sessionObject.Value<String>("session");

                // Session Recheck
                try
                {
                    Recheck = sessionObject.Value<DateTime>("session_recheck");
                }
                catch (Exception) { }

                if (Recheck == null)
                    Recheck = DateTime.UtcNow.AddMinutes(-1);
            }

        }

        /// <summary>
        /// Initializer retrieving maestrano session from user
        /// </summary>
        /// <param name="httpSessionObj"></param>
        /// <param name="user"></param>
        public Session(Configuration.Sso ssoConfiguration, HttpSessionStateBase httpSessionObj, User user)
        {
            this.ssoConfiguration = ssoConfiguration;
            HttpSession = httpSessionObj;

            if (user != null)
            {
                Uid = user.Uid;
                GroupUid = user.GroupUid;
                SessionToken = user.SsoSession;
                Recheck = user.SsoSessionRecheck;
            }
        }

        /// <summary>
        /// Returns whether the session needs to be checked
        /// remotely from maestrano or not
        /// </summary>
        /// <returns></returns>
        public Boolean isRemoteCheckRequired()
        {
            if (Uid != null && SessionToken != null && Recheck != null)
            {
                return (Recheck.CompareTo(DateTime.UtcNow) <= 0);
            }
            return true;
        }

        /// <summary>
        /// Check whether the remote maestrano session is still
        /// valid
        /// </summary>
        /// <param name="client"></param>
        /// <returns></returns>
        public Boolean PerformRemoteCheck(RestClient client)
        {
            if (Uid != null && SessionToken != null && Uid.Length > 0 && SessionToken.Length > 0)
            {
                // Prepare request
                var request = new RestRequest("api/v1/auth/saml/{id}", Method.GET);
                request.AddUrlSegment("id", Uid);
                request.AddParameter("session", SessionToken);
                JObject resp = new JObject();
                try {
                    resp = JObject.Parse(client.Execute(request).Content);
                }
                catch (Exception) { }

                bool valid = Convert.ToBoolean(resp.Value<String>("valid"));
                DateTime dateResp = resp.Value<DateTime>("recheck");
                if ( valid && dateResp != null)
                {
                    Recheck = dateResp;
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// Check whether the remote maestrano session is still
        /// valid
        /// </summary>
        /// <returns></returns>
        public Boolean PerformRemoteCheck()
        {
            var client = new RestClient(ssoConfiguration.Idp);
            return PerformRemoteCheck(client);
        }

        /// <summary>
        /// Return wether the session is valid or not. Perform
        /// remote check to maestrano if recheck is overdue.
        /// </summary>
        /// <param name="client"></param>
        /// <param name="ifSession"></param>
        /// <returns></returns>
        public Boolean IsValid(RestClient client, Boolean ifSession = false)
        {
            // Return true if maestrano session not set
            // and ifSession option enabled
            if (ifSession && (HttpSession == null || HttpSession[ssoConfiguration.Marketplace] == null))
                return true;

            // Return false if HttpSession is nil
            if (HttpSession == null)
                return false;

            if (isRemoteCheckRequired())
            {
                if (PerformRemoteCheck(client))
                {
                    Save();
                    return true;
                }
                else
                {
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// return the Maestrano logout url to be used for redirecting a user after logout
        /// </summary>
        public string LogoutUrl()
        {
            return ssoConfiguration.LogoutUrl(this.Uid);
        }

        /// <summary>
        /// Return wether the session is valid or not. Perform
        /// remote check to maestrano if recheck is overdue.
        /// </summary>
        /// <param name="ifSession">If set to true then session return false ONLY if maestrano session exists and is invalid</param>
        /// <returns></returns>
        public Boolean IsValid(Boolean ifSession = false)
        {
            var client = new RestClient(ssoConfiguration.Idp);
            return IsValid(client,ifSession);
        }

        /// <summary>
        /// Save the Maestrano session in
        /// HTTP Session
        /// </summary>
        public void Save()
        {
            var enc = System.Text.Encoding.UTF8;
            JObject sessionObject = new JObject(
                new JProperty("uid",Uid),
                new JProperty("session",SessionToken),
                new JProperty("session_recheck",Recheck.ToString("s")),
                new JProperty("group_uid",GroupUid));

            // Finally store the maestrano session
            HttpSession[ssoConfiguration.Marketplace] = Convert.ToBase64String(enc.GetBytes(sessionObject.ToString()));
        }

    }
}


text:
define(
    function (require) {
        var etpl = require( 'etpl' );
        var readText = require( 'readTextSync' );
        var text = readText( 'spec/simpleTarget.text.html' );

        var render = etpl.compile( text['normal'] );
        var renderAutoclose = etpl.compile( text['auto-close'] );

        describe('Simple Target', function() {
            it('should parse correctly when closed manually', function() {
                expect(render({})).toEqual(text.expect);
                expect(render).toBe(etpl.getRenderer('simpleTarget'));
            });

            it('should parse correctly when auto closed', function() {
                expect(renderAutoclose({})).toEqual(text.expect);
                expect(renderAutoclose).toBe(etpl.getRenderer('simpleTarget-autoclose'));
            });
        });
    }
);

redpajama_set_name: RedPajamaGithub


text:
from generator.actions import Actions
import random
import subprocess
import string
import struct

MAX_NUM_MSG = 100
MAX_NUM_USERS = 999
TYPE_PROTECTED = 1
TYPE_NORMAL = 0

p = lambda f,x: struct.pack(f,x)

def random_string(size=20):
  return ''.join([random.choice(string.ascii_letters) for x in xrange(random.randint(1,size))])

class LulzChat(Actions):
  def start(self):
    self.user_id = 1
    self.state['users'] = list()
    self.state['messages'] = list()
    self.state['current_user'] = None

    welcome_str = "[INFO] LulzChat Client v0.1\n[INFO] Type 'h' for help menu\n"
    self.read(length=len(welcome_str), expect=welcome_str)

  def menu(self):
    self.read(length=2, expect='> ')

  def help(self):
    help_str = "---- Commands --------------------\n" + \
               " 'h'elp - display this help menu\n" +   \
               " 'r'egister - register a user\n" +      \
               " 'l'ogin - login\n" +                   \
               " 'o'ut - logout\n" +                    \
               " 'e'numerate - list messages\n" +       \
               " 'v'iew - view a message\n" +           \
               " 's'end - send a message\n" +           \
               " 'd'elete - delete a message\n" +       \
               " 'q'uit - quit\n" +                     \
               "----------------------------------\n"
    if self.chance(0.25):
      self.write('h\n')
    elif self.chance(0.25):
      self.write('H\n')
    elif self.chance(0.25):
      self.write('help\n')
    else:
      self.write('HELP\n')
    self.read(length=len(help_str), expect=help_str);

  def register(self):
    if self.chance(0.25):
      self.write('r\n')
    elif self.chance(0.25):
      self.write('R\n')
    elif self.chance(0.25):
      self.write('register\n')
    else:
      self.write('REGISTER\n')

    username = random_string(random.randint(1,63))
    password = random_string(random.randint(1,63))

    self.read(length=len('\n[[[ REGISTER ]]]\n'), expect='\n[[[ REGISTER ]]]\n')
    self.read(length=len('- username: '), expect='- username: ')
    self.write(username + '\n')
    self.read(length=len('- password: '), expect='- password: ')
    self.write(password + '\n')
    self.read(length=len('- password confirm: '), expect='- password confirm: ')
    self.write(password + '\n')
    self.read(length=1, expect='\n')

    # server logic
    if any(user['username'] == username for user in self.state['users']):
      self.read(length=len('[ERROR] Username already exists.\n'), expect='[ERROR] Username already exists.\n')
      return
    if len(self.state['users']) == MAX_NUM_USERS:
      self.read(length=len('[ERROR] Registration Failed..\n'), expect='[ERROR] Registration Failed..\n')
      return

    self.read(length=len('[INFO] Registration Successful! (%s)\n' % username), expect='[INFO] Registration Successful! (%s)\n' % username)
    self.state['users'].append({'username': username, 'password': password, 'user_id': self.user_id})
    self.user_id += 1

  def login(self):
    in_db = False
    user = None
    if self.chance(0.25):
      self.write('l\n')
    elif self.chance(0.25):
      self.write('L\n')
    elif self.chance(0.25):
      self.write('login\n')
    else:
      self.write('LOGIN\n')

    if self.chance(0.10) or len(self.state['users']) == 0:
      username = random_string(random.randint(1,63))
      password = random_string(random.randint(1,63))
    else:
      user = random.choice(self.state['users'])
      username = user['username']
      password = user['password']
      in_db = True
    self.read(length=len('\n[[[ LOGIN ]]]\n'), expect='\n[[[ LOGIN ]]]\n')
    self.read(length=len('- username: '), expect='- username: ')
    self.write(username + '\n')
    self.read(length=len('- password: '), expect='- password: ')
    self.write(password + '\n')

    # server logic
    if in_db:
      self.read(length=len('[INFO] Login Successful!\n'), expect='[INFO] Login Successful!\n')
      if self.state['current_user'] != None:
        self.read(length=len('[INFO] Successfully logged out.\n'), expect='[INFO] Successfully logged out.\n')
      self.state['current_user'] = user
    else:
      self.read(length=len('[ERROR] Login Failed.\n'), expect='[ERROR] Login Failed.\n')

  def logout(self):
    if self.chance(0.25):
      self.write('o\n')
    elif self.chance(0.25):
      self.write('O\n')
    elif self.chance(0.25):
      self.write('out\n')
    else:
      self.write('OUT\n')

    if self.state['current_user']:
      self.read(length=len('[INFO] Successfully logged out.\n'), expect='[INFO] Successfully logged out.\n')
      self.state['current_user'] = None
    else:
      self.read(length=len('[ERROR] Not logged in.\n'), expect='[ERROR] Not logged in.\n')

  def list(self):
    if self.chance(0.25):
      self.write('e\n')
    elif self.chance(0.25):
      self.write('E\n')
    elif self.chance(0.25):
      self.write('enumerate\n')
    else:
      self.write('ENUMERATE\n')

    if self.state['current_user'] == None:
      self.read(length=len('[ERROR] Login first, please.\n'), expect='[ERROR] Login first, please.\n')
      return

    self.read(length=len('\n[[[ MESSAGES ]]]\n'), expect='\n[[[ MESSAGES ]]]\n')
    self.read(length=len('idx. <from_id, length, type>\n'), expect='idx. <from_id, length, type>\n')
    self.read(length=len('----------------------------\n'), expect='----------------------------\n')
    tmp_list =  filter(lambda m: m['to_id'] == self.state['current_user']['user_id'], self.state['messages'])

    for i in xrange(min(len(tmp_list), MAX_NUM_MSG)):
      m = tmp_list[i]
      if (m['type'] == TYPE_PROTECTED):
        es = '%d. <%d, N/A, Protected>\n' % (i+1, m['from_id'])
      else:
        es = '%d. <%d, %d bytes, Normal>\n' % (i+1, m['from_id'], m['text_len'])
      self.read(length=len(es), expect=es)
    ts = 'Total %d message(s).\n\n' % len(tmp_list)
    self.read(length=len(ts), expect=ts)

  def view(self):
    if self.chance(0.25):
      self.write('v\n')
    elif self.chance(0.25):
      self.write('V\n')
    elif self.chance(0.25):
      self.write('view\n')
    else:
      self.write('VIEW\n')

    if self.state['current_user'] == None:
      self.read(length=len('[ERROR] Login first, please.\n'), expect='[ERROR] Login first, please.\n')
      return

    self.read(length=len('\n[[[ MESSAGES ]]]\n'), expect='\n[[[ MESSAGES ]]]\n')
    self.read(length=len('idx. <from_id, length, type>\n'), expect='idx. <from_id, length, type>\n')
    self.read(length=len('----------------------------\n'), expect='----------------------------\n')
    tmp_list =  filter(lambda m: m['to_id'] == self.state['current_user']['user_id'], self.state['messages'])

    for i in xrange(min(len(tmp_list), MAX_NUM_MSG)):
      m = tmp_list[i]
      if (m['type'] == TYPE_PROTECTED):
        es = '%d. <%d, N/A, Protected>\n' % (i+1, m['from_id'])
      else:
        es = '%d. <%d, %d bytes, Normal>\n' % (i+1, m['from_id'], m['text_len'])
      self.read(length=len(es), expect=es)
    ts = 'Total %d message(s).\n\n' % len(tmp_list)
    self.read(length=len(ts), expect=ts)

    if len(tmp_list) == 0:
      self.read(length=len('[INFO] You have no message.\n'), expect='[INFO] You have no message.\n')
      return

    self.read(length=len('Select idx > '), expect='Select idx > ')
    select = random.randint(1, len(tmp_list))
    self.write('%d\n' % select)
    self.read(length=1, expect='\n')

    m = tmp_list[select - 1]
    fs = 'From: USER_%d\n' % m['from_id']
    self.read(length=len(fs), expect=fs)
    ts = 'Type: %s\n' % ('Protected' if m['type'] == TYPE_PROTECTED else 'Normal')
    self.read(length=len(ts), expect=ts)
    ls = 'Length: %d byte(s)\n' % len(m['text'])
    self.read(length=len(ls), expect=ls)
    ms = 'Message: %s\n' % m['text']
    self.read(length=len(ms), expect=ms)

  def send(self):
    in_db = False
    if self.chance(0.25):
      self.write('s\n')
    elif self.chance(0.25):
      self.write('S\n')
    elif self.chance(0.25):
      self.write('send\n')
    else:
      self.write('SEND\n')

    if self.state['current_user'] == None:
      self.read(length=len('[ERROR] Login first, please.\n'), expect='[ERROR] Login first, please.\n')
      return

    self.read(length=len('\n[[[ SEND ]]]\n'), expect='\n[[[ SEND ]]]\n')
    self.read(length=len(' - To: '), expect=' - To: ')

    if self.chance(0.10) or len(self.state['users']) == 0:
      target = random_string(random.randint(1, 63))
    else:
      user = random.choice(self.state['users'])
      target = user['username']
      in_db = True
    self.write(target + '\n')

    self.read(length=len(' - Type (0: normal, 1: protected): '), expect=' - Type (0: normal, 1: protected): ')
    if self.chance(0.50):
      t = TYPE_PROTECTED
    else:
      t = TYPE_NORMAL
    self.write('%d\n' % t)

    self.read(length=len(' - Message: '), expect=' - Message: ')
    msg = random_string(random.randint(1, 511))
    self.write(msg + '\n')
    self.read(length=1, expect='\n')

    to_id = 0
    for u in self.state['users']:
      if u['username'] == target:
        to_id = u['user_id']
        break
    from_id = self.state['current_user']['user_id']
    if to_id == 0:
      self.read(length=len('[ERROR] Send Failed.\n'), expect='[ERROR] Send Failed.\n')
      return
    self.state['messages'].append({'type': t, 'to_id': to_id, 'from_id': from_id, 'text_len': len(msg), 'text': msg})

  def delete(self):
    if self.chance(0.25):
      self.write('d\n')
    elif self.chance(0.25):
      self.write('D\n')
    elif self.chance(0.25):
      self.write('delete\n')
    else:
      self.write('DELETE\n')

    if self.state['current_user'] == None:
      self.read(length=len('[ERROR] Login first, please.\n'), expect='[ERROR] Login first, please.\n')
      return

    self.read(length=len('\n[[[ MESSAGES ]]]\n'), expect='\n[[[ MESSAGES ]]]\n')
    self.read(length=len('idx. <from_id, length, type>\n'), expect='idx. <from_id, length, type>\n')
    self.read(length=len('----------------------------\n'), expect='----------------------------\n')
    tmp_list =  filter(lambda m: m['to_id'] == self.state['current_user']['user_id'], self.state['messages'])

    for i in xrange(min(len(tmp_list), MAX_NUM_MSG)):
      m = tmp_list[i]
      if (m['type'] == TYPE_PROTECTED):
        es = '%d. <%d, N/A, Protected>\n' % (i+1, m['from_id'])
      else:
        es = '%d. <%d, %d bytes, Normal>\n' % (i+1, m['from_id'], m['text_len'])
      self.read(length=len(es), expect=es)
    ts = 'Total %d message(s).\n\n' % len(tmp_list)
    self.read(length=len(ts), expect=ts)

    if len(tmp_list) == 0:
      self.read(length=len('[INFO] You have no message.\n'), expect='[INFO] You have no message.\n')
      return

    self.read(length=len('Select idx > '), expect='Select idx > ')
    select = random.randint(1, len(tmp_list))
    self.write('%d\n' % select)
    self.read(length=1, expect='\n')

    to_remove = tmp_list[select-1]
    self.state['messages'].remove(to_remove)
    self.read(length=len('[INFO] Successfully deleted.\n'), expect='[INFO] Successfully deleted.\n')
    ns = '%d message(s) left.\n' % (len(tmp_list) - 1)
    self.read(length=len(ns), expect=ns)

  def quit(self):
    if self.chance(0.25):
      self.write('q\n')
    elif self.chance(0.25):
      self.write('Q\n')
    elif self.chance(0.25):
      self.write('quit\n')
    else:
      self.write('QUIT\n')
    self.read(length=12, expect='[INFO] Bye!\n')


text:
"""Test preproc."""

import mne
import pytest
import os.path as op
import numpy as np

import nipype.pipeline.engine as pe

from ephypype.interfaces.mne.spectral import TFRmorlet

import matplotlib
matplotlib.use('Agg')  # for testing don't use X server

data_path = mne.datasets.testing.data_path()
raw_fname = op.join(data_path, 'MEG', 'sample',
                    'sample_audvis_trunc_raw.fif')
events_file = op.join(data_path, 'MEG', 'sample',
                      'sample_audvis_trunc_raw-eve.fif')

@pytest.mark.usefixtures("change_wd")
def test_tfr():
    """Test time-frequency transform (PSD and ITC)."""

    # create epoched data
    raw = mne.io.read_raw_fif(raw_fname)
    picks = mne.pick_types(raw.info, meg=True, eeg=False, eog=False,
                           stim=False, exclude='bads')
    # Define and read epochs:
    events = mne.find_events(raw, stim_channel='STI 014')
    # Define epochs parameters:
    event_id = dict(aud_l=1, aud_r=2)  # event trigger and conditions
    tmin = -0.2  # start of each epoch (200ms before the trigger)
    tmax = 0.5  # end of each epoch (500ms after the trigger)
    epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True,
                        picks=picks, baseline=(None, 0), preload=False)
    # Save all epochs in a fif file:
    epo_fname = raw_fname.replace('.fif', '-epo.fif')
    epochs.save(epo_fname, overwrite=True)

    # Test
    freqs = np.arange(6, 20, 5)
    compute_tfr_morlet = pe.Node(interface=TFRmorlet(), name='tfr_morlet')
    compute_tfr_morlet.inputs.freqs = freqs
    compute_tfr_morlet.inputs.n_cycles = freqs / 4.
    compute_tfr_morlet.inputs.epo_file = epo_fname

    compute_tfr_morlet.run()

    assert compute_tfr_morlet.result.outputs.power_file


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>BinaryStream (Hibernate JavaDocs)</title>
<meta name="date" content="2014-03-03">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.hibernate.engine.jdbc

Interface BinaryStream

All Known Implementing Classes:

BinaryStreamImpl

public interface BinaryStream

Wraps a binary stream to also provide the length which is needed when binding.

Method Summary

Methods

Modifier and Type
Method and Description

byte[]
getBytes()

InputStream
getInputStream()

long
getLength()

void
release()

Method Detail

getInputStream

InputStream getInputStream()

Retrieve the input stream.

Returns:

The input stream

getBytes

byte[] getBytes()

Access to the bytes.

Returns:

The bytes.

getLength

long getLength()

Retrieve the length of the input stream

Returns:

The input stream length

release

void release()

Release any underlying resources.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2001-2014 Red Hat, Inc.  All Rights Reserved.


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Wyam.Common.Documents;
using Wyam.Common.IO;

namespace Wyam.Common.Meta
{
    ///
    /// Common metadata keys for modules in the core library.
    ///
    public static class Keys
    {
        ///
        /// The host to use when generating links.
        ///
        /// <type><see cref="string"/></type>
        public const string Host = nameof(Host);

        ///
        /// Indicates if generated links should use HTTPS instead of HTTP as the scheme.
        ///
        /// <type><see cref="bool"/></type>
        public const string LinksUseHttps = nameof(LinksUseHttps);

        ///
        /// The default root path to use when generating links
        /// (for example, "/virtual/directory").
        /// Note that you may also want to use the --virtual-dir
        /// argument on the command line when using this setting so that
        /// the preview server serves the site at the same path as the generated links
        /// (for example, --virtual-dir "/virtual/directory").
        ///
        /// <type><see cref="string"/></type>
        public const string LinkRoot = nameof(LinkRoot);

        ///
        /// Indicates whether to hide index pages by default when generating links.
        ///
        /// <type><see cref="bool"/></type>
        public const string LinkHideIndexPages = nameof(LinkHideIndexPages);

        ///
        /// Indicates whether to hide ".html" and ".htm" extensions by default when generating links.
        ///
        /// <type><see cref="bool"/></type>
        public const string LinkHideExtensions = nameof(LinkHideExtensions);

        ///
        /// Indicates that links should always be rendered in lowercase.
        ///
        /// <type><see cref="bool"/></type>
        public const string LinkLowercase = nameof(LinkLowercase);

        ///
        /// Indicates whether caching should be used.
        ///
        /// <type><see cref="bool"/></type>
        public const string UseCache = nameof(UseCache);

        ///
        /// Indicates whether to clean the output path on each execution.
        ///
        /// <type><see cref="bool"/></type>
        public const string CleanOutputPath = nameof(CleanOutputPath);

        ///
        /// Indicates the culture to use for reading and interpreting dates as input.
        ///
        /// <type><see cref="string"/> or <see cref="CultureInfo"/></type>
        public const string DateTimeInputCulture = nameof(DateTimeInputCulture);

        ///
        /// Indicates the culture to use for displaying dates in output.
        ///
        /// <type><see cref="string"/> or <see cref="CultureInfo"/></type>
        public const string DateTimeDisplayCulture = nameof(DateTimeDisplayCulture);

        // ReadFile/WriteFiles/CopyFiles

        ///
        /// The absolute root search path without any nested directories
        /// (I.e., the path that was searched, and possibly descended, for the given pattern).
        ///
        /// <type><see cref="DirectoryPath"/></type>
        public const string SourceFileRoot = nameof(SourceFileRoot);

        ///
        /// The name of the original file without extension.
        ///
        /// <type><see cref="FilePath"/></type>
        public const string SourceFileBase = nameof(SourceFileBase);

        ///
        /// The extension of the original file (including the ".").
        ///
        /// <type><see cref="string"/></type>
        public const string SourceFileExt = nameof(SourceFileExt);

        ///
        /// The file name of the original file with extension.
        ///
        /// <type><see cref="FilePath"/></type>
        public const string SourceFileName = nameof(SourceFileName);

        ///
        /// The absolute path to the folder of the original file.
        ///
        /// <type><see cref="DirectoryPath"/></type>
        public const string SourceFileDir = nameof(SourceFileDir);

        ///
        /// The absolute path to the original file.
        ///
        /// <type><see cref="FilePath"/></type>
        public const string SourceFilePath = nameof(SourceFilePath);

        ///
        /// The absolute path to the original file without the file extension.
        ///
        /// <type><see cref="FilePath"/></type>
        public const string SourceFilePathBase = nameof(SourceFilePathBase);

        ///
        /// The path to the file relative to the input folder. This metadata
        /// value is used when generating links to the document.
        ///
        /// <type><see cref="FilePath"/></type>
        public const string RelativeFilePath = nameof(RelativeFilePath);

        ///
        /// The path to the file relative to the input folder without extension.
        ///
        /// <type><see cref="FilePath"/></type>
        public const string RelativeFilePathBase = nameof(RelativeFilePathBase);

        ///
        /// The path to the folder containing the file relative to the input folder.
        ///
        /// <type><see cref="DirectoryPath"/></type>
        public const string RelativeFileDir = nameof(RelativeFileDir);

        ///
        /// The file name without any extension. Equivalent
        /// to <c>Path.GetFileNameWithoutExtension(DestinationFilePath)</c>.
        ///
        /// <type><see cref="FilePath"/></type>
        public const string DestinationFileBase = nameof(DestinationFileBase);

        ///
        /// The extension of the file. Equivalent
        /// to <c>Path.GetExtension(DestinationFilePath)</c>.
        ///
        /// <type><see cref="string"/></type>
        public const string DestinationFileExt = nameof(DestinationFileExt);

        ///
        /// The full file name. Equivalent
        /// to <c>Path.GetFileName(DestinationFilePath)</c>.
        ///
        /// <type><see cref="FilePath"/></type>
        public const string DestinationFileName = nameof(DestinationFileName);

        ///
        /// The full absolute directory of the file.
        /// Equivalent to <c>Path.GetDirectoryName(DestinationFilePath)</c>.
        ///
        /// <type><see cref="DirectoryPath"/></type>
        public const string DestinationFileDir = nameof(DestinationFileDir);

        ///
        /// The full absolute path (including file name)
        /// of the destination file.
        ///
        /// <type><see cref="FilePath"/></type>
        public const string DestinationFilePath = nameof(DestinationFilePath);

        ///
        /// The full absolute path (including file name)
        /// of the destination file without the file extension.
        ///
        /// <type><see cref="FilePath"/></type>
        public const string DestinationFilePathBase = nameof(DestinationFilePathBase);

        ///
        /// The extension to use when writing the file.
        ///
        /// <type><see cref="string"/></type>
        public const string WriteExtension = nameof(WriteExtension);

        ///
        /// The file name to use when writing the file.
        ///
        /// <type><see cref="FilePath"/></type>
        public const string WriteFileName = nameof(WriteFileName);

        ///
        /// The path to use when writing the file.
        ///
        /// <type><see cref="FilePath"/></type>
        public const string WritePath = nameof(WritePath);

        // Paginate

        ///
        /// Contains all the documents for the current page.
        ///
        /// <type><c>IEnumerable<IDocument></c></type>
        public const string PageDocuments = nameof(PageDocuments);

        ///
        /// The index of the current page (1 based).
        ///
        /// <type><see cref="int"/></type>
        public const string CurrentPage = nameof(CurrentPage);

        ///
        /// The total number of pages.
        ///
        /// <type><see cref="int"/></type>
        public const string TotalPages = nameof(TotalPages);

        ///
        /// The total number of items across all pages.
        ///
        /// <type><see cref="int"/></type>
        public const string TotalItems = nameof(TotalItems);

        ///
        /// Whether there is another page after this one.
        ///
        /// <type><see cref="bool"/></type>
        public const string HasNextPage = nameof(HasNextPage);

        ///
        /// Whether there is another page before this one.
        ///
        /// <type><see cref="bool"/></type>
        public const string HasPreviousPage = nameof(HasPreviousPage);

        ///
        /// The next page.
        ///
        /// <type><see cref="IDocument"/></type>
        public const string NextPage = nameof(NextPage);

        ///
        /// The previous page.
        ///
        /// <type><see cref="IDocument"/></type>
        public const string PreviousPage = nameof(PreviousPage);

        // GroupBy

        ///
        /// Contains all the documents for the current group.
        ///
        /// <type><c>IEnumerable<IDocument></c></type>
        public const string GroupDocuments = nameof(GroupDocuments);

        ///
        /// The key for the current group.
        ///
        /// <type><see cref="object"/></type>
        public const string GroupKey = nameof(GroupKey);

        // Index

        ///
        /// The one-based index of the current document relative to other documents in the pipeline.
        ///
        /// <type><see cref="int"/></type>
        public const string Index = nameof(Index);

        // Sitemap

        ///
        /// Contains a document-specific sitemap item for use when generating a sitemap.
        ///
        /// <type><see cref="Modules.Contents.SitemapItem"/></type>
        public const string SitemapItem = nameof(SitemapItem);

        // Download

        ///
        /// The URI where the document was downloaded from.
        ///
        /// <type><see cref="string"/></type>
        public const string SourceUri = nameof(SourceUri);

        ///
        /// The web headers of the document.
        ///
        /// <type><c>Dictionary<string, string></c></type>
        public const string SourceHeaders = nameof(SourceHeaders);

        // Tree

        ///
        /// The parent of this node or <c>null</c> if it is a root.
        ///
        /// <type><see cref="IDocument"/></type>
        public const string Parent = nameof(Parent);

        ///
        /// All the children of this node.
        ///
        /// <type><see cref="IReadOnlyCollection{IDocument}"/></type>
        public const string Children = nameof(Children);

        ///
        /// The previous sibling, that is the previous node in the children
        /// collection of the parent or <c>null</c> if this is the first node in the collection or the parent is null.
        ///
        /// <type><see cref="IDocument"/></type>
        public const string PreviousSibling = nameof(PreviousSibling);

        ///
        /// The next sibling, that is the next node in the children collection
        /// of the parent or <c>null</c> if this is the last node in the collection or the parent is null.
        ///
        /// <type><see cref="IDocument"/></type>
        public const string NextSibling = nameof(NextSibling);

        ///
        /// The next node in the tree using a depth-first
        /// search or <c>null</c> if this was the last node.
        ///
        /// <type><see cref="IDocument"/></type>
        public const string Next = nameof(Next);

        ///
        /// The previous node in the tree using a depth-first
        /// search or <c>null</c> if this was the first node.
        ///
        /// <type><see cref="IDocument"/></type>
        public const string Previous = nameof(Previous);

        ///
        /// The path that represents this node in the tree.
        ///
        /// <type><see cref="Array"/></type>
        public const string TreePath = nameof(TreePath);

        ///
        /// Gets set on documents that were created as a placeholder for tree roots.
        ///
        /// <type><see cref="bool"/></type>
        public const string TreePlaceholder = nameof(TreePlaceholder);

        // Title

        ///
        /// The calculated title of the document.
        ///
        /// <type><see cref="string"/></type>
        public const string Title = nameof(Title);

        // RedirectFrom

        ///
        /// The path(s) where the document should be redirected from.
        ///
        /// <type><see cref="FilePath"/></type>
        public const string RedirectFrom = nameof(RedirectFrom);
    }
}


text:
int main(int argc, char const *argv[])
{
	coco::CoCoApp h;

	// create objects and assign names (TODO anonymous)
	auto x = coco::vision::OpenNIReaderTask("reader");
	auto y = coco::vision::X264EncoderTask("enc");

    x.
	// returns Connectionf or customization
	y.image_IN << x.rgb_buffer_OUT;

	// put into container
	h << x << y;

	h.generateXML();
	//h.run();

	return 0;
}


text:
package com.sun.jini.test.spec.jeri.mux.util;

//java.io
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Utility class to represent a Jini ERI Multiplexing Protocol Ping message.
 */
public class PingMessage implements Message {

    private static final byte[] reference =
        new byte[] {0x04,0x00,0x00,0x00};
    private byte[] received = null;
    private byte[] payload = null;

    //inherit javadoc
    public void send(OutputStream out) throws IOException {
        out.write(reference);
        out.flush();
    }

    //inherit javadoc
    public Object receive(InputStream in, long timeout)
        throws IOException, ProtocolException {
        long stopTime = System.currentTimeMillis() +  timeout;
        while (System.currentTimeMillis()<stopTime) {
            try {
                if (in.available()>=reference.length) {
                    break;
                }
                Thread.sleep(100);
            } catch (InterruptedException ignore) {
            }
        }
        if (in.available()<reference.length) {
            return new byte[0];
        }
        received = new byte[reference.length];
        in.read(received);
        check(received);
        payload = new byte[] {received[2],received[3]};
        return received;
    }

    //inherit javadoc
    public Object getPayload() {
        return payload;
    }

    //inherit javadoc
    public byte[] getRawMessage() {
        return received;
    }

    //inherit javadoc
    public String toString() {
        return (received!=null) ? Util.convert(received) :
            Util.convert(reference);
    }

    /**
     * Returns the cookie associated with this message
     *
     * @return The value of the cookie associated with this message.
     */
    public int getCookie() {
        return (received!=null) ? (received[2]<<8) + received[3]
            : (reference[2]<<8) + reference[3];
    }

    /**
     * Sets the cookie that is associated with this message.
     *
     * @param cookie The cookie to be associated with this message.
     * @return The object that was operated on
     */
    public PingMessage setCookie(short cookie) {
        reference[2] = (byte) ((cookie>>>8)&0x00ff);
        reference[3] = (byte) (cookie & 0x00ff);;
        return this;
    }

    /**
     * Checks that the message passed in conforms
     * to the format for a Ping message
     *
     * @param The message to check
     */
    private void check(byte[] message) throws ProtocolException {
        //check the type of the message
        if ((received[0]|reference[0])!=reference[0]) {
            throw new ProtocolException("The message received: "
                + Util.convert(received) + " is not of Ping message type");
        }
        //check that the reserved byte is not used
        if ((received[1]|0x00)!=0x00) {
            throw new ProtocolException("The received Ping message makes"
                + " use of reservered bits");
        }
    }
}


text:
"""This code example archives a proposal line item.

To determine which proposal line items exist, run
get_all_proposal_line_items.py.
"""

# Import appropriate modules from the client library.
from googleads import dfp

# Set the id of the proposal line item to archive.
PROPOSAL_LINE_ITEM_ID = 'INSERT_PROPOSAL_LINE_ITEM_ID_HERE'

def main(client, proposal_line_item_id):
  # Initialize appropriate service.
  proposal_line_item_service = client.GetService(
      'ProposalLineItemService', version='v201411')

  # Create query.
  values = [{
      'key': 'id',
      'value': {
          'xsi_type': 'NumberValue',
          'value': proposal_line_item_id
      }
  }]
  query = 'WHERE id = :id'
  statement = dfp.FilterStatement(query, values, 1)

  proposal_line_items_archived = 0

  # Get proposal line items by statement.
  while True:
    response = proposal_line_item_service.getProposalLineItemsByStatement(
        statement.ToStatement())
    if 'results' in response:
      for proposal_line_item in response['results']:
        print ('Proposal line item with id \'%s\', '
               'belonging to proposal id \'%s\', and '
               'name \'%s\' will be archived.' %
               (proposal_line_item['id'], proposal_line_item['proposalId'],
                proposal_line_item['name']))

      # Perform action.
      result = proposal_line_item_service.performProposalLineItemAction(
          {'xsi_type': 'ArchiveProposalLineItems'}, statement.ToStatement())
      if result and int(result['numChanges']) > 0:
        proposal_line_items_archived += int(result['numChanges'])
      statement.offset += dfp.SUGGESTED_PAGE_LIMIT
    else:
      break

  # Display results.
  if proposal_line_items_archived > 0:
    print ('Number of proposal line items '
           'archived: %s' % proposal_line_items_archived)
  else:
    print 'No proposal line items were archived.'

if __name__ == '__main__':
  # Initialize client object.
  dfp_client = dfp.DfpClient.LoadFromStorage()
  main(dfp_client, PROPOSAL_LINE_ITEM_ID)


text:
date: 1-01-2014
title: Omnis qui aperiam
preface: Quidem temporibus eveniet sapiente aspernatur qui veniam ut molestiae mollitia! Voluptatum, unde molestias distinctio est sit omnis qui aperiam
tags:
  - javascript
---

# Omnis qui aperiam

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quidem temporibus eveniet sapiente aspernatur qui veniam ut molestiae mollitia! Voluptatum, unde molestias distinctio est sit omnis qui aperiam. Veniam, eum, assumenda.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quidem temporibus eveniet sapiente aspernatur qui veniam ut molestiae mollitia! Voluptatum, unde molestias distinctio est sit omnis qui aperiam. Veniam, eum, assumenda.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quidem temporibus eveniet sapiente aspernatur qui veniam ut molestiae mollitia! Voluptatum, unde molestias distinctio est sit omnis qui aperiam. Veniam, eum, assumenda.


text:
<?php

declare(strict_types=1);

namespace Cappuccino\Node\Expression\Binary;

use Cappuccino\Compiler;
use const PHP_VERSION_ID;

/**
 * Class NotEqualBinary
 *
 * @author Bas Milius <bas@mili.us>
 * @package Cappuccino\Node\Expression\Binary
 * @since 1.0.0
 */
class NotEqualBinary extends AbstractBinary
{

	/**
	 * {@inheritdoc}
	 * @author Bas Milius <bas@mili.us>
	 * @since 1.0.0
	 */
	public function compile(Compiler $compiler): void
	{
		if (PHP_VERSION_ID >= 80000)
		{
			parent::compile($compiler);

			return;
		}

		$compiler
			->raw('0 !== StaticMethods::compare(')
			->subcompile($this->getNode('left'))
			->raw(', ')
			->subcompile($this->getNode('right'))
			->raw(')');
	}

	/**
	 * {@inheritdoc}
	 * @author Bas Milius <bas@mili.us>
	 * @since 1.0.0
	 */
	public function operator(Compiler $compiler): Compiler
	{
		return $compiler->raw('!=');
	}

}


text:
import unittest

import numpy

import chainer
from chainer.backends import cuda
from chainer import functions
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr

@testing.parameterize(*testing.product_dict(
    [{'dtype': numpy.float16,
      'forward_options': {'rtol': 5e-3, 'atol': 5e-3},
      'backward_options': {'eps': 1e-1, 'rtol': 1e0, 'atol': 1e0},
      'double_backward_options': {'eps': 1e-1, 'rtol': 1e0, 'atol': 1e0}},
     {'dtype': numpy.float32,
      'forward_options': {},
      'backward_options': {'eps': 1e-2, 'rtol': 1e-2, 'atol': 1e-2},
      'double_backward_options': {'eps': 1e-2, 'rtol': 1e-1, 'atol': 1e-1}},
     {'dtype': numpy.float64,
      'forward_options': {},
      'backward_options': {'eps': 1e-2, 'rtol': 1e-2, 'atol': 1e-2},
      'double_backward_options': {'eps': 1e-2, 'rtol': 1e-1, 'atol': 1e-1}},
     ],
    [{'reduce': 'no'},
     {'reduce': 'sum_along_second_axis'},
     ],
))
class TestHuberLoss(unittest.TestCase):

    def setUp(self):
        self._config_user = chainer.using_config('dtype', self.dtype)
        self._config_user.__enter__()

        self.shape = (4, 10)
        self.x = (numpy.random.random(self.shape) - 0.5) * 20
        self.x = self.x.astype(self.dtype)
        self.t = numpy.random.random(self.shape).astype(self.dtype)
        if self.reduce == 'sum_along_second_axis':
            gy_shape = self.shape[0]
        else:
            gy_shape = self.shape
        self.gy = numpy.random.random(gy_shape).astype(self.dtype)
        self.ggx = numpy.random.uniform(-1, 1, self.x.shape)
        self.ggx = self.ggx.astype(self.dtype)
        self.ggt = numpy.random.uniform(-1, 1, self.t.shape)
        self.ggt = self.ggt.astype(self.dtype)

    def tearDown(self):
        self._config_user.__exit__(None, None, None)

    def check_forward(self, x_data, t_data):
        x = chainer.Variable(x_data)
        t = chainer.Variable(t_data)
        loss = functions.huber_loss(x, t, delta=1, reduce=self.reduce)
        self.assertEqual(loss.data.dtype, self.dtype)
        loss_value = cuda.to_cpu(loss.data)

        diff_data = cuda.to_cpu(x_data) - cuda.to_cpu(t_data)
        loss_expect = numpy.zeros(self.shape)
        mask = numpy.abs(diff_data) < 1
        loss_expect[mask] = 0.5 * diff_data[mask] ** 2
        loss_expect[~mask] = numpy.abs(diff_data[~mask]) - 0.5
        if self.reduce == 'sum_along_second_axis':
            loss_expect = numpy.sum(loss_expect, axis=1)
        testing.assert_allclose(
            loss_value, loss_expect, **self.forward_options)

    def test_forward_cpu(self):
        self.check_forward(self.x, self.t)

    @attr.gpu
    def test_forward_gpu(self):
        self.check_forward(cuda.to_gpu(self.x), cuda.to_gpu(self.t))

    def check_backward(self, x_data, t_data, y_grad):
        def f(x, t):
            return functions.huber_loss(x, t, delta=1, reduce=self.reduce)

        gradient_check.check_backward(
            f, (x_data, t_data), y_grad, **self.backward_options)

    def test_backward_cpu(self):
        self.check_backward(self.x, self.t, self.gy)

    @attr.gpu
    def test_backward_gpu(self):
        self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(self.t),
                            cuda.to_gpu(self.gy))

    def check_double_backward(self, x_data, t_data, y_grad, x_grad_grad,
                              t_grad_grad):
        def f(x, t):
            return functions.huber_loss(x, t, delta=1, reduce=self.reduce)

        gradient_check.check_double_backward(
            f, (x_data, t_data), y_grad, (x_grad_grad, t_grad_grad),
            **self.double_backward_options)

    def test_double_backward_cpu(self):
        self.check_double_backward(self.x, self.t, self.gy, self.ggx, self.ggt)

    @attr.gpu
    def test_double_backward_gpu(self):
        self.check_double_backward(
            cuda.to_gpu(self.x), cuda.to_gpu(self.t), cuda.to_gpu(self.gy),
            cuda.to_gpu(self.ggx), cuda.to_gpu(self.ggt))

class TestHuberLossInvalidReductionOption(unittest.TestCase):

    def setUp(self):
        self.x = numpy.random.uniform(-1, 1, (4, 10)).astype(numpy.float32)
        self.t = numpy.random.uniform(-1, 1, (4, 10)).astype(numpy.float32)

    def check_invalid_option(self, xp):
        x = xp.asarray(self.x)
        t = xp.asarray(self.t)
        with self.assertRaises(ValueError):
            functions.huber_loss(x, t, 1, 'invalid_option')

    def test_invalid_option_cpu(self):
        self.check_invalid_option(numpy)

    @attr.gpu
    def test_invalid_option_gpu(self):
        self.check_invalid_option(cuda.cupy)

testing.run_module(__name__, __file__)


text:
<?php

namespace ApiBundle\Security\Authorization\Voter;

use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;

class GrantEverythingVoter implements VoterInterface
{
    public function supportsAttribute($attribute)
    {
        return true;
    }

    public function supportsClass($class)
    {
        return true;
    }

    public function vote(TokenInterface $token, $object, array $attributes)
    {
        return static::ACCESS_GRANTED;
    }
}


text:
<?xml version="1.0" ?>
<INPUT>

	<MEDALS>
		<MEDAL Id="1" MEDAL_THRESHOLD="45000" TYPE="Gold"/>
		<MEDAL Id="2" MEDAL_THRESHOLD="69000" TYPE="Silver"/>
		<MEDAL Id="3" MEDAL_THRESHOLD="89000" TYPE="Bronze"/>

	</MEDALS>

	<SpeedSettings Default="18" Max="150" Min="0"/>

	<PenaltySettings SpeedLost="0.1" TimeLost="15"/>

	<PROBLEM_SET>
		<PROBLEM_SUBSET>
			<TARGET TYPE="Fraction">
				<ContentSettings denominator="1000" numerator="391"/>
			</TARGET>
			<QUESTION INDEX="1">
				<Content TYPE="String">
					<ContentSettings string="0.186"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="0.325"/>
				</Content>
				<Answer VALUE="2"/>
			</QUESTION>
			<QUESTION INDEX="2">
				<Content TYPE="String">
					<ContentSettings string="0.343"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="0.577"/>
				</Content>
				<Answer VALUE="1"/>
			</QUESTION>
			<QUESTION INDEX="3">
				<Content TYPE="String">
					<ContentSettings string="0.917"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="0.961"/>
				</Content>
				<Answer VALUE="0"/>
			</QUESTION>
			<QUESTION INDEX="4">
				<Content TYPE="String">
					<ContentSettings string="0.136"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="0.277"/>
				</Content>
				<Answer VALUE="2"/>
			</QUESTION>
			<QUESTION INDEX="5">
				<Content TYPE="String">
					<ContentSettings string="0.997"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="1"/>
				</Content>
				<Answer VALUE="0"/>
			</QUESTION>
			<QUESTION INDEX="6">
				<Content TYPE="String">
					<ContentSettings string="0.187"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="0.276"/>
				</Content>
				<Answer VALUE="2"/>
			</QUESTION>
		</PROBLEM_SUBSET>
		<PROBLEM_SUBSET>
			<TARGET TYPE="Fraction">
				<ContentSettings denominator="100" numerator="57"/>
			</TARGET>
			<QUESTION INDEX="7">
				<Content TYPE="String">
					<ContentSettings string="0.69"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="0.91"/>
				</Content>
				<Answer VALUE="0"/>
			</QUESTION>
			<QUESTION INDEX="8">
				<Content TYPE="String">
					<ContentSettings string="0.27"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="0.86"/>
				</Content>
				<Answer VALUE="1"/>
			</QUESTION>
			<QUESTION INDEX="9">
				<Content TYPE="String">
					<ContentSettings string="0.08"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="0.54"/>
				</Content>
				<Answer VALUE="2"/>
			</QUESTION>
			<QUESTION INDEX="10">
				<Content TYPE="String">
					<ContentSettings string="0.52"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="0.68"/>
				</Content>
				<Answer VALUE="1"/>
			</QUESTION>
			<QUESTION INDEX="11">
				<Content TYPE="String">
					<ContentSettings string="0.11"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="0.32"/>
				</Content>
				<Answer VALUE="2"/>
			</QUESTION>
			<QUESTION INDEX="12">
				<Content TYPE="String">
					<ContentSettings string="0.88"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="1.01"/>
				</Content>
				<Answer VALUE="0"/>
			</QUESTION>
		</PROBLEM_SUBSET>
		<PROBLEM_SUBSET>
			<TARGET TYPE="Fraction">
				<ContentSettings denominator="100" numerator="52"/>
			</TARGET>
			<QUESTION INDEX="13">
				<Content TYPE="String">
					<ContentSettings string="0.98"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="1"/>
				</Content>
				<Answer VALUE="0"/>
			</QUESTION>
			<QUESTION INDEX="14">
				<Content TYPE="String">
					<ContentSettings string="0.08"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="0.51"/>
				</Content>
				<Answer VALUE="2"/>
			</QUESTION>
			<QUESTION INDEX="15">
				<Content TYPE="String">
					<ContentSettings string="0.54"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="0.83"/>
				</Content>
				<Answer VALUE="0"/>
			</QUESTION>
			<QUESTION INDEX="16">
				<Content TYPE="String">
					<ContentSettings string="0.31"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="0.91"/>
				</Content>
				<Answer VALUE="1"/>
			</QUESTION>
			<QUESTION INDEX="17">
				<Content TYPE="String">
					<ContentSettings string="0.34"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="0.54"/>
				</Content>
				<Answer VALUE="1"/>
			</QUESTION>
			<QUESTION INDEX="18">
				<Content TYPE="String">
					<ContentSettings string="0.41"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="0.8"/>
				</Content>
				<Answer VALUE="1"/>
			</QUESTION>
		</PROBLEM_SUBSET>

	</PROBLEM_SET>

</INPUT>


text:
<#
The MIT License (MIT)

Copyright (c) 2015 Objectivity Bespoke Software Specialists

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
#>

function Resolve-ServerConnectionConfigElement {
    <#
    .SYNOPSIS
    Resolves a single ServerConnection config element.

    .PARAMETER AllServerConnections
    Hashtable containing all defined ServerConnection objects.

    .PARAMETER ServerConnection
    ServerConnection object to resolve.

    .PARAMETER Environment
    Name of the environment which the ServerRoles should be resolved for.

    .PARAMETER ResolvedTokens
    Resolved tokens.

    .EXAMPLE
    $serverConn = Resolve-ServerConnectionConfigElement -AllServerConnections $AllServerConnections -ServerConnection $serverConnectionName -ResolvedTokens $resolvedTokens -Environment $Environment

    #>
    [CmdletBinding()]
    [OutputType([object])]
    param(
        [Parameter(Mandatory=$true)]
        [hashtable]
        $AllServerConnections,

        [Parameter(Mandatory=$true)]
        [hashtable]
        $ServerConnection,

        [Parameter(Mandatory=$true)]
        [string]
        $Environment,

        [Parameter(Mandatory=$true)]
        [hashtable]
        $ResolvedTokens

    )

    $basedOnHierarchy = Resolve-BasedOnHierarchy -AllElements $AllServerConnections -SelectedElement $ServerConnection.Name -ConfigElementName 'ServerConnection'

    $result = @{ Name = $ServerConnection.Name }
    # traverse ServerConnections from top to bottom to set / override ServerConnection properties
    foreach ($scName in $basedOnHierarchy) {
        $sc = $AllServerConnections[$scName]
        foreach ($entry in $sc.GetEnumerator()) {
            $result[$entry.Key] = $entry.Value
        }
    }

    $result.Nodes = Resolve-ScriptedToken -ScriptedToken $result.Nodes -ResolvedTokens $resolvedTokens -Environment $Environment -TokenName "[ServerConnection '$($ServerConnection.Name)' / -Nodes]"
    # Other properties will be resolved later as they require tokens with $NodeName

    if (!$result.RemotingMode) {
        $result.RemotingMode = 'PSRemoting'
    }

    return $result
}


text:
'use strict';
// @ngInject
var appSettings = require('./app.constants');
var angular = require('angular');
var $ = require('jquery');
var Mousetrap = require('mousetrap');
var flexImages = require('./lib.flex-images.js');

// Require the dependencies that does not support returning name from the require.
require('angular-local-storage');
require('winjs');
require('angular-winjs');
require('angular-busy');
require('./app.errors');

// @ngInject
var app = angular.module(appSettings.appName, [
        require('angular-ui-router'),
        require('angular-animate'),
        'LocalStorageModule',
        require('./core').name,
        require('./home').name,
        require('./search').name,
        require('./auth').name,
        require('./about').name,
        require('./profile').name,
        require('./folder').name,
        require('./download').name,
        require('./settings').name,
        require('./favorites').name,
        'winjs',
        'cgBusy'
]);

app.constant('appSettings', appSettings);
app.constant('licenses', require('./app.licenses.js'));
app.value('userSettings', {});
app.value('userToken', {});
app.value('state', require('./app.state.js'));
app.value('runtime', require('./app.runtime.js'));
app.value('cgBusyDefaults', {
    message: 'Loading...',
    templateUrl: 'views/core/templates/angular-busy.html',
    delay: 0,
    backdrop: false,
    minDuration: 500
});
app.config(require('./app.config'));
app.run(require('./app.run'));
app.controller('AppController', require('./app.controller.js'));

angular.element(document).ready(function () {
    angular.bootstrap(document, [appSettings.appName]);
});

module.exports = app;


text:
(function() {
  'use strict';

  // PasswordValidator service used for testing the password strength
  angular
    .module('users')
    .factory('PasswordValidator', PasswordValidator);

  PasswordValidator.$inject = ['$window'];

  function PasswordValidator($window) {
    var owaspPasswordStrengthTest = $window.owaspPasswordStrengthTest;

    return {
      getResult: function (password) {
        var result = owaspPasswordStrengthTest.test(password);
        return result;
      },
      getPopoverMsg: function () {
        var popoverMsg = 'Please enter a passphrase or password with greater than 10 characters, numbers, lowercase, upppercase, and special characters.';
        return popoverMsg;
      }
    };
  }
})();


text:
/** \file xtests/util/temp_directory.hpp
 *
 * [C++ only] Definition of the temp_directory class.
 */

#ifndef XTESTS_INCL_XTESTS_UTIL_HPP_TEMP_DIRECTORY
#define XTESTS_INCL_XTESTS_UTIL_HPP_TEMP_DIRECTORY

#ifndef XTESTS_DOCUMENTATION_SKIP_SECTION
# define XTESTS_VER_XTESTS_UTIL_HPP_TEMP_DIRECTORY_MAJOR    0
# define XTESTS_VER_XTESTS_UTIL_HPP_TEMP_DIRECTORY_MINOR    1
# define XTESTS_VER_XTESTS_UTIL_HPP_TEMP_DIRECTORY_REVISION 6
# define XTESTS_VER_XTESTS_UTIL_HPP_TEMP_DIRECTORY_EDIT     8
#endif /* !XTESTS_DOCUMENTATION_SKIP_SECTION */

/* /////////////////////////////////////////////////////////////////////////
 * includes - 0
 */

#ifndef XTESTS_INCL_XTESTS_H_XTESTS
# include <xtests/xtests.h>
#endif /* !XTESTS_INCL_XTESTS_H_XTESTS */

/* /////////////////////////////////////////////////////////////////////////
 * compatibility
 */

#ifndef STLSOFT_CF_EXCEPTION_SUPPORT
# error temp_directory can only be used in a compilation unit in which exception support is enabled
#endif /* !STLSOFT_CF_EXCEPTION_SUPPORT */

/* /////////////////////////////////////////////////////////////////////////
 * includes - 1
 */

#ifndef XTESTS_INCL_XTESTS_UTIL_HPP_FILESYSTEM_EXCEPTION
# include <xtests/util/filesystem_exception.hpp>
#endif /* !XTESTS_INCL_XTESTS_UTIL_HPP_FILESYSTEM_EXCEPTION */

#include <platformstl/filesystem/directory_functions.hpp>
#include <platformstl/filesystem/filesystem_traits.hpp>
#include <platformstl/filesystem/readdir_sequence.hpp>

#if 0
#elif defined(PLATFORMSTL_OS_IS_UNIX)

# include <errno.h>
# include <unistd.h>
#elif defined(PLATFORMSTL_OS_IS_WINDOWS)

# include <comstl/util/guid.hpp>
#else

# error Operating system not discriminated
#endif

#include <stlsoft/memory/auto_buffer.hpp>

#include <stlsoft/shims/access/string/fwd.h>

#include <string>

/* /////////////////////////////////////////////////////////////////////////
 * namespace
 */

namespace xtests
{
namespace cpp
{
namespace util
{

/* /////////////////////////////////////////////////////////////////////////
 * classes
 */

/// Creates and manages a temporary directory for use in testing
class temp_directory
{
public: // Types
    /// The character type
    typedef char                            char_type;
    /// The size type
    typedef size_t                          size_type;
    /// This type
    typedef temp_directory                  class_type;

    /// Flags that control behaviour of ctor and/or dtor
    enum Flags
    {
            None                    =   0
        ,   EmptyOnOpen             =   0x0001
        ,   EmptyOnClose            =   0x0002
        ,   RemoveOnOpen            =   0x0004
        ,   RemoveOnClose           =   0x0008
    };

    class could_not_create_temporary_directory_exception;

private:
    typedef std::basic_string<char_type>                string_type_;
    typedef platformstl::filesystem_traits<char_type>   fs_traits_type_;
    typedef fs_traits_type_::file_handle_type           file_handle_type_;

public: // Construction
    /// Establishes an empty temporary file according to the given
    /// flags
    explicit temp_directory(Flags flags);
private:
    temp_directory(class_type const&);
    class_type& operator =(class_type const&);
public:
    ~temp_directory() stlsoft_throw_0();

public: // Accessors
    /// Length of the path of the temporary directory
    size_type           size() const;
    /// C-style string pointer to the path of the temporary directory
    char_type const*    c_str() const;

private: // Implementation
    static
    void
    create_(
        Flags           flags
    ,   string_type_&   path
    );

    static
    void
    create_directory_(
        string_type_&   path
    );

    static
    bool
    remove_subdirectories_(
        string_type_&   path
    );

private: // Fields
    Flags const     m_flags;
    string_type_    m_path;
};

/* /////////////////////////////////////////////////////////////////////////
 * operators
 */

#ifndef XTESTS_DOCUMENTATION_SKIP_SECTION

inline
temp_directory::Flags
operator |(
    temp_directory::Flags    lhs
,   temp_directory::Flags    rhs
)
{
    return static_cast<temp_directory::Flags>(int(lhs) | int(rhs));
}

#endif /* !XTESTS_DOCUMENTATION_SKIP_SECTION */

/* /////////////////////////////////////////////////////////////////////////
 * implementation
 */

#ifndef XTESTS_DOCUMENTATION_SKIP_SECTION

class temp_directory::could_not_create_temporary_directory_exception
    : public filesystem_exception
{
public: // Types
    typedef could_not_create_temporary_directory_exception  class_type;
private:
    typedef filesystem_exception                            parent_class_type;
public:
    typedef parent_class_type::result_code_type             result_code_type;

public: // Construction
    explicit
    could_not_create_temporary_directory_exception(
        result_code_type    rc
    );
    could_not_create_temporary_directory_exception(
        result_code_type    rc
    ,   char_type const*    message
    );
    could_not_create_temporary_directory_exception(
        result_code_type    rc
    ,   string_type const&  message
    );
};

inline
temp_directory::could_not_create_temporary_directory_exception::could_not_create_temporary_directory_exception(
    result_code_type    rc
)
    : parent_class_type(rc)
{}

inline
temp_directory::could_not_create_temporary_directory_exception::could_not_create_temporary_directory_exception(
    result_code_type    rc
,   char_type const*    message
)
    : parent_class_type(rc, message)
{}

inline
temp_directory::could_not_create_temporary_directory_exception::could_not_create_temporary_directory_exception(
    result_code_type    rc
,   string_type const&  message
)
    : parent_class_type(rc, message)
{}

inline
/* static */
bool
temp_directory::remove_subdirectories_(
    string_type_&   path
)
{
    // Can't use platformstl::remove_directory_recurse() because it
    // deletes the directory itself, so instead do a search for
    // all files and sub-directories and despatch them accordingly

    using ::platformstl::readdir_sequence;

    bool succeeded = true;

    readdir_sequence files(path, readdir_sequence::files | readdir_sequence::fullPath);

    { for(readdir_sequence::const_iterator i = files.begin(); files.end() != i; ++i)
    {
        if(!fs_traits_type_::delete_file(stlsoft::c_str_ptr(*i)))
        {
            succeeded = false;
        }
    }}

    readdir_sequence directories(path, readdir_sequence::directories | readdir_sequence::fullPath);

    { for(readdir_sequence::const_iterator i = directories.begin(); directories.end() != i; ++i)
    {
        if(!platformstl::remove_directory_recurse(*i))
        {
            succeeded = false;
        }
    }}

    return succeeded;
}

inline
/* static */
void
temp_directory::create_directory_(
    string_type_&   path
)
{
    //
    // This is done by:
    //
    // - getting a unique path name
    //

#if defined(PLATFORMSTL_OS_IS_WINDOWS)

    // On Windows, we'll work in one of %TEMP%, %TMP%, %USERPROFILE%, or

    static LPCSTR const s_roots[] =
    {
            "%TEMP%"
        ,   "%TMP%"
        ,   "%USERPROFILE%"
        ,   "."
    };

    comstl::guid                unique_name;
    DWORD                       e = ERROR_SUCCESS;
    stlsoft::auto_buffer<char>  buff(1);

    { for(size_t i = 0; i != STLSOFT_NUM_ELEMENTS(s_roots); )
    {
        LPCSTR const root = s_roots[i];

        size_t n1 = fs_traits_type_::expand_environment_strings(root, NULL, 0);

        if(0 != n1)
        {
            if(buff.resize(n1))
            {
                size_t const n2 = fs_traits_type_::expand_environment_strings(root, &buff[0], buff.size() + (1 + comstl::COMSTL_CCH_GUID));

                if(0 != n2)
                {
                    if(n2 < buff.size() - (1 + comstl::COMSTL_CCH_GUID))
                    {
                        fs_traits_type_::ensure_dir_end(&buff[0] + (n2 - 2));

                        size_t const    n3  =   fs_traits_type_::str_len(buff.data());
                        char* const     p3  =   buff.data() + n3;

                        fs_traits_type_::char_copy(p3, stlsoft::c_str_ptr_a(unique_name), comstl::COMSTL_CCH_GUID);
                        p3[comstl::COMSTL_CCH_GUID] = '\0';

                        if(fs_traits_type_::create_directory(buff.data()))
                        {
                            path.assign(buff.data(), n3 + comstl::COMSTL_CCH_GUID);

                            return;
                        }
                        else
                        {
                            e = fs_traits_type_::get_last_error();
                        }
                    }
                }
            }
        }

        ++i;
    }}

    throw could_not_create_temporary_directory_exception(e, "could not create directory in any of the possible locations");
#else

    char tmp_path[] = "/tmp/xtests-temp-dir.XXXXXXXX";

# ifdef _WIN32
    char* const tmp_path_win_ = &tmp_path[0] + 4;
#  define tmp_path  tmp_path_win_
# endif

    if(NULL == ::mkdtemp(tmp_path))
    {
        int const e = errno;

        throw could_not_create_temporary_directory_exception(e, "could not create directory in any of the possible locations");
    }

    path = tmp_path;

# ifdef _WIN32
#  undef tmp_path
# endif

#endif
}

inline
/* static */
void
temp_directory::create_(
    temp_directory::Flags           flags
,   temp_directory::string_type_&   path
)
{
    // Algorithm:
    //
    // 1. Generate a unique, new directory name
    // 2. Empty it, if required
    // 3. Delete it, if required

    // 1. Generate a unique, new directory name

    create_directory_(path);

    // 2. Empty it, if required
    if(0 != (EmptyOnOpen & flags))
    {
        remove_subdirectories_(path);
    }

    // 3. Delete it, if required

    if(0 != (RemoveOnOpen & flags))
    {
        fs_traits_type_::remove_directory(path.c_str());
    }
}

inline
/* explicit */ temp_directory::temp_directory(
    temp_directory::Flags flags
)
    : m_flags(flags)
    , m_path()
{
    create_(m_flags, m_path);
}

inline
temp_directory::~temp_directory() stlsoft_throw_0()
{
    bool removed_recursively = false;

    if(0 != (EmptyOnClose & m_flags))
    {
        removed_recursively = remove_subdirectories_(m_path);
    }

    if( !removed_recursively &&
        0 != (RemoveOnClose & m_flags))
    {
        fs_traits_type_::remove_directory(m_path.c_str());
    }
}

inline
temp_directory::size_type
temp_directory::size() const
{
    return m_path.size();
}

inline
temp_directory::char_type const*
temp_directory::c_str() const
{
    return m_path.c_str();
}

#endif /* !XTESTS_DOCUMENTATION_SKIP_SECTION */

/* /////////////////////////////////////////////////////////////////////////
 * shims
 */

#ifndef XTESTS_DOCUMENTATION_SKIP_SECTION

inline
size_t
c_str_len_a(
    temp_directory const& t
)
{
    return t.size();
}

inline
char const*
c_str_data_a(
    temp_directory const& t
)
{
    return t.c_str();
}

inline
char const*
c_str_ptr_a(
    temp_directory const& t
)
{
    return t.c_str();
}

inline
size_t
c_str_len(
    temp_directory const& t
)
{
    return t.size();
}

inline
char const*
c_str_data(
    temp_directory const& t
)
{
    return t.c_str();
}

inline
char const*
c_str_ptr(
    temp_directory const& t
)
{
    return t.c_str();
}

#endif /* !XTESTS_DOCUMENTATION_SKIP_SECTION */

/* /////////////////////////////////////////////////////////////////////////
 * namespace
 */

} /* namespace util */
} /* namespace cpp */
} /* namespace xtests */

/* /////////////////////////////////////////////////////////////////////////
 * shims
 */

#ifndef XTESTS_DOCUMENTATION_SKIP_SECTION

# if !defined(_STLSOFT_NO_NAMESPACE) && \
     !defined(STLSOFT_NO_NAMESPACE)
namespace stlsoft
{
# endif

    inline
    size_t
    c_str_len_a(
        ::xtests::cpp::util::temp_directory const& t
    )
    {
        return t.size();
    }

    inline
    char const*
    c_str_data_a(
        ::xtests::cpp::util::temp_directory const& t
    )
    {
        return t.c_str();
    }

    inline
    char const*
    c_str_ptr_a(
        ::xtests::cpp::util::temp_directory const& t
    )
    {
        return t.c_str();
    }

    inline
    size_t
    c_str_len(
        ::xtests::cpp::util::temp_directory const& t
    )
    {
        return t.size();
    }

    inline
    char const*
    c_str_data(
        ::xtests::cpp::util::temp_directory const& t
    )
    {
        return t.c_str();
    }

    inline
    char const*
    c_str_ptr(
        ::xtests::cpp::util::temp_directory const& t
    )
    {
        return t.c_str();
    }

# if !defined(_STLSOFT_NO_NAMESPACE) && \
    !defined(STLSOFT_NO_NAMESPACE)
} /* namespace stlsoft */
# endif

#endif /* !XTESTS_DOCUMENTATION_SKIP_SECTION */

/* ////////////////////////////////////////////////////////////////////// */

#endif /* XTESTS_INCL_XTESTS_UTIL_HPP_TEMP_DIRECTORY */

/* ///////////////////////////// end of file //////////////////////////// */


text:
package jp.joao.android.dashclock.holidays;

import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.view.MenuItem;

public class SettingsActivity extends PreferenceActivity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setIcon(R.drawable.ic_calendar_icon);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

        setupSimplePreferencesScreen();
    }

    private void setupSimplePreferencesScreen() {
        // In the simplified UI, fragments are not used at all and we instead
        // use the older PreferenceActivity APIs.

        // Add 'general' preferences.
        addPreferencesFromResource(R.xml.pref_general);

        bindPreferenceSummaryToValue(findPreference(HolidaysExtension.PREF_CALENDAR));
        bindPreferenceSummaryToValue(findPreference(HolidaysExtension.PREF_LANG));
    }

    @Override
    protected boolean isValidFragment(String fragmentName) {
        return false;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * A preference value change listener that updates the preference's summary
     * to reflect its new value.
     */
    private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object value) {
            String stringValue = value.toString();

            if (preference instanceof ListPreference) {
                // For list preferences, look up the correct display value in
                // the preference's 'entries' list.
                ListPreference listPreference = (ListPreference) preference;
                int index = listPreference.findIndexOfValue(stringValue);

                // Set the summary to reflect the new value.
                preference.setSummary(
                        index >= 0
                                ? listPreference.getEntries()[index]
                                : null);

            } else {
                // For all other preferences, set the summary to the value's
                // simple string representation.
                preference.setSummary(stringValue);
            }
            return true;
        }
    };

    /**
     * Binds a preference's summary to its value. More specifically, when the
     * preference's value is changed, its summary (line of text below the
     * preference title) is updated to reflect the value. The summary is also
     * immediately updated upon calling this method. The exact display format is
     * dependent on the type of preference.
     *
     * @see #sBindPreferenceSummaryToValueListener
     */
    private static void bindPreferenceSummaryToValue(Preference preference) {
        // Set the listener to watch for value changes.
        preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);

        // Trigger the listener immediately with the preference's
        // current value.
        sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
                PreferenceManager
                        .getDefaultSharedPreferences(preference.getContext())
                        .getString(preference.getKey(), ""));
    }

}


text:
layout: post
title: An inaugural post
tags: [other]
---

As with any such endeavor, we need an inaugural post to test the system out. Because this is all written in [markdown](https://daringfireball.net/projects/markdown/), I need to test out a few basic features.

1. This is the first point in an ordered list.
2. This is the second point.
    1. This is a sub-point.
    2. And this is a second.

We can write codeblocks:

```python
import sys

if len(sys.argv) != 3:
    print main.__doc__
    sys.exit()

main()
```

```r
library(ggplot2)

# If I had some data I would make a plot here...

ggplot(dat, aes(x, y)) +
    geom_jittter()
```

I will need or want to add images to posts (e.g., plots or photos), which means this should work:

![_config.yml]({{ site.baseurl }}/images/posts/inaugural/PA107229.JPG)
*Hopefully there's a photo of a monarch butterfly immediately above this.*

Oh, and I will need to embed `iframe`s sometimes, including [Soundcloud](http://soundcloud.com) recordings:

<iframe width="100%" height="450" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/251595089&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&visual=true"></iframe>

And there _should_ be a player above.


text:
import mock
import netaddr
from neutron.conf.agent.metadata import config as metadata_config
from oslo_config import fixture as cfg_fixture

from dragonflow.controller.apps import metadata_service
from dragonflow.db.models import switch
from dragonflow.tests import base as tests_base
from dragonflow.tests.unit import test_app_base

class TestMetadataServiceApp(test_app_base.DFAppTestBase):
    apps_list = ["metadata_service"]

    def setUp(self):
        super(TestMetadataServiceApp, self).setUp()
        self.meta_app = self.open_flow_app.dispatcher.apps['metadata_service']

    def test_metadata_interface_online(self):
        with mock.patch.object(self.meta_app,
                               '_add_tap_metadata_port') as mock_func:
            # Device without mac will not trigger update flow
            self.controller.update(
                switch.SwitchPort(
                    id='fake_switch_port',
                    port_num=1,
                    name=self.meta_app._interface,
                )
            )
            mock_func.assert_not_called()
            mock_func.reset_mock()

            # Other device update will not trigger update flow
            self.controller.update(
                switch.SwitchPort(
                    id='fake_switch_port',
                    port_num=1,
                    name='no-interface',
                    mac_in_use='aa:bb:cc:dd:ee:ff',
                )
            )
            mock_func.assert_not_called()
            mock_func.reset_mock()

            # Device with mac will trigger update flow
            self.controller.update(
                switch.SwitchPort(
                    id='fake_switch_port',
                    port_num=1,
                    name=self.meta_app._interface,
                    mac_in_use='aa:bb:cc:dd:ee:ff',
                )
            )
            mock_func.assert_called_once_with(1, "aa:bb:cc:dd:ee:ff")
            mock_func.reset_mock()

            # Duplicated updated will not trigger update flow
            self.controller.update(
                switch.SwitchPort(
                    id='fake_switch_port1',
                    port_num=1,
                    name=self.meta_app._interface,
                    mac_in_use='aa:bb:cc:dd:ee:ff',
                )
            )
            mock_func.assert_not_called()

class TestMetadataServiceProxy(tests_base.BaseTestCase):
    def setUp(self):
        super(TestMetadataServiceProxy, self).setUp()
        self.nb_api = mock.Mock()
        self.cfg = self.useFixture(cfg_fixture.Config())
        self.cfg.register_opts(metadata_config.METADATA_PROXY_HANDLER_OPTS)
        self.cfg.config(nova_metadata_host='nova-host',
                        nova_metadata_port=443,
                        nova_metadata_protocol='https')
        self.proxy = metadata_service.DFMetadataProxyHandler(self.cfg.conf,
                                                             self.nb_api)

    def test_proxy_get_headers(self):
        req = mock.Mock()
        req.remote_addr = '128.0.0.3'
        req.headers = {}
        lport = mock.Mock()
        lport.topic = 'tenant1'
        lport.device_id = 'device_id1'
        lport.ip = netaddr.IPAddress('10.0.0.3')
        lport.unique_key = 3
        self.nb_api.get_all.return_value = [lport]
        with mock.patch.object(self.proxy, '_sign_instance_id') as sign:
            sign.return_value = 'instance_id'
            headers = self.proxy.get_headers(req)
            self.assertEqual({
                              'X-Forwarded-For': '10.0.0.3',
                              'X-Tenant-ID': 'tenant1',
                              'X-Instance-ID': 'device_id1',
                              'X-Instance-ID-Signature': 'instance_id',
                             }, headers)

    def test_proxy_get_host(self):
        host = self.proxy.get_host(mock.sentinel)
        self.assertEqual('nova-host:443', host)

    def test_proxy_get_scheme(self):
        scheme = self.proxy.get_scheme(mock.sentinel)
        self.assertEqual('https', scheme)


text:
import crypto from 'crypto';

const clientOptions ={
  cypher: 'AES-256-CBC',
  key: 'MySuperSecretKeyForParamsToken12',
};

const encrypt = (value) => {
  const iv = crypto.randomBytes(16);
  const cipher = crypto.createCipheriv(clientOptions.cypher, clientOptions.key, iv);

  let crypted = cipher.update(JSON.stringify(value), 'utf8', 'base64');
  crypted += cipher.final('base64');

  const data = {
    iv: iv.toString('base64'),
    value: crypted,
  };

  let jsonstr = JSON.stringify(data);
  let encoded = new Buffer(jsonstr).toString('base64');
  return encoded;
};

export default encrypt;


text:
BOT_NAME = 'example'

SPIDER_MODULES = ['example.spiders']
NEWSPIDER_MODULE = SPIDER_MODULES[0]
ITEM_PIPELINES = {
    'example.pipelines.ExamplePipeline': 102,
    'scrapy_kafka.pipelines.KafkaPipeline': 103,
}

# scrapy-kafka settings
SCRAPY_KAFKA_HOSTS = ['localhost:9092']
SCRAPY_KAFKA_SPIDER_CONSUMER_GROUP = 'scrapy-kafka'

# Crawl responsibly by identifying yourself (and your website) on the user-agent
# USER_AGENT = 'example (+http://www.yourdomain.com)'