text:
using System;
using System.Linq;
using System.Threading.Tasks;
using Bloqs.Data.Commands;
using NUnit.Framework;

namespace Bloqs.Data
{
    [TestFixture]
    public class AccountDbCommandTest : DbCommandTestBase
    {
        private readonly AccountDbCommand _dbCommand = new AccountDbCommand(Constants.ConnectionString);

        [TestCase]
        public async Task CreateTest()
        {
            var account = Account.NewAccount("Create Test", "Owner", StorageType.Common);

            await _dbCommand.CreateAsync(account);
            var registered = await _dbCommand.FindAsync(account.Id);
            registered.IsStructuralEqual(account);
        }

        [TestCase]
        public async Task CreateWithUsingStorageTest()
        {
            var account = Account.NewAccount("CreateWithUsingStorageTest", "Owner", StorageType.Personal);
            account.Storages.Add(MockStorages.Personal1);

            await _dbCommand.CreateAsync(account);
            var registered = await _dbCommand.FindAsync(account.Id);
            registered.IsStructuralEqual(account);
        }

        [TestCase]
        public async Task CreateWithUsingMultipleStoragesTest()
        {
            var account = Account.NewAccount("CreateWithUsingStorageTest", "Owner", StorageType.Personal);

            account.Storages.Add(MockStorages.Personal1);
            account.Storages.Add(MockStorages.Personal2);

            await _dbCommand.CreateAsync(account);
            var registered = await _dbCommand.FindAsync(account.Id);
            registered.IsStructuralEqual(account);
        }

        [TestCase]
        public async Task UpdateTest()
        {
            var account = Account.NewAccount("Update Test", "Owner", StorageType.Common);
            await _dbCommand.CreateAsync(account);
            var target = await _dbCommand.FindAsync(account.Id);
            target.Name = "UpdatedTestRename";
            target.CreatedUtcDateTime = new DateTime(2001,12,31);
            target.LastModifiedUtcDateTime = new DateTime(2002,1,1);
            target.PrimaryAccessKey = Account.CreateNewAccessKeyString();
            target.SecondaryAccessKey = Account.CreateNewAccessKeyString();
            target.Owner = "UpdateTest";
            target.StorageType = StorageType.Personal;

            await _dbCommand.UpdateAsync(target.Id, target);
            var updated = await _dbCommand.FindAsync(target.Id);
            updated.IsStructuralEqual(target);
        }

        [TestCase]
        public async Task UpdateWithUsingStorageTest()
        {
            var account = Account.NewAccount("UpdateWithUsingStorageTest", "Owner", StorageType.Personal);

            account.Storages.Add(MockStorages.Personal1);
            account.Storages.Add(MockStorages.Personal2);

            await _dbCommand.CreateAsync(account);
            var target = await _dbCommand.FindAsync(account.Id);
            target.Name = "UpdateWithUsingStorageTestRename";
            target.CreatedUtcDateTime = new DateTime(2001, 12, 31);
            target.LastModifiedUtcDateTime = new DateTime(2002, 1, 1);
            target.PrimaryAccessKey = Account.CreateNewAccessKeyString();
            target.SecondaryAccessKey = Account.CreateNewAccessKeyString();
            target.Owner = "UpdateTest";
            target.StorageType = StorageType.Personal;
            target.Storages.Clear();

            target.Storages.Add(MockStorages.Personal2);
            target.Storages.Add(MockStorages.Personal3);

            await _dbCommand.UpdateAsync(target.Id, target);
            var updated = await _dbCommand.FindAsync(target.Id);
            updated.IsStructuralEqual(target);
        }

        [TestCase]
        public async Task FindByNameTest()
        {
            var account = Account.NewAccount("FindByNameTest", "Owner", StorageType.Common);
            await _dbCommand.CreateAsync(account);
            var found = await _dbCommand.FindByNameAsync(account.Name);
            found.IsStructuralEqual(account);
        }

        [TestCase]
        public async Task FindByNameWithUsingStorageTest()
        {
            var account = Account.NewAccount("FindByNameWithUsingStorageTest", "Owner", StorageType.Common);

            account.Storages.Add(MockStorages.Personal2);
            account.Storages.Add(MockStorages.Personal3);

            await _dbCommand.CreateAsync(account);
            var found = await _dbCommand.FindByNameAsync(account.Name);
            found.IsStructuralEqual(account);
        }

        [TestCase]
        public async Task DeleteTest()
        {
            var account = Account.NewAccount("DeleteTest", "Owner", StorageType.Common);
            await _dbCommand.CreateAsync(account);
            var found = await _dbCommand.FindAsync(account.Id);
            Assert.IsNotNull(found);
            await _dbCommand.DeleteAsync(account.Id);
            found = await _dbCommand.FindAsync(account.Id);
            Assert.IsNull(found);
        }

        [TestCase(@"森鷗外")]
        [TestCase("% %")]
        [TestCase("_a_")]
        [TestCase("AAA")]
        [TestCase("%")]
        [TestCase("_")]
        [TestCase("name")]
        public async Task ExistsTest(string name)
        {
            var account = Account.NewAccount(name, "Owner", StorageType.Common);
            await _dbCommand.CreateAsync(account);

            var exists = await _dbCommand.ExistsAsync(name);
            exists.IsTrue();

            exists = await _dbCommand.ExistsAsync("_" + name);
            exists.IsFalse();
        }

        [TestCase(@"森鷗外")]
        [TestCase("% %")]
        [TestCase("_a_")]
        [TestCase("AAA")]
        [TestCase("%")]
        [TestCase("_")]
        [TestCase("name")]
        public async Task CountByOwnerTest(string ownerName)
        {
            var account1 = Account.NewAccount("CountByOwner1", ownerName, StorageType.Common);
            var account2 = Account.NewAccount("CountByOwner2", ownerName, StorageType.Common);
            var account3 = Account.NewAccount("CountByOwner3", "_" + ownerName, StorageType.Common);
            var account4 = Account.NewAccount("CountByOwner4", ownerName, StorageType.Common);

            await _dbCommand.CreateAsync(account1);
            await _dbCommand.CreateAsync(account2);
            await _dbCommand.CreateAsync(account3);
            await _dbCommand.CreateAsync(account4);

            var count = await _dbCommand.CountByOwnerAsync(ownerName);

            count.Is(3);
        }

        [TestCase]
        public async Task GetListByOwnerTest()
        {
            var account1 = Account.NewAccount("GetListByOwner1", "ListTestOwner1-1", StorageType.Common);
            var account2 = Account.NewAccount("GetListByOwner2", "ListTestOwner1-1", StorageType.Common);
            var account3 = Account.NewAccount("GetListByOwner3", "ListTestOwner1-2", StorageType.Common);
            var account4 = Account.NewAccount("GetListByOwner4", "ListTestOwner1-1", StorageType.Common);

            await _dbCommand.CreateAsync(account1);
            await _dbCommand.CreateAsync(account2);
            await _dbCommand.CreateAsync(account3);
            await _dbCommand.CreateAsync(account4);

            var list = (await _dbCommand.GetListByOwnerAsync("ListTestOwner1-1", 1, 2)).ToArray();

            list.IsStructuralEqual(new []{account2, account4});
        }

        [TestCase]
        public async Task GetListByOwnerWithUsingStorageTest()
        {
            var account1 = Account.NewAccount("GetListByOwner1", "ListTestOwner2-1", StorageType.Personal);
            var account2 = Account.NewAccount("GetListByOwner2", "ListTestOwner2-1", StorageType.Personal);
            var account3 = Account.NewAccount("GetListByOwner3", "ListTestOwner2-2", StorageType.Personal);
            var account4 = Account.NewAccount("GetListByOwner4", "ListTestOwner2-1", StorageType.Personal);

            account1.Storages.Add(MockStorages.Personal1);
            account1.Storages.Add(MockStorages.Personal2);
            account2.Storages.Add(MockStorages.Personal1);
            account2.Storages.Add(MockStorages.Personal3);
            account3.Storages.Add(MockStorages.Personal1);
            account3.Storages.Add(MockStorages.Personal2);
            account3.Storages.Add(MockStorages.Personal3);
            account4.Storages.Add(MockStorages.Personal1);

            await _dbCommand.CreateAsync(account1);
            await _dbCommand.CreateAsync(account2);
            await _dbCommand.CreateAsync(account3);
            await _dbCommand.CreateAsync(account4);

            var list = (await _dbCommand.GetListByOwnerAsync("ListTestOwner2-1", 1, 2)).ToArray();

            list.IsStructuralEqual(new[] { account2, account4 });
        }
    }
}


text:
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
<title>Automatisches generien von Formularen</title>
<meta name="generator" content="DocBook XSL Stylesheets V1.29">
<link rel="home" href="index.html" title="Caroshi-Tutorial">
<link rel="up" href="ch05.html" title="Chapter 5. Erweiterungen der Benutzeroeberfläche">
<link rel="previous" href="ch05s02.html" title="Volltextsuche">
<link rel="next" href="ch05s04.html" title="Leere SQL-Record via Link erstellen">

Automatisches generien von Formularen

Prev
Chapter 5. Erweiterungen der Benutzeroeberfläche
 Next

Automatisches generien von Formularen

Der Aufruf von

  $this->personen_formular ();

laesst sich ersetzen durch

  tk_autoform_create_form ($this, 'source');

und fuehrt zum gleichen Resultat, wenn die Beschreibungen der Feldnamen in
die Datenbankbeschreibung eingetragen und die automatische Ausgabe des
Primarschluessels unterdrueckt wird.

    # Definiere Tabelle 'personen' mit Feldnamen und SQL-Typ.
    $def->define_table (
      'personen',
      array (array ('n' => 'id',
                    'autoform' => 'hide', # Keine automatisches Widget erzeugen.
                    't' => 'INT NOT NULL AUTO_INCREMENT PRIMARY KEY'),
             array ('n' => 'name',
	            'd' => 'Name',
	            't' => 'VARCHAR(255) NOT NULL'),
             array ('n' => 'vorname',
	            'd' => 'Vorname',
	            't' => 'VARCHAR(255) NOT NULL'),
             array ('n' => 'email',
	            'd' => 'E-Mail',
	            't' => 'VARCHAR(255) NOT NULL'),
             array ('n' => 'fon',
	            'd' => 'Fon',
	            't' => 'VARCHAR(255) NOT NULL'),
             array ('n' => 'fax',
	            'd' => 'Fax',
	            't' => 'VARCHAR(255) NOT NULL'))
    );

Nun kann personen_formular() entfernt werden.

Prev
Home
 Next

Volltextsuche
Up
 Leere SQL-Record via Link erstellen

redpajama_set_name: RedPajamaGithub


text:
> friendly [`getopts`](http://en.wikipedia.org/wiki/Getopts) for [fish](https://fishshell.com) :fish:

## Usage

```fish
Add `getopts` to your `$fish_plugins` or import directly into your library via `import plugins/getopts`.
```

## Premise
Every utility / function needs to handle arguments. What usually happens is that every function does all the grunt work to parse `$argv` itself, and while some patterns do tend to recur, it's different almost every time. Enter fish `getopts`.

## Synopsis
  `getopts <option string> [ARGV...]`

## Options
#### `<option string> [:][<letter>][[:]<word>[:[^]]]`

A string containing the option characters recognized by the utility calling `getopts`. If a `<letter>` or `<word>` ends in `:`, the option is expected to have an argument, which may be supplied separately or next to the option without spaces in the same string.

To indicate long options: `<letter>:<word>` and `<word>` are both valid option strings that will attempt to match `-<letter>` and `--<word>`.

To indicate _only_ short options, do not specify a `:<word>` after `<letter>`. For example, `a b` will match `-a` or `-b`.

To indicate optional arguments, use a `^` character after a `:` at the end of the option in the option string. For example `<letter>:^` and `<letter>:<word>:^` are both valid. Optional arguments should be supplied in the same string as the option and without spaces, e.g, `-<letter>value` will correctly assign `value` as the argument to the the option `<letter>`, but `-<letter>` value, will parse `value` as the next argument in `<ARGV>`.

To specify optional arguments using the option's long form, use a `=` character after the option: `--<word>=value`.

Use a `:` at the beginning of the option string to enable strict mode. If enabled, `getopts` will exit with a status __> 0__ if or when an unknown option is found. See [Diagnostics](#diagnostics).

#### `<ARGV>`

List of options and operands to parse. `getopts` prints any matched options as well as available argument separated by a \n to stdout and returns with a status of __0__ if there are still arguments; else returns with a status __> 0__ if the end of the options is reached or an error occurs. See [Diagnostics](#diagnostics).

#### Summary

| Option String          |  Argument     | Short Style     | Long Style   |
|:---------------:|:--------------:|------------------|:--------------------:|
   `"q:qqq:"`          | Required   | `-q1` `-q 1`    | `--qqq 1`           |
   `"q:qqq:^"`         | Optional    | `-q1`              | `--qqq=3`              |

## Description
`getopts` obtains options and their arguments from a list of parameters that, as indicated by <option string>, are single letters preceded by a `-` or words preceded by `--` and possibly followed by an argument value.

fish `getopts` follows the specifications described in the [Utility Syntax Guidelines](http://pubs.opengroup.org/onlinepubs/7908799/xbd/utilconv.html). The following is a summary of the features:

+ Short options; single letters preceded by `-`, and long options; words preceded by `--`, are both supported.

+ Single letters may be grouped. `-abc` → `-a -b -c`

+ Options required to take an argument can specify the argument either in the same string as the option or separated from the by a space. (1) `-a argument`, (2) `-aargument`

+ Options that can take an argument optionally shall specify the argument in the same string as the option argument if in short option style: `-aargument`, or separated by a `=` if in long form: `--long-form=argument`. If a blank space is used, the following argument will be treated independently.

+ Options can appear multiple times in the same argument list. `getopts` will print every match sequentially on each call, and should default to the short form of the option if available.

+ The option delimiter `:` and optional argument character `^` shall not be used as an option.

+ `getopts` will return the remaining operands when the end of the options is reached, i.e, a `--` argument that is not an option is found, or an argument that does not begin with `-` is found.

## Environment Variables
The following environment variables are used internally by `getopts`. These variables are erased from memory when the function returns 1.

+ `__getopts_optstr` _Whitespace trimmed option string._

+ `__getopts_argv` _Preprocessed copy of arguments._

+ `__getopts_index` _Index of the next argument to handle._

+ `__getopts_required` _List of options with required arguments._

+ `__getopts_optional` _List of options with optional arguments._

## Diagnostics
Possible exit status values are:

+ __0__: An argument formed like an option was found. This causes getopts to print the option short-style and its argument if available. If strict-mode is enabled setting the first character of the option to `:`, an unknown option will cause `getopts` to fail. See below.

+ __1__: The end of the options was reached. Remaining operands are also sent to stdout.

+ __2__: An option argument was missing.

+ __3__: An unknown option was found. Only if strict-mode is enabled.

## Examples
```fish
  function my_utility
    while set optarg (getopts "l:long x: o:optional:^" $argv)
      switch $optarg[1]
        case l
          echo handle `-l --long`
        case x
          echo handle `-x` w/ argument `$optarg[2]`
        case o
          echo handle `-o --optional` w/ optional argument `$optarg[2]`
        case \*
          echo unknown option `$optarg[1]`
      end
    end
    echo -n operands: "`$optarg`"
  end
```

## Links
+ [UNIX Utility Conventions](http://pubs.opengroup.org/onlinepubs/7908799/xbd/utilconv.html)

## License
[MIT](http://opensource.org/licenses/MIT) © [Jorge Bucaran](http://bucaran.me)


text:
<?php

declare(strict_types=1);

namespace Speckbein\DependencyInjector\Exceptions;

class DependencyInjectorInvalidArgumentException extends \InvalidArgumentException
{

}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:drawable="@color/activate_btn_normal_bg" />
    <item android:state_enabled="true" android:drawable="@color/activate_btn_pressed_bg" />
    <item android:state_checked="true" android:drawable="@color/activate_btn_pressed_bg" />
    <item android:state_selected="true" android:drawable="@color/activate_btn_pressed_bg" />
    <item android:state_focused="true" android:drawable="@color/activate_btn_pressed_bg" />
    <item android:drawable="@color/activate_btn_normal_bg" />
</selector>


text:
using System.Collections;
using System.IO;
using System.Threading;
using TESUnity.Inputs;
using UnityEngine;
using UnityEngine.Android;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

namespace TESUnity.Components
{
    public sealed class MenuComponent : MonoBehaviour
    {
        private MusicPlayer m_MusicPlayer = null;
        private Thread m_PreloadThread = null;
        private string m_GamePath = string.Empty;
        private bool m_MenuLoaded = false;

        [Header("Panels")]
        [SerializeField]
        private GameObject m_PermissionPanel = null;
        [SerializeField]
        private GameObject m_PreloadPanel = null;
        [SerializeField]
        private GameObject m_MenuPanel = null;
        [SerializeField]
        private GameObject m_OptionsPanel = null;

        [Header("UI Elements")]
        [SerializeField]
        private Image m_Background = null;

        [Header("Preloading")]
        [SerializeField]
        private GameObject m_DesktopPathSelection = null;
        [SerializeField]
        private GameObject m_MobilePathSelection = null;
        [SerializeField]
        private Text m_PathValidationText = null;

        [Header("Menu")]
        [SerializeField]
        private InputField m_PathSelector = null;
        [SerializeField]
        private Button m_LoadButton = null;
        [SerializeField]
        private Text m_InfoMessage = null;
        [SerializeField]
        private GameObject m_ButtonsContainer = null;

#if UNITY_EDITOR
        [Header("Editor Only")]
        [SerializeField]
        private bool m_DisplayDesktopPathOnAndroid = true;
#endif

        private void Awake()
        {
            if (!CanReadStorage())
            {
                RequestReadStoragePermission();
                StartCoroutine(DeferredLoad());
            }
            else
                Initialize();
        }

        private void Initialize()
        {
            m_GamePath = GameSettings.GetDataPath();

            if (GameSettings.IsValidPath(m_GamePath))
                LoadMenu();
            else
                LoadPreloader();
        }

        private IEnumerator DeferredLoad()
        {
            SetPanelVisible(-1);

            var wait = new WaitForEndOfFrame();

            while (!CanReadStorage())
            {
                if (InputManager.GetButtonDown(MWButton.Menu))
                    Quit();

                yield return wait;
            }

            Initialize();
        }

        #region PreLoading

        private void LoadPreloader()
        {
            var mobile = false;

#if UNITY_ANDROID || UNITY_IOS
            mobile = true;

#if UNITY_EDITOR
            if (m_DisplayDesktopPathOnAndroid)
                mobile = false;
#endif
#endif

            m_DesktopPathSelection.SetActive(!mobile);
            m_MobilePathSelection.SetActive(mobile);

            SetPanelVisible(0);
        }

        public void ValidatePathSelection()
        {
            m_GamePath = m_PathSelector.text;

            if (GameSettings.IsValidPath(m_GamePath))
            {
                GameSettings.SetDataPath(m_GamePath);
                m_PathValidationText.enabled = false;
                LoadMenu();
            }
            else
                m_PathValidationText.enabled = true;
        }

        #endregion

        #region Menu

        private void LoadMenu()
        {
            // Preload data if the reader is not yet initialized.
            if (TESManager.MWDataReader == null)
            {
                m_PreloadThread = new Thread(new ThreadStart(() =>
                {
                    TESManager.MWDataReader = new MorrowindDataReader(m_GamePath);
                }));

                m_PreloadThread.Start();

                StartCoroutine(CheckLoadButton());
            }

            SetPanelVisible(1);

            var path = Path.Combine(m_GamePath, "Splash");

            if (Directory.Exists(path))
            {
                var files = Directory.GetFiles(path);
                if (files.Length > 0)
                {
                    var target = files[Random.Range(0, files.Length - 1)];
                    var texture = TGALoader.LoadTGA(target);
                    var sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero);
                    m_Background.sprite = sprite;
                    m_Background.color = Color.white;
                }
            }

            path = Path.Combine(m_GamePath, "Music", "Explore", "Morrowind Title.mp3");

            if (File.Exists(path))
            {
                m_MusicPlayer = new MusicPlayer();
                m_MusicPlayer.AddSong(path);
                m_MusicPlayer.Play();
            }

            m_MenuLoaded = true;
        }

        public void LoadWorld() => StartCoroutine(LoadWorld(m_GamePath));

        private IEnumerator CheckLoadButton()
        {
            var wait = new WaitForSeconds(0.5f);

            m_InfoMessage.text = "Please wait while loading Morrowind's data...";
            m_InfoMessage.enabled = true;

            m_LoadButton.interactable = false;

            while (m_PreloadThread.IsAlive)
                yield return wait;

            m_LoadButton.interactable = true;
            m_InfoMessage.enabled = false;
        }

        private IEnumerator LoadWorld(string path)
        {
            m_ButtonsContainer.gameObject.SetActive(false);
            m_InfoMessage.text = "Loading...";
            m_InfoMessage.enabled = true;

            yield return new WaitForEndOfFrame();

            var asyncOperation = SceneManager.LoadSceneAsync("Game");
            var waitForSeconds = new WaitForSeconds(0.1f);

            while (!asyncOperation.isDone)
            {
                m_InfoMessage.text = string.Format("Loading {0}%", Mathf.RoundToInt(asyncOperation.progress * 100.0f));
                yield return waitForSeconds;
            }
        }

        public void Quit()
        {
            var dataReader = TESManager.MWDataReader;
            dataReader?.Close();

#if UNITY_EDITOR
            UnityEditor.EditorApplication.isPlaying = false;
#endif

            Application.Quit();
        }

        #endregion

        #region Options

        public void ShowOptions(bool visible)
        {
            if (visible)
                SetPanelVisible(2);
            else
                SetPanelVisible(1);
        }

        #endregion

        private void RequestReadStoragePermission()
        {
#if UNITY_ANDROID
            Permission.RequestUserPermission(Permission.ExternalStorageRead);
#endif
        }

        public bool CanReadStorage()
        {
#if UNITY_ANDROID
            return Permission.HasUserAuthorizedPermission(Permission.ExternalStorageRead);
#else
            return true;
#endif
        }

        public bool CanLoadWorld()
        {
            return m_MenuLoaded && (m_PreloadThread == null || !m_PreloadThread.IsAlive);
        }

        public void SetPanelVisible(int index)
        {
            m_PermissionPanel.SetActive(index == -1);
            m_PreloadPanel.SetActive(index == 0);
            m_MenuPanel.SetActive(index == 1);
            m_OptionsPanel.SetActive(index == 2);
        }

        private IEnumerator ShowMessage(string message, float duration)
        {
            m_InfoMessage.text = message;
            m_InfoMessage.enabled = true;
            yield return new WaitForSeconds(duration);
            m_InfoMessage.enabled = false;
        }
    }
}


text:
<!doctype html>

        <title>CCA News Network</title>
        <link href="/css/styles-animation.css" rel="stylesheet">

Home

Page 2

About Us

First News Story

This is my article.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus lobortis pretium finibus. Nullam magna nunc, sodales in laoreet vitae, tristique in magna. Cras vehicula dui sed ornare tincidunt. Maecenas vehicula et diam vitae tempor. Nam scelerisque est et accumsan tempor. Cras facilisis ac massa ut tincidunt. Maecenas at lacus lobortis, dignissim dolor vulputate, pellentesque lorem. Proin viverra turpis vitae purus iaculis, quis euismod sem mattis. Maecenas sit amet porta nulla, nec finibus enim. Nunc egestas libero id leo fermentum, quis cursus erat posuere. Donec interdum velit non lacus euismod, in feugiat metus cursus.

This is my caption

Quisque porta tempor dui id suscipit. Donec varius dignissim ipsum, a dignissim ligula cursus ut. Cras posuere enim tortor, vel tempor risus lacinia nec. Vestibulum lacus magna, finibus sit amet erat in, congue vulputate est. Quisque vitae tincidunt risus. Vestibulum sollicitudin semper libero eu sodales. Fusce eget gravida turpis. Donec odio lorem, lacinia eu justo vel, semper suscipit leo. Nullam vulputate et sem a accumsan. Vestibulum dapibus magna vel scelerisque convallis. Integer luctus, libero non luctus mattis, velit eros pretium leo, id varius nunc neque pulvinar eros. Ut condimentum, lorem sit amet facilisis interdum, dolor quam sodales massa, ac blandit enim ligula eu urna. Donec feugiat turpis turpis. Mauris tincidunt, orci sit amet tempor pretium, arcu erat consequat libero, at condimentum velit ipsum non ligula. Aliquam ligula justo, tincidunt vel ex sed, ultricies blandit risus. Vivamus posuere ipsum a augue malesuada, vel interdum massa varius.

<< Prev

Next >>

Most Popular Stories

Our Top stories of the year!

First News Story

Third News Story

Buy Our Cool Stuff!

Our stuff is so cool you should buy it!

Great for babies and great-great-grandparents!

© <time datetime="2017">2017</time> Code Career Academy


text:
package com.github.hitgif.powerscore.speech.util;

import android.content.Context;
import android.preference.EditTextPreference;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.widget.Toast;

import java.util.regex.Pattern;

/**
 * 输入框输入范围控制
 */
public class SettingTextWatcher implements TextWatcher {
	private int editStart ;
	private int editCount ;
	private EditTextPreference mEditTextPreference;
	int minValue;//最小值
	int maxValue;//最大值
	private Context mContext;

	public SettingTextWatcher(Context context,EditTextPreference e,int min, int max) {
		mContext = context;
		mEditTextPreference = e;
		minValue = min;
		maxValue = max;
	 }

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
//		Log.e("demo", "onTextChanged start:"+start+" count:"+count+" before:"+before);
		editStart = start;
		editCount = count;
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,int after) {
//		Log.e("demo", "beforeTextChanged start:"+start+" count:"+count+" after:"+after);
	}

	@Override
	public void afterTextChanged(Editable s) {
		if (TextUtils.isEmpty(s)) {
			return;
		}
		String content = s.toString();
//		Log.e("demo", "content:"+content);
		if (isNumeric(content)) {
			int num = Integer.parseInt(content);
			if (num > maxValue || num < minValue) {
				s.delete(editStart, editStart+editCount);
				mEditTextPreference.getEditText().setText(s);
				Toast.makeText(mContext, "超出有效值范围", Toast.LENGTH_SHORT).show();
			}
		}else {
			s.delete(editStart, editStart+editCount);
			mEditTextPreference.getEditText().setText(s);
			Toast.makeText(mContext, "只能输入数字哦", Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * 正则表达式-判断是否为数字
	 */
	public static boolean isNumeric(String str){
	    Pattern pattern = Pattern.compile("[0-9]*");
	    return pattern.matcher(str).matches();
	 }

};


text:
\hypertarget{group__i_o_s}{\section{i\-O\-S}
\label{group__i_o_s}\index{i\-O\-S@{i\-O\-S}}
}
\subsection*{Classes}
\begin{DoxyCompactItemize}
\item
class \hyperlink{interface_m_d_i_o_s_app_delegate}{M\-D\-I\-O\-S\-App\-Delegate}
\item
class \hyperlink{interface_m_d_i_o_s_consumption_table_view_cell}{M\-D\-I\-O\-S\-Consumption\-Table\-View\-Cell}
\item
class \hyperlink{interface_m_d_i_o_s_consumption_view}{M\-D\-I\-O\-S\-Consumption\-View}
\item
class \hyperlink{interface_m_d_i_o_s_consumption_view_controller}{M\-D\-I\-O\-S\-Consumption\-View\-Controller}
\item
class \hyperlink{interface_m_d_i_o_s_rooms_view_controller}{M\-D\-I\-O\-S\-Rooms\-View\-Controller}
\item
class \hyperlink{interface_m_d_i_o_s_room_table_view_cell}{M\-D\-I\-O\-S\-Room\-Table\-View\-Cell}
\item
class \hyperlink{interface_m_d_i_o_s_scenes_table_view_controller}{M\-D\-I\-O\-S\-Scenes\-Table\-View\-Controller}
\item
class \hyperlink{interface_m_d_i_o_s_settings_view_controller}{M\-D\-I\-O\-S\-Settings\-View\-Controller}
\end{DoxyCompactItemize}

\subsection{Detailed Description}


text:
package de.bytefish.jtinycsvparser;

import de.bytefish.jtinycsvparser.tokenizer.ITokenizer;
import de.bytefish.jtinycsvparser.tokenizer.StringSplitTokenizer;

public class CsvParserOptions {

    private boolean skipHeader;

    private boolean parallel;

    private ITokenizer tokenizer;

    public CsvParserOptions(boolean skipHeader, String delimiter) {
        this(skipHeader, new StringSplitTokenizer(delimiter, false));
    }

    public CsvParserOptions(boolean skipHeader, String delimiter, boolean parallel) {
        this(skipHeader, new StringSplitTokenizer(delimiter, false), parallel);
    }

    public CsvParserOptions(boolean skipHeader, ITokenizer tokenizer) {
        this(skipHeader, tokenizer, false);
    }

    public CsvParserOptions(boolean skipHeader, ITokenizer tokenizer, boolean parallel) {
        this.skipHeader = skipHeader;
        this.tokenizer = tokenizer;
        this.parallel = parallel;
    }

    public boolean getSkipHeader() {
        return skipHeader;
    }

    public ITokenizer getTokenizer() {
        return tokenizer;
    }

    public boolean getParallel() {
        return parallel;
    }

    @Override
    public String toString() {
        return "CsvParserOptions{" +
                "skipHeader=" + skipHeader +
                ", parallel=" + parallel +
                ", tokenizer=" + tokenizer +
                '}';
    }
}


text:
"""
Copyright (c) 2011, 2012, Regents of the University of California
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

 - Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
 - Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the
   distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
"""
"""
@author Stephen Dawson-Haggerty <stevedh@eecs.berkeley.edu>
"""

import os
import urlparse

from twisted.internet import reactor, task, defer, threads
from twisted.internet.endpoints import TCP6ClientEndpoint
from twisted.web.error import SchemeNotSupported
from twisted.web.client import Agent
from twisted.web.http_headers import Headers
from twisted.python import log
import logging

import util
import disklog
import sjson as json
from contrib import client
from smap.formatters import get_formatter
from smap.iface.plotly import PlotlyStream

try:
    from smap.ssl import SslClientContextFactory
except ImportError:
    log.err("Failed to import ssl... only HTTP delivery will be available")

# this is the largest number of records we will store.
BUFSIZE_LIMIT = 100000

# the most records to pack into a single log entry/message to the server
REPORT_RECORD_LIMIT = 10000

def reporting_copy(obj):
    if isinstance(obj, dict):
        rv = dict(obj)
        for k in rv.keys():
            rv[k] = reporting_copy(rv[k])
        return rv
    elif isinstance(obj, list):
        rv = list(obj)
        for i in xrange(0, len(rv)):
            rv[i] = reporting_copy(rv[i])
        return rv
    else:
        return obj

"""Iterate over all the colletions and timeseries contained in a
report object.
"""
def reporting_map(rpt, col_cb, ts_cb):
    q = ['/']
    while len(q) > 0:
        cur_path = util.norm_path(q.pop(0))
        cur = rpt.get(cur_path, None)
        if not cur: continue
        if 'Contents' in cur:
            for pc in cur['Contents']:
                q.append(cur_path + '/' + pc)
            col_cb(cur_path, cur)
        else:
            ts_cb(cur_path, cur)
        del rpt[cur_path]

    for p, v in rpt.iteritems():
        if 'Contents' in v:
            col_cb(p, v)
        else:
            ts_cb(p, v)

def is_https_url(url):
    return urlparse.urlparse(url).scheme == 'https'

class Agent6(Agent):
    def _getEndpoint(self, uri):
        try:
            return super(Agent6, self)._getEndpoint(uri)
        except SchemeNotSupported:
            if uri.scheme == 'http6':
                return TCP6ClientEndpoint(self._reactor, uri.host, uri.port)
            else:
                raise

class DataBuffer:
    """Buffer outgoing data.

    This buffer class allows you to add readings which are stored into
    a circular buffer.  It supports split-phase adding and delivery by
    returning a "truncation specification" along with the data so that
    if you later wish to shorten the buffer to remove previously read
    data, you can do that.  Note that since this is a circular buffer,
    that may mean removing less data than you read back (some may have
    been overwritten).
    """
    def __init__(self, datadir):
        """
        :param int max_size: the maximum total log size, in records
        """
        log.msg("Create databuffer " + datadir)
        self.datadir = datadir
        self.data = disklog.DiskLog(datadir)
        self.head_metric = self.metric(self.data.tail())
        # if we do a read, we have to add a new log record so we don't
        # keep appending to the same one
        self.clear = False

    def __str__(self):
        return "DataBuffer len: %i" % len(self.data)

    def __len__(self):
        return len(self.data)

    def sync(self):
        self.data.sync()

    def metric(self, val):
        if hasattr(val, '__iter__'):
            if 'Readings' in val:
                val_metric = len(val['Readings'])
            else: val_metric = sum(map(len, val))
        else:
            val_metric = 1
        return val_metric

    def add(self, key, val):
        """Enqueue a new object for delivery with a subscription

        :param string key: The key for the data stream
        :param string val: The new value for the object.  Copied.
        """
        tail = self.data.tail()

        # length of the head
        val_metric = self.metric(val)

        if tail == None or self.clear:
            self.data.append({key: reporting_copy(val)})
            self.head_metric = val_metric
            self.clear = False
        elif 'Contents' in val and len(val['Contents']) == 0:
            # okay to skip b/c it doesn't apply to anything
            pass
        elif key in tail and len(val) == 2 and \
                'Readings' in val and 'uuid' in val:
            if not 'Readings' in tail[key]:
                tail[key]['Readings'] = []
            if self.head_metric < REPORT_RECORD_LIMIT:
                tail[key]['Readings'].extend(val['Readings'])
                self.data.update_tail(tail)
                self.head_metric += val_metric
            else:
                self.data.append({key: reporting_copy(val)})
                self.head_metric = val_metric

        # really this might just want to merge updates...
        elif key in tail and val == tail[key]:
            pass
        elif not key in tail and self.head_metric < REPORT_RECORD_LIMIT:
            tail[key] = reporting_copy(val)
            self.data.update_tail(tail)
            self.head_metric += val_metric
        else:
            self.data.append({key: reporting_copy(val)})
            self.head_metric = val_metric

    def truncate(self):
        """Truncate a set of readings based on the sequence number
        stored from a previous read"""
        self.data.pop()

    def read(self):
        """Read n points (per stream) back as a flat list.  AlsoFi
        return a truncation specification so we can remove this data
        later if desired

        :rvalue: readings, tspec.  ``readings`` is the reading object
        you can send to a consumer.  ``tspec`` can be passed to
        ``truncate()`` and will removme exactly the data you just read
        -- note this is necessary because the log is a circular buffer
        and may have wrapped while you were processing the readings.
        """
        if len(self.data) > 0:
            self.clear = True
            return self.data.head()
        else:
            raise util.SmapException("No Pending Data!")

class MongoReportInstance(dict):
    """Publish latest data to Mongo store
    """
    def __init__(self, datadir, *args):
        from pymongo import MongoClient
        dict.__init__(self, *args)
        u = urlparse.urlparse(self['ReportDeliveryLocation'][0])
        url, port = u.netloc.split(':')
        self['MongoClient'] = MongoClient(url, int(port))
        if 'MongoDatabaseName' not in self:
            self['MongoDatabaseName'] = 'meteor'
        if 'MongoCollectionName' not in self:
            self['MongoCollectionName'] = 'points'
        self['MongoDatabase'] = getattr(self['MongoClient'], self['MongoDatabaseName'])
        self['DataDir'] = datadir
        self['PendingData'] = DataBuffer(datadir)

    @staticmethod
    def accepts(dests):
        for d in dests:
            if not d.scheme in ['openbas']:
                return False
        return True

    def deliverable(self):
        return True

    def insert_or_update(self, v):
        db = self['MongoDatabase']
        c = getattr(db, self['MongoCollectionName'])

        d = c.find_one({"uuid": v['uuid']})
        if d is None:
            c.insert(v)
        else:
            c.update({"uuid": v['uuid']}, { '$set': v })

    def attempt(self):
        data = self['PendingData'].read()
        for key in data:
            d = data[key]
            if 'Readings' in d:
                try:
                    latest = d['Readings'].pop()
                    v = {'time': latest[0], 'value': latest[1], 'uuid': str(d['uuid']), 'Path': key}
                    log.msg(v)
                    self.insert_or_update(v)
                except Exception, e:
                    log.msg(e)
        self['PendingData'].truncate()
        if len(self['PendingData']) > 0:
            self.attempt()

class HttpReportInstance(dict):
    """Represent the stored state pending for one report destination
    """
    def __init__(self, datadir, *args):
        dict.__init__(self, *args)
        if not 'MinPeriod' in self:
            self['MinPeriod'] = 0
        if not 'MaxPeriod' in self:
            self['MaxPeriod'] = 2 ** 31 - 1
        self['DataDir'] = datadir
        self['PendingData'] = DataBuffer(datadir)
        self['ReportDeliveryIdx'] = 0
        self['LastAttempt'] = 0
        self['LastSuccess'] = 0
        self['Busy'] = False

    @staticmethod
    def accepts(dests):
        for d in dests:
            if not d.scheme in ['http', 'https', 'http6']:
                return False
        return True

    def deliverable(self):
        """Check if attempt should be called
        :rvalue boolean: True if a report should be sent
        """
        now = util.now()
        if self.get('Paused', False): return False
        return (now - self['LastSuccess'] > self['MaxPeriod']) or \
            (len(self['PendingData']) > 0 and \
                 (now - self['LastSuccess']) > self['MinPeriod'])

    def _log_response(self, resp, url):
        def response_printer(resp):
            log.msg("Reply from %s: '%s'" % (url,resp.strip()))
        done = defer.Deferred()
        resp.deliverBody(util.BufferProtocol(done))
        done.addCallback(response_printer)
        return done

    def _success(self, resp):
        self['Busy'] = False
        if resp.code in [200, 201, 204]:
            # on success record the time and remove the data
            self['LastSuccess'] = util.now()
            self['PendingData'].truncate()
            if len(self['PendingData']) > 0:
                # this causes a new deferred to get added to
                # the chain, so we continue immediately at the
                # next log position if this one worked.
                return self.attempt()
            else:
                return resp
        else:
            # but most HTTP codes indicate a failure
            log.msg("Report delivery to %s returned %i" % (
                    self['ReportDeliveryLocation'][self['ReportDeliveryIdx']],
                    resp.code))
            response = self._log_response(resp,
                     self['ReportDeliveryLocation'][self['ReportDeliveryIdx']])
            self['ReportDeliveryIdx'] = ((self['ReportDeliveryIdx'] + 1) %
                                         len(self['ReportDeliveryLocation']))
            return response

    def _failure(self, fail):
        self['Busy'] = False
        try:
            log.msg("Report delivery to %s failed: %s" %
                    (self['ReportDeliveryLocation'][self['ReportDeliveryIdx']],
                     str(fail.value)))
            self['ReportDeliveryIdx'] = ((self['ReportDeliveryIdx'] + 1) %
                                         len(self['ReportDeliveryLocation']))
        except:
            log.err()
        return fail

    def attempt(self):
        """Try to make a delivery
        :rvalue: a :py:class:`Deferred` of the attempt
        """
        if ('Busy' in self and self['Busy']) or \
                ('Paused' in self and self['Paused']):
            return

        try:
            data = self['PendingData'].read()
            if data == None:
                self['PendingData'].truncate()
                return
        except:
            log.err()
            return

        self['LastAttempt'] = util.now()
        log.msg("publishing to %s: %i %s" %
                (self['ReportDeliveryLocation'][self['ReportDeliveryIdx']],
                 len(data),
                 str([len(x['Readings'])
                      for x in data.itervalues()
                      if 'Readings' in x])),
                logLevel=logging.DEBUG)
        # set up an agent to push the data to the consumer

        dest_url = self['ReportDeliveryLocation'][self['ReportDeliveryIdx']]
        if is_https_url(dest_url):
            agent = Agent6(reactor, SslClientContextFactory(self))
        else:
            agent = Agent6(reactor)

        try:
            formatter = get_formatter(self.get('Format', 'json'))
            headers = {'Content-type' : [formatter.content_type]}
            if formatter.content_encoding:
                headers['Content-encoding'] = [formatter.content_encoding]
            d = agent.request('POST',
                              dest_url,
                              Headers(headers),
                              formatter(data))
        except:
            log.err()
            return

        self['Busy'] = True
        d.addCallback(self._success)
        d.addErrback(self._failure)
        return d
# default for backwards compatibility
ReportInstance = HttpReportInstance

class PlotlyReportInstance(dict):
    def __init__(self, datadir, *args):
        dict.__init__(self, *args)
        self['PendingData'] = DataBuffer(datadir)
        u = urlparse.urlparse(self['ReportDeliveryLocation'][0])
        uri = "http://" + u.netloc
        streamid = u.path.lstrip('/')
        print "Publishing plot.ly stream to", uri, "streamid:", streamid
        self['Publisher'] = PlotlyStream(streamid, uri)

    @staticmethod
    def accepts(dests):
        for d in dests:
            if not d.scheme in ['plotly']:
                return False
        return True

    def deliverable(self):
        return True

    def attempt(self):
        data = self['PendingData'].read()
        self['PendingData'].truncate()
        if data is None:
            return
        elif len(data) != 1:
            log.msg("Plotly only supports a single stream -- specify a resource")
            return
        else:
            data = data.values()[0]
            if 'Readings' in data:
                for ts, val in data['Readings']:
                    self['Publisher'].add(ts, val)

def get_report_class(deliver_locations):
    deliverylocs = map(urlparse.urlparse, deliver_locations)
    report_instance = None
    for report_class in [HttpReportInstance, PlotlyReportInstance, MongoReportInstance]:
        if report_class.accepts(deliverylocs):
            return report_class

class Reporting:
    def __init__(self, inst, autoflush=1.0, reportfile=None, max_size=BUFSIZE_LIMIT):
        """Create a new report manager, responsible for delivering
        data to subscribers.  Buffers data on disk until it can be
        delivered, storing up to *max_size* points per timeseries.

        :param inst: the :py:class:`~smap.core.SmapInstance` we'll be
         delivering reports for.
        :param float autoflush: how often to call flush, which attempts
         to deliver all data.
        :param string reportfile: backing store for reporting instances
         and data which hasn't been delivered yet.
        :param int max_size: the maximum number of points we will buffer for
         any stream.
        """
        self.inst = inst
        self.subscribers = []
        self.reportfile = reportfile
        self.max_size = max_size
        self.autoflush = autoflush
        if self.reportfile:
            self.load_reports()

        if autoflush != None:
            # add a blank callback to the deferred to kill off any errors
            def flush():
                d = self._flush()
                if d: d.addBoth(lambda _ : None)
            self.t = task.LoopingCall(flush)
            reactor.callLater(autoflush, self.t.start, autoflush)

        # add a shutdown handler so we save the final reports after exiting
        if reportfile:
            reactor.addSystemEventTrigger('after', 'shutdown',
                                          self.save_reports)

    def get_report(self, id):
        return util.find(lambda item: item['uuid'] == id, self.subscribers)

    def add_report(self, rpt):
        dir = os.path.join(self.reportfile + '-reports',
                           str(rpt['uuid']))
        rpt['ReportDeliveryLocation'] = map(str, rpt['ReportDeliveryLocation'])

        report_class = get_report_class(rpt['ReportDeliveryLocation'])
        if report_class == None:
            print "No report deliverer found for " + str(rpt['ReportDeliveryLocation'])
            return
        else:
            report_instance = report_class(dir, rpt)

        log.msg("Creating report -- dest is %s" % str(rpt['ReportDeliveryLocation']))
        self._update_subscriptions(report_instance)
        self.subscribers.append(report_instance)

        # publish the full data set when we add a subscription so we
        # can compress from here
        for k, v in self.inst.lookup(report_instance['ReportResource']).iteritems():
            self.publish(k, v)

    def del_report(self, id):
        rpt = self.get_report(id)
        if rpt:
            log.msg("removing report " + str(id))
            del self.subscribers[self.subscribers.index(rpt)]
        return rpt

    def update_report(self, rpt):
        """Copy in fields from a new reporting object
        """
        cur = self.get_report(rpt['uuid'])
        log.msg("updating report %s: dest is now %s" % (
                str(rpt['uuid']),
                str(rpt['ReportDeliveryLocation'])))
        if cur:
            cur.update(rpt)
            self._update_subscriptions(cur)
            return True
        return False

    def _update_subscriptions(self, sub):
        result = self.inst.lookup(sub['ReportResource'])
        if isinstance(result, dict) and 'uuid' in result:
            # is a single time series
            sub['Topics'] = set([getattr(result, 'path')])
        elif isinstance(result, dict):
            # is a dict of {path: value}
            sub['Topics'] = set(result.iterkeys())
        else:
            # is nothing
            sub['Topics'] = set()

    def update_subscriptions(self):
        """Should be called whenever the set of resources changes so we can
        update the list of uuids for each subscriber."""
        map(self._update_subscriptions, self.subscribers)

    def publish(self, path, val, prepend=False):
        """Publish a new reading to the stream identified by a path.

        Not thread safe.
        """
        path = util.norm_path(path)
        for sub in self.subscribers:
            if path in sub['Topics']:
                sub['PendingData'].add(path, val)

    def load_reports(self):
        self.subscribers = util.pickle_load(self.reportfile)
        if self.subscribers == None:
            self.subscribers = []
        for s in self.subscribers:
            s['Busy'] = False
            s['Paused'] = False
            if not 'Format' in s:
                s['Format'] = 'json'

    def save_reports(self, *args):
        """Save reports while holding the filesystem lock.
        """
        util.pickle_dump(self.reportfile, self.subscribers)
        for s in self.subscribers:
            s['PendingData'].sync()

        if len(args) == 1:
            return args[0]
        else:
            return

    def _flush(self, force=False):
        """Send out json-packed report objects to registered listeners.

        :param boolean force: if True, ignore ``MinPeriod``/``MaxPeriod``
         and force the reporting metadata to disk
        :rtype: a :py:class:`twisted.internet.task.DeferredList`
         instance which will fire when deliver to all subscribers has
         finished, or errBack when any fail
        """
        deferList, deleteList = [], []
        for sub in self.subscribers:
            now = util.now()
            if sub.get('ExpireTime', now) < now:
                # remove expired reports
                deleteList.append(sub['uuid'])

            # either we've gone too long without trying and so need to
            # deliver a report or else we have new data and have
            # waited for at least MinPeriod since the last report.
            elif force or sub.deliverable():
                d = defer.maybeDeferred(sub.attempt)
                # we don't need an errBack for this case since we want
                # to propagate the error and don't need to do any
                # cleanup
                deferList.append(d)

        map(self.del_report, deleteList)
        d = defer.DeferredList(deferList, fireOnOneErrback=True, consumeErrors=True)
        if force: d.addBoth(self.save_reports)
        return d

    def flush(self):
        """Causes delivery to be attempted for all non-busy reports
        now.  Threaded version; blocks until :py:meth:`_flush` finishes.
        """
        return threads.blockingCallFromThread(reactor, self.inst._flush)

    def pause(self):
        for s in self.subscribers:
            s['Paused'] = True

    def unpause(self):
        for s in self.subscribers:
            s['Paused'] = False
        return self._flush()


text:
// The MIT License (MIT)
//
// Copyright (c) 2017 Arnaud Vazard
//
// See LICENSE file.

/*
Package quote contains quote commands
*/
package core

import (
	"github.com/thoj/go-ircevent"
	"testing"
)

func Test_GetTargetFromEvent(t *testing.T) {

	// Channel
	event := irc.Event{
		Nick:      "Sender",
		Arguments: []string{"#test_channel", "test message"}}
	expectedResult := "#test_channel"

	result := GetTargetFromEvent(&event)

	if result != expectedResult {
		t.Errorf("Result not matching expected result (%q != %q)", result, expectedResult)
	}

	// Nick
	event = irc.Event{
		Nick:      "Sender",
		Arguments: []string{"Receiver", "test message"}}
	expectedResult = "Sender"

	result = GetTargetFromEvent(&event)

	if result != expectedResult {
		t.Errorf("Result not matching expected result (%q != %q)", result, expectedResult)
	}
}


text:
"""
utils
~~~~~

Provides miscellaneous utility methods
"""

from __future__ import (
    absolute_import, division, print_function, with_statement,
    unicode_literals)

import requests
import itertools as it

from urllib2 import urlopen
from datetime import datetime as dt
from ijson import items
from tabutils.process import merge

def _make_requirements(obj):
    funding = obj['funding']

    if 'current_requirement' in obj or 'current_requirements' in obj:
        requirement = obj.get(
            'current_requirements', obj.get('current_requirement'))

        coverage = funding / requirement if requirement else 0
        requirements = {
            'requirement': requirement,
            'funding': funding,
            'coverage': coverage,
        }
    else:
        requirements = {'funding': funding}

    return requirements

def _find_countries(countries, url):
    black_list = {'Region', 'none', '', None}

    if countries in black_list:
        r = requests.get(url)

        if 'grouping' in r.json():
            all_countries = (g['type'] for g in r.json()['grouping'])
        else:
            all_countries = (g['country'] for g in r.json())

        func = lambda x: x not in black_list
        country_set = set(it.ifilter(func, all_countries))

        if country_set:
            countries = '"%s"' % '","'.join(country_set)
        else:
            countries = 'N/A'

    return countries

def gen_data(start_year=None, end_year=None, mode=False, **kwargs):
    """Generates historical or current data"""
    end_year = int(end_year or dt.now().year) + 1
    start_year = start_year or end_year - 1
    years = range(start_year, end_year)

    appeals_mode = mode.startswith('A')
    cluster_mode = mode.startswith('C')
    emergency_mode = mode.startswith('E')

    base = kwargs['BASE_URL']
    suffix = kwargs['SUFFIX']

    for year in years:
        appeals = urlopen('%s/appeal/year/%s%s' % (base, year, suffix))
        emergencies = urlopen('%s/emergency/year/%s%s' % (
            base, year, suffix))

        if appeals_mode or cluster_mode:
            data_items = items(appeals, kwargs['DATA_LOCATION'])
            emergency_items = items(
                emergencies, kwargs['DATA_LOCATION'])
            emergency_lookup = {
                e['id']: e['title'] for e in emergency_items}
        else:
            data_items = items(emergencies, kwargs['DATA_LOCATION'])

        for item in data_items:
            if appeals_mode or cluster_mode:
                emergency_id = item['emergency_id']
                emergency_name = emergency_lookup.get(emergency_id, 'N/A')
                appeal_id = item['id']
                url = '%s/project/appeal/%s%s' % (base, appeal_id, suffix)
            else:
                emergency_id = item['id']
                url = '%s/funding%s?groupby=country&emergency=%s' % (
                    base, suffix, emergency_id)
                emergency_name = item['title']

            record = {
                'emergency_id': emergency_id,
                'emergency_name': emergency_name,
                'countries': _find_countries(item['country'], url),
                'year': item['year'],
            }

            if appeals_mode or cluster_mode:
                record.update({
                    'appeal_id': appeal_id,
                    'appeal_name': item['title'],
                    'funding_type': item['type']})

            if appeals_mode or emergency_mode:
                yield merge(record, _make_requirements(item))
            else:
                url = '%s/cluster/appeal/%s%s' % (base, appeal_id, suffix)
                r = requests.get(url)

                for cluster in r.json():
                    additional = _make_requirements(cluster)
                    additional['cluster'] = cluster['name']
                    yield merge(record, additional)


text:
package rbac

import (
	"github.com/rancher/norman/authorization"
	"github.com/rancher/norman/types"
)

type contextKey struct{}

type contextBased struct {
	all    authorization.AllAccess
	lookup contextLookup
}

type contextLookup func(ctx *types.APIContext) (types.AccessControl, bool)

func newContextBased(lookup contextLookup) types.AccessControl {
	return &contextBased{
		lookup: lookup,
	}
}

func (c *contextBased) Expire(apiContext *types.APIContext, schema *types.Schema) {
	ac, ok := c.lookup(apiContext)
	if !ok {
		return
	}
	if e, ok := ac.(types.Expire); ok {
		e.Expire(apiContext, schema)
	}
}

func (c *contextBased) CanCreate(apiContext *types.APIContext, schema *types.Schema) error {
	ac, ok := c.lookup(apiContext)
	if ok {
		return ac.CanCreate(apiContext, schema)
	}
	return c.all.CanCreate(apiContext, schema)
}

func (c *contextBased) CanList(apiContext *types.APIContext, schema *types.Schema) error {
	ac, ok := c.lookup(apiContext)
	if ok {
		return ac.CanList(apiContext, schema)
	}
	return c.all.CanList(apiContext, schema)
}

func (c *contextBased) CanGet(apiContext *types.APIContext, schema *types.Schema) error {
	ac, ok := c.lookup(apiContext)
	if ok {
		return ac.CanGet(apiContext, schema)
	}
	return c.all.CanGet(apiContext, schema)
}

func (c *contextBased) CanUpdate(apiContext *types.APIContext, obj map[string]interface{}, schema *types.Schema) error {
	ac, ok := c.lookup(apiContext)
	if ok {
		return ac.CanUpdate(apiContext, obj, schema)
	}
	return c.all.CanUpdate(apiContext, obj, schema)
}

func (c *contextBased) CanDelete(apiContext *types.APIContext, obj map[string]interface{}, schema *types.Schema) error {
	ac, ok := c.lookup(apiContext)
	if ok {
		return ac.CanDelete(apiContext, obj, schema)
	}
	return c.all.CanDelete(apiContext, obj, schema)
}

func (c *contextBased) CanDo(apiGroup, resource, verb string, apiContext *types.APIContext, obj map[string]interface{}, schema *types.Schema) error {
	ac, ok := c.lookup(apiContext)
	if ok {
		return ac.CanDo(apiGroup, resource, verb, apiContext, obj, schema)
	}
	return c.all.CanDo(apiGroup, resource, verb, apiContext, obj, schema)
}

func (c *contextBased) Filter(apiContext *types.APIContext, schema *types.Schema, obj map[string]interface{}, context map[string]string) map[string]interface{} {
	ac, ok := c.lookup(apiContext)
	if ok {
		return ac.Filter(apiContext, schema, obj, context)
	}
	return obj
}

func (c *contextBased) FilterList(apiContext *types.APIContext, schema *types.Schema, obj []map[string]interface{}, context map[string]string) []map[string]interface{} {
	ac, ok := c.lookup(apiContext)
	if ok {
		return ac.FilterList(apiContext, schema, obj, context)
	}
	return obj
}


text:
SYNONYM

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

#### Published in
Bull. Torrey bot. Club 35: 408 (1908)

#### Original name
Amauroderma ramosii Murrill, 1908

### Remarks
null


text:
from django.conf.urls import patterns, include, url

urlpatterns = patterns('vodkamartiniqa.views.answers',
    # used for getting ajax answers
    url(r'^get-answers/(?P<question_id>\d+)/(?P<start>\d+)/(?P<end>\d+)/$', 'get_answers_ajax', name='vodkamartiniqa_answers_get_ajax'),
)


text:
import file from '../file.txt';
export { file };


text:
using System;
using System.Collections.Generic;
using System.Net;

namespace IP2Country.Net
{
    public class IPAddressComparer : IComparer<IPAddress>
    {
        public int Compare(IPAddress x, IPAddress y)
        {
            if (x == null)
            {
                return -1;
            }
            if (y == null)
            {
                return 1;
            }
            var result = x.AddressFamily.CompareTo(y.AddressFamily);
            if (result != 0)
            {
                return result;
            }

            var xBytes = x.GetAddressBytes();
            var yBytes = y.GetAddressBytes();

            var octets = Math.Min(xBytes.Length, yBytes.Length);
            for (var i = 0; i < octets; i++)
            {
                var octetResult = xBytes[i].CompareTo(yBytes[i]);
                if (octetResult != 0)
                {
                    return octetResult;
                }
            }
            return 0;
        }
    }
}


text:
@interface SGAccountManager : NSObject

+ (instancetype)sharedManager;
- (void)registerAccountWithPassword:(NSString *)password errorMessage:(NSString * __autoreleasing *)errorMessage;
- (SGAccount *)getAccountByPwd:(NSString *)pwd;
- (SGAccount *)getTouchIDAccount;
- (UIViewController *)getRootViewController;

@property (nonatomic, strong) SGAccount *currentAccount;

@end


text:
/*
 * Copyright (C) 1998, 1999, 2000,
 *
 * Arjuna Solutions Limited,
 * Newcastle upon Tyne,
 * Tyne and Wear,
 * UK.
 *
 * $Id: Util.java 2342 2006-03-30 13:06:17Z  $
 */

package com.hp.mwtests.ts.jts.utils;

import org.jboss.logging.Logger;

import java.util.Random;

public class Util
{
    public static final Logger logger = Logger.getLogger("Util");

    public static void indent (char thr, int level)
    {
	System.out.print(thr+" ");

	for (int i = 0; i < level; i++)
	    System.out.print(" ");
    }

    public static void indent (int thr, int level)
    {
	System.out.print(thr+" ");

	for (int i = 0; i < level; i++)
	    System.out.print(" ");
    }

    public static void lowProbYield () {
        while ((rand.nextInt() % 2) != 0) {
            logger.trace("low Yielding");
            Thread.yield();
            logger.trace("Yielded");
        }
    }

    public static void highProbYield ()
    {
	while ((rand.nextInt() % 4) != 0) {
        logger.trace("high Yielding");
        Thread.yield();
        logger.trace("Yielded");
    }
    }

    public static Random rand = new Random();

}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.literal = undefined;

var _ast = require('../../ast');

var _syntax = require('../../syntax');

var type = (0, _ast.defineType)({
  type: 'Nil',
  constructor: function constructor() {},
  methods: {
    print: function print() {
      return 'nil';
    },
    inspect: function inspect() {
      return 'Nil#nil';
    }
  }
});
exports.default = type;
var literal = exports.literal = (0, _syntax.defineLiteral)(type, /^nil$/);


text:
<?php

namespace Hackzilla\TicketMessage\Entity;

use Hackzilla\TicketMessage\Entity\Traits\TicketTrait;
use Hackzilla\TicketMessage\Model\TicketInterface;

/**
 * Ticket.
 */
class TicketWithAttachment implements TicketInterface
{
    use TicketTrait;

    /**
     * @var int
     */
    protected $id;

    /**
     * Get id.
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }
}


text:
namespace Tangram {

const std::vector<float> FontContext::s_fontRasterSizes = { 16, 28, 40 };

FontContext::FontContext(std::shared_ptr<const Platform> _platform) :
    m_sdfRadius(SDF_WIDTH),
    m_atlas(*this, GlyphTexture::size, m_sdfRadius),
    m_batch(m_atlas, m_scratch),
    m_platform(_platform) {}

void FontContext::setPixelScale(float _scale) {
    m_sdfRadius = SDF_WIDTH * _scale;
}

void FontContext::loadFonts() {
    auto fallbacks = m_platform->systemFontFallbacksHandle();

    for (size_t i = 0; i < s_fontRasterSizes.size(); i++) {
        m_font[i] = m_alfons.addFont("default", s_fontRasterSizes[i]);
    }

    for (auto fallback : fallbacks) {

        if (!fallback.isValid()) { continue; }

        alfons::InputSource source;

        if (fallback.pathOrFontName.empty()) {
            source = alfons::InputSource(fallback.load);
        } else {
            source = alfons::InputSource(fallback.pathOrFontName, fallback.isFontName);
        }

        for (size_t i = 0; i < s_fontRasterSizes.size(); i++) {
            m_font[i]->addFace(m_alfons.addFontFace(source, s_fontRasterSizes[i]));
        }
    }
}

// Synchronized on m_mutex in layoutText(), called on tile-worker threads
void FontContext::addTexture(alfons::AtlasID id, uint16_t width, uint16_t height) {

    std::lock_guard<std::mutex> lock(m_textureMutex);

    if (m_textures.size() == max_textures) {
        LOGE("Way too many glyph textures!");
        return;
    }
    m_textures.emplace_back();
}

// Synchronized on m_mutex in layoutText(), called on tile-worker threads
void FontContext::addGlyph(alfons::AtlasID id, uint16_t gx, uint16_t gy, uint16_t gw, uint16_t gh,
                           const unsigned char* src, uint16_t pad) {

    std::lock_guard<std::mutex> lock(m_textureMutex);

    if (id >= max_textures) { return; }

    auto& texData = m_textures[id].texData;
    auto& texture = m_textures[id].texture;

    size_t stride = GlyphTexture::size;
    size_t width =  GlyphTexture::size;

    unsigned char* dst = &texData[(gx + pad) + (gy + pad) * stride];

    for (size_t y = 0, pos = 0; y < gh; y++, pos += gw) {
        std::memcpy(dst + (y * stride), src + pos, gw);
    }

    dst = &texData[size_t(gx) + (size_t(gy) * width)];
    gw += pad * 2;
    gh += pad * 2;

    size_t bytes = size_t(gw) * size_t(gh) * sizeof(float) * 3;
    if (m_sdfBuffer.size() < bytes) {
        m_sdfBuffer.resize(bytes);
    }

    sdfBuildDistanceFieldNoAlloc(dst, width, m_sdfRadius,
                                 dst, gw, gh, width,
                                 &m_sdfBuffer[0]);

    texture.setDirty(gy, gh);
    m_textures[id].dirty = true;
}

void FontContext::releaseAtlas(std::bitset<max_textures> _refs) {
    if (!_refs.any()) { return; }
    std::lock_guard<std::mutex> lock(m_textureMutex);
    for (size_t i = 0; i < m_textures.size(); i++) {
        if (_refs[i]) { m_atlasRefCount[i] -= 1; }
    }
}

void FontContext::updateTextures(RenderState& rs) {
    std::lock_guard<std::mutex> lock(m_textureMutex);

    for (auto& gt : m_textures) {
        if (gt.dirty) {
            gt.dirty = false;
            auto td = reinterpret_cast<const GLuint*>(gt.texData.data());
            gt.texture.update(rs, 0, td);
        }
    }
}

void FontContext::bindTexture(RenderState& rs, alfons::AtlasID _id, GLuint _unit) {
    std::lock_guard<std::mutex> lock(m_textureMutex);
    m_textures[_id].texture.bind(rs, _unit);

}

bool FontContext::layoutText(TextStyle::Parameters& _params, const icu::UnicodeString& _text,
                             std::vector<GlyphQuad>& _quads, std::bitset<max_textures>& _refs,
                             glm::vec2& _size, TextRange& _textRanges) {

    std::lock_guard<std::mutex> lock(m_fontMutex);

    alfons::LineLayout line = m_shaper.shapeICU(_params.font, _text, MIN_LINE_WIDTH,
                                                _params.wordWrap ? _params.maxLineWidth : 0);

    if (line.missingGlyphs() || line.shapes().size() == 0) {
        // Nothing to do!
        return false;
    }

    line.setScale(_params.fontScale);

    // m_batch.drawShapeRange() calls FontContext's TextureCallback for new glyphs
    // and MeshCallback (drawGlyph) for vertex quads of each glyph in LineLayout.

    m_scratch.quads = &_quads;

    size_t quadsStart = _quads.size();
    alfons::LineMetrics metrics;

    std::array<bool, 3> alignments = {};
    if (_params.align != TextLabelProperty::Align::none) {
        alignments[int(_params.align)] = true;
    }

    // Collect possible alignment from anchor fallbacks
    for (int i = 0; i < _params.labelOptions.anchors.count; i++) {
        auto anchor = _params.labelOptions.anchors[i];
        TextLabelProperty::Align alignment = TextLabelProperty::alignFromAnchor(anchor);
        if (alignment != TextLabelProperty::Align::none) {
            alignments[int(alignment)] = true;
        }
    }

    if (_params.wordWrap) {
        m_textWrapper.clearWraps();

        if (_params.maxLines != 0) {
            uint32_t numLines = 0;
            int pos = 0;
            int max = line.shapes().size();

            for (auto& shape : line.shapes()) {
                pos++;
                if (shape.mustBreak) {
                    numLines++;
                    if (numLines >= _params.maxLines && pos < max) {
                        shape.mustBreak = false;
                        line.removeShapes(shape.isSpace ? pos-1 : pos, max);

                        auto ellipsis = m_shaper.shape(_params.font, "…");
                        line.addShapes(ellipsis.shapes());
                        break;
                    }
                }
            }
        }

        float width = m_textWrapper.getShapeRangeWidth(line);

        for (size_t i = 0; i < 3; i++) {

            int rangeStart = m_scratch.quads->size();
            if (!alignments[i]) {
                _textRanges[i] = Range(rangeStart, 0);
                continue;
            }
            int numLines = m_textWrapper.draw(m_batch, width, line, TextLabelProperty::Align(i),
                                              _params.lineSpacing, metrics);
            int rangeEnd = m_scratch.quads->size();

            _textRanges[i] = Range(rangeStart, rangeEnd - rangeStart);

            // For single line text alignments are the same
            if (i == 0 && numLines == 1) {
                _textRanges[1] = Range(rangeEnd, 0);
                _textRanges[2] = Range(rangeEnd, 0);
                break;
            }
        }
    } else {
        glm::vec2 position(0);
        int rangeStart = m_scratch.quads->size();
        m_batch.drawShapeRange(line, 0, line.shapes().size(), position, metrics);
        int rangeEnd = m_scratch.quads->size();

        _textRanges[0] = Range(rangeStart, rangeEnd - rangeStart);

        _textRanges[1] = Range(rangeEnd, 0);
        _textRanges[2] = Range(rangeEnd, 0);
    }

    auto it = _quads.begin() + quadsStart;
    if (it == _quads.end()) {
        // No glyphs added
        return false;
    }

    // TextLabel parameter: Dimension
    float width = metrics.aabb.z - metrics.aabb.x;
    float height = metrics.aabb.w - metrics.aabb.y;
    _size = glm::vec2(width, height);

    // Offset to center all glyphs around 0/0
    glm::vec2 offset((metrics.aabb.x + width * 0.5) * TextVertex::position_scale,
                     (metrics.aabb.y + height * 0.5) * TextVertex::position_scale);

    {
        std::lock_guard<std::mutex> lock(m_textureMutex);
        for (; it != _quads.end(); ++it) {

            if (!_refs[it->atlas]) {
                _refs[it->atlas] = true;
                m_atlasRefCount[it->atlas]++;
            }

            it->quad[0].pos -= offset;
            it->quad[1].pos -= offset;
            it->quad[2].pos -= offset;
            it->quad[3].pos -= offset;
        }

        // Clear unused textures
        for (size_t i = 0; i < m_textures.size(); i++) {
            if (m_atlasRefCount[i] == 0) {
                m_atlas.clear(i);
                m_textures[i].texData.assign(GlyphTexture::size *
                                             GlyphTexture::size, 0);
            }
        }
    }

    return true;
}

void FontContext::addFont(const FontDescription& _ft, alfons::InputSource _source) {

    // NB: Synchronize for calls from download thread
    std::lock_guard<std::mutex> lock(m_fontMutex);

    for (size_t i = 0; i < s_fontRasterSizes.size(); i++) {
        auto font = m_alfons.getFont(_ft.alias, s_fontRasterSizes[i]);
        font->addFace(m_alfons.addFontFace(_source, s_fontRasterSizes[i]));

        // add fallbacks from default font
        font->addFaces(*m_font[i]);
    }
}

void FontContext::releaseFonts() {
    // Unload Freetype and Harfbuzz resources for all font faces
    m_alfons.unload();

    // Release system font fallbacks input source data from default fonts, since
    // those are 'weak' resources (would be automatically reloaded by alfons from
    // its URI or source callback.
    for (auto& font : m_font) {
        for (auto& face : font->faces()) {
            alfons::InputSource& fontSource = face->descriptor().source;

            if (fontSource.isUri() || fontSource.hasSourceCallback()) {
                fontSource.clearData();
            }
        }
    }
}

void FontContext::ScratchBuffer::drawGlyph(const alfons::Rect& q, const alfons::AtlasGlyph& atlasGlyph) {
    if (atlasGlyph.atlas >= max_textures) { return; }

    auto& g = *atlasGlyph.glyph;

    quads->push_back({
            atlasGlyph.atlas,
            {{glm::vec2{q.x1, q.y1} * TextVertex::position_scale, {g.u1, g.v1}},
             {glm::vec2{q.x1, q.y2} * TextVertex::position_scale, {g.u1, g.v2}},
             {glm::vec2{q.x2, q.y1} * TextVertex::position_scale, {g.u2, g.v1}},
             {glm::vec2{q.x2, q.y2} * TextVertex::position_scale, {g.u2, g.v2}}}});
}

std::shared_ptr<alfons::Font> FontContext::getFont(const std::string& _family, const std::string& _style,
                                                   const std::string& _weight, float _size) {

    // Pick the smallest font that does not scale down too much
    float fontSize = s_fontRasterSizes.back();
    size_t sizeIndex = s_fontRasterSizes.size() - 1;

    auto fontSizeItr = std::lower_bound(s_fontRasterSizes.begin(), s_fontRasterSizes.end(), _size);
    if (fontSizeItr != s_fontRasterSizes.end()) {
        fontSize = *fontSizeItr;
        sizeIndex = fontSizeItr - s_fontRasterSizes.begin();
    }

    std::lock_guard<std::mutex> lock(m_fontMutex);

    auto font = m_alfons.getFont(FontDescription::Alias(_family, _style, _weight), fontSize);
    if (font->hasFaces()) { return font; }

    // 1. Bundle
    // Assuming bundled ttf file follows this convention
    std::string bundleFontPath = m_sceneResourceRoot + "fonts/" +
        FontDescription::BundleAlias(_family, _style, _weight);

    std::vector<char> fontData = m_platform->bytesFromFile(bundleFontPath.c_str());

    // 2. System font
    if (fontData.size() == 0) {
        bool useFallbackFont = false;

        auto systemFontHandle = m_platform->systemFont(_family, _weight, _style);
        if (systemFontHandle.isValid()) {
            alfons::InputSource source;

            if (systemFontHandle.pathOrFontName.empty()) {
                fontData = systemFontHandle.load();
                if (fontData.size() > 0) {
                    source = alfons::InputSource(systemFontHandle.load);
                    font->addFace(m_alfons.addFontFace(source, fontSize));
                    if (m_font[sizeIndex]) {
                        font->addFaces(*m_font[sizeIndex]);
                    }
                } else {
                    useFallbackFont = true;
                }
            } else {
                source = alfons::InputSource(systemFontHandle.pathOrFontName, systemFontHandle.isFontName);
                font->addFace(m_alfons.addFontFace(source, fontSize));
                if (m_font[sizeIndex]) {
                    font->addFaces(*m_font[sizeIndex]);
                }
            }
        } else {
            useFallbackFont = true;
        }

        if (useFallbackFont) {
            LOGN("Could not load font file %s", FontDescription::BundleAlias(_family, _style, _weight).c_str());

            // 3. Add fallbacks from default font
            if (m_font[sizeIndex]) {
                font->addFaces(*m_font[sizeIndex]);
            }
        }
    }

    return font;
}

}


text:
package org.fax4j.common;

import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import java.util.logging.StreamHandler;
import org.fax4j.FaxClient;

/**
 * This is a simple proxy implementation of the logger that transfers
 * all log events to the JDK logger.
 *
 * @author 	Sagie Gur-Ari
 * @version 1.03
 * @since	0.27
 */
public class JDKLogger extends AbstractLogger
{
	/**The JDK logger*/
	protected final Logger JDK_LOGGER;

	/**
	 * This is the default constructor.
	 */
	public JDKLogger()
	{
		super();

		//init logger
		this.JDK_LOGGER=JDKLogger.initializeLogger();
	}

	/**
	 * This function initializes and returns the logger.
	 *
	 * @return	The logger
	 */
	protected static final Logger initializeLogger()
	{
		//get logger
		Logger logger=Logger.getLogger(FaxClient.class.getName());

		//enable all log events (fax4j logger filters out uneeded log events)
		logger.setLevel(Level.ALL);
		logger.setFilter(null);

		//enable to pass log events to parent loggers
		logger.setUseParentHandlers(true);

		//create handler
		Formatter formatter=new SimpleFormatter();
		Handler handler=new StreamHandler(System.out,formatter);

		//set filtering
		handler.setLevel(logger.getLevel());
		handler.setFilter(logger.getFilter());

		//add handler
		logger.addHandler(handler);

		return logger;
	}

	/**
	 * Logs the provided data.
	 *
	 * @param 	level
	 * 			The log level
	 * @param	message
	 * 			The message parts (may be null)
	 * @param 	throwable
	 * 			The error (may be null)
	 */
	@Override
	protected void logImpl(LogLevel level,Object[] message,Throwable throwable)
	{
		//get log level
		int levelValue=level.getValue();
		Level jdkLevel=null;
		switch(levelValue)
		{
			case LogLevel.DEBUG_LOG_LEVEL_VALUE:
				jdkLevel=Level.FINEST;
				break;
			case LogLevel.ERROR_LOG_LEVEL_VALUE:
				jdkLevel=Level.SEVERE;
				break;
			case LogLevel.INFO_LOG_LEVEL_VALUE:
			default:
				jdkLevel=Level.FINE;
				break;
		}

		if(jdkLevel!=null)
		{
			//format log message (without exception)
			String text=this.formatLogMessage(level,message,null);

			//log
			this.JDK_LOGGER.log(jdkLevel,text,throwable);
		}
	}
}


text:
koa-device
==========

A Koa.js wrapper for express-device

```
$ npm install koa-device
```


text:
enum TestDataType {
    Regression = 1,               // data for regression
    Classification = 2,           // data for classification
    ClassificationAnalog = 3,     // data for classification with analog input features
};

struct DataParameters {
    DataParameters() {
        numberOfSamples = 1024;
        inpFeatureDimensionality = 1;
        outFeatureDimensionality = 1;
        W0 = -2.f;
        B0 = 3.f;
    }
    int numberOfSamples;
    int inpFeatureDimensionality;
    int outFeatureDimensionality;
    float W0;
    float B0;
};

inline void generateTestData(const std::string& path, const TestDataType testDataType, const DataParameters& dataParameters, std::ostream& out) {
    std::vector<std::vector<unsigned int> > vSampleTestInput, vSampleTestInputTime;
    std::vector<std::vector<float> > vSampleTestInputData;
    std::vector<std::vector<unsigned int> > vSampleTestOutput, vSampleTestOutputTime;
    std::vector<std::vector<float> > vSampleTestOutputData;
    std::vector<std::string> vSamplesName(dataParameters.numberOfSamples);
    std::map<std::string, unsigned int> mFeatureNameToIndex;

    for (int d = 0; d < dataParameters.inpFeatureDimensionality; d++) {
        std::string feature_name = std::string("feature") + std::to_string((long long) d);
        mFeatureNameToIndex[feature_name] = d;
    }

    for (int s = 0; s < dataParameters.numberOfSamples; s++) {
        vSamplesName[s] = std::string("sample") + std::to_string((long long) s);
    }

    for (int s = 0; s < dataParameters.numberOfSamples; s++) {
        vector<unsigned int> inpFeatureIndex, inpTime;
        vector<float> inpFeatureValue;
        vector<unsigned int> outFeatureIndex, outTime;
        vector<float> outFeatureValue;

        switch (testDataType) {
        case Regression:
            for (int d = 0; d < dataParameters.inpFeatureDimensionality; d++) {
                inpFeatureIndex.push_back(d);
                inpFeatureValue.push_back((float) s);
                inpTime.push_back(s);
            }

            for (int d = 0; d < dataParameters.outFeatureDimensionality; d++) {
                outFeatureIndex.push_back(d);
                outFeatureValue.push_back(dataParameters.W0 * inpFeatureValue[d] + dataParameters.B0);
                outTime.push_back(s);
            }

            vSampleTestInput.push_back(inpFeatureIndex);
            vSampleTestInputData.push_back(inpFeatureValue);
            vSampleTestInputTime.push_back(inpTime);
            vSampleTestOutput.push_back(outFeatureIndex);
            vSampleTestOutputData.push_back(outFeatureValue);
            vSampleTestOutputTime.push_back(outTime);
            break;
        case Classification:
            inpFeatureIndex.push_back(s % dataParameters.inpFeatureDimensionality); // one activation per sample
            inpTime.push_back(s);

            outFeatureIndex.push_back(s % dataParameters.outFeatureDimensionality); // one activation per sample
            outTime.push_back(s);

            vSampleTestInput.push_back(inpFeatureIndex);
            vSampleTestInputTime.push_back(inpTime);
            vSampleTestOutput.push_back(outFeatureIndex);
            vSampleTestOutputTime.push_back(outTime);
            break;
        case ClassificationAnalog:
            inpFeatureIndex.push_back(s % dataParameters.inpFeatureDimensionality); // one activation per sample
            inpFeatureValue.push_back((float) s);
            inpTime.push_back(s);

            for (int d = 0; d < dataParameters.outFeatureDimensionality; d++) {
                outFeatureIndex.push_back(d);
                outFeatureValue.push_back(((s + d) % 2) + 1);
                outTime.push_back(s);
            }
            vSampleTestInput.push_back(inpFeatureIndex);
            vSampleTestInputData.push_back(inpFeatureValue);
            vSampleTestInputTime.push_back(inpTime);

            vSampleTestOutput.push_back(outFeatureIndex);
            vSampleTestOutputData.push_back(outFeatureValue);
            vSampleTestOutputTime.push_back(outTime);

            break;
        default:
            out << "unsupported mode";
            exit(2);
        }
    }

    int minInpDate = std::numeric_limits<int>::max(), maxInpDate = std::numeric_limits<int>::min(),
                    minOutDate = std::numeric_limits<int>::max(), maxOutDate = std::numeric_limits<int>::min();
    const bool alignFeatureNumber = false;
    writeNETCDF(path + std::string("test.nc"), vSamplesName, mFeatureNameToIndex, vSampleTestInput, vSampleTestInputTime,
                    vSampleTestInputData, mFeatureNameToIndex, vSampleTestOutput, vSampleTestOutputTime,
                    vSampleTestOutputData, minInpDate, maxInpDate, minOutDate, maxOutDate, alignFeatureNumber, 2);
}

inline bool validateNeuralNetwork(const size_t batch, const std::string& modelPath, const TestDataType testDataType, const DataParameters& dataParameters, std::ostream& out) {
    out << "start validation of " << modelPath << std::endl;

    NNNetwork* pNetwork = NULL;
    std::vector<NNDataSetBase*> vDataSet;
    const std::string dataName = string("test.nc");
    const std::string dataPath(TEST_DATA_PATH);
    generateTestData(dataPath, testDataType, dataParameters, out);
    vDataSet = LoadNetCDF(dataPath + dataName);
    pNetwork = LoadNeuralNetworkJSON(modelPath, batch, vDataSet);
    pNetwork->LoadDataSets(vDataSet);
    pNetwork->SetCheckpoint("check", 1);
    pNetwork->SetTrainingMode(SGD);
    bool valid = pNetwork->Validate();
    if (valid) {
        out << "SUCCESFUL validation" << std::endl;
    } else {
        out << "FAILED validation" << std::endl;
    }

    int totalGPUMemory, totalCPUMemory;
    getGpu().GetMemoryUsage(&totalGPUMemory, &totalCPUMemory);
    out << "GPU Memory Usage: " << totalGPUMemory << " KB" << std::endl;
    out << "CPU Memory Usage: " << totalCPUMemory << " KB" << std::endl;

    delete pNetwork;

    // Delete datasets
    for (auto p : vDataSet) {
        delete p;
    }
    return valid;
}


text:
<?php

namespace InoOicClient\Client\Authenticator;

interface AuthenticatorInterface
{

    public function configureHttpRequest(\Zend\Http\Request $httpRequest);
}


text:
/**
* This class represents a card.
* A card has an immutable rank and suit
*/
function Card(rank, suit) {

        //PRIVATE FIELDS

        var isFaceUp = true;
        var view = null;
        var covered = [];
        var covering = [];

	//PUBLIC FUNCTIONS

	/**
	* suit getter method
	* returns String suit
	*/
	this.getSuit = function () {
		return suit;
	};

        /**
         * Returns "r" if the card is red (hearts or diamonds) and "s"
         * otherwise.
         */
        this.getColor = function () {
                return (suit == "h" || suit == "d") ? "r" : "s";
        };

        /**
        * Returns whether the card is face up or not.
        */
        this.isFaceUp = function () {
                return isFaceUp;
        };

        /**
        * Sets whether the card is face up--true means it is.
        */
        this.setFaceUp = function (flag) {
            isFaceUp = flag;
            if(view != null)
            {
                view.onFaceChange(isFaceUp);
            }
        };

	/**
	* rank getter method
	* returns int rank
	*/
	this.getRank = function () {
		return rank;
	};

	/**
	* rank getter method
	* returns String rank
	*/
	this.getRankAsString = function () {
		switch(rank) {
			case 11:
				return "J";
			case 12:
				return "Q";
			case 13:
				return "K";
			case 1:
				return "A";
			default:
				return rank+'';
		}
	};

    this.getRankAndSuitAsString = function() {
        return this.getRankAsString() + this.getSuit();
    }

    this.getView = function() {
        return view;
    };

    this.setView = function(v){
        view = v;
    };

    this.canPickUp = function(){
        return covered.length <= 0;
    };

    this.removeCardOnTop = function(card){
        var index = covered.indexOf(card);
        if(index !== -1)
        {
            covered.splice(index, 1);
            if(covered.length <= 0)
            {
                this.setFaceUp(true);
            }
        }
    };

    this.cover = function (anotherCard)
    {
        if(covering.indexOf(anotherCard) === -1)
        {
            covering.push(anotherCard);
            anotherCard.coveredBy(this);
        }
    }

    this.coveredBy = function(anotherCard)
    {
        if(covered.indexOf(anotherCard) === -1)
        {
            covered.push(anotherCard);
        }
    }

    this.pickUp = function(){
        if(this.canPickUp())
        {
            for (var i = 0; i < covering.length; i++) {
                covering[i].removeCardOnTop(this);
            };
            return true;
        }
        return false;
    };

    this.seeCovered = function(){
        return covered;
    };

    this.seeCovering = function(){
        return covering;
    };
}