text:
sap.ui.define(['sap/ui/core/UIComponent'],
	function (UIComponent) {
		"use strict";

		var Component = UIComponent.extend("sap.m.tutorial.walkthrough.03.Component", {

			metadata: {
				config: {
					sample: {
						iframe: "webapp/index.html",
						stretch: true,
						files: [
							"webapp/index.html"
						]
					}
				}
			}

		});

		return Component;

	});


text:
// Copyright 2021 The Terasology Foundation
// SPDX-License-Identifier: Apache-2.0
package org.terasology.engine.monitoring;

import gnu.trove.map.TObjectDoubleMap;
import org.terasology.engine.monitoring.impl.NullPerformanceMonitor;
import org.terasology.engine.monitoring.impl.PerformanceMonitorImpl;
import org.terasology.engine.monitoring.impl.PerformanceMonitorInternal;

/**
 * Maintains a running average of execution times and memory allocated by different activities.
 * Activities call to denote when they start and stop.
 *

 * Activities may be nested, and while a nested activity is running the collection of data from outer activities
 * is paused: time passing and allocated memory are not assigned to them.
 *

 * Performance monitor is intended only for use by the main thread of Terasology, and does not handle
 * activities being started and ended on other threads at this time.
 */
public final class PerformanceMonitor {
    private static PerformanceMonitorInternal instance;

    static {
        instance = new NullPerformanceMonitor();
    }

    private PerformanceMonitor() {
    }

    /**
     * Indicates the start of an activity. All started activities must either be ended with a call to endActivity()
     * (see example 1) or take advantage of the autocloseable interface implemented by Activity (see example 2).

     *

     *
     * Example 1 - explicitly ending an activity:
     *

     * PerformanceMonitor.startActivity("myActivity")
     * doSomething();
     * PerformanceMonitor.endActivity()
     *

     *
     * Example 2 - the end of the activity is handled internally:
     *

     * try (Activity ignored = PerformanceMonitor.startActivity("myActivity") {
     *     doSomething();
     * }
     *

     *
     * The latter case is particularly useful whenever the activity's code has a number of possible exit paths,
     * as it might be undesirable or simply non-trivial to add an endActivity() call at the end of each.

     *

     *
     * Activities may be nested. Example: (the indentation pattern is not strictly necessary)
     *

     * PerformanceMonitor.startActivity("myActivity")
     * doSomething();
     *
     *     PerformanceMonitor.startActivity("myNestedActivity")
     *     doSomethingNested();
     *     PerformanceMonitor.endActivity()
     *
     * doSomethingElse()
     * PerformanceMonitor.endActivity()
     *

     *
     * @param activityName the name of the activity starting.
     */
    public static Activity startActivity(String activityName) {
        return instance.startActivity(activityName);
    }

    /**
     * Indicates the end of the last started activity.
     */
    public static void endActivity() {
        instance.endActivity();
    }

    /**
     * Drops old information and updates the metrics. Should be called once per frame.
     */
    public static void rollCycle() {
        instance.rollCycle();
    }

    /**
     * Returns a mapping from the name of an activity to a running mean of its execution times, over a number of cycles.
     *

     * Activities may be nested, and while a nested activity is running the collection of data from outer activities
     * is paused and time passing is not assigned to them.
     *
     * @return a mapping from activity name to running mean of execution times.
     */
    public static TObjectDoubleMap<String> getRunningMean() {
        return instance.getRunningMean();
    }

    /**
     * Returns a mapping from the name of an activity to the activity's largest execution time, decayed by time.
     *

     * Without decay this method would return the absolute largest execution time for each activity, since
     * it was first started. Instead, this method returns the largest -most recent- execution time for
     * each activity.
     *
     * @return a mapping from activity name to largest most recent execution time per cycle.
     */
    // TODO: change to return the largest execution time over the monitored interval - no decay involved. See comment in
    // TODO: https://github.com/emanuele3d/Terasology/commit/36cf9bf23b42f76793a5d5968ef4e25986aa9706#commitcomment-11445526
    public static TObjectDoubleMap<String> getDecayingSpikes() {
        return instance.getDecayingSpikes();
    }

    /**
     * Returns a mapping from the name of an activity to a running mean of allocated memory during
     * the execution of the activity, over a number of cycles.
     *

     * Activities may be nested, and while a nested activity is running the collection of data from
     * outer activities is paused and allocated memory is not assigned to them.
     *

     * No guarantee can be given that the memory allocated during the execution of an activity is
     * entirely due to the activity. Other threads for example might increase or decrease the
     * figure.
     *
     * @return a mapping from activity name to running mean of allocated memory.
     */
    public static TObjectDoubleMap<String> getAllocationMean() {
        return instance.getAllocationMean();
    }

    /**
     * Enables or disables the Performance Monitoring system.
     *

     * When disabled all data is purged and calls to startActivity()/endActivity() and rollCycle() are ignored.
     *
     * @param enabled True turns the Performance Monitoring system ON. False turns it OFF.
     */
    public static void setEnabled(boolean enabled) {
        if (enabled && !(instance instanceof PerformanceMonitorImpl)) {
            instance = new PerformanceMonitorImpl();
        } else if (!enabled && !(instance instanceof NullPerformanceMonitor)) {
            instance = new NullPerformanceMonitor();
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
package gov.va.med.imaging.storage.cache;

import gov.va.med.imaging.storage.cache.exceptions.CacheException;

import java.util.Iterator;

/**
 * Implemented by a MutableNamedObject that is a Set of Group (Group and Region).
 * @see Group
 * @see Region
 * @author VHAISWBECKEC
 *
 * NOTE: this interface defines methods that generally follow the Set methods though the method
 * naming is different.  This is because InstanceSet and GroupSet may both be implemented by a
 * single class and the naming would get confused otherwise.
 *
 * NOTE: the word "delete" is used to mean specifically remove from a Collection.  The word
 * "remove" is used to mean specifically remove a persistent copy of an Instance or Group.
 */
public interface GroupSet
{
	public Iterator<? extends Group> getGroups()
	throws CacheException;

	public Group getOrCreateChildGroup(String group)
	throws CacheException;

	public Group getChildGroup(String group)
	throws CacheException;

	public void deleteChildGroup(Group childGroup, boolean forceDelete)
	throws CacheException;

	public void deleteAllChildGroups(boolean forceDelete)
	throws CacheException;

	// ============================================================================
	// Eviction Related Methods
	// ============================================================================
	/**
	 * @param judge
	 * @return
	 * @throws CacheException
	 */
	public int evaluateAndEvictChildGroups(EvictionJudge<Group> judge)
	throws CacheException;
}


text:
"""
Created on July 2017

@author: JulienWuthrich
"""
import string

def format_str(bad_str, hard=False):
    try:
        if hard:
            for char in string.punctuation:
                bad_str = bad_str.replace(char, '')

        return " ".join(bad_str.split()).lower()
    except TypeError as te:
        return bad_str


text:
import os
import re

_punctuation_mapper = dict(zip(
    u'?!。,、:《》""'' ',
    u'?!.,,:<>""\'\' '))

def _load_character_mapper():
    mapper = dict()
    filename = os.path.dirname(__file__)
    filename += '/chars.txt'
    f = open(filename)
    try:
        for line in f:
            if re.match('^[\s]*#', line):
                continue
            line = line.strip()
            columns = re.split('[\s(,)]+', line)
            ch = unichr(int(columns[0], 16))
            pinyin = columns[1:-1]
            if len(pinyin) > 1:
                mapper[ch] = pinyin
            else:
                mapper[ch] = pinyin[0]
    finally:
        f.close()
    return mapper

_character_mapper = _load_character_mapper()

class Tokenizer:
    def __init__(self, text):
        assert isinstance(text, unicode)

        self._text = text
        self._pos = 0
        self._length = len(text)

    def __iter__(self):
        return self

    def next(self):
        if self._pos >= self._length:
            raise StopIteration

        i = self._pos
        type = self._char_type(self._text[i])

        while True:
            i += 1
            if i >= self._length or self._char_type(self._text[i]) != type:
                break

        try:
            return type, self._text[self._pos:i]
        finally:
            self._pos = i

    def _char_type(self, ch):
        if re.match('[\s]', ch):
            return 4
        elif ch in _punctuation_mapper:
            return 3
        elif ord(ch) <= 255:
            return 1
        else:
            return 2

class WordMapper:
    def __init__(self):
        self._mapper = dict()

    def load_from_file(self, filename):
        f = open(filename)
        try:
            for line in f:
                if re.match('^[\s]*#', line):
                    continue
                line = line.strip()
                columns = re.split('[\s]+', line)
                word = unicode(columns[0], 'UTF-8')
                pinyin = columns[1:]
                self[word] = pinyin
        finally:
            f.close()

    def __setitem__(self, word, pinyin):
        assert isinstance(word, unicode)

        mapper = self._mapper
        for ch in word:
            if not ch in mapper:
                mapper[ch] = dict()
            mapper = mapper[ch]

        mapper['PY'] = pinyin

    def __getitem__(self, word):
        assert isinstance(word, unicode)

        length = len(word)

        pinyin = []
        pos = 0
        last_pinyin = None
        last_pos = 0
        mapper = self._mapper

        while pos < length:
            ch = word[pos]
            if ch in mapper:
                mapper = mapper[ch]
                if 'PY' in mapper:
                    last_pinyin = mapper['PY']
                    last_pos = pos
                pos += 1
                if pos < length:
                    continue

            if last_pinyin is None:
                ch = word[last_pos]
                if ch in _character_mapper:
                    last_pinyin = _character_mapper[ch]
                else:
                    last_pinyin = ch
                if len(last_pinyin) > 1:
                    pinyin.append(last_pinyin)
                else:
                    pinyin.extend(last_pinyin)
            else:
                pinyin.extend(last_pinyin)

            pos = last_pos + 1
            mapper = self._mapper
            last_pinyin = None
            last_pos = pos

        if last_pinyin is not None:
            pinyin.extend(last_pinyin)

        return pinyin

class Converter:
    def __init__(self, word_mapper=WordMapper()):
        self._word_mapper = word_mapper

    def load_word_file(self, filename):
        self._word_mapper.load_from_file(filename)

    def convert(self, text, fmt='df', sc=True, pp=False, fuzzy=0):
        if not isinstance(text, unicode):
            text = unicode(text, 'UTF-8')

        tokenizer = Tokenizer(text)
        tokens = map(self._convert_token, tokenizer)

        pinyin = ''
        last_type = 4
        for type, word in tokens:
            if type == 2:
                if last_type != 4:
                    pinyin += ' '
                pinyin += self._format_word(word, fmt, sc, pp, fuzzy)
                pass
            elif type == 3:
                pinyin += word
            elif type == 4:
                pinyin += word
            else:
                if last_type == 2:
                    pinyin += ' '
                pinyin += word

            last_type = type

        return pinyin

    def _convert_token(self, token):
        type, word = token
        if type == 2:
            return type, self._word_mapper[word]
        elif type == 3:
            return type, _punctuation_mapper[word]
        else:
            return type, word.encode('UTF-8')

    def _format_word(self, word, fmt, sc, pp, fuzzy):
        if pp and not sc:
            pinyin_set = set()
            pinyin_list = [None] * len(word)
            def func(idx):
                if idx >= len(word):
                    pinyin_set.add(''.join(pinyin_list))
                    return
                ch = word[idx]
                if isinstance(ch, list):
                    for c in ch:
                        pinyin_list[idx] = self._format_ch(c, fmt, fuzzy)
                        func(idx+1)
                else:
                    pinyin_list[idx] = self._format_ch(ch, fmt, fuzzy)
                    func(idx+1)
            func(0)
            return '|'.join(pinyin_set)

        def func(ch):
            if isinstance(ch, list):
                pinyin_list = []
                if pp:
                    for c in ch:
                        pinyin_list.append(self._format_ch(c, fmt, fuzzy))
                else:
                    pinyin_list.append(self._format_ch(ch[0], fmt, fuzzy))
                return '|'.join(set(pinyin_list))
            else:
                return self._format_ch(ch, fmt, fuzzy)

        pinyin_list = map(func, word)
        if sc:
            return ' '.join(pinyin_list)
        else:
            return ''.join(pinyin_list)

    def _format_ch(self, ch, fmt, fuzzy):
        if fuzzy > 0:
            raise Exception('Not implemented')

        if fmt == 'df':
            return ch[:-1]

        if fmt == 'tn':
            return ch

        if fmt == 'fl':
            return ch[0]

        raise Exception('Not implemented')


text:
=======
Iter IO
=======

.. automodule:: werkzeug.contrib.iterio

.. autoclass:: IterIO
   :members:


text:
module Haml
  module Generator
    def source_root
      File.expand_path("../#{generator_name}/templates", __FILE__)
    end

    def self.extended(klass)
      klass.class_eval { def handler() :haml end }
    end
  end
end


text:
import Blog from './blog';

'use strict';

let $module = angular.mock.module;
let $inject = angular.mock.inject;
let $dump = (arg: any): void => console.log(angular.mock.dump(arg));

describe('# Blog Module', () => {
  beforeEach($module(Blog));

  describe('## Existence', () => {
    let mod;

    beforeEach(() => mod = angular.module(Blog));

    it('should exist', () => {
      expect(mod).not.toBeUndefined();
      expect(mod).not.toBeNull;
    });

    it('should have deps', () => {
      expect(mod.requires).toContain('ngComponentRouter');
      expect(mod.requires).toContain('app.components.material');
    });
  });

  describe('## Log enabled', () => {
    let $log;

    beforeEach(() => {
      $inject(_$log_ => {
        $log = _$log_;
      });
    });

    it('should log registration', () => {
      let loaded = ['ngModule', Blog, 'loaded'].join(' ');
      expect($log.debug.logs).toContain([loaded]);
    });
  });

  describe('## Log disabled', () => {
    let $log;

    beforeEach(() => {
      $module($logProvider => {
        $logProvider.debugEnabled(false);
      });

      $inject(_$log_ => {
        $log = _$log_;
      });
    });

    it('should not log registration', () => {
      expect($log.assertEmpty).not.toThrow();
    });
  });
});


text:
<?php return '<select id="default_manga_list_path" name="default_manga_list_path">
    <option value="reading">Reading</option>
    <option value="plan_to_read">Plan to Read</option>
    <option value="on_hold">On Hold</option>
    <option value="dropped">Dropped</option>
    <option value="completed">Completed</option>
    <option value="all">All</option>
</select>
';


text: Tests XHR network resource payload is not corrupted by transcoding.


text:
The Suppliers Listing lists all customers who have an outstanding balance by default. You can change it to list all suppliers by clicking *Show All* (and change it back by clicking *Outstanding only*). Click on a supplier to select it.

## Supplier Detail

When you have clicked on a supplier, you see the Supplier Detail screen. This shows all outstanding invoices (and credit notes and payments) - documents - for the supplier. You can change it to list all documents by clicking *Show All*. Click on a document to display it.

## Bills & Credits

Click _New Bill_ or _New Credit_ to create a new one. Or choose an existing one from the supplier listing to edit it.

Type the supplier name in the supplier field. As you type, a drop down of existing suppliers with similar names appears, which you can click on to choose one. If you type a new supplier name in, when you leave the field you will be asked if you want to create a new supplier, and then you can type in their address. If you choose an existing supplier, the address field will automatically be filled from the supplier record, although you can overwrite it if the invoice is from a different address (but that won't update the supplier record). Also, the lines from the last invoice from that supplier will be copied in, which you can amend or delete as appropriate.

Check the date is correct (the default date is today).

Number the invoice - you can either type in your own invoice number, or press the *Next* button - the next unused invoice number will be assigned when you save the invoice.

Now add the invoice lines - for each line, choose an account. Enter the Vat Code and Amount. Note that you can overwrite the calculated VAT if the supplier has calculated the VAT differently (perhaps they use a different rounding method). You can add a note to the line in the Memo field if you like. As you enter each new line, a new blank line will appear below. You can delete an existing line by pressing the red ![x](../images/close.png).

Note that the total and VAT total are updated automatically as you amend the lines.

## Bill Payments

To pay one or more supplier invoices, use the *Suppliers*/*New Bill Payment* screen. Select the required supplier from the dropdown. The supplier address and phone number will be filled in, and a list of all outstanding invoices and credit notes will appear.

Then enter the bank account from which to make the payment. Check the date is correct.

Now choose the invoices to pay, by ticking the invoices - this will add each invoice to the amount to pay. If you tick a credit, the amount to pay will obviously reduce. If you want to only part pay an invoice, reduce the Amount Paid against that invoice.

Note - if you have a credit note you want to allocate to an invoice, you can create a Bill Payment of zero, and tick the credit note and the invoice.

## Amending a document that has been allocated

By default, only documents that have not been fully allocated appear in the Supplier Detail screen - however, if you click *Show All* at the top left, you can see all the documents, and click on one to edit it.


text:
![](Screenshot.jpg)

This sample demonstrates how to integrate the [Shadowing component](https://github.com/DiligentGraphics/DiligentFX/tree/master/Components#shadows)
into an application to render high-quality shadows.

Sample controls:

* Left mouse button - rotate camera
* Right mouse button - rotate light
* W,S,A,D,Q,E - move camera
* Shift - accelerate
* Ctrl - super accelerate


text:
"""test tts module."""
import random
import string
import unittest
try:  # py3
    from unittest import mock
except ImportError:  # py2
    import mock

import pytest

try:
    from melissa.tts import tts
except IOError:
    # NOTE: don't test with existing profile.
    # taken from http://stackoverflow.com/a/8658332
    # mocking the import so mock_profile could be loaded.
    # Store original __import__
    orig_import = __import__
    # This will be the profile module
    mock_profile = mock.Mock()
    # set mock as default value to make run the test
    DEFAULT_PROFILE_DATA = {
        'va_gender': mock.Mock(),
        'tts': mock.Mock(),
    }
    mock_profile.data = DEFAULT_PROFILE_DATA

    # mock_import side effect
    def import_mock(name, *args):
        """import mock side effect."""
        if name == 'profile':
            return mock_profile
        return orig_import(name, *args)

    with mock.patch('__builtin__.__import__', side_effect=import_mock):
        from melissa.tts import tts

def get_random_string(exclude_list):
    """get random gender which is not 'female' or 'male'."""
    length = 10
    result = ''.join(random.choice(string.lowercase) for i in range(length))
    while result in exclude_list:
        result = ''.join(
            random.choice(string.lowercase) for i in range(length)
        )
    return result

def test_empty_string():
    """test empty string."""
    assert tts('') == 0

def test_mock_input():
    """test using different type of variable such as Mock object."""
    # NOTE: tts only receive string or equivalent as input.
    with pytest.raises(TypeError):
        tts(mock.Mock())

@mock.patch('melissa.tts.subprocess')
@mock.patch('melissa.tts.sys')
class TestDifferentPlatform(unittest.TestCase):
    """test different platform."""

    def setUp(self):
        """set up func."""
        self.message = ''
        mock_profile.data = DEFAULT_PROFILE_DATA

    def test_default_mock(self, mock_sys, mock_subprocess):
        """test using default mock obj."""
        tts(self.message)
        # NOTE: the default for linux/win32 with gender male.
        # ( see non-exitent 'ven+f3' flag)
        mock_call = mock.call.call(['espeak', '-s170', self.message])
        assert mock_call in mock_subprocess.mock_calls
        assert len(mock_subprocess.mock_calls) == 1

    def test_darwin_platform(self, mock_sys, mock_subprocess):
        """test darwin platform."""
        random_gender = get_random_string(exclude_list=('female', 'male'))
        # tuple contain (gender, mock_call)
        data = (
            (None, lambda x: mock.call.call(['say', x])),
            (random_gender, lambda x: mock.call.call(['say', x])),
            ('female', lambda x: mock.call.call(['say', x])),
            ('male', lambda x: mock.call.call(['say', '-valex', x])),
        )
        mock_sys.platform = 'darwin'
        for gender, mock_call in data:
            if gender is not None:
                DEFAULT_PROFILE_DATA['va_gender'] = gender
            mock_profile.data = DEFAULT_PROFILE_DATA
            tts(self.message)
            # NOTE: the default for macos with gender female.
            # (it don't have 'valex' flag)
            assert mock_call(self.message) in mock_subprocess.mock_calls
            assert len(mock_subprocess.mock_calls) == 1
            mock_subprocess.reset_mock()

    def test_random_platform(self, mock_sys, mock_subprocess):
        """test random platform."""
        mock_sys.platform = get_random_string(
            exclude_list=('linux', 'darwin', 'win32')
        )
        tts(self.message)
        # empty list/mock_subprocess not called
        assert not mock_subprocess.mock_calls

    def test_linux_win32_platform(self, mock_sys, mock_subprocess):
        """test linux and win32 platform."""
        random_gender = get_random_string(exclude_list=('female', 'male'))
        # tuple contain (gender, mock_call)

        def gender_mock_call(language=None):
            """mock_call func for testing."""
            if language is None:
                return lambda x: mock.call.call(['espeak', '-s170', x])
            else:
                return lambda x: mock.call.call(
                    ['espeak', language, '-s170', x]
                )

        male_mock_call = gender_mock_call()
        female_mock_call = gender_mock_call(language='-ven+f3')
        data = (
            (None, male_mock_call),
            (random_gender, male_mock_call),
            ('female', female_mock_call),
            ('male', male_mock_call),
        )
        for gender, gmock_call in data:
            if gender is not None:
                mock_profile.data['va_gender'] = gender
            for platform in ['linux', 'win32']:
                mock_sys.platform = platform

                tts(self.message)
                last_mock_call = gmock_call(self.message)
                test_rep = 'platform:[{}], gender:[{}]'.format(
                    platform, gender
                )
                assert last_mock_call in mock_subprocess.mock_calls, test_rep
                assert len(mock_subprocess.mock_calls) == 1

                # reset mock_subprocess
                mock_subprocess.reset_mock()

    def test_pyvona(self, mock_sys, mock_subprocess):
        """test pyvona."""
        random_gender = get_random_string(
            exclude_list=('female', 'male')
        )
        mock_access_key = mock.Mock()
        mock_secret_key = mock.Mock()
        for gender in ('male', 'female', random_gender):
            mock_profile.data = {
                'va_gender': gender,
                'tts': 'ivona',
                'ivona': {
                    'access_key': mock_access_key,
                    'secret_key': mock_secret_key,
                }
            }
            with mock.patch('melissa.tts.pyvona') as mock_pyvona:
                tts(self.message)
                # test voice name
                assert len(mock_pyvona.mock_calls) == 2
                # test voice name
                if gender == 'female':
                    assert mock_pyvona.create_voice().voice_name == 'Salli'
                elif gender == 'male':
                    assert mock_pyvona.create_voice().voice_name == 'Joey'
                else:
                    assert mock_pyvona.create_voice().voice_name == 'Joey'
                create_voice_call = mock.call.create_voice(
                    mock_access_key, mock_secret_key
                )
                assert create_voice_call in mock_pyvona.mock_calls
                engine_speak_call = mock.call.create_voice().speak(
                    self.message
                )
                assert engine_speak_call in mock_pyvona.mock_calls


text:
{-# LANGUAGE CPP #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UndecidableInstances #-}
#ifdef TRUSTWORTHY
{-# LANGUAGE Trustworthy #-}
#endif
{-# OPTIONS_GHC -fno-warn-orphans #-}
-----------------------------------------------------------------------------
-- |
-- Module      :  Control.Lens.Internal.Zoom
-- Copyright   :  (C) 2012-2014 Edward Kmett
-- License     :  BSD-style (see the file LICENSE)
-- Maintainer  :  Edward Kmett <ekmett@gmail.com>
-- Stability   :  experimental
-- Portability :  non-portable
--
----------------------------------------------------------------------------
module Control.Lens.Internal.Zoom
  (
  -- * Zoom
    Zoomed
  , Focusing(..)
  , FocusingWith(..)
  , FocusingPlus(..)
  , FocusingOn(..)
  , FocusingMay(..), May(..)
  , FocusingErr(..), Err(..)
  -- * Magnify
  , Magnified
  , EffectRWS(..)
  ) where

import Control.Applicative
import Control.Category
import Control.Comonad
import Control.Lens.Internal.Action
import Control.Monad.Reader as Reader
import Control.Monad.Trans.State.Lazy as Lazy
import Control.Monad.Trans.State.Strict as Strict
import Control.Monad.Trans.Writer.Lazy as Lazy
import Control.Monad.Trans.Writer.Strict as Strict
import Control.Monad.Trans.RWS.Lazy as Lazy
import Control.Monad.Trans.RWS.Strict as Strict
import Control.Monad.Trans.Error
import Control.Monad.Trans.List
import Control.Monad.Trans.Identity
import Control.Monad.Trans.Maybe
import Data.Functor.Bind
import Data.Functor.Contravariant
import Data.Semigroup
import Prelude hiding ((.),id)

------------------------------------------------------------------------------
-- Zoomed
------------------------------------------------------------------------------

-- | This type family is used by 'Control.Lens.Zoom.Zoom' to describe the common effect type.
type family Zoomed (m :: * -> *) :: * -> * -> *
type instance Zoomed (Strict.StateT s z) = Focusing z
type instance Zoomed (Lazy.StateT s z) = Focusing z
type instance Zoomed (ReaderT e m) = Zoomed m
type instance Zoomed (IdentityT m) = Zoomed m
type instance Zoomed (Strict.RWST r w s z) = FocusingWith w z
type instance Zoomed (Lazy.RWST r w s z) = FocusingWith w z
type instance Zoomed (Strict.WriterT w m) = FocusingPlus w (Zoomed m)
type instance Zoomed (Lazy.WriterT w m) = FocusingPlus w (Zoomed m)
type instance Zoomed (ListT m) = FocusingOn [] (Zoomed m)
type instance Zoomed (MaybeT m) = FocusingMay (Zoomed m)
type instance Zoomed (ErrorT e m) = FocusingErr e (Zoomed m)

------------------------------------------------------------------------------
-- Focusing
------------------------------------------------------------------------------

-- | Used by 'Control.Lens.Zoom.Zoom' to 'Control.Lens.Zoom.zoom' into 'Control.Monad.State.StateT'.
newtype Focusing m s a = Focusing { unfocusing :: m (s, a) }

instance Monad m => Functor (Focusing m s) where
  fmap f (Focusing m) = Focusing $ do
     (s, a) <- m
     return (s, f a)
  {-# INLINE fmap #-}

instance (Monad m, Semigroup s) => Apply (Focusing m s) where
  Focusing mf <.> Focusing ma = Focusing $ do
    (s, f) <- mf
    (s', a) <- ma
    return (s <> s', f a)
  {-# INLINE (<.>) #-}

instance (Monad m, Monoid s) => Applicative (Focusing m s) where
  pure a = Focusing (return (mempty, a))
  {-# INLINE pure #-}
  Focusing mf <*> Focusing ma = Focusing $ do
    (s, f) <- mf
    (s', a) <- ma
    return (mappend s s', f a)
  {-# INLINE (<*>) #-}

------------------------------------------------------------------------------
-- FocusingWith
------------------------------------------------------------------------------

-- | Used by 'Control.Lens.Zoom.Zoom' to 'Control.Lens.Zoom.zoom' into 'Control.Monad.RWS.RWST'.
newtype FocusingWith w m s a = FocusingWith { unfocusingWith :: m (s, a, w) }

instance Monad m => Functor (FocusingWith w m s) where
  fmap f (FocusingWith m) = FocusingWith $ do
     (s, a, w) <- m
     return (s, f a, w)
  {-# INLINE fmap #-}

instance (Monad m, Semigroup s, Semigroup w) => Apply (FocusingWith w m s) where
  FocusingWith mf <.> FocusingWith ma = FocusingWith $ do
    (s, f, w) <- mf
    (s', a, w') <- ma
    return (s <> s', f a, w <> w')
  {-# INLINE (<.>) #-}

instance (Monad m, Monoid s, Monoid w) => Applicative (FocusingWith w m s) where
  pure a = FocusingWith (return (mempty, a, mempty))
  {-# INLINE pure #-}
  FocusingWith mf <*> FocusingWith ma = FocusingWith $ do
    (s, f, w) <- mf
    (s', a, w') <- ma
    return (mappend s s', f a, mappend w w')
  {-# INLINE (<*>) #-}

------------------------------------------------------------------------------
-- FocusingPlus
------------------------------------------------------------------------------

-- | Used by 'Control.Lens.Zoom.Zoom' to 'Control.Lens.Zoom.zoom' into 'Control.Monad.Writer.WriterT'.
newtype FocusingPlus w k s a = FocusingPlus { unfocusingPlus :: k (s, w) a }

instance Functor (k (s, w)) => Functor (FocusingPlus w k s) where
  fmap f (FocusingPlus as) = FocusingPlus (fmap f as)
  {-# INLINE fmap #-}

instance Apply (k (s, w)) => Apply (FocusingPlus w k s) where
  FocusingPlus kf <.> FocusingPlus ka = FocusingPlus (kf <.> ka)
  {-# INLINE (<.>) #-}

instance Applicative (k (s, w)) => Applicative (FocusingPlus w k s) where
  pure = FocusingPlus . pure
  {-# INLINE pure #-}
  FocusingPlus kf <*> FocusingPlus ka = FocusingPlus (kf <*> ka)
  {-# INLINE (<*>) #-}

------------------------------------------------------------------------------
-- FocusingOn
------------------------------------------------------------------------------

-- | Used by 'Control.Lens.Zoom.Zoom' to 'Control.Lens.Zoom.zoom' into 'Control.Monad.Trans.Maybe.MaybeT' or 'Control.Monad.Trans.List.ListT'.
newtype FocusingOn f k s a = FocusingOn { unfocusingOn :: k (f s) a }

instance Functor (k (f s)) => Functor (FocusingOn f k s) where
  fmap f (FocusingOn as) = FocusingOn (fmap f as)
  {-# INLINE fmap #-}

instance Apply (k (f s)) => Apply (FocusingOn f k s) where
  FocusingOn kf <.> FocusingOn ka = FocusingOn (kf <.> ka)
  {-# INLINE (<.>) #-}

instance Applicative (k (f s)) => Applicative (FocusingOn f k s) where
  pure = FocusingOn . pure
  {-# INLINE pure #-}
  FocusingOn kf <*> FocusingOn ka = FocusingOn (kf <*> ka)
  {-# INLINE (<*>) #-}

------------------------------------------------------------------------------
-- May
------------------------------------------------------------------------------

-- | Make a 'Monoid' out of 'Maybe' for error handling.
newtype May a = May { getMay :: Maybe a }

instance Semigroup a => Semigroup (May a) where
  May Nothing <> _ = May Nothing
  _ <> May Nothing = May Nothing
  May (Just a) <> May (Just b) = May (Just (a <> b))
  {-# INLINE (<>) #-}

instance Monoid a => Monoid (May a) where
  mempty = May (Just mempty)
  {-# INLINE mempty #-}
  May Nothing `mappend` _ = May Nothing
  _ `mappend` May Nothing = May Nothing
  May (Just a) `mappend` May (Just b) = May (Just (mappend a b))
  {-# INLINE mappend #-}

------------------------------------------------------------------------------
-- FocusingMay
------------------------------------------------------------------------------

-- | Used by 'Control.Lens.Zoom.Zoom' to 'Control.Lens.Zoom.zoom' into 'Control.Monad.Error.ErrorT'.
newtype FocusingMay k s a = FocusingMay { unfocusingMay :: k (May s) a }

instance Functor (k (May s)) => Functor (FocusingMay k s) where
  fmap f (FocusingMay as) = FocusingMay (fmap f as)
  {-# INLINE fmap #-}

instance Apply (k (May s)) => Apply (FocusingMay k s) where
  FocusingMay kf <.> FocusingMay ka = FocusingMay (kf <.> ka)
  {-# INLINE (<.>) #-}

instance Applicative (k (May s)) => Applicative (FocusingMay k s) where
  pure = FocusingMay . pure
  {-# INLINE pure #-}
  FocusingMay kf <*> FocusingMay ka = FocusingMay (kf <*> ka)
  {-# INLINE (<*>) #-}

------------------------------------------------------------------------------
-- Err
------------------------------------------------------------------------------

-- | Make a 'Monoid' out of 'Either' for error handling.
newtype Err e a = Err { getErr :: Either e a }

instance Semigroup a => Semigroup (Err e a) where
  Err (Left e) <> _ = Err (Left e)
  _ <> Err (Left e) = Err (Left e)
  Err (Right a) <> Err (Right b) = Err (Right (a <> b))
  {-# INLINE (<>) #-}

instance Monoid a => Monoid (Err e a) where
  mempty = Err (Right mempty)
  {-# INLINE mempty #-}
  Err (Left e) `mappend` _ = Err (Left e)
  _ `mappend` Err (Left e) = Err (Left e)
  Err (Right a) `mappend` Err (Right b) = Err (Right (mappend a b))
  {-# INLINE mappend #-}

------------------------------------------------------------------------------
-- FocusingErr
------------------------------------------------------------------------------

-- | Used by 'Control.Lens.Zoom.Zoom' to 'Control.Lens.Zoom.zoom' into 'Control.Monad.Error.ErrorT'.
newtype FocusingErr e k s a = FocusingErr { unfocusingErr :: k (Err e s) a }

instance Functor (k (Err e s)) => Functor (FocusingErr e k s) where
  fmap f (FocusingErr as) = FocusingErr (fmap f as)
  {-# INLINE fmap #-}

instance Apply (k (Err e s)) => Apply (FocusingErr e k s) where
  FocusingErr kf <.> FocusingErr ka = FocusingErr (kf <.> ka)
  {-# INLINE (<.>) #-}

instance Applicative (k (Err e s)) => Applicative (FocusingErr e k s) where
  pure = FocusingErr . pure
  {-# INLINE pure #-}
  FocusingErr kf <*> FocusingErr ka = FocusingErr (kf <*> ka)
  {-# INLINE (<*>) #-}

------------------------------------------------------------------------------
-- Magnified
------------------------------------------------------------------------------

-- | This type family is used by 'Control.Lens.Zoom.Magnify' to describe the common effect type.
type family Magnified (m :: * -> *) :: * -> * -> *
type instance Magnified (ReaderT b m) = Effect m
type instance Magnified ((->)b) = Const
type instance Magnified (Strict.RWST a w s m) = EffectRWS w s m
type instance Magnified (Lazy.RWST a w s m) = EffectRWS w s m
type instance Magnified (IdentityT m) = Magnified m

------------------------------------------------------------------------------
-- EffectRWS
------------------------------------------------------------------------------

-- | Wrap a monadic effect with a phantom type argument. Used when magnifying 'Control.Monad.RWS.RWST'.
newtype EffectRWS w st m s a = EffectRWS { getEffectRWS :: st -> m (s,st,w) }

instance Functor (EffectRWS w st m s) where
  fmap _ (EffectRWS m) = EffectRWS m
  {-# INLINE fmap #-}

instance (Semigroup s, Semigroup w, Bind m) => Apply (EffectRWS w st m s) where
  EffectRWS m <.> EffectRWS n = EffectRWS $ \st -> m st >>- \ (s,t,w) -> fmap (\(s',u,w') -> (s <> s', u, w <> w')) (n t)
  {-# INLINE (<.>) #-}

instance (Monoid s, Monoid w, Monad m) => Applicative (EffectRWS w st m s) where
  pure _ = EffectRWS $ \st -> return (mempty, st, mempty)
  {-# INLINE pure #-}
  EffectRWS m <*> EffectRWS n = EffectRWS $ \st -> m st >>= \ (s,t,w) -> n t >>= \ (s',u,w') -> return (mappend s s', u, mappend w w')
  {-# INLINE (<*>) #-}

instance Contravariant (EffectRWS w st m s) where
  contramap _ (EffectRWS m) = EffectRWS m
  {-# INLINE contramap #-}


text:
<?php

require_once dirname(__FILE__) . '/PlatformMigrationTestProvider.php';
require_once dirname(__FILE__) . '/../../../../generator/lib/platform/PgsqlPlatform.php';
require_once dirname(__FILE__) . '/../../../../generator/lib/model/Column.php';
require_once dirname(__FILE__) . '/../../../../generator/lib/model/VendorInfo.php';

/**
 *
 * @package    generator.platform
 */
class PgsqlPlatformMigrationTest extends PlatformMigrationTestProvider
{

    /**
     * Get the Platform object for this class
     *
     * @return Platform
     */
    protected function getPlatform()
    {
        return new PgsqlPlatform();
    }

    /**
     * @dataProvider providerForTestGetModifyDatabaseDDL
     */
    public function testGetModifyDatabaseDDL($databaseDiff)
    {
        $expected = <<<END

DROP TABLE IF EXISTS "foo1" CASCADE;

ALTER TABLE "foo3" RENAME TO "foo4";

CREATE TABLE "foo5"
(
    "id" serial NOT NULL,
    "lkdjfsh" INTEGER,
    "dfgdsgf" TEXT,
    PRIMARY KEY ("id")
);

ALTER TABLE "foo2" RENAME COLUMN "bar" TO "bar1";

ALTER TABLE "foo2" ALTER COLUMN "baz" DROP NOT NULL;

ALTER TABLE "foo2" ADD "baz3" TEXT;

END;
        $this->assertEquals($expected, $this->getPlatform()->getModifyDatabaseDDL($databaseDiff));
    }

    /**
     * @dataProvider providerForTestGetRenameTableDDL
     */
    public function testGetRenameTableDDL($fromName, $toName)
    {
        $expected = '
ALTER TABLE "foo1" RENAME TO "foo2";
';
        $this->assertEquals($expected, $this->getPlatform()->getRenameTableDDL($fromName, $toName));
    }

    /**
     * @dataProvider providerForTestGetModifyTableDDL
     */
    public function testGetModifyTableDDL($tableDiff)
    {
        $expected = <<<END

ALTER TABLE "foo" DROP CONSTRAINT "foo1_FK_2";

ALTER TABLE "foo" DROP CONSTRAINT "foo1_FK_1";

DROP INDEX "bar_baz_FK";

DROP INDEX "bar_FK";

ALTER TABLE "foo" RENAME COLUMN "bar" TO "bar1";

ALTER TABLE "foo" ALTER COLUMN "baz" DROP NOT NULL;

ALTER TABLE "foo" ADD "baz3" TEXT;

CREATE INDEX "bar_FK" ON "foo" ("bar1");

CREATE INDEX "baz_FK" ON "foo" ("baz3");

ALTER TABLE "foo" ADD CONSTRAINT "foo1_FK_1"
    FOREIGN KEY ("bar1")
    REFERENCES "foo2" ("bar");

END;
        $this->assertEquals($expected, $this->getPlatform()->getModifyTableDDL($tableDiff));
    }

    /**
     * @dataProvider providerForTestGetModifyTableColumnsDDL
     */
    public function testGetModifyTableColumnsDDL($tableDiff)
    {
        $expected = <<<END

ALTER TABLE "foo" RENAME COLUMN "bar" TO "bar1";

ALTER TABLE "foo" ALTER COLUMN "baz" DROP NOT NULL;

ALTER TABLE "foo" ADD "baz3" TEXT;

END;
        $this->assertEquals($expected, $this->getPlatform()->getModifyTableColumnsDDL($tableDiff));
    }

    /**
     * @dataProvider providerForTestGetModifyTablePrimaryKeysDDL
     */
    public function testGetModifyTablePrimaryKeysDDL($tableDiff)
    {
        $expected = <<<END

ALTER TABLE "foo" DROP CONSTRAINT "foo_pkey";

ALTER TABLE "foo" ADD PRIMARY KEY ("id","bar");

END;
        $this->assertEquals($expected, $this->getPlatform()->getModifyTablePrimaryKeyDDL($tableDiff));
    }

    /**
     * @dataProvider providerForTestGetModifyTableIndicesDDL
     */
    public function testGetModifyTableIndicesDDL($tableDiff)
    {
        $expected = <<<END

DROP INDEX "bar_FK";

CREATE INDEX "baz_FK" ON "foo" ("baz");

DROP INDEX "bar_baz_FK";

CREATE INDEX "bar_baz_FK" ON "foo" ("id","bar","baz");

END;
        $this->assertEquals($expected, $this->getPlatform()->getModifyTableIndicesDDL($tableDiff));
    }

    /**
     * @dataProvider providerForTestGetModifyTableForeignKeysDDL
     */
    public function testGetModifyTableForeignKeysDDL($tableDiff)
    {
        $expected = <<<END

ALTER TABLE "foo1" DROP CONSTRAINT "foo1_FK_1";

ALTER TABLE "foo1" ADD CONSTRAINT "foo1_FK_5"
    FOREIGN KEY ("baz")
    REFERENCES "foo2" ("baz");

ALTER TABLE "foo1" DROP CONSTRAINT "foo1_FK_2";

ALTER TABLE "foo1" ADD CONSTRAINT "foo1_FK_2"
    FOREIGN KEY ("bar","id")
    REFERENCES "foo2" ("bar","id");

END;
        $this->assertEquals($expected, $this->getPlatform()->getModifyTableForeignKeysDDL($tableDiff));
    }

    /**
     * @dataProvider providerForTestGetModifyTableForeignKeysSkipSqlDDL
     */
    public function testGetModifyTableForeignKeysSkipSqlDDL($tableDiff)
    {
        $expected = <<<END

ALTER TABLE "foo1" DROP CONSTRAINT "foo1_FK_1";

END;
        $this->assertEquals($expected, $this->getPlatform()->getModifyTableForeignKeysDDL($tableDiff));
        $expected = <<<END

ALTER TABLE "foo1" ADD CONSTRAINT "foo1_FK_1"
    FOREIGN KEY ("bar")
    REFERENCES "foo2" ("bar");

END;
        $this->assertEquals($expected, $this->getPlatform()->getModifyTableForeignKeysDDL($tableDiff->getReverseDiff()));
    }

    /**
     * @dataProvider providerForTestGetModifyTableForeignKeysSkipSql2DDL
     */
    public function testGetModifyTableForeignKeysSkipSql2DDL($tableDiff)
    {
        $expected = '';
        $this->assertEquals($expected, $this->getPlatform()->getModifyTableForeignKeysDDL($tableDiff));
        $expected = '';
        $this->assertEquals($expected, $this->getPlatform()->getModifyTableForeignKeysDDL($tableDiff->getReverseDiff()));
    }

    /**
     * @dataProvider providerForTestGetRemoveColumnDDL
     */
    public function testGetRemoveColumnDDL($column)
    {
        $expected = '
ALTER TABLE "foo" DROP COLUMN "bar";
';
        $this->assertEquals($expected, $this->getPlatform()->getRemoveColumnDDL($column));
    }

    /**
     * @dataProvider providerForTestGetRenameColumnDDL
     */
    public function testGetRenameColumnDDL($fromColumn, $toColumn)
    {
        $expected = '
ALTER TABLE "foo" RENAME COLUMN "bar1" TO "bar2";
';
        $this->assertEquals($expected, $this->getPlatform()->getRenameColumnDDL($fromColumn, $toColumn));
    }

    /**
     * @dataProvider providerForTestGetModifyColumnDDL
     */
    public function testGetModifyColumnDDL($columnDiff)
    {
        $expected = '
ALTER TABLE "foo" ALTER COLUMN "bar" TYPE DOUBLE PRECISION;
';
        $this->assertEquals($expected, $this->getPlatform()->getModifyColumnDDL($columnDiff));
    }

    public function testGetModifyColumnDDLWithChangedTypeAndDefault()
    {
        $t1 = new Table('foo');
        $c1 = new Column('bar');
        $c1->getDomain()->copy($this->getPlatform()->getDomainForType('DOUBLE'));
        $c1->getDomain()->replaceSize(2);
        $t1->addColumn($c1);
        $t2 = new Table('foo');
        $c2 = new Column('bar');
        $c2->getDomain()->copy($this->getPlatform()->getDomainForType('DOUBLE'));
        $c2->getDomain()->replaceSize(3);
        $c2->getDomain()->setDefaultValue(new ColumnDefaultValue(-100, ColumnDefaultValue::TYPE_VALUE));
        $t2->addColumn($c2);
        $columnDiff = PropelColumnComparator::computeDiff($c1, $c2);
        $expected = <<<END

ALTER TABLE "foo" ALTER COLUMN "bar" TYPE DOUBLE PRECISION;

ALTER TABLE "foo" ALTER COLUMN "bar" SET DEFAULT -100;

END;
        $this->assertEquals($expected, $this->getPlatform()->getModifyColumnDDL($columnDiff));
    }

    /**
     * @dataProvider providerForTestGetModifyColumnsDDL
     */
    public function testGetModifyColumnsDDL($columnDiffs)
    {
        $expected = <<<END

ALTER TABLE "foo" ALTER COLUMN "bar1" TYPE DOUBLE PRECISION;

ALTER TABLE "foo" ALTER COLUMN "bar2" SET NOT NULL;

END;
        $this->assertEquals($expected, $this->getPlatform()->getModifyColumnsDDL($columnDiffs));
    }

    /**
     * @dataProvider providerForTestGetAddColumnDDL
     */
    public function testGetAddColumnDDL($column)
    {
        $expected = '
ALTER TABLE "foo" ADD "bar" INTEGER;
';
        $this->assertEquals($expected, $this->getPlatform()->getAddColumnDDL($column));
    }

    /**
     * @dataProvider providerForTestGetAddColumnsDDL
     */
    public function testGetAddColumnsDDL($columns)
    {
        $expected = <<<END

ALTER TABLE "foo" ADD "bar1" INTEGER;

ALTER TABLE "foo" ADD "bar2" DOUBLE PRECISION DEFAULT -1 NOT NULL;

END;
        $this->assertEquals($expected, $this->getPlatform()->getAddColumnsDDL($columns));
    }

    public function testGetModifyColumnDDLWithVarcharWithoutSize()
    {
        $t1 = new Table('foo');
        $c1 = new Column('bar');
        $c1->setTable($t1);
        $c1->getDomain()->copy($this->getPlatform()->getDomainForType('VARCHAR'));
        $c1->getDomain()->replaceSize(null);
        $c1->getDomain()->replaceScale(null);
        $t1->addColumn($c1);

        $schema = <<<EOF
<database name="test">

        <column name="id" primaryKey="true" type="INTEGER" autoIncrement="true" />
        <column name="bar" type="VARCHAR" />

</database>
EOF;

        $table = $this->getDatabaseFromSchema($schema)->getTable('foo');
        $c2 = $table->getColumn('bar');
        $columnDiff = PropelColumnComparator::computeDiff($c1, $c2);
        $expected = false;
        $this->assertSame($expected, $columnDiff);
    }

public function testGetModifyColumnDDLWithVarcharWithoutSizeAndPlatform()
    {
        $t1 = new Table('foo');
        $c1 = new Column('bar');
        $c1->setTable($t1);
        $c1->getDomain()->copy($this->getPlatform()->getDomainForType('VARCHAR'));
        $c1->getDomain()->replaceSize(null);
        $c1->getDomain()->replaceScale(null);
        $t1->addColumn($c1);

        $schema = <<<EOF
<database name="test">

        <column name="id" primaryKey="true" type="INTEGER" autoIncrement="true" />
        <column name="bar"/>

</database>
EOF;

        $xtad = new XmlToAppData(null);
        $appData = $xtad->parseString($schema);
        $db = $appData->getDatabase();
        $table = $db->getTable('foo');
        $c2 = $table->getColumn('bar');
        $columnDiff = PropelColumnComparator::computeDiff($c1, $c2);
        $expected = false;
        $this->assertSame($expected, $columnDiff);
    }

    /**
     * @dataProvider providerForTestGetModifyColumnRemoveDefaultValueDDL
     */
    public function testGetModifyColumnRemoveDefaultValueDDL($columnDiffs)
    {
        $expected = <<<EOF

ALTER TABLE "test" ALTER COLUMN "test" DROP DEFAULT;

EOF;
        $this->assertEquals($expected, $this->getPlatform()->getModifyColumnDDL($columnDiffs));
    }

    /**
     * @dataProvider providerForTestGetModifyTableForeignKeysSkipSql3DDL
     */
    public function testGetModifyTableForeignKeysSkipSql3DDL($databaseDiff)
    {
        $this->assertFalse($databaseDiff);
    }

    /**
     * @dataProvider providerForTestGetModifyTableForeignKeysSkipSql4DDL
     */
    public function testGetModifyTableForeignKeysSkipSql4DDL($databaseDiff)
    {
        $this->assertFalse($databaseDiff);
    }

}


text:
<?php
/**
 * Class for migrating theme options ( from earlier Hoot version ) to
 * theme mods (customizer settings in Hoot 2.0.0)
 * File loaded via after_setup_theme hook @priority 10
 *
 * @package hoot
 * @subpackage framework
 * @since hoot 2.0.0
 */

if ( defined( 'HOOT_MIGRATION' ) && HOOT_MIGRATION !== true )
	return;

/**
 * Migration class
 * Hoot 1.x.x to Hoot 2.0.0
 *
 * @since 2.0.0
 * @access public
 */
final class Hoot_Migration {

	/**
	 * The one instance of Hoot_Migration.
	 *
	 * @since 2.0.0
	 * @access private
	 * @var Hoot_Migration The one instance for the singleton.
	 */
	private static $instance;

	/**
	 * Hook into actions and filters
	 *
	 * @since 2.0.0
	 * @access public
	 * @return void
	 */
	public function __construct() {
		if ( is_admin() && current_user_can( 'edit_theme_options' ) ) {

			/* init migration */
			add_action( 'init', array( $this, 'init' ) );

		}
	}

	/**
	 * Init migration
	 *
	 * @since 2.0.0
	 * @access public
	 * @return void
	 */
	public function init() {

		$migrated = get_option( THEME_SLUG . '-migrated' );
		if ( !$migrated ) {
			$migrate = get_option( THEME_SLUG . '-migrate' );
			$optionsname = ( function_exists( 'hootoptions_option_name' ) ) ? hootoptions_option_name() : THEME_SLUG . '-options';
			$optionsvalue = get_option( $optionsname );
			if ( $optionsvalue ) {
				$this->migrate( $optionsvalue );
				if ( $migrate )
					update_option( THEME_SLUG . '-migrated', 'complete' );
				else
					update_option( THEME_SLUG . '-migrate', 'pass' );
				$migrated = 'complete';
			} else {
				update_option( THEME_SLUG . '-migrated', 'not-required' );
				update_option( THEME_SLUG . '-migrate', 'pass' );
				$migrated = 'not-required';
			}
		}

		if ( $migrated == 'complete' ) {
			$dismissed = get_option( THEME_SLUG . '-migration-notice-dismissed' );
			if ( !$dismissed ) {
				add_action( 'admin_enqueue_scripts', array( $this, 'enqueue' ) );
				add_action( 'admin_head', array( $this, 'inline_css' ) );
				add_action( 'admin_notices', array( $this, 'notice' ) );
			}
		}

	}

	/**
	 * Add message
	 *
	 * @since 2.0.0
	 * @access public
	 * @return void
	 */
	public function notice() {
		$migration_doc = apply_filters( 'hoot_theme_migration_doc_url', 'http://wphoot.com/support/hoot-2-0-migration/' );
		?>

<?php printf( __( 'Thank you for updating the theme. This version uses the new Hoot 2.0 framework.
You will find substantial changes in the new theme. %sClick here%s for support regarding migration to the new version.', 'responsive-brix' ), '', '' ); ?>

<?php _e( 'Dismiss', 'responsive-brix' ); ?>

		<?php
	}

	/**
	 * add css
	 *
	 * @since 2.0.0
	 * @access public
	 * @return void
	 */
	public function inline_css() {
		echo '';
	}

	/**
	 * enqueue migration notice scripts
	 *
	 * @since 2.0.0
	 * @access public
	 * @return void
	 */
	public function enqueue() {
		wp_enqueue_script( 'hoot_notice_update', trailingslashit( HOOT_THEMEURI ) . 'admin/js/notice-update.js', array( 'jquery' ), HOOT_VERSION, true );
		wp_localize_script( 'hoot_notice_update', 'hootdata', array(
			'ajax_url' => admin_url( 'admin-ajax.php' )
		));
	}

	/**
	 * Migrate values
	 *
	 * @since 2.0.0
	 * @param array $values
	 * @access public
	 * @return void
	 */
	public function migrate( $optionsvalue ) {

		foreach ( $optionsvalue as $key => $value ) {
			$newkey = $key;
			$newvalue = '';

			/** Calculate mod values for option values **/
			switch( $key ) {

				case 'logo_image_width':
					$newvalue = intval( $value );
					break;

				case 'favicon':
					$newkey = $newvalue = '';
					break;

				// Group - HTML Slider
				case 'wt_html_slider':
					$newvalue = array();
					$count = 1;
					if ( is_array( $value ) ) {
						foreach ( $value as $slide ) {
							if ( is_array( $slide ) ) {
								foreach ( $slide as $slideatt => $slideattval ) {
									if ( $slideatt != 'background' ) {
										$newvalue[ "wt_html_slide_{$count}-{$slideatt}" ] = $slideattval;
									} else {
										$background = $this->migrate_background( "wt_html_slide_{$count}-background", $slideattval );
										$newvalue = array_merge( $newvalue, $background );
									}
								}
							}
							$count++;
						}
					}
					break;

				// Group - Image Slider
				case 'wt_img_slider':
					$newvalue = array();
					$count = 1;
					if ( is_array( $value ) ) {
						foreach ( $value as $slide ) {
							if ( is_array( $slide ) ) {
								foreach ( $slide as $slideatt => $slideattval ) {
									$newvalue[ "wt_img_slide_{$count}-{$slideatt}" ] = $slideattval;
								}
							}
							$count++;
						}
					}
					break;

				// Group to Sortlist - Logo Custom
				case 'logo_custom':
					$newvalue = array();
					$count = 1;
					if ( is_array( $value ) ) {
						foreach ( $value as $line ) {
							if ( is_array( $line ) ) {
								$newvalue['logo_custom']["line{$count}"] = $line;
								$newvalue['logo_custom']["line{$count}"]['sortitem_hide'] = 0;
							}
							$count++;
						}
					}
					if ( !empty( $newvalue ) )
						$newvalue = http_build_query( $newvalue );
					else
						$newkey = $newvalue = '';
					break;

				// Sortlist (and others) - Widgetized Template Sections
				case 'widgetized_template_area_d_width':
				case 'widgetized_highlight_template_area':
					$newkey = $newvalue = '';
					break;
				case 'widgetized_template_sections':
					$newkey = $newvalue = '';
					break;

				// Checkboxes
				case 'disable_lightbox':
				case 'disable_sticky_header':
				case 'disable_goto_top':
				case 'post_featured_image':
				case 'post_prev_next_links':
				case 'custom_js_inheader':
					$newvalue = ( empty( $value ) ) ? 0 : 1;
					break;

				// Multicheckboxes
				case 'page_header_full':
				case 'archive_post_meta':
				case 'post_meta': case 'page_meta':
					if ( is_array( $value ) ) {
						foreach ( $value as $bgkey => $bgval ) {
							if ( !empty( $bgval ) )
								$newvalue .= $bgkey.',';
						}
					}
					$newvalue = trim( $newvalue, "," );
					break;

				// Background
				case 'background':
				case 'pageheader_background':
				case 'subfooter_background':
				case 'footer_background':
					$newvalue = $this->migrate_background( $key, $value );
					break;

				// Font
				case 'font_body':
				case 'font_h1': case 'font_h2': case 'font_h3': case 'font_h4': case 'font_h5': case 'font_h6':
				case 'font_logo': case 'font_tagline':
				case 'font_nav_menu': case 'font_nav_dropdown':
				case 'font_sidebar_heading': case 'font_sidebar':
				case 'font_footer_heading': case 'font_footer':
					$newvalue = array();
					if ( is_array( $value ) ) {
						foreach ( $value as $bgkey => $bgval ) {
							if ( !empty( $bgval ) )
								$newvalue[ $key . '-' . $bgkey ] = $bgval;
						}
					}
					break;

				// Rest options
				default:
					$newvalue = $value;

			}

			/** Allow modifications / additions **/
			$newkey = apply_filters( 'hoot_migration_newoptionkey', $newkey, $key, $value );
			$newvalue = apply_filters( 'hoot_migration_newoptionvalue', $newvalue, $key, $value );

			/** Set mods **/
			if ( !empty( $newkey ) ) {
				if ( is_string( $newkey ) && !is_array( $newvalue ) ) {
					set_theme_mod( $newkey, $newvalue );
				} elseif ( is_array( $newvalue ) ) {
					foreach ( $newvalue as $newvaluekey => $newvalueval ) {
						if ( is_string( $newvaluekey ) && is_string( $newvalueval ) ) {
							set_theme_mod( $newvaluekey, $newvalueval );
						}
					}
				}
			}

		}

		// Set Extra Options
		set_theme_mod( 'load_minified', 1 );

	}

	/**
	 * Calculate background
	 *
	 * @since 2.0.0
	 * @param string $key
	 * @param array $value
	 * @access public
	 * @return void
	 */
	public function migrate_background( $key, $value ) {

		$newvalue = array();
		if ( is_array( $value ) ) {
			foreach ( $value as $bgkey => $bgval ) {
				if ( $bgkey == 'pattern' && $bgval ){ // bgval is not 0
					if ( file_exists( trailingslashit(THEME_DIR) . 'hoot/images/patterns/' . $bgval ) ) {
						$bgval = 'hoot/images/patterns/' . $bgval;
					} else {
						// premium bg filenames were modified (to start from 1)
						$bgfile = intval( $bgval ) - 8;
						$bgext = substr( $bgval, -4 );
						if ( file_exists( trailingslashit(THEME_DIR) . 'premium/hoot/images/patterns/' . $bgfile . $bgext ) ) {
							$bgval = 'premium/hoot/images/patterns/' . $bgfile . $bgext;
						} else {
							$bgval = 0;
						}
					}
				}
				$newvalue[ $key . '-' . $bgkey ] = $bgval;
			}
		}
		return $newvalue;

	}

	/**
	 * Instantiate or return the one Hoot_Migration instance.
	 *
	 * @since 2.0.0
	 * @access public
	 * @return object
	 */
	public static function get_instance() {
		if ( is_null( self::$instance ) ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

}

/* Ajax call for migration notice */
add_action( 'wp_ajax_nopriv_hoot_dismiss_migration_notice', 'hoot_dismiss_migration_notice' );
add_action( 'wp_ajax_hoot_dismiss_migration_notice', 'hoot_dismiss_migration_notice' );
function hoot_dismiss_migration_notice() {
	if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
		update_option( THEME_SLUG . '-migration-notice-dismissed', '1' );
	}
}

/* Initialize class */
global $hoot_migration;
$hoot_migration = Hoot_Migration::get_instance();

/* Hook into this action to add options */
do_action( 'hoot_migration_loaded', $hoot_migration );


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable enable

using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;

namespace Microsoft.CodeAnalysis.Remote
{
    /// <summary>
    /// Create new <see cref="RemoteHostClient"/>.
    ///
    /// <see cref="IRemoteHostClientFactory"/> will use this to create new <see cref="RemoteHostClient"/>
    /// </summary>
    internal interface IRemoteHostClientFactory : IWorkspaceService
    {
        Task<RemoteHostClient?> CreateAsync(Workspace workspace, CancellationToken cancellationToken);
    }
}


text:
declare var fabric: any;
declare module 'fabricjs' {
  export = fabric;
}


text:
module Language.GroteTrap.Language (

  -- * Language
  Language(..), language,

  -- * Operators
  Operator(..),
  Fixity1(..), Fixity2(..),
  isUnary, isBinary, isAssoc,
  findOperator,

  -- * Functions
  Function(..),
  findFunction,
  function1, function2

  ) where

------------------------------------
-- Language
------------------------------------

-- | Language connects the syntax of identifiers, numbers, operators and functions with their semantics. GroteTrap is able to derive a parser and evaluator from a Language, as well as convert between source text selections and tree selections.
data Language a  =   Language
  { variable     ::  Maybe (String -> a)
  , number       ::  Maybe (Int -> a)
  , operators    ::  [Operator a]
  , functions    ::  [Function a]
  }

-- | An empty language. Use this as the starting base of your languages, setting only those fields that are of importance.
language :: Language a
language = Language
  { variable    = Nothing
  , number      = Nothing
  , operators   = []
  , functions   = []
  }

------------------------------------
-- Operators
------------------------------------

-- | Representation of an operator.
data Operator a
  = -- | An operator expecting one operand.
    Unary
    { opSem1        :: a -> a
    , opFixity1     :: Fixity1
    , opPrio        :: Int
    , opToken       :: String
    }
  | -- | A non-associative operator expecting two operands.
    Binary
    { opSem2        :: a -> a -> a
    , opFixity2     :: Fixity2
    , opPrio        :: Int
    , opToken       :: String
    }
  | -- | An infix associative operator that chains together many operands.
    Assoc
    { opSemN        :: [a] -> a
    , opPrio        :: Int
    , opToken       :: String
    }

-- | Fixity for unary operators.
data Fixity1
  = Prefix  -- ^ The operator is written before its operand.
  | Postfix -- ^ The operator is written after its operand.
  deriving (Show, Enum, Eq)

-- | Fixity for infix binary operators.
data Fixity2
  = InfixL  -- ^ The operator associates to the left.
  | InfixR  -- ^ The operator associates to the right.
  deriving (Show, Enum, Eq)

isUnary, isBinary, isAssoc  ::  Operator a -> Bool
isUnary   (Unary  _ _ _ _)  =   True
isUnary   _                 =   False
isBinary  (Binary _ _ _ _)  =   True
isBinary  _                 =   False
isAssoc   (Assoc _ _ _)     =   True
isAssoc   _                 =   False

-- | @findOperator name p os@ yields the operator from @os@ that matches the predicate @p@ and has token @name@. Fails if there are no or several matching operators.
findOperator :: Monad m => String -> (Operator a -> Bool) -> [Operator a] -> m (Operator a)
findOperator name f os = case filter (\o -> f o && opToken o == name) os of
  []  -> fail ("no such operator: " ++ name)
  [o] -> return o
  _   -> fail ("duplicate operator: " ++ name)

------------------------------------
-- Functions
------------------------------------

-- | Representation of a function.
data Function a = Function
  { fnSem   :: [a] -> a
  , fnName  :: String
  }

-- | Lifts a unary function to a 'Function'.
function1 :: (a -> a) -> String -> Function a
function1 f = Function (\[x] -> f x)

-- | Lifts a binary function to a 'Function'.
function2 :: (a -> a -> a) -> String -> Function a
function2 f = Function (\[x, y] -> f x y)

-- | Yelds the function with the specified name. Fails if there are no or several matching functions.
findFunction :: Monad m => String -> [Function a] -> m (Function a)
findFunction name fs = case filter ((== name) . fnName) fs of
  []  -> fail ("no such function: " ++ name)
  [f] -> return f
  _   -> fail ("duplicate function: " ++ name)


text:
using namespace MX;
using namespace MX::Widgets;

StackWidget::StackWidget()
{
}

void StackWidget::PushWidget(const std::shared_ptr<Widget>& widget)
{

    {
        auto guard = _subWidgets.guard();
        auto it = _subWidgets.begin();
        while (it != _subWidgets.end())
        {
            (*it)->ChangeVisibility(1);
            _subWidgets.temp_advance(it);
        }
    }

    _stackSize++;
    widget->SetSize(Width(), Height());
    AddWidget(widget);
    _top = widget;
    onTopWidgetChanged(widget);
}

void StackWidget::PopWidget()
{
    if (_stackSize == 0)
    {
        assert(false);
        return;
    }

    std::shared_ptr<Widget> last;
    std::shared_ptr<Widget> prev;
    {
        auto guard = _subWidgets.guard();
        auto it = _subWidgets.begin();
        while (it != _subWidgets.end())
        {
            prev = last;
            last = (*it);
            (*it)->ChangeVisibility(-1);
            _subWidgets.temp_advance(it);
        }
    }
    if (last)
    {
        last->ChangeVisibility(1);
        last->Unlink();
    }

    _stackSize--;
    _top = prev;
    onTopWidgetChanged(prev);
}

void StackWidget::ReplaceTopWidget(const std::shared_ptr<Widget>& widget)
{
    if (stackSize() == 0)
    {
        PushWidget(widget);
        return;
    }

    std::shared_ptr<Widget> last;
    std::shared_ptr<Widget> prev;
    {
        auto guard = _subWidgets.guard();
        auto it = _subWidgets.begin();
        while (it != _subWidgets.end())
        {
            last = (*it);
            _subWidgets.temp_advance(it);
        }
    }

    if (last)
        last->Unlink();

    widget->SetSize(Width(), Height());
    AddWidget(widget);
    _top = widget;
    onTopWidgetChanged(widget);
}

void StackWidget::OnAreaInsideChanged()
{
    Widget::OnAreaInsideChanged();

    {
        auto guard = _subWidgets.guard();
        auto it = _subWidgets.begin();
        while (it != _subWidgets.end())
        {
            (*it)->SetSize(Width(), Height());
            _subWidgets.temp_advance(it);
        }
    }
}

StackWidget* StackWidget::stack_of(Widget* widget)
{
    SpriteActor* act = widget;
    while (act->linked())
    {
        act = &(act->sprite_scene());
        auto stack = dynamic_cast<StackWidget*>(act);
        if (stack)
            return stack;
    }
    return nullptr;
}


text:
/* jshint indent: 2 */

module.exports = function(sequelize, DataTypes) {
  return sequelize.define('phpbb_mafia_modifiers', {
    modifier_id: {
      type: DataTypes.INTEGER(10),
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    modifier_name: {
      type: DataTypes.STRING,
      allowNull: false
    }
  }, {
    tableName: 'phpbb_mafia_modifiers'
  });
};


text:
[![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=LRHN43F4DFLU6&lc=US&item_name=Elizabeth%20Schneider&item_number=ZendeskAPI%20support&currency_code=USD&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted)
[![Join the chat at https://gitter.im/mozts2005/ZendeskApi_v2](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/mozts2005/ZendeskApi_v2?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Build status](https://ci.appveyor.com/api/projects/status/6ve1ey4x7ctd5029?svg=true)](https://ci.appveyor.com/project/mozts2005/zendeskapi-v2)
[![NuGet Version](https://img.shields.io/nuget/v/ZendeskApi_v2.svg)](https://www.nuget.org/packages/ZendeskApi_v2/)
[![MyGet Prerelease](https://img.shields.io/myget/zendeskapi_v2_prerelease/vpre/ZendeskApi_v2.svg?label=MyGet_Prerelease)](https://www.myget.org/feed/zendeskapi_v2_prerelease/package/nuget/ZendeskApi_v2)

This is a client for [Zendesk's v2 REST api](http://developer.zendesk.com/documentation/rest_api/introduction.html).

The client uses the Zendesk api however it is not supported by the zendesk for questions
about the client please join our gitter room.

If you have questions about your account or the api its self please contact the zendesk team at [api@zendesk.com](mailto:api@zendesk.com)

#### Contributing

Any and all are welcome to contribute to this project.
Please read our [Contributing Guidelines](CONTRIBUTING.md)

#### Special Thanks
Thank you to the team at [Zendesk](https://www.zendesk.com/) for their support. They provide this project with a sponsored account. Allowing a greater level of testing and faster support of API changes.

##### License
This code is released under the [Apache Version 2 License](LICENSE.md).


text:
#ifndef __MESH6LOWPAN_ND_H__
#define __MESH6LOWPAN_ND_H__

#include "AbstractMesh.h"

/**
 * \brief 6LoWPAN ND mesh networking class.
 */

class Mesh6LoWPAN_ND : public AbstractMesh
{

public:

    virtual ~Mesh6LoWPAN_ND();

    /**
     * \brief Read own global IP address
     *
     * \param address is where the IP address will be copied
     * \param len is the length of the address buffer, must be at least 40 bytes
     * \return true if address is read successfully, false otherwise
     */
    bool getOwnIpAddress(char *address, int8_t len);

    /**
     * \brief Read border router IP address
     *
     * \param address is where the IP address will be copied
     * \param len is the length of the address buffer, must be at least 40 bytes
     * \return true if address is read successfully, false otherwise
     */
    bool getRouterIpAddress(char *address, int8_t len);

    friend class MeshInterfaceFactory;

private:
    /*
     * \brief private constructor for the 6LoWPAN_ND
     */
    Mesh6LoWPAN_ND();

    /*
     * avoid copy/assign object
     */
    Mesh6LoWPAN_ND(Mesh6LoWPAN_ND const &copy);
    Mesh6LoWPAN_ND &operator=(Mesh6LoWPAN_ND const &copy);
};

#endif /* __MESH6LOWPAN_ND_H__ */


text:
<?php

namespace Google\Service\Vision;

class WebLabel extends \Google\Model
{
  /**
   * @var string
   */
  public $label;
  /**
   * @var string
   */
  public $languageCode;

  /**
   * @param string
   */
  public function setLabel($label)
  {
    $this->label = $label;
  }
  /**
   * @return string
   */
  public function getLabel()
  {
    return $this->label;
  }
  /**
   * @param string
   */
  public function setLanguageCode($languageCode)
  {
    $this->languageCode = $languageCode;
  }
  /**
   * @return string
   */
  public function getLanguageCode()
  {
    return $this->languageCode;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(WebLabel::class, 'Google_Service_Vision_WebLabel');


text:
<template name="page_loader">

Loading...

</template>


text:
package com.angkorteam.framework.wicket.extensions.markup.html.repeater.data.table.filter;

import com.angkorteam.framework.wicket.WicketBiFunction;
import com.angkorteam.framework.wicket.WicketTriConsumer;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;

import java.util.Map;

/**
 * Created by socheat on 12/7/16.
 */
public class ItemProgressBarLink extends Panel {

    public ItemProgressBarLink(String id,
                               IModel<Map<String, Object>> rowModel,
                               IModel<?> model,
                               WicketBiFunction<String, Map<String, Object>, ItemCss> itemCss,
                               WicketBiFunction<String, Map<String, Object>, Boolean> progressBarActive,
                               WicketTriConsumer<String, Map<String, Object>, AjaxRequestTarget> itemClick,
                               String identity) {
        super(id);

        AjaxLink<Map<String, Object>> link = new AjaxLink<Map<String, Object>>("link", rowModel) {
            @Override
            public void onClick(AjaxRequestTarget target) {
                if (itemClick != null) {
                    itemClick.accept(identity, rowModel.getObject(), target);
                }
            }
        };
        add(link);

        WebMarkupContainer progressBar = new WebMarkupContainer("progressBar");
        link.add(progressBar);
        WebMarkupContainer progressValue = new WebMarkupContainer("progressValue");
        progressBar.add(progressValue);

        boolean active = false;
        if (progressBarActive != null) {
            active = progressBarActive.apply(identity, rowModel.getObject());
        }

        if (active) {
            progressBar.add(AttributeModifier.replace("class", "progress progress-xs progress-striped active"));
        } else {
            progressBar.add(AttributeModifier.replace("class", "progress progress-xs"));
        }

        ItemCss htmlLambdaCss = itemCss.apply(identity, rowModel.getObject());
        if (htmlLambdaCss == null || htmlLambdaCss == ItemCss.NONE) {
            htmlLambdaCss = ItemCss.PRIMARY;
        }

        if (htmlLambdaCss == ItemCss.SUCCESS) {
            progressValue.add(AttributeModifier.replace("class", "progress-bar progress-bar-success"));
        } else if (htmlLambdaCss == ItemCss.PRIMARY) {
            progressValue.add(AttributeModifier.replace("class", "progress-bar progress-bar-primary"));
        } else if (htmlLambdaCss == ItemCss.WARNING) {
            progressValue.add(AttributeModifier.replace("class", "progress-bar progress-bar-yellow"));
        } else if (htmlLambdaCss == ItemCss.DANGER) {
            progressValue.add(AttributeModifier.replace("class", "progress-bar progress-bar-danger"));
        }
        progressValue.add(AttributeModifier.replace("style", Model.of("width: ").combineWith(model, this::prefix).combineWith(Model.of("%"), this::suffix)));
    }

    private String prefix(String s, Object u) {
        if (u == null || !(u instanceof Number)) {
            return s + "0";
        } else {
            double percentage = ((Number) u).doubleValue();
            if (percentage < 0) {
                percentage = 0;
            } else if (percentage > 100) {
                percentage = 100;
            }
            return s + String.valueOf(percentage);
        }
    }

    private String suffix(String s, String u) {
        return s + u;
    }
}


text:
<?php

use Okatea\Tao\L10n\Date;
use Okatea\Tao\Forms\Statics\FormElements as form;
use Okatea\Modules\News\Helpers as NewsHelpers;

$okt->page->datePicker();

?>

<?php _e('m_news_post_tab_title_options')?>

		<?php _e('m_news_post_date') ?>
	<?php echo form::text('p_date', 20, 255, $aPostData['extra']['date'], 'datepicker')?>
	<?php _e('m_news_post_date_note') ?>

			<?php _e('m_news_post_hour') ?>
		<?php echo form::text('p_hours', 2, 2, $aPostData['extra']['hours']) ?>

			<?php _e('m_news_post_minute') ?>
		<?php echo form::text('p_minutes', 2, 2, $aPostData['extra']['minutes']) ?>

	<?php if ($okt->module('News')->config->categories['enable']) : ?>

		<?php _e('m_news_post_category')?>
		<select id="p_category_id" name="p_category_id">
			<option value="0"><?php _e('m_news_post_category_first_level') ?></option>
		<?php
		while ($rsCategories->fetch())
		{
			echo '<option value="' . $rsCategories->id . '"' . ($aPostData['post']['category_id'] == $rsCategories->id ? ' selected="selected"' : '') . '>' . str_repeat('   ', $rsCategories->level) . '• ' . $view->escape($rsCategories->title) . '</option>';
		}
		?>
	</select>

	<?php endif; ?>

	<?php
	# si les permissions de groupe sont activées
	if ($okt->module('News')->config->enable_group_perms)
	:
		?>

<?php _e('m_news_post_permissions_group')?>

			<?php foreach ($aGroups as $g_id=>$g_title) : ?>

<?php echo form::checkbox(array('perms[]','perm_g_'.$g_id), $g_id, in_array($g_id, (array)$aPostData['perms'])) ?> <?php echo $g_title ?>

			<?php endforeach; ?>

	<?php endif; ?>

	<?php if (!empty($aPostData['post']['id'])) : ?>

		<?php if ($aPostData['post']['active'] == 3) : ?>
			<?php if ($aPermissions['bCanPublish']) : ?>

		<?php _e('m_news_post_status') ?>
				<?php echo form::select('p_active', NewsHelpers::getPostsStatus(true), $aPostData['post']['active']) ?>

			<?php else : ?>

		<?php _e('m_news_post_delayed_publication') ?>

			<?php endif; ?>

		<?php elseif ($aPostData['post']['active'] == 2) : ?>

			<?php if ($aPermissions['bCanPublish']) :  ?>

		<a
			href="<?php echo $view->generateAdminUrl('News_post', array('post_id' => $aPostData['post']['id'])).'?publish=1' ?>"
			class="icon time"><?php _e('m_news_post_publish_post') ?>

			<?php else : ?>

		 <?php _e('m_news_post_awaiting_validation') ?>

			<?php endif; ?>

		<?php else : ?>
			<?php if ($aPermissions['bCanPublish']) : ?>

		<?php _e('m_news_post_status') ?>
				<?php echo form::select('p_active', NewsHelpers::getPostsStatus(true), $aPostData['post']['active']) ?>

			<?php endif; ?>
		<?php endif; ?>

	<?php elseif ($aPermissions['bCanPublish']) : ?>

		<?php _e('m_news_post_status') ?>
		<?php echo form::select('p_active', NewsHelpers::getPostsStatus(true), $aPostData['post']['active']) ?>

	<?php endif; ?>

	<?php if (!empty($okt->module('News')->config->templates['item']['usables'])) : ?>

		<?php _e('m_news_post_tpl') ?>
	<?php echo form::select('p_tpl', $aTplChoices, $aPostData['post']['tpl'])?>

	<?php endif; ?>

		<?php echo form::checkbox('p_selected', 1, $aPostData['post']['selected'])?>
	<?php _e('m_news_post_selected') ?>


text:
#if !WINRT
namespace Microsoft.ApplicationInsights.Extensibility
{
    using System;
    using System.Globalization;
#if NET35 || NET40 || NET45
    using System.Management;
#endif
    using System.Reflection;
    using System.Threading;
    using Microsoft.ApplicationInsights.DataContracts;
#if WINDOWS_PHONE || WINDOWS_PHONE_APP || WINDOWS_STORE
    using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
#else
    using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif
#if WINRT
    using Windows.ApplicationModel.Core;
    using Windows.Graphics.Display;
    using Windows.Security.ExchangeActiveSyncProvisioning;
    using Windows.UI.Core;
    using Windows.UI.Xaml;
#endif
    using Assert = Xunit.Assert;

    /// <summary>
    /// Device telemetry source tests.
    /// </summary>
    [TestClass]
    public partial class DeviceContextInitializerTest
    {
        [TestMethod]
        public void DeviceContextInitializerClassIsPublicToEnableInstantiation()
        {
#if NET40 || NET45
            Assert.True(typeof(DeviceContextInitializer).IsPublic);
#else
            Assert.True(typeof(DeviceContextInitializer).GetTypeInfo().IsPublic);
#endif
        }

        [TestMethod]
        public void CallingInitializeOnDeviceContextInitializerWithNullThrowsArgumentNullException()
        {
            DeviceContextInitializer source = new DeviceContextInitializer();
            Assert.Throws<ArgumentNullException>(() => source.Initialize(null));
        }

        [TestMethod]
        public void ReadingDeviceTypeYieldsCorrectValue()
        {
            DeviceContextInitializer source = new DeviceContextInitializer();
            var telemetryContext = new TelemetryContext();

            Assert.Null(telemetryContext.Device.Type);

            source.Initialize(telemetryContext);

            string expected = "Other";
#if SILVERLIGHT || WINDOWS_PHONE
            expected = "Phone";
#elif NET35 || NET40 || NET45
            expected = "PC";
#endif
            Assert.Equal(expected, telemetryContext.Device.Type);
        }

        [TestMethod]
        public void ReadingDeviceUniqueIdYieldsStableValue()
        {
            DeviceContextInitializer source = new DeviceContextInitializer();
            var telemetryContext = new TelemetryContext();

            Assert.Null(telemetryContext.Device.Id);

            source.Initialize(telemetryContext);

            string id = telemetryContext.Device.Id;
            Assert.Equal(false, id.IsNullOrWhiteSpace());

            // clear the fallback context and expect the same result
            DeviceContextReader.Instance = new DeviceContextReader();
            telemetryContext.Device.Id = string.Empty;

            // second run
            source.Initialize(telemetryContext);

            Assert.Equal(id, telemetryContext.Device.Id);
        }

        [TestMethod]
        public void ReadingOSYieldsStableValue()
        {
            DeviceContextInitializer source = new DeviceContextInitializer();
            var telemetryContext = new TelemetryContext();

            Assert.Null(telemetryContext.Device.OperatingSystem);

            source.Initialize(telemetryContext);

            string version = null;
            int retryCount = 100;
            while (retryCount > 0)
            {
                version = telemetryContext.Device.OperatingSystem;
                if (string.IsNullOrEmpty(version) == false)
                {
                    break;
                }

                retryCount--;
                Thread.Sleep(100);
            }

            Assert.Equal(false, version.IsNullOrWhiteSpace());

            // clear the fallback context and expect the same result
            DeviceContextReader.Instance = new DeviceContextReader();
            telemetryContext.Device.OperatingSystem = string.Empty;

            // second run
            source.Initialize(telemetryContext);

            retryCount = 100;
            while (retryCount > 0)
            {
                if (string.IsNullOrEmpty(telemetryContext.Device.OperatingSystem) == false)
                {
                    break;
                }

                retryCount--;
                Thread.Sleep(100);
            }

            Assert.Equal(version, telemetryContext.Device.OperatingSystem);
        }

        [TestMethod]
        public void ReadingOSYieldsCorrectValue()
        {
            DeviceContextInitializer source = new DeviceContextInitializer();
            var telemetryContext = new TelemetryContext();

            Assert.Null(telemetryContext.Device.OperatingSystem);

            source.Initialize(telemetryContext);

            string version = null;
            int retryCount = 100;
            while (retryCount > 0)
            {
                version = telemetryContext.Device.OperatingSystem;
                if (string.IsNullOrEmpty(version) == false)
                {
                    break;
                }

                retryCount--;
                Thread.Sleep(100);
            }

#if WINDOWS_STORE
            Assert.Equal("Windows NT 6.3.9600.16384", version);
#elif !SILVERLIGHT && !NET35 && !NET40 && !NET45
            Assert.Equal("Windows NT 6.3.9651.0", version);
#else
            Assert.Equal(string.Format(CultureInfo.InvariantCulture, "Windows NT {0}", Environment.OSVersion.Version.ToString(4)), version);
#endif
        }

        [TestMethod]
        public void ReadingOemNameYieldsStableValue()
        {
            DeviceContextInitializer source = new DeviceContextInitializer();
            var telemetryContext = new TelemetryContext();

            Assert.Null(telemetryContext.Device.OemName);

            source.Initialize(telemetryContext);

            string manufacturer = telemetryContext.Device.OemName;
            Assert.Equal(false, manufacturer.IsNullOrWhiteSpace());

            // clear the fallback context and expect the same result
            DeviceContextReader.Instance = new DeviceContextReader();
            telemetryContext.Device.OemName = string.Empty;

            // second run
            source.Initialize(telemetryContext);

            Assert.Equal(manufacturer, telemetryContext.Device.OemName);
        }

        [TestMethod]
        public void ReadingDeviceManufacturerYieldsCorrectValue()
        {
            DeviceContextInitializer source = new DeviceContextInitializer();
            var telemetryContext = new TelemetryContext();

            Assert.Null(telemetryContext.Device.OemName);

            source.Initialize(telemetryContext);

            string manufacturer = telemetryContext.Device.OemName;
            string expected = "Microsoft";
#if NET35 || NET40 || NET45
            this.RunWmiQuery("Win32_ComputerSystem", "Manufacturer", ref expected);
#elif WINDOWS_STORE
            EasClientDeviceInformation deviceInfo = new EasClientDeviceInformation();
            expected = deviceInfo.SystemManufacturer;
#endif
            Assert.Equal(expected, telemetryContext.Device.OemName);
        }

        [TestMethod]
        public void ReadingDeviceModelYieldsStableValue()
        {
            DeviceContextInitializer source = new DeviceContextInitializer();
            var telemetryContext = new TelemetryContext();

            Assert.Null(telemetryContext.Device.Model);

            source.Initialize(telemetryContext);

            string model = telemetryContext.Device.Model;
            Assert.Equal(false, model.IsNullOrWhiteSpace());

            // clear the fallback context and expect the same result
            DeviceContextReader.Instance = new DeviceContextReader();
            telemetryContext.Device.Model = string.Empty;

            // second run
            source.Initialize(telemetryContext);

            Assert.Equal(model, telemetryContext.Device.Model);
        }

        [TestMethod]
        public void ReadingDeviceModelYieldsCorrectValue()
        {
            DeviceContextInitializer source = new DeviceContextInitializer();
            var telemetryContext = new TelemetryContext();

            Assert.Null(telemetryContext.Device.Model);

            source.Initialize(telemetryContext);

            string manufacturer = telemetryContext.Device.Model;
            string expected = null;
#if SILVERLIGHT
            expected = "XDeviceEmulator";
#elif NET35 || NET40 || NET45
            this.RunWmiQuery("Win32_ComputerSystem", "Model", ref expected);
#elif WINDOWS_STORE
            EasClientDeviceInformation deviceInfo = new EasClientDeviceInformation();
            expected = deviceInfo.SystemProductName;
#else
            expected = "Virtual";
#endif
            Assert.Equal(expected, manufacturer);
        }

        [TestMethod]
        public void ReadingNetworkTypeYieldsStableValue()
        {
            DeviceContextInitializer source = new DeviceContextInitializer();
            var telemetryContext = new TelemetryContext();

            source.Initialize(telemetryContext);

            string networkType = telemetryContext.Device.NetworkType;
            Assert.NotEqual("0", networkType);

            // clear the fallback context and expect the same result
            DeviceContextReader.Instance = new DeviceContextReader();
            telemetryContext.Device.NetworkType = "0";

            // second run
            source.Initialize(telemetryContext);

            Assert.Equal(networkType, telemetryContext.Device.NetworkType);
        }

        [TestMethod]
        public void ReadingNetworkTypeYieldsCorrectValue()
        {
            DeviceContextInitializer source = new DeviceContextInitializer();
            var telemetryContext = new TelemetryContext();

            source.Initialize(telemetryContext);

            string networkType = telemetryContext.Device.NetworkType;
            Assert.Equal("6", networkType);
        }

        [TestMethod]
        public void ReadingScreenResolutionYieldsStableValue()
        {
            DeviceContextInitializer source = new DeviceContextInitializer();
            var telemetryContext = new TelemetryContext();

            Assert.Null(telemetryContext.Device.ScreenResolution);

            const string DefaultValue = "abc";
            telemetryContext.Device.ScreenResolution = DefaultValue;
            source.Initialize(telemetryContext);

            string screenResolution = null;
            int retryCount = 100;
            while (retryCount > 0)
            {
                screenResolution = telemetryContext.Device.ScreenResolution;
                if (string.Compare(screenResolution, DefaultValue, StringComparison.OrdinalIgnoreCase) != 0)
                {
                    break;
                }

                retryCount--;
                Thread.Sleep(100);
            }

#if NET35 || NET40 || NET45
            Assert.True(screenResolution.IsNullOrWhiteSpace());
#else
            Assert.False(screenResolution.IsNullOrWhiteSpace());
#endif

            // clear the fallback context and expect the same result
            DeviceContextReader.Instance = new DeviceContextReader();
            telemetryContext.Device.ScreenResolution = DefaultValue;

            // second run
            source.Initialize(telemetryContext);

            retryCount = 100;
            while (retryCount > 0)
            {
                screenResolution = telemetryContext.Device.ScreenResolution;
                if (string.Compare(screenResolution, DefaultValue, StringComparison.OrdinalIgnoreCase) != 0)
                {
                    break;
                }

                retryCount--;
                Thread.Sleep(100);
            }

            Assert.Equal(screenResolution, telemetryContext.Device.ScreenResolution);
        }

        [TestMethod]
        public void ReadingScreenResolutionYieldsCorrectValue()
        {
            DeviceContextInitializer source = new DeviceContextInitializer();
            var telemetryContext = new TelemetryContext();

            Assert.Null(telemetryContext.Device.ScreenResolution);

            source.Initialize(telemetryContext);

            string screenResolution = null;
            int retryCount = 100;
            while (retryCount > 0)
            {
                screenResolution = telemetryContext.Device.ScreenResolution;
                if (string.IsNullOrEmpty(screenResolution) == false)
                {
                    break;
                }

                retryCount--;
                Thread.Sleep(100);
            }

            string expected = "480x800";
#if NET35 || NET40 || NET45
            expected = null;
#elif WINDOWS_STORE
            CoreDispatcher dispatcher = CoreApplication.MainView.CoreWindow.Dispatcher;
            DispatchedHandler executor = () =>
            {
                double actualHeight = Window.Current.Bounds.Height;
                double actualWidth = Window.Current.Bounds.Width;
                double resolutionScale = (double)DisplayInformation.GetForCurrentView().ResolutionScale / 100;
                expected = string.Format(CultureInfo.InvariantCulture, "{0}x{1}", (int)(actualWidth * resolutionScale), (int)(actualHeight * resolutionScale));
            };

            dispatcher.RunAsync(CoreDispatcherPriority.Low, executor).GetAwaiter().GetResult();
#endif
            Assert.Equal(expected, screenResolution);
        }

        [TestMethod]
        public void ReadingLanguageYieldsStableValue()
        {
            DeviceContextInitializer source = new DeviceContextInitializer();
            var telemetryContext = new TelemetryContext();

            Assert.Null(telemetryContext.Device.Language);

            source.Initialize(telemetryContext);

            string locate = telemetryContext.Device.Language;
            Assert.Equal(false, locate.IsNullOrWhiteSpace());

            // clear the fallback context and expect the same result
            DeviceContextReader.Instance = new DeviceContextReader();
            telemetryContext.Device.Language = string.Empty;

            // second run
            source.Initialize(telemetryContext);

            Assert.Equal(locate, telemetryContext.Device.Language);
        }

        [TestMethod]
        public void ReadingLanguageYieldsCorrectValue()
        {
            DeviceContextInitializer source = new DeviceContextInitializer();
            var telemetryContext = new TelemetryContext();

            Assert.Null(telemetryContext.Device.Language);

            source.Initialize(telemetryContext);

            string manufacturer = telemetryContext.Device.Language;
            Assert.Equal("en-US", manufacturer);
        }

#if NET35 || NET40 || NET45
        private void RunWmiQuery(string table, string property, ref string output)
        {
            output = "Unknown";
            try
            {
                using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(string.Format(CultureInfo.InvariantCulture, "SELECT {0} FROM {1}", property, table)))
                {
                    foreach (ManagementObject currentObj in searcher.Get())
                    {
                        object data = currentObj[property];
                        if (data != null)
                        {
                            output = data.ToString();
                            return;
                        }
                    }
                }
            }
            catch (Exception)
            {
                // a lot of things can go wrong with WMI ... as such, apply Pokemon pattern ...
            }
        }
#endif
    }
}
#endif


text:
namespace safe_browsing {

// Base class for managing the SafeBrowsing interstitial pages.
class BaseBlockingPage
    : public security_interstitials::SecurityInterstitialPage {
 public:
  typedef security_interstitials::UnsafeResource UnsafeResource;
  typedef security_interstitials::BaseSafeBrowsingErrorUI
      BaseSafeBrowsingErrorUI;
  typedef std::vector<UnsafeResource> UnsafeResourceList;
  typedef std::unordered_map<content::WebContents*, UnsafeResourceList>
      UnsafeResourceMap;

  ~BaseBlockingPage() override;

  static const BaseSafeBrowsingErrorUI::SBErrorDisplayOptions
  CreateDefaultDisplayOptions(const UnsafeResourceList& unsafe_resources);

  // Returns true if the passed |unsafe_resources| is blocking the load of
  // the main page.
  static bool IsMainPageLoadBlocked(const UnsafeResourceList& unsafe_resources);

  // SecurityInterstitialPage method:
  void CommandReceived(const std::string& command) override;

  // Checks the threat type to decide if we should report ThreatDetails.
  static bool ShouldReportThreatDetails(SBThreatType threat_type);

 protected:
  // Don't instantiate this class directly, use ShowBlockingPage instead.
  BaseBlockingPage(
      BaseUIManager* ui_manager,
      content::WebContents* web_contents,
      const GURL& main_frame_url,
      const UnsafeResourceList& unsafe_resources,
      std::unique_ptr<
          security_interstitials::SecurityInterstitialControllerClient>
          controller_client,
      const BaseSafeBrowsingErrorUI::SBErrorDisplayOptions& display_options);

  // SecurityInterstitialPage methods:
  bool ShouldCreateNewNavigation() const override;
  void PopulateInterstitialStrings(
      base::DictionaryValue* load_time_data) override;
  void OnInterstitialClosing() override;

  // Called when the interstitial is going away. Intentionally do nothing in
  // this base class.
  virtual void FinishThreatDetails(const base::TimeDelta& delay,
                                   bool did_proceed,
                                   int num_visits);

  // A list of SafeBrowsingUIManager::UnsafeResource for a tab that the user
  // should be warned about. They are queued when displaying more than one
  // interstitial at a time.
  static UnsafeResourceMap* GetUnsafeResourcesMap();

  static std::string GetMetricPrefix(
      const UnsafeResourceList& unsafe_resources,
      BaseSafeBrowsingErrorUI::SBInterstitialReason interstitial_reason);

  static std::string GetExtraMetricsSuffix(
      const UnsafeResourceList& unsafe_resources);

  // Return the most severe interstitial reason from a list of unsafe resources.
  // Severity ranking: malware > UwS (harmful) > phishing.
  static BaseSafeBrowsingErrorUI::SBInterstitialReason GetInterstitialReason(
      const UnsafeResourceList& unsafe_resources);

  BaseUIManager* ui_manager() const;

  const GURL main_frame_url() const;

  UnsafeResourceList unsafe_resources() const;

  bool proceeded() const;

  int64_t threat_details_proceed_delay() const;

  BaseSafeBrowsingErrorUI* sb_error_ui() const;

  void set_proceeded(bool proceeded);

  static security_interstitials::MetricsHelper::ReportDetails GetReportingInfo(
      const UnsafeResourceList& unsafe_resources);

  // Called after OnProceed(). Does nothing in this class, but can be overridden
  // to handle malicious subresources.
  virtual void HandleSubresourcesAfterProceed();

  void SetThreatDetailsProceedDelayForTesting(int64_t delay);

  static std::unique_ptr<
      security_interstitials::SecurityInterstitialControllerClient>
  CreateControllerClient(content::WebContents* web_contents,
                         const UnsafeResourceList& unsafe_resources,
                         BaseUIManager* ui_manager,
                         PrefService* pref_service);

  int GetHTMLTemplateId() override;

  void set_sb_error_ui(std::unique_ptr<BaseSafeBrowsingErrorUI> sb_error_ui);

  void OnDontProceedDone();

 private:
  // For reporting back user actions.
  BaseUIManager* ui_manager_;

  // The URL of the main frame that caused the warning.
  GURL main_frame_url_;

  // The index of a navigation entry that should be removed when DontProceed()
  // is invoked, -1 if entry should not be removed.
  const int navigation_entry_index_to_remove_;

  // The list of unsafe resources this page is warning about.
  UnsafeResourceList unsafe_resources_;

  // Indicate whether user has proceeded this blocking page.
  bool proceeded_;

  // After a safe browsing interstitial where the user opted-in to the
  // report but clicked "proceed anyway", we delay the call to
  // ThreatDetails::FinishCollection() by this much time (in
  // milliseconds), in order to get data from the blocked resource itself.
  int64_t threat_details_proceed_delay_ms_;

  // For displaying safe browsing interstitial.
  std::unique_ptr<BaseSafeBrowsingErrorUI> sb_error_ui_;

  DISALLOW_COPY_AND_ASSIGN(BaseBlockingPage);
};

}  // namespace safe_browsing

#endif  // COMPONENTS_SAFE_BROWSING_CONTENT_BASE_BLOCKING_PAGE_H_