text:
'use strict';

const argv = require('minimist')(process.argv.slice(2));
const del = require('del');
const fs = require('fs-extra');
const path = require('path');
const {cyan, yellow} = require('kleur/colors');
const {ignoreFile, splitIgnoreListByHeader} = require('./check-ignore-lists');
const {log} = require('../common/logging');

const ROOT_DIR = path.resolve(__dirname, '../../');

/**
 * Rewrite glob patterns according to .gitignore syntax relative to cwd.
 * https://git-scm.com/docs/gitignore#_pattern_format
 * @param {string} pattern In .gitignore format
 * @return {string} Pattern in standard glob format
 */
function gitignoreToGlobPattern(pattern) {
  // If there is a separator at the beginning or middle (or both) of the
  // pattern, then the pattern is relative to the directory level of the
  // particular .gitignore file itself.
  if (pattern.startsWith('/')) {
    return pattern.substr(1);
  }
  // Otherwise the pattern may also match at any level below the .gitignore level.
  return `**/${pattern}`;
}

/**
 * @return {Promise<string[]>}
 */
async function getPathsFromIgnoreList() {
  const [, below] = splitIgnoreListByHeader(
    await fs.readFile(ignoreFile, 'utf8')
  );
  return (
    below
      .split('\n')
      // Comments and empty lines
      .filter((line) => line.trim().length > 0 && !line.startsWith('#'))
      .map((line) => gitignoreToGlobPattern(line))
  );
}

/**
 * Cleans up various cache and output directories. Optionally cleans up inner
 * node_modules package directories, or excludes some directories from deletion.
 * @return {Promise<void>}
 */
async function clean() {
  const pathsFromIgnoreList = [
    ...(await getPathsFromIgnoreList()),
    '!**/third_party',
    '!**/node_modules',
  ];

  const pathsFromArgv = [];

  if (argv.include_subpackages) {
    pathsFromArgv.push('**/node_modules', '!node_modules');
  }

  // User configuration files
  // Keep this list in sync with .gitignore
  const customConfigs = [
    'build-system/global-configs/custom-config.json',
    'build-system/global-configs/custom-flavors-config.json',
  ];
  if (argv.include_custom_configs) {
    pathsFromArgv.push(...customConfigs);
  } else {
    for (const customConfig of customConfigs) {
      if (fs.existsSync(customConfig)) {
        log(yellow('Skipping path:'), cyan(customConfig));
      }
    }
  }

  const excludes =
    argv.exclude?.split(',').map((exclude) => `!${exclude}`) ?? [];

  const delOptions = {
    expandDirectories: false,
    dryRun: argv.dry_run,
  };
  const deletedPaths = [
    ...(await del([...pathsFromIgnoreList, ...excludes], delOptions)),
    ...(await del([...pathsFromArgv, ...excludes], delOptions)),
  ].sort();

  if (deletedPaths.length > 0) {
    log(argv.dry_run ? "Paths that would've been deleted:" : 'Deleted paths:');
    deletedPaths.forEach((deletedPath) => {
      log('\t' + cyan(path.relative(ROOT_DIR, deletedPath)));
    });
  }
}

module.exports = {
  clean,
};

clean.description = 'Clean up various cache and output directories';
clean.flags = {
  'dry_run': 'Do a dry run without actually deleting anything',
  'include_subpackages': 'Also clean up inner node_modules package directories',
  'include_custom_configs':
    'Also clean up custom config files from build-system/global-configs',
  'exclude': 'Comma-separated list of directories to exclude from deletion',
};


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

<title>GNU libgomp: OMP_DYNAMIC</title>

<meta name="description" content="GNU libgomp: OMP_DYNAMIC">
<meta name="keywords" content="GNU libgomp: OMP_DYNAMIC">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="Top">
<link href="Library-Index.html#Library-Index" rel="index" title="Library Index">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="Environment-Variables.html#Environment-Variables" rel="up" title="Environment Variables">
<link href="OMP_005fMAX_005fACTIVE_005fLEVELS.html#OMP_005fMAX_005fACTIVE_005fLEVELS" rel="next" title="OMP_MAX_ACTIVE_LEVELS">
<link href="OMP_005fDEFAULT_005fDEVICE.html#OMP_005fDEFAULT_005fDEVICE" rel="prev" title="OMP_DEFAULT_DEVICE">

Next: OMP_MAX_ACTIVE_LEVELS, Previous: OMP_DEFAULT_DEVICE, Up: Environment Variables   [Contents][Index]

3.4 OMP_DYNAMIC – Dynamic adjustment of threads

Description:

Enable or disable the dynamic adjustment of the number of threads
within a team.  The value of this environment variable shall be
TRUE or FALSE.  If undefined, dynamic adjustment is
disabled by default.

See also:

omp_set_dynamic

Reference:

OpenMP specification v4.0, Section 4.3

redpajama_set_name: RedPajamaGithub


text:
package nautical.chart.web.ui.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 * 各种数据转换器
 *
 * @author Cheng Feng 2013-11-20 16:03:30
 */
public class Transformer {
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

	public static long stringDate2Long(String stringDate) {
		try {
			return sdf.parse(stringDate).getTime();
		} catch (ParseException e) {
			return System.currentTimeMillis();
		}
	}
}


text:
06/18/2018
## Wellington Algorithm
Wellington algorithm is a novel method for the accurate identification of digital genomic footprints from DNase-seq data
proposed by [*Jason Piper etc. 2013*](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3834841/), which shares the same
charateristics with identifiction of insertion free region within open chromatins from ATAC-seq data. The
[`ATAC-seq_wellington.R`](../pipe_code/ATAC-seq_wellington.R) is an implemention of applying Wellington algorithm to peaks
from ATAC-seq data called by MACS2.

Using the same notations of the original paper, let  be
the length (in base pairs) of the possible IFR, and  be
the length (in base pairs) of the shoulder on each side of the possible IFR. We consider three insertion counts in these
regions: the total number of insetions inside the possible IFR
(), the insertion count in the upstream shoulder region on
the forward reference strand (), and the insertion count
in the downstream shoulder region on the backward reference strand
().

We will test the null hypothesis that the number of insertions is proportional to the region length by using a binomial
test. Considered the characteristics of our PEasSE peakcalling strategy, we will test the both strands together without losing
sensitivity but having higher proficiency. With  being
the binomial culmulative distribution function, i.e. the probability of achieving at least
 out of
 success with the probability of each success
, the *p*-value will be calculated by
, which is given
for a combination of possible  and
.

Then, *p*-values for all posisble combination of
different  and
 will be calculated independently and adjusted for
multiple testing by the user-specified method. We can identify IFR within the peaks by using an appropriate threshold for the
*p*-value and subsequently using a greedy selection strategy for IFR identification. The parameters
 and
 are individually determined for each IFR using maximum
likelihood estimation. The combination of  and
, which leads to the smallest *p*-value as well as smaller
than the given threshold, will be condsidered as the true possible IFR.

For a given peak, we first identified the most significant IFR within the whole peak. If there is an IFR, we then remove the
identified IFR from the peak and search any other possible IFR within the rest part of the peak, until no IFR can be identified.

## Parameters Description
We have incorporated the IFR identication into our ATAC-seq pipeline, and user can simply add `-i` in the bash command to
enable IFR identification with default parameters. User can also specify their own parameters by using
`-i <min_lfp,max_lfp,step_lfp,min_lsh,max_lsh,step_lsh,method,p_cutoff>`. **These parameters are positional!!!**

(1) `min_lfp`: the minimum value of  (default `5`).
(2) `max_lfp`: the maximum value of  (default `15`).
(3) `step_lfp`: the increasing searching step of  from minimum
to maximum (default `2`).
(4) `min_lsh`: the minimum value of  (default `50`).
(5) `max_lsh`: the maximum value of  (default `200`).
(6) `step_lsh`: the increasing searching step of  from minimum
to maximum (default `20`).
(7) `method`: the method used for multiple testing adjustment (default `BH`). Possible values include `BH`, `BY`, `fdr`, `holm`,
`bonferroni`, `hochberg` and `hommel`.
(8) `p_cutoff`: the threshold of *p*-value (default `0.05`).

## Parallel Processing
Parallel processing is enabled by [GNU](https://www.gnu.org/software/parallel/parallel_tutorial.html), and shared the same
number of thread in the whole pipeline process.


text:
<ivy-module
    version="2.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="http://ant.apache.org/ivy/schemas/ivy.xsd">
  <info organisation="com.ztools" module="z-rmiclient" revision="1.0">
    <ivyauthor name="Bliss Chung" url="mailto:bliss@3zso.com" />
    <description>
    </description>
  </info>
  <publications>
    <artifact name="${ivy.module}" type="jar" ext="jar" />
    <artifact name="${ivy.module}" type="source" ext="jar" />
  </publications>

  <dependencies defaultconf="*->default">
    <dependency org="org.hamcrest" name="hamcrest-all" rev="1.3" />
    <dependency org="junit" name="junit" rev="4.8.2" transitive="false" />

    <!-- put your dependencies -->
    <dependency org="com.ztools" name="ztools" rev="1.19"/>

    <!-- globe exclude -->
    <exclude org="*" ext="*" type="source" />
    <exclude org="*" ext="*" type="javadoc" />
  </dependencies>
</ivy-module>


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using GalaSoft.MvvmLight.Command;
using GongSolutions.Wpf.DragDrop;
using Meridian.Controls;
using Meridian.Model;
using Meridian.Resources.Localization;
using Meridian.Services;
using Meridian.View.Flyouts;
using Meridian.ViewModel.Messages;
using Neptune.Extensions;
using VkLib.Core.Audio;

namespace Meridian.ViewModel.Main
{
    public class MusicViewModel : ViewModelBase, IDropTarget
    {
        private const int MAX_WALL_AUDIOS = 300;
        private const int MAX_NEWS_AUDIOS = 300;

        private ObservableCollection<VkPlaylist> _albums;
        private ObservableCollection<Audio> _tracks;
        private ObservableCollection<AudioArtist> _artists;
        private ObservableCollection<Audio> _newsTracks;
        private ObservableCollection<Audio> _wallTracks;
        private ObservableCollection<Audio> _favoritesTracks;
        private VkPlaylist _selectedAlbum;
        private CancellationTokenSource _cancellationToken;
        private int _totalAlbumsCount;
        private int _selectedTabIndex;
        private AudioArtist _selectedArtist;

        #region Commands

        /// <summary>
        /// Команда воспроизведения аудиозаписи
        /// </summary>
        public RelayCommand<Audio> PlayAudioCommand { get; private set; }

        /// <summary>
        /// Команда дозагрузки альбомов
        /// </summary>
        public RelayCommand LoadMoreAlbumsCommand { get; private set; }

        /// <summary>
        /// Команда добавления нового альбома
        /// </summary>
        public RelayCommand AddAlbumCommand { get; private set; }

        /// <summary>
        /// Команда редактирования альбома
        /// </summary>
        public RelayCommand<VkPlaylist> EditAlbumCommand { get; private set; }

        /// <summary>
        /// Команда удаления альбома
        /// </summary>
        public RelayCommand<VkAudioAlbum> RemoveAlbumCommand { get; private set; }

        /// <summary>
        /// Команда обновления списка аудиозаписей
        /// </summary>
        public RelayCommand RefreshCommand { get; private set; }

        /// <summary>
        /// Команда воспроизведения альбома
        /// </summary>
        public RelayCommand<VkAudioAlbum> PlayAlbumCommand { get; private set; }

        /// <summary>
        /// Команда добавления альбома в NowPlaying
        /// </summary>
        public RelayCommand<VkAudioAlbum> AddAlbumToNowPlayingCommand { get; private set; }

        /// <summary>
        /// Команда воспроизведения исполнителя
        /// </summary>
        public RelayCommand<AudioArtist> PlayArtistCommand { get; private set; }

        /// <summary>
        /// Команда добавления исполнителя в NowPlaying
        /// </summary>
        public RelayCommand<AudioArtist> AddArtistToNowPlayingCommand { get; private set; }

        #endregion

        /// <summary>
        /// Albums list
        /// </summary>
        public ObservableCollection<VkPlaylist> Albums
        {
            get { return _albums; }
            set { Set(ref _albums, value); }
        }

        /// <summary>
        /// Tracks list
        /// </summary>
        public ObservableCollection<Audio> Tracks
        {
            get { return _tracks; }
            set { Set(ref _tracks, value); }
        }

        /// <summary>
        /// Artists list
        /// </summary>
        public ObservableCollection<AudioArtist> Artists
        {
            get { return _artists; }
            set { Set(ref _artists, value); }
        }

        /// <summary>
        /// Selected album
        /// </summary>
        public VkPlaylist SelectedAlbum
        {
            get { return _selectedAlbum; }
            set
            {
                if (Set(ref _selectedAlbum, value))
                {
                    CancelAsync();

                    if (value != null)
                    {
                        switch ((int)value.Id)
                        {
                            case -100:
                                LoadNewsAudios(_cancellationToken.Token);
                                break;
                            case -101:
                                LoadWallAudios(_cancellationToken.Token);
                                break;
                            case -102:
                                LoadFavoritesAudios(_cancellationToken.Token);
                                break;
                            default:
                                LoadTracks(_cancellationToken.Token);
                                break;
                        }
                    }
                }
            }
        }

        public int SelectedTabIndex
        {
            get { return _selectedTabIndex; }
            set
            {
                if (Set(ref _selectedTabIndex, value))
                {
                    CancelAsync();

                    switch (_selectedTabIndex)
                    {
                        case 2:
                            LoadNewsAudios(_cancellationToken.Token);
                            break;

                        case 3:
                            LoadWallAudios(_cancellationToken.Token);
                            break;

                        case 4:
                            LoadFavoritesAudios(_cancellationToken.Token);
                            break;
                    }
                }
            }
        }

        public AudioArtist SelectedArtist
        {
            get { return _selectedArtist; }
            set { Set(ref _selectedArtist, value); }
        }

        public ObservableCollection<Audio> NewsTracks
        {
            get { return _newsTracks; }
            set { Set(ref _newsTracks, value); }
        }

        public ObservableCollection<Audio> WallTracks
        {
            get { return _wallTracks; }
            set { Set(ref _wallTracks, value); }
        }

        public ObservableCollection<Audio> FavoritesTracks
        {
            get { return _favoritesTracks; }
            set { Set(ref _favoritesTracks, value); }
        }

        public MusicViewModel()
        {
            _cancellationToken = new CancellationTokenSource();

            InitializeCommands();
            InitializeMessageInterception();

            RegisterTasks("audio", "albums", "news", "wall", "favorites");
        }

        public override async void Activate()
        {
            if (Albums.IsNullOrEmpty())
                await LoadAlbums();

            if (Artists.IsNullOrEmpty())
                await LoadArtists(_cancellationToken.Token);
        }

        public override void Deactivate()
        {
            CancelAsync();

            MessengerInstance.Unregister<UserTracksChangedMessage>(this, OnUserTracksChanged);
        }

        private void InitializeCommands()
        {
            PlayAudioCommand = new RelayCommand<Audio>(audio =>
            {
                AudioService.Play(audio);

                switch (SelectedTabIndex)
                {
                    case 0:
                        var searchControl = LocalSearchControl.GetForCurrentView();
                        if (searchControl != null && searchControl.IsFiltering)
                        {
                            AudioService.SetCurrentPlaylist((searchControl.Source.View).Cast<Audio>());
                        }
                        else
                            AudioService.SetCurrentPlaylist(Tracks);
                        break;

                    case 1:
                        if (SelectedArtist != null)
                            AudioService.SetCurrentPlaylist(SelectedArtist.Tracks);
                        break;

                    case 2:
                        AudioService.SetCurrentPlaylist(NewsTracks);
                        break;

                    case 3:
                        AudioService.SetCurrentPlaylist(WallTracks);
                        break;

                    case 4:
                        AudioService.SetCurrentPlaylist(FavoritesTracks);
                        break;
                }
            });

            LoadMoreAlbumsCommand = new RelayCommand(() => LoadMoreAlbums());

            RefreshCommand = new RelayCommand(() =>
            {
                CancelAsync();
                LoadTracks(_cancellationToken.Token);
                LoadArtists(_cancellationToken.Token);
            });

            AddAlbumCommand = new RelayCommand(AddNewAlbum);

            EditAlbumCommand = new RelayCommand<VkPlaylist>(EditAlbum);

            RemoveAlbumCommand = new RelayCommand<VkAudioAlbum>(RemoveAlbum);

            PlayAlbumCommand = new RelayCommand<VkAudioAlbum>(PlayAlbum);

            AddAlbumToNowPlayingCommand = new RelayCommand<VkAudioAlbum>(AddAlbumToNowPlaying);

            PlayArtistCommand = new RelayCommand<AudioArtist>(artist =>
            {
                AudioService.Play(artist.Tracks.First());
                AudioService.SetCurrentPlaylist(artist.Tracks);
            });

            AddArtistToNowPlayingCommand = new RelayCommand<AudioArtist>(artist =>
            {
                foreach (var track in artist.Tracks)
                {
                    AudioService.Playlist.Add(track);
                }
            });
        }

        private void InitializeMessageInterception()
        {
            MessengerInstance.Register<UserTracksChangedMessage>(this, OnUserTracksChanged);
        }

        private async void OnUserTracksChanged(UserTracksChangedMessage message)
        {
            if (SelectedAlbum.Id == -1)
            {
                CancelAsync();
                await LoadTracks(_cancellationToken.Token);
            }
        }

        private async Task LoadAlbums()
        {
            IsWorking = true;
            OnTaskStarted("albums");

            try
            {
                var response = await DataService.GetUserAlbums(count: 100);

                var albums = response.Items;

                _totalAlbumsCount = response.TotalCount;

                if (albums == null)
                    albums = new List<VkPlaylist>();

                albums.Insert(0, new VkPlaylist() { Id = -1, Title = MainResources.MyMusicAllTracks });
                //albums.Insert(1, new VkAudioAlbum() { Id = -100, Title = MainResources.MyMusicNews });
                //albums.Insert(2, new VkAudioAlbum() { Id = -101, Title = MainResources.MyMusicWall });
                //albums.Insert(3, new VkAudioAlbum() { Id = -102, Title = MainResources.MyMusicFavorites });
                //albums.Insert(4, new VkAudioAlbum() { Id = int.MinValue }); //separator

                Albums = new ObservableCollection<VkPlaylist>(albums);

                SelectedAlbum = albums.First();
            }
            catch (Exception ex)
            {
                LoggingService.Log(ex);

                OnTaskError("albums", ErrorResources.LoadAlbumsErrorCommon);
            }

            IsWorking = false;
            OnTaskFinished("albums");
        }

        private async Task LoadMoreAlbums()
        {
            if (Albums == null || Albums.Count - 5 >= _totalAlbumsCount)
                return;

            IsWorking = true;

            try
            {
                var response = await DataService.GetUserAlbums(0, Albums.Count - 5);

                if (response.Items != null)
                {
                    foreach (var album in response.Items)
                    {
                        Albums.Add(album);
                    }
                }
            }
            catch (Exception ex)
            {
                LoggingService.Log(ex);
            }

            IsWorking = false;
        }

        private async Task LoadTracks(CancellationToken token)
        {
            if (SelectedAlbum == null)
                return;

            IsWorking = true;
            OnTaskStarted("audio");

            try
            {
                var response = await DataService.GetUserTracks(0, 0, SelectedAlbum.Id != 0 ? SelectedAlbum.Id : 0);
                if (response.Items != null && response.Items.Count > 0)
                {
                    if (token.IsCancellationRequested)
                    {
                        Debug.WriteLine("Tracks load cancelled");
                        return;
                    }

                    Tracks = new ObservableCollection<Audio>(response.Items);

                    if (AudioService.CurrentAudio == null)
                    {
                        AudioService.SetCurrentPlaylist(Tracks.ToList());
                        AudioService.CurrentAudio = Tracks.First();
                        AudioService.CurrentAudio.IsPlaying = true;
                    }
                }
                else
                {
                    OnTaskError("audio", ErrorResources.LoadAudiosErrorEmpty);
                    Tracks = null;
                }
            }
            catch (Exception ex)
            {
                LoggingService.Log(ex);

                OnTaskError("audio", ErrorResources.LoadAudiosErrorCommon);
            }

            IsWorking = false;
            OnTaskFinished("audio");
        }

        private async void LoadNewsAudios(CancellationToken token)
        {
            IsWorking = true;
            OnTaskStarted("news");

            NewsTracks = new ObservableCollection<Audio>();

            try
            {
                var nextFrom = string.Empty;
                int count = 150;
                int requestsCount = 0;

                while (NewsTracks != null && NewsTracks.Count < MAX_NEWS_AUDIOS)
                {
                    if (token.IsCancellationRequested)
                    {
                        Debug.WriteLine("News audio cancelled");
                        break;
                    }

                    var a = await DataService.GetNewsAudio(count, nextFrom, token);
                    if (a.Items.IsNullOrEmpty())
                        break;
                    else if (a.Items.Count > 0)
                    {
                        OnTaskFinished("news");
                    }

                    if (token.IsCancellationRequested)
                    {
                        Debug.WriteLine("News audio cancelled");
                        break;
                    }

                    nextFrom = a.NextFrom;

                    foreach (var audio in a.Items)
                    {
                        NewsTracks.Add(audio);
                    }

                    requestsCount++;

                    if (requestsCount >= 2) //не больше 2-х запросов в секунду
                    {
                        requestsCount = 0;
                        await Task.Delay(1000);
                    }

                    Debug.WriteLine("Loading more audios from news");
                }

                if (NewsTracks.IsNullOrEmpty() && !token.IsCancellationRequested)
                    OnTaskError("news", ErrorResources.LoadAudiosErrorEmpty);
            }
            catch (Exception ex)
            {
                LoggingService.Log(ex);
                OnTaskError("news", ErrorResources.LoadAudiosErrorCommon);
            }

            IsWorking = false;
            OnTaskFinished("news");
        }

        private async void LoadWallAudios(CancellationToken token)
        {
            IsWorking = true;
            OnTaskStarted("wall");

            WallTracks = new ObservableCollection<Audio>();

            try
            {
                int offset = 0;
                int count = 50;
                int requestsCount = 0;

                while (WallTracks != null && WallTracks.Count < MAX_WALL_AUDIOS)
                {
                    var a = await DataService.GetWallAudio(count, offset, 0, token);
                    if (a == null || a.Count == 0)
                        break;
                    else if (a.Count > 0)
                    {
                        OnTaskFinished("wall");
                    }

                    if (token.IsCancellationRequested)
                    {
                        Debug.WriteLine("Wall audios cancelled");
                        break;
                    }

                    offset += count;

                    foreach (var audio in a)
                    {
                        WallTracks.Add(audio);
                    }

                    requestsCount++;

                    if (requestsCount >= 2) //не больше 2-х запросов в секунду
                    {
                        requestsCount = 0;
                        await Task.Delay(1000);
                    }

                    Debug.WriteLine("Loading more audios from wall");
                }

                if (WallTracks.IsNullOrEmpty() && !token.IsCancellationRequested)
                    OnTaskError("wall", ErrorResources.LoadAudiosErrorEmpty);
            }
            catch (Exception ex)
            {
                OnTaskError("wall", ErrorResources.LoadAudiosErrorCommon);

                LoggingService.Log(ex);
            }

            IsWorking = false;
            OnTaskFinished("wall");
        }

        private async void LoadFavoritesAudios(CancellationToken token)
        {
            IsWorking = true;
            OnTaskStarted("favorites");

            FavoritesTracks = new ObservableCollection<Audio>();

            try
            {
                int offset = 0;
                int count = 50;
                int requestsCount = 0;

                while (FavoritesTracks != null && FavoritesTracks.Count < MAX_WALL_AUDIOS)
                {
                    var a = await DataService.GetFavoritesAudio(count, offset, 0, token);
                    if (a == null || a.Count == 0)
                        break;
                    else if (a.Count > 0)
                    {
                        OnTaskFinished("favorites");
                    }

                    if (token.IsCancellationRequested)
                    {
                        Debug.WriteLine("Favorites audios cancelled");
                        break;
                    }

                    offset += count;

                    foreach (var audio in a)
                    {
                        FavoritesTracks.Add(audio);
                    }

                    requestsCount++;

                    if (requestsCount >= 2) //не больше 2-х запросов в секунду
                    {
                        requestsCount = 0;
                        await Task.Delay(1000);
                    }

                    Debug.WriteLine("Loading more audios from favorites");
                }

                if (FavoritesTracks.IsNullOrEmpty() && !token.IsCancellationRequested)
                    OnTaskError("favorites", ErrorResources.LoadAudiosErrorEmpty);
            }
            catch (Exception ex)
            {
                LoggingService.Log(ex);

                OnTaskError("favorites", ErrorResources.LoadAudiosErrorCommon);
            }

            IsWorking = false;
            OnTaskFinished("favorites");
        }

        private async Task LoadArtists(CancellationToken token)
        {
            try
            {
                var audio = await DataService.GetUserTracks();

                if (audio.Items == null || token.IsCancellationRequested)
                {
                    return;
                }

                var tracks = audio.Items;

                var artists = await DataService.GetArtistsFromTracks(tracks, token);
                if (artists != null)
                {
                    Artists = new ObservableCollection<AudioArtist>(artists);

                    SelectedArtist = Artists.FirstOrDefault();
                }
            }
            catch (Exception ex)
            {
                LoggingService.Log(ex);
            }
        }

        private void CancelAsync()
        {
            if (_cancellationToken != null)
                _cancellationToken.Cancel();

            _cancellationToken = new CancellationTokenSource();
        }

        private async void AddNewAlbum()
        {
            var album = new VkPlaylist() { Title = "New album" };

            var flyout = new FlyoutControl();
            flyout.FlyoutContent = new EditAlbumView(album);
            var result = await flyout.ShowAsync();
            if ((bool)result)
            {
                try
                {
                    var newAlbumId = await ViewModelLocator.Vkontakte.Audio.AddAlbum(album.Title);
                    if (newAlbumId != 0)
                    {
                        album.Id = newAlbumId;
                        album.OwnerId = ViewModelLocator.Vkontakte.AccessToken.UserId;
                        Albums.Insert(5, album);
                    }
                }
                catch (Exception ex)
                {
                    LoggingService.Log(ex);
                }
            }
        }

        private async void EditAlbum(VkPlaylist album)
        {
            var flyout = new FlyoutControl();
            flyout.FlyoutContent = new EditAlbumView(album);

            var result = await flyout.ShowAsync();
            if (result != null && (bool)result)
            {
                try
                {
                    if (await ViewModelLocator.Vkontakte.Audio.EditAlbum(album.Id.ToString(), album.Title))
                    {
                        Albums[Albums.IndexOf(album)].Title = album.Title;
                    }
                }
                catch (Exception ex)
                {
                    LoggingService.Log(ex);
                }
            }
        }

        private async void RemoveAlbum(VkAudioAlbum album)
        {
            try
            {
                var result = await ViewModelLocator.Vkontakte.Audio.DeleteAlbum(album.Id);
                if (result)
                {
                    Albums.Remove(Albums.FirstOrDefault(a => a.Id == album.Id));

                    SelectedAlbum = Albums.FirstOrDefault();
                }
            }
            catch (Exception ex)
            {
                LoggingService.Log(ex);
            }
        }

        private async void PlayAlbum(VkAudioAlbum album)
        {
            try
            {
                var audio = await DataService.GetUserTracks(albumId: album.Id, ownerId: album.OwnerId);
                if (audio.Items != null && audio.Items.Count > 0)
                {
                    AudioService.Play(audio.Items.First());
                    AudioService.SetCurrentPlaylist(audio.Items);
                }
            }
            catch (Exception ex)
            {
                LoggingService.Log(ex);
            }
        }

        private async void AddAlbumToNowPlaying(VkAudioAlbum album)
        {
            try
            {
                var audio = await DataService.GetUserTracks(albumId: album.Id, ownerId: album.OwnerId);
                if (audio.Items != null && audio.Items.Count > 0)
                {
                    foreach (var track in audio.Items)
                    {
                        AudioService.Playlist.Add(track);
                    }
                }
            }
            catch (Exception ex)
            {
                LoggingService.Log(ex);
            }
        }

        #region Drag&Drop

        public void DragOver(IDropInfo dropInfo)
        {
            if (dropInfo.Data is Audio && !ViewModelLocator.Main.ShowShareBar)
            {
                if (dropInfo.TargetCollection == Tracks)
                {
                    dropInfo.Effects = DragDropEffects.Move;
                    dropInfo.DropTargetAdorner = DropTargetAdorners.Insert;
                }
                else if (dropInfo.TargetCollection is ListCollectionView)
                {
                    var c = (ListCollectionView)dropInfo.TargetCollection;
                    if (c.SourceCollection == Tracks && c.IsLiveFiltering == false)
                    {
                        dropInfo.Effects = DragDropEffects.Move;
                        dropInfo.DropTargetAdorner = DropTargetAdorners.Insert;
                    }
                }
                else if (dropInfo.TargetCollection == Albums && (dropInfo.TargetItem is VkAudioAlbum && ((VkAudioAlbum)dropInfo.TargetItem).Id >= -1))
                {
                    dropInfo.Effects = DragDropEffects.Move;
                    dropInfo.DropTargetAdorner = DropTargetAdorners.Highlight;
                }
            }
        }

        public async void Drop(IDropInfo dropInfo)
        {
            if (dropInfo.Data is Audio)
            {
                var source = (Audio)dropInfo.Data;
                IEnumerable targetCollection = dropInfo.TargetCollection;
                IEnumerable sourceCollection = dropInfo.DragInfo.SourceCollection;

                if (targetCollection is ListCollectionView)
                {
                    var c = (ListCollectionView)targetCollection;
                    targetCollection = c.SourceCollection;
                }

                if (sourceCollection is ListCollectionView)
                {
                    var c = (ListCollectionView)sourceCollection;
                    sourceCollection = c.SourceCollection;
                }

                if (targetCollection == Tracks)
                {
                    var target = (Audio)dropInfo.TargetItem;
                    if (source == target)
                        return;
                    string afterAid, beforeAid;

                    int index = Tracks.IndexOf(target);
                    if (index > 0)
                    {
                        //проверяем куда вставлять: после taget или перед
                        if (Tracks[index - 1] == source)
                        {
                            afterAid = target.Id;
                            beforeAid = index == Tracks.Count - 1 ? "0" : Tracks[index + 1].Id;
                        }
                        else
                        {
                            afterAid = Tracks[index - 1].Id;
                            beforeAid = target.Id;
                        }
                    }
                    else if (index == 0)
                    {
                        afterAid = "0";
                        beforeAid = target.Id;
                    }
                    else
                        return;

                    if (await ViewModelLocator.Vkontakte.Audio.Reorder(long.Parse(source.Id), long.Parse(afterAid), long.Parse(beforeAid)))
                    {
                        ((IList)sourceCollection).Remove(source);
                        ((IList)targetCollection).Insert(index, source);
                    }
                    else
                    {
                        LoggingService.Log("Unable to reorder tracks.");
                    }
                }
                else
                {
                    var target = (VkAudioAlbum)dropInfo.TargetItem;
                    long targetId = target.Id;
                    //перемещаем в альбом
                    try
                    {
                        if (targetId < 0)
                            targetId = 0;

                        if (await ViewModelLocator.Vkontakte.Audio.MoveToAlbum(targetId,
                            new List<long>() { long.Parse(source.Id) }))
                        {
                            if (SelectedAlbum.Id > 0)
                                ((ListCollectionView)dropInfo.DragInfo.SourceCollection).Remove(source);
                        }
                        else
                        {
                            LoggingService.Log("Unable to move track to album.");
                        }
                    }
                    catch (Exception ex)
                    {
                        LoggingService.Log(ex);
                    }

                }
            }
        }

        #endregion
    }
}


text:
import java.util.regex._

import scala.reflect.internal.SymbolTable
import scala.reflect.macros.blackbox._
import language.experimental.macros

object Macro {
  /**
    * Equivalent to Pattern.compile(pat).matcher(text), but caches the compiled regex (using invokedynamic) if
    * `pat` is a literal.
    */
  def matcher(pat: String, text: CharSequence): Matcher = macro Macro.impl
  def impl(c: Context)(pat: c.Tree, text: c.Tree): c.Tree = {
    def Indy(bootstrapMethod: c.Symbol, bootstrapArgs: List[c.universe.Literal], dynArgs: List[c.Tree]): c.Tree = {
      val symtab = c.universe.asInstanceOf[SymbolTable]
      import symtab._
      val paramSym = NoSymbol.newTermSymbol(TermName("x")).setInfo(typeOf[CharSequence])
      val dummySymbol = NoSymbol.newTermSymbol(TermName("matcher")).setInfo(internal.methodType(paramSym :: Nil, typeOf[java.util.regex.Matcher]))
      val bootstrapArgTrees: List[Tree] = Literal(Constant(bootstrapMethod)).setType(NoType) :: bootstrapArgs.asInstanceOf[List[Tree]]
      val result = ApplyDynamic(Ident(dummySymbol).setType(dummySymbol.info), bootstrapArgTrees ::: dynArgs.asInstanceOf[List[Tree]])
      result.setType(dummySymbol.info.resultType)
      result.asInstanceOf[c.Tree]
    }
    import c.universe._
    pat match {
      case l @ Literal(Constant(pat: String)) =>
        val bootstrapSym = typeOf[test.Bootstrap].companion.member(TermName("bootstrap"))
        Indy(bootstrapSym, l :: Nil, text :: Nil)
      case _ =>
        q"_root_.java.util.regex.Pattern.compile($pat).matcher($text)"
    }
  }
}


text:
package tools

// The ring monitor will constantly scan the on-disk rings to detect when they
// change or need to be rebalanced. It will queue replication jobs when it
// detects changes by comparing the new and old rings. It will also trigger a
// fast-scan for the ring scan process to send out new rings.
//
// In /etc/hummingbird/andrewd-server.conf:
// [ring-monitor]
// initial_delay = 1      # seconds to wait between ring checks for the first pass
// pass_time_target = 60  # seconds to try to make subsequent passes take
// report_interval = 600  # seconds between progress reports

import (
	"fmt"
	"math/rand"
	"sync"
	"sync/atomic"
	"time"

	"github.com/troubling/hummingbird/common/ring"
	"github.com/uber-go/tally"
	"go.uber.org/zap"
)

type ringMonitor struct {
	aa *AutoAdmin
	// delay between each ring check; adjusted each pass to try to make passes last passTimeTarget
	delay                        time.Duration
	passTimeTarget               time.Duration
	reportInterval               time.Duration
	prefix                       string
	suffix                       string
	ringMD5CacheLock             sync.Mutex
	ringMD5Cache                 map[string]map[int]ring.RingMD5
	passesMetric                 tally.Timer
	checksMetric                 tally.Counter
	errorsMetric                 tally.Counter
	partitionCopiesChangedMetric tally.Counter
}

func newRingMonitor(aa *AutoAdmin) *ringMonitor {
	rm := &ringMonitor{
		aa:                           aa,
		delay:                        time.Duration(aa.serverconf.GetInt("ring-monitor", "initial_delay", 1)) * time.Second,
		passTimeTarget:               time.Duration(aa.serverconf.GetInt("ring-monitor", "pass_time_target", 60)) * time.Second,
		reportInterval:               time.Duration(aa.serverconf.GetInt("ring-monitor", "report_interval", 600)) * time.Second,
		ringMD5Cache:                 map[string]map[int]ring.RingMD5{},
		passesMetric:                 aa.metricsScope.Timer("ring_mon_passes"),
		checksMetric:                 aa.metricsScope.Counter("ring_mon_checks"),
		errorsMetric:                 aa.metricsScope.Counter("ring_mon_errors"),
		partitionCopiesChangedMetric: aa.metricsScope.Counter("ring_mon_changes"),
	}
	if rm.delay < 0 {
		rm.delay = time.Second
	}
	if rm.passTimeTarget < 0 {
		rm.passTimeTarget = time.Second
	}
	if rm.reportInterval < 0 {
		rm.reportInterval = time.Second
	}
	rm.prefix, rm.suffix = getAffixes()
	rm.ringMD5Cache["account"] = map[int]ring.RingMD5{}
	rm.ringMD5Cache["container"] = map[int]ring.RingMD5{}
	rm.ringMD5Cache["object"] = map[int]ring.RingMD5{}
	return rm
}

func (rm *ringMonitor) runForever() {
	for {
		sleepFor := rm.runOnce()
		if sleepFor < 0 {
			break
		}
		time.Sleep(sleepFor)
	}
}

type ringTaskInstance struct {
	typ           string
	policy        int
	ring          ring.RingMD5
	previousMD5   string
	nextRebalance time.Time
}

func (rm *ringMonitor) runOnce() time.Duration {
	defer rm.passesMetric.Start().Stop()
	start := time.Now()
	logger := rm.aa.logger.With(zap.String("process", "ring monitor"))
	logger.Debug("starting pass")
	if err := rm.aa.db.startProcessPass("ring monitor", "", 0); err != nil {
		logger.Error("startProcessPass", zap.Error(err))
	}
	var delays int64
	var errors int64
	var partitionCopiesChanged int64
	var ringTasks []*ringTaskInstance
	ryng, err := rm.GetRingMD5("account", 0)
	if err != nil {
		errors++
		rm.errorsMetric.Inc(1)
		logger.Error("could not load ring", zap.String("type", "account"), zap.Int("policy", 0), zap.Error(err))
	} else {
		ringTasks = append(ringTasks, &ringTaskInstance{
			typ:  "account",
			ring: ryng,
		})
	}
	ryng, err = rm.GetRingMD5("container", 0)
	if err != nil {
		errors++
		rm.errorsMetric.Inc(1)
		logger.Error("could not load ring", zap.String("type", "container"), zap.Int("policy", 0), zap.Error(err))
	} else {
		ringTasks = append(ringTasks, &ringTaskInstance{
			typ:  "container",
			ring: ryng,
		})
	}
	for _, policy := range rm.aa.policies {
		if !policy.Deprecated {
			ryng, err = rm.GetRingMD5("object", policy.Index)
			if err != nil {
				errors++
				rm.errorsMetric.Inc(1)
				logger.Error("could not load ring", zap.String("type", "object"), zap.Int("policy", policy.Index), zap.Error(err))
				continue
			}
			ringTasks = append(ringTasks, &ringTaskInstance{
				typ:    "object",
				policy: policy.Index,
				ring:   ryng,
			})
		}
	}
	cancel := make(chan struct{})
	progressDone := make(chan struct{})
	go func() {
		for {
			select {
			case <-cancel:
				close(progressDone)
				return
			case <-time.After(rm.reportInterval):
				d := atomic.LoadInt64(&delays)
				e := atomic.LoadInt64(&errors)
				p := atomic.LoadInt64(&partitionCopiesChanged)
				var eta time.Duration
				if d > 0 {
					eta = time.Duration(int64(time.Since(start)) / d * (int64(len(ringTasks)) - d))
				}
				logger.Debug("progress", zap.Int64("rings so far", d), zap.Int("total rings", len(ringTasks)), zap.Int64("errors", e), zap.Int64("partition copies changed", p), zap.String("eta", eta.String()))
				if err := rm.aa.db.progressProcessPass("ring monitor", "", 0, fmt.Sprintf("%d of %d rings, %d errors, %d partition copies changed, eta %s", d, len(ringTasks), e, p, eta)); err != nil {
					logger.Error("progressProcessPass", zap.Error(err))
				}
			}
		}
	}()
	for _, ringTask := range ringTasks {
		atomic.AddInt64(&delays, 1)
		rm.checksMetric.Inc(1)
		time.Sleep(rm.delay)
		taskLogger := logger.With(zap.String("type", ringTask.typ), zap.Int("policy", ringTask.policy))
		if ringTask.previousMD5 == "" {
			ringTask.previousMD5, ringTask.nextRebalance, err = rm.aa.db.ringHash(ringTask.typ, ringTask.policy)
			if err != nil {
				atomic.AddInt64(&errors, 1)
				rm.errorsMetric.Inc(1)
				taskLogger.Error("couldn't retreive previous hash", zap.Error(err))
				continue
			}
		}
		if ringTask.ring.MD5() == ringTask.previousMD5 && !ringTask.nextRebalance.IsZero() && time.Now().After(ringTask.nextRebalance) {
			if !rm.rebalance(taskLogger, ringTask) {
				atomic.AddInt64(&errors, 1)
				rm.errorsMetric.Inc(1)
				continue
			}
		}
		if ringTask.ring.MD5() == ringTask.previousMD5 {
			continue
		}
		rm.aa.fastRingScan <- struct{}{}
		if ringTask.previousMD5 == "" {
			// First time seeing this ring
			rm.aa.db.setRingHash(ringTask.typ, ringTask.policy, ringTask.ring.MD5(), time.Now().Add(randomDuration(time.Minute*30, time.Hour)))
			continue
		}
		changeTaskLogger := taskLogger.With(zap.String("previous md5", ringTask.previousMD5), zap.String("current md5", ringTask.ring.MD5()))
		changeTaskLogger.Debug("ring md5 changed")
		previousRing := ringTask.ring.RingMatching(ringTask.previousMD5)
		if previousRing == nil {
			atomic.AddInt64(&errors, 1)
			rm.errorsMetric.Inc(1)
			changeTaskLogger.Error("can't find previous ring; assuming nothing changed")
			rm.aa.db.setRingHash(ringTask.typ, ringTask.policy, ringTask.ring.MD5(), time.Now().Add(randomDuration(time.Minute*30, time.Hour)))
			continue
		}
		partitionCount := previousRing.PartitionCount()
		if partitionCount != ringTask.ring.PartitionCount() {
			atomic.AddInt64(&errors, 1)
			rm.errorsMetric.Inc(1)
			changeTaskLogger.Error(
				"cannot handle changing partition counts; assuming new ring as if no previous ring ever existed",
				zap.Uint64("previous partition count", previousRing.PartitionCount()),
				zap.Uint64("current partition count", ringTask.ring.PartitionCount()),
			)
			rm.aa.db.setRingHash(ringTask.typ, ringTask.policy, ringTask.ring.MD5(), time.Now().Add(randomDuration(time.Minute*30, time.Hour)))
			continue
		}
		replicaCount := previousRing.ReplicaCount()
		if replicaCount != ringTask.ring.ReplicaCount() {
			atomic.AddInt64(&errors, 1)
			rm.errorsMetric.Inc(1)
			changeTaskLogger.Error(
				"cannot handle changing replica counts; assuming new ring as if no previous ring ever existed",
				zap.Uint64("previous replica count", previousRing.ReplicaCount()),
				zap.Uint64("current replica count", ringTask.ring.ReplicaCount()),
			)
			rm.aa.db.setRingHash(ringTask.typ, ringTask.policy, ringTask.ring.MD5(), time.Now().Add(randomDuration(time.Minute*30, time.Hour)))
			continue
		}
		failed := false
		for partition := uint64(0); partition < partitionCount && !failed; partition++ {
			previousDev := previousRing.GetNodes(partition)
			currentDev := ringTask.ring.GetNodes(partition)
			for replica := uint64(0); replica < replicaCount; replica++ {
				if previousDev[replica].Id != currentDev[replica].Id {
					if err := rm.aa.db.queuePartitionReplication(
						ringTask.typ,
						ringTask.policy,
						partition,
						"ring change",
						previousDev[replica].Id,
						currentDev[replica].Id,
					); err != nil {
						atomic.AddInt64(&errors, 1)
						rm.errorsMetric.Inc(1)
						changeTaskLogger.Error(
							"could not queue ring change; will try again next pass",
							zap.Uint64("partition", partition),
							zap.Uint64("replica", replica),
							zap.Int("previous id", previousDev[replica].Id),
							zap.Int("current id", currentDev[replica].Id),
							zap.Error(err),
						)
						failed = true
						break
					} else {
						atomic.AddInt64(&partitionCopiesChanged, 1)
						rm.partitionCopiesChangedMetric.Inc(1)
					}
				}
			}
		}
		if !failed {
			if err = rm.aa.db.setRingHash(ringTask.typ, ringTask.policy, ringTask.ring.MD5(), time.Now().Add(randomDuration(time.Minute*30, time.Hour))); err != nil {
				atomic.AddInt64(&errors, 1)
				rm.errorsMetric.Inc(1)
				changeTaskLogger.Error(
					"could not record the new ring hash; will try again next pass",
					zap.Error(err),
				)
			}
		}
	}
	close(cancel)
	<-progressDone
	if delays > 0 {
		rm.delay = rm.passTimeTarget / time.Duration(delays)
	}
	sleepFor := time.Until(start.Add(rm.passTimeTarget))
	if sleepFor < 0 {
		sleepFor = 0
	}
	logger.Debug("pass complete", zap.Int("total rings", len(ringTasks)), zap.Int64("errors", errors), zap.Int64("partition copies changed", partitionCopiesChanged), zap.String("next delay", rm.delay.String()), zap.String("sleep for", sleepFor.String()))
	if err := rm.aa.db.progressProcessPass("ring monitor", "", 0, fmt.Sprintf("%d of %d rings, %d errors, %d partition copies changed", delays, len(ringTasks), errors, partitionCopiesChanged)); err != nil {
		logger.Error("progressProcessPass", zap.Error(err))
	}
	if err := rm.aa.db.completeProcessPass("ring monitor", "", 0); err != nil {
		logger.Error("completeProcessPass", zap.Error(err))
	}
	return sleepFor
}

func (rm *ringMonitor) GetRingMD5(typ string, policy int) (ring.RingMD5, error) {
	rm.ringMD5CacheLock.Lock()
	defer rm.ringMD5CacheLock.Unlock()
	if ryng, ok := rm.ringMD5Cache[typ][policy]; ok {
		return ryng, ryng.Reload()
	}
	ryng, err := ring.GetRingMD5(typ, rm.prefix, rm.suffix, policy)
	if err != nil {
		return nil, err
	}
	rm.ringMD5Cache[typ][policy] = ryng
	return ryng, nil
}

func (rm *ringMonitor) rebalance(logger *zap.Logger, ringTask *ringTaskInstance) bool {
	ringBuilder, ringBuilderFilePath, err := ring.GetRingBuilder(ringTask.typ, ringTask.policy)
	if err != nil {
		logger.Error("Could not find builder", zap.Error(err))
		return false
	}
	ringBuilderLock, err := ring.LockBuilderPath(ringBuilderFilePath)
	if err != nil {
		logger.Error("Could not lock builder path", zap.String("ring builder file path", ringBuilderFilePath), zap.Error(err))
		return false
	}
	defer ringBuilderLock.Close()
	ringBuilder, ringBuilderFilePath, err = ring.GetRingBuilder(ringTask.typ, ringTask.policy)
	if err != nil {
		logger.Error("Could not find builder after lock", zap.Error(err))
		return false
	}
	var changedReplicas int
	changedReplicas, _, _, err = ring.Rebalance(ringBuilderFilePath, false, false, true)
	if err != nil {
		logger.Error("Error while rebalancing", zap.String("path", ringBuilderFilePath), zap.Error(err))
		return false
	}
	md5BeforeRebalance := ringTask.ring.MD5()
	if ringTask.ring, err = rm.GetRingMD5(ringTask.typ, ringTask.policy); err != nil {
		logger.Error("could not load modified ring", zap.Error(err))
		return false
	}
	// So we don't get stuck rebalancing a ring by tiny amounts for forever:
	settled := float64(changedReplicas)/(float64(ringBuilder.Parts)*ringBuilder.Replicas) < 0.01
	if settled {
		for _, dev := range ringTask.ring.AllDevices() {
			if dev == nil {
				continue
			}
			if dev.Weight == 0 && ringTask.ring.AssignmentCount(dev.Id) > 0 {
				settled = false
				break
			}
		}
	}
	if settled {
		rm.aa.db.addRingLog(ringTask.typ, ringTask.policy, fmt.Sprintf("rebalanced due to schedule; now settled"))
		rm.aa.db.setRingHash(ringTask.typ, ringTask.policy, md5BeforeRebalance, time.Time{})
	} else {
		rm.aa.db.addRingLog(ringTask.typ, ringTask.policy, fmt.Sprintf("rebalanced due to schedule"))
		rm.aa.db.setRingHash(ringTask.typ, ringTask.policy, md5BeforeRebalance, time.Now().Add(time.Hour*time.Duration(ringBuilder.MinPartHours)+randomDuration(time.Minute, 15*time.Minute)))
	}
	return true
}

func randomDuration(min, max time.Duration) time.Duration {
	return time.Duration(int64(min) + rand.Int63n(int64(max)-int64(min)+1))
}


text:
<?php

namespace App\Http\Controllers\Users;

use App\Http\Controllers\Controller;
use App\Models\Users\PermissionGroup;
use App\Models\Users\User;
use App\Repositories\Users\Roles\RolesInterface;
use Illuminate\Http\Request;

use App\Http\Requests;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Response;

class RolesController extends Controller {
	/**
	 * @var RolesInterface $repositoryObj
	 */
	protected $rolesInterface;

	/**
	 * PermissionController constructor.
	 *
	 * @param RolesInterface $obj
	 */
	public function __construct( RolesInterface $obj ) {
		$this->rolesInterface = $obj;
	}

	/**
	 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
	 */
	public function index() {

		$page_format = new \PageFormat( [
			'title' => 'Roles and permissions',
			'h1'    => 'Roles and permissions'
		] );

		return view( 'auth.users.roles.index', [
			'roles'  => $this->rolesInterface->buildViewEditData(),
			'titles' => $page_format->makeTitle()
		] );
	}

	/**
	 * @param Request $request
	 *
	 * @return \Illuminate\Http\RedirectResponse
	 */
	public function store( Request $request ) {
		// Form validation is done in Modules\Core\Http\Requests\CreateUserRequest
		$data = $this->rolesInterface->store( [ 'request' => $request ] );

		return redirect()->route( 'users.index' );
	}

	/**
	 * @param $id
	 *
	 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
	 */
	public function edit( $id ) {
		$edit_user = $this->userInterface->findUser( $id );

		$titles        = new \stdClass();
		$titles->title = $edit_user->name . ' ' . $edit_user->last_name . ' - Edit user';
		$titles->h1    = $edit_user->name . ' ' . $edit_user->last_name . ' <small>Edit user</small>';

		return view( 'auth.users.edit', compact( 'edit_user', 'titles' ) );
	}

	/**
	 * @param Request $request
	 *
	 * @return Response
	 */
	public function update( Request $request ) {
		$this->rolesInterface->update( [ 'request' => $request ] );

		return response()->json( array(
			'success' => true,
			'msg'     => 'Permissions updated'
		) );
	}

	/**
	 * @param Request $request
	 * @param mixed $id
	 */
	public function destroy( Request $request, $id = null ) {
		if ( $request->ajax() ) {
			$id = $request->get( 'id' );
		}

		if ( ! isset( $id ) ) {
			dd( 'User id is not set.' );
		}

		$this->userInterface->deleteUser( array( 'id' => $id ) );

	}

	/**
	 * @param int $user_id
	 */
	public function loginAs( $user_id ) {
		$user = User::find( $user_id );
		Auth::login( $user );

		return redirect()->route( 'dashboard' );
	}

	/**
	 * /**
	 *  Change permission for Role
	 *
	 * @param Request $request
	 */
	public function changePermission( Request $request ) {

		$role_id        = $request->get( 'role_id' );
		$permission_id  = $request->get( 'permission_id' );
		$has_permission = $request->get( 'has_permission' );

		if ( $has_permission == 1 ) {
			$this->rolesInterface->addRolePermission( $role_id, $permission_id );
		} else {
			$this->rolesInterface->deleteRolePermission( $role_id, $permission_id );
		}

		return response()->json( array(
			'success' => true,
			'msg'     => 'Permissions updated'
		) );

	}
}


text:
We are thrilled you are considering contributing to `acceleration`!

You are welcome to comment on issues and open new issues.

We welcome pull requests proposing source code changes or additions.

If you contribute any source code, we need you to agree to the following:

## Developer's Certificate of Origin 1.1

By making a contribution to this project, I certify that:

* The contribution was created in whole or in part by me and I
  have the right to submit it under the open source license
  indicated in the file; or

* The contribution is based upon previous work that, to the best
  of my knowledge, is covered under an appropriate open source
  license and I have the right under that license to submit that
  work with modifications, whether created in whole or in part
  by me, under the same open source license (unless I am
  permitted to submit under a different license), as indicated
  in the file; or

* The contribution was provided directly to me by some other
  person who certified (a), (b) or (c) and I have not modified
  it.

* I understand and agree that this project and the contribution
  are public and that a record of the contribution (including all
  personal information I submit with it, including my sign-off) is
  maintained indefinitely and may be redistributed consistent with
  this project or the open source license(s) involved.

You will be prompted to sign the Contributor License Agreement when you submit
your first pull request.

[![CLA assistant](https://cla-assistant.io/readme/badge/Watson-Explorer/acceleration-ruby)](https://cla-assistant.io/Watson-Explorer/acceleration-ruby)


text:
package creational.abstractFactory;

import static creational.abstractFactory.AbstractFactory.getUIObject;

class Main {

  String renderUIObject(int objectId) {
    IRender uiObject = getUIObject(objectId);
    return uiObject.render();
  }
}


text:
package uk.co.thefishlive.maths.config;

import com.google.common.base.Throwables;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import uk.co.thefishlive.auth.session.Session;
import uk.co.thefishlive.auth.user.UserProfile;
import uk.co.thefishlive.maths.Main;
import uk.co.thefishlive.meteor.data.AuthToken;
import uk.co.thefishlive.meteor.session.MeteorSession;
import uk.co.thefishlive.auth.session.exception.SessionException;
import uk.co.thefishlive.meteor.user.MeteorUserProfile;
import uk.co.thefishlive.meteor.utils.SerialisationUtils;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 *
 */
public class AuthDatabase implements ConfigFile {

    private static final Gson GSON = SerialisationUtils.getGsonInstance();
    private static final Logger LOGGER = LogManager.getLogger();

    private final File file;

    private Session session;

    public AuthDatabase(File file) {
        this.file = file;
    }

    @Override
    public File getFile() {
        return this.file;
    }

    @Override
    public void load() {
        LOGGER.info("Loading stored session from {} ", this.file.getAbsolutePath());
        if (!this.file.exists()) {
            return;
        }

        JsonParser parser = new JsonParser();

        try (FileReader reader = new FileReader(this.file)) {
            JsonElement element = parser.parse(reader);

            if (!element.isJsonObject()) {
                return;
            }

            JsonObject session = element.getAsJsonObject();

            JsonObject user = session.getAsJsonObject("user");
            UserProfile profile = new MeteorUserProfile(
                    AuthToken.decode(user.get("id").getAsString()),
                    user.get("name").getAsString(),
                    user.get("display-name").getAsString()
            );

            this.session = new MeteorSession(
                    Main.getInstance().getAuthHandler().getSessionHandler(),
                    profile,
                    null,
                    AuthToken.decode(session.get("refresh-token").getAsString())
            );

            this.session = this.session.refreshSession();

            LOGGER.info("Loaded session {}", this.session.toString());
            Main.getInstance().getAuthHandler().setActiveSession(this.session);
        } catch (IOException | SessionException e) {
            Throwables.propagate(e);
        }
    }

    @Override
    public void save() {
        LOGGER.info("Saving stored session ({}) to {}", session.toString(), this.file.getAbsolutePath());
        JsonObject json = new JsonObject();

        JsonObject user = new JsonObject();
        user.addProperty("id", this.session.getProfile().getId().toString());
        user.addProperty("name", this.session.getProfile().getName());
        user.addProperty("display-name", this.session.getProfile().getDisplayName());
        json.add("user", user);

        json.addProperty("refresh-token", ((MeteorSession) session).getRefreshToken().toString());

        if (!this.file.getParentFile().exists()) this.file.getParentFile().mkdirs();

        try (FileWriter writer = new FileWriter(this.file)) {
            GSON.toJson(json, writer);
        } catch (IOException e) {
            Throwables.propagate(e);
        }
    }

    public Session getSession() {
        return session;
    }

    public void updateSession(Session session) {
        LOGGER.info("Updating stored session to {}", session.toString());
        this.session = session;
    }
}


text:
import reducersFor from "./map/reducersFor";

export default {
  reducersFor
};


text:
title: "Developer Sandbox using Vagrant"
layout: single
type: posts
author_profile: true
comments: true
category: Tech
share: true
related: true
excerpt: "Onboarding a new developer or setting up a developer environment would take time. A Solution using Vagrant"
sitemap: false
permalink: /tech/Vagrant.html
---

## How to build a predefined developerbox using Vagrant


text:
package org.apache.oozie.executor.jpa;

import org.apache.oozie.CoordinatorActionBean;
import org.apache.oozie.CoordinatorJobBean;
import org.apache.oozie.ErrorCode;
import org.apache.oozie.client.CoordinatorAction;
import org.apache.oozie.client.CoordinatorJob;
import org.apache.oozie.local.LocalOozie;
import org.apache.oozie.service.JPAService;
import org.apache.oozie.service.Services;
import org.apache.oozie.test.XDataTestCase;

public class TestCoordActionRemoveJPAExecutor extends XDataTestCase {
    Services services;

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        services = new Services();
        services.init();
        cleanUpDBTables();
    }

    @Override
    protected void tearDown() throws Exception {
        services.destroy();
        super.tearDown();
    }

    public void testCoordActionRemove() throws Exception {
        int actionNum = 1;
        CoordinatorJobBean job = addRecordToCoordJobTable(CoordinatorJob.Status.RUNNING, false, false);
        CoordinatorActionBean action = addRecordToCoordActionTable(job.getId(), actionNum,
                CoordinatorAction.Status.WAITING, "coord-action-get.xml", 0);
        _testCoordActionRemove(job.getId(), action.getId());
    }

    private void _testCoordActionRemove(String jobId, String actionId) throws Exception {
        JPAService jpaService = Services.get().get(JPAService.class);
        assertNotNull(jpaService);
        CoordActionRemoveJPAExecutor coordRmvCmd = new CoordActionRemoveJPAExecutor(actionId);
        jpaService.execute(coordRmvCmd);

        try {
            CoordActionGetJPAExecutor coordGetCmd = new CoordActionGetJPAExecutor(actionId);
            CoordinatorActionBean newAction = jpaService.execute(coordGetCmd);
            fail("Action " + actionId + " Should be removed");
        }
        catch (JPAExecutorException je) {

        }
    }

    public void testRunningActionDelete() throws Exception {
        CoordinatorJobBean job = addRecordToCoordJobTable(CoordinatorJob.Status.RUNNING, false, false);
        CoordinatorActionBean action = addRecordToCoordActionTable(job.getId(), 1,
                CoordinatorAction.Status.RUNNING, "coord-action-get.xml", 0);

        JPAService jpaService = Services.get().get(JPAService.class);
        assertNotNull(jpaService);
        CoordActionRemoveJPAExecutor coordRmvCmd = new CoordActionRemoveJPAExecutor(action.getId());

        try {
            jpaService.execute(coordRmvCmd);
            fail("Should have thrown JPAExecutorException");
        } catch(JPAExecutorException e) {
            System.out.println(e.getErrorCode());
            e.printStackTrace();
            if(e.getErrorCode() != ErrorCode.E1022)
                fail("Error code should be E1022");
        }
    }
}


text:
layout: default
category: consumers
title: "Invantive Query Tool"
link: "http://www.invantive.com/products/invantives-free-query-tool/"
version: 2,3,4
---
Based upon ANSI-SQL with extension you can use Invantive SQL to retrieve and update information contained in OData-based platforms. The SQL grammar is described on http://www.invantive.com/products/invantive-sql/grammar. This free SQL product does not support the use of joins and queries and updates distributed across multiple data containers in the cloud. An online version is available for several platforms on https://online-sql-editor.com, supported on iPhone, iPad, Mac and Windows.


text:
#include "StdAfx.h"
#include ".\bscontroller.h"
#include "HeadsetPresenterDlg.h"
#include "SS_Log.h"

BSController::BSController(void)
{
	//mySoleilProxy = new SoleilProxy();
	controllerMode = NORMAL_MODE_BLUESOLEIL;
	Log("BSC:Set controller mode to NORMAL_MODE_BLUESOLEIL = %d",NORMAL_MODE_BLUESOLEIL);
	servicesListAsCStringList = new CStringList(); //Kept here since it is used by ServiceSelectionDlg in case of manual serviceselection

	deviceDiscoveryDialog = new DeviceDiscoveryDialog(); //Should use the same declare in constructor?
	serviceDiscoveryDialog = new ServiceDiscoveryDialog();
	deviceDiscoveryDialog->SetController(this);  //Can this be done in the superclass?????
	serviceDiscoveryDialog->SetController(this);

	Log("BSC:Create BSController");

	isInitialised = false;

}

BSController::~BSController(void)
{
	Log("BSC:Delete BSController");
	if(isInitialised) //If we failed to init, do not uninit
	{
		BS_DisconnectService();  //Always call disconnect the Proxy will know if we are connected
		BS_UnInitializeStack();
	}
}

bool BSController::ShouldHPQueryForPIN()
{
	return true; //could be a setting decide which is best TBI in proxy
}

bool BSController::BondDevice()
{
	LogEnterFunction("BTC:BondDevice");
	//Currently only soleil pin dialog
	bool bondOK = BS_PairSelectedDevice();
	return bondOK;
}

void BSController::CancelDeviceDiscovery()
{
	Log("BSC:CancelDeviceDiscovery not impl. in BSC yet");
}

void BSController::UnbondDevice()
{
	//Pending usage of this for BS might be needed
	//mySoleilProxy.UnpairSelectedDevice();
}

//Used by controller factory when checking for Soleil support
//Could create with new and keep the object instead
bool BSController::IsRadioAvailable()
{
	//DWORD dwBtVersion;
	bool radioAvailable = false;
	//No logging can be done before this code, the IsBlueSoleilAvailable does not log neither produce error messages
	if(BS_IsBlueSoleilAvailable())
	{
		Log("BSC: BlueSoleil dll was found");
		if(BS_InitializeStack())
		{
			Log("BSC: BlueSoleil init ok");
			radioAvailable = true;
			isInitialised = true;
			BS_SetControllerObject(this);
			BS_SetDataCallback(&DataCallbackFunc);
			BS_SetDeviceCallback(&DeviceCallbackFunc);
			BS_SetEventCallback(&EventCallbackFunc);
		}
		else
		{
			Log("BSC: BlueSoleil init failed");
			radioAvailable = false;
		}
	}
	else
	{
		Log("BSC: BlueSoleil dll was not found");
	}
	//NOTE must I make an unit before making init again when creatin the real controller
	return radioAvailable;
}

bool BSController::ConnectToLastUsedDevice()
{
	MessageBox(NULL,"Reconnection is not supported by BlueSoleil.\nThe pairing wizard or Advanced mode must be used.","Reconnection not possible.",MB_OK|MB_TOPMOST|MB_ICONINFORMATION);
	//BS_SetLastUsedDevice(NULL);  //Connect without pairing is not possible
	//BS_ConnectService(2);
	return false;
}
bool BSController::ShowDeviceSearchDialog()
{
	return SuperShowDeviceSearchDialog();
}

void BSController::DiscoverDevices(bool refresh)
{
	LogEnterFunction("BSC:DiscoverDevices");
	CStringList*  discoveredDevices = new CStringList();
	BS_DoInquiry(discoveredDevices, refresh);
	POSITION cur;
	cur = discoveredDevices->GetHeadPosition();
	while(cur != NULL)
	{
		deviceDiscoveryDialog->AddDeviceToList(discoveredDevices->GetNext(cur));
	}
	//deviceDiscoveryDialog->AddDeviceToList("nisse");
}

void BSController::DeviceSelected(int deviceIndex)
{
	BS_DeviceSelected(deviceIndex);
}

/*Called by ServiceSelectionDialog. Gets the stored list from DiscoverServicesSync*/
CStringList* BSController::GetServiceListAsCStringList()
{
	return servicesListAsCStringList;
}

bool BSController::ConnectToSelectedDevice(int SCN, CString serviceName )
{
	BS_ConnectService(SCN);
	return true;
}

void BSController::DiscoverServicesAsync()
{

}

/*The service list is always built and kept by DiscoverServicesSync
*if the manual service selection dlg wants the list it gets the stored one*/
bool BSController::DiscoverServicesSync()
{
	BS_DoServiceSearch(servicesListAsCStringList);
	return true;
}

int BSController::GetNoOfServicesDiscovered()
{
	return BS_GetNoOfServicesFound();
}
int BSController::GetSCNOfService(CString serviceNameToFind)
{
	return BS_GetSCNOfService(serviceNameToFind);
}

void BSController::InitLocalSettings()
{
	if(!mySettingsControl->GetLogDisabled())
	{
		BS_ActivateLogging();
	}
}
int BSController::GetMode()
{
	return controllerMode;
}

bool BSController::Start()
{
	return true;
}

/*The DataCallbackFunc must be static to work with the dll callback
  Therefor the dll gets the object pointer to use in the callback and then
  it is typecasted here to call the non static functions.
  */
int __stdcall BSController::DataCallbackFunc(char* msg, void* controller)
{
	BSController* myController = (BSController*)controller;
	myController->OnReadCompleted(msg);
	return 1;  //Not used
}

/*The DataCallbackFunc must be static to work with the dll callback
  Therefor the dll gets the object pointer to use in the callback and then
  it is typecasted here to call the non static functions.
  */
int __stdcall BSController::DeviceCallbackFunc(char* msg, void* controller)
{
	BSController* myController = (BSController*)controller;
	myController->DeviceFound(msg);
	return 1;  //Not used
}

/*Handle events callback, currently limited to:
1. DeviceDiscoveryComplete
  */
int __stdcall BSController::EventCallbackFunc(char* msg, void* controller)
{
	BSController* myController = (BSController*)controller;
	myController->HandleEvent(msg);
	return 1;  //Not used
}

void BSController::DeviceFound(char* deviceName)
{
	Log("BSC:Device found named %s", deviceName);
	deviceDiscoveryDialog->AddDeviceToList(deviceName);
}

void BSController::OnReadCompleted(char* data)
{
	//bool dataIsATCommand = false;
	int commandType = 0;
	CString dataString;
	dataString = data;
	Log("GC:data read and copied as : %s",dataString);

	//1. Check if it is an AT command
	if(dataString.Find("AT+") != -1 )
	{
		Log("GC:Data is AT command");
		//dataIsATCommand = true;
		commandType = AT_COMMAND;
		HandleStatesAndForwardCommand(dataString, commandType, TRUE);
	}
	/*Not AT command, AVRCP not supported
	else
	{
		commandType = AVRCP_COMMAND;
		Log("GC:Data is not AT command, not forwarding : %s",dataString);
	}*/

}

void BSController::Write(unsigned char* data){}


text:
<?php

namespace ickx\fw2\mvc\app\controllers\traits;

/**
 * Flywheel2 Controller向けRedirect特性です。
 *
 * @category	Flywheel2
 * @package		mvc
 * @author		wakaba <wakabadou@gmail.com>
 * @license		http://opensource.org/licenses/MIT The MIT License MIT
 * @varsion		2.0.0
 */
trait RedirecterTrait {
	/**
	 * リダイレクトを設定します。
	 *
	 * @param	string	$url		リダイレクト先URL
	 * @param	array	$parameter	オプションパラメータ
	 */
	public function redirect ($url, $parameter = []) {
		$this->forceNext($url, static::NEXT_REDIRECT);
	}

	/**
	 * リダイレクトが設定されているかどうかを返します。
	 *
	 * @return	bool	リダイレクトが設定されている場合はtrue, そうでない場合はfalse
	 */
	public function isRedirect () {
		return ($this->nextRule === static::NEXT_REDIRECT && $this->nextUrl !== null);
	}

	public function forceRedirect ($url) {
		$this->setUrl($url);
		$this->nextRule		= static::NEXT_REDIRECT;
		$this->cancelEvents = true;
	}
}


text:
package org.gradle.test.fixtures.server.http;

import com.sun.net.httpserver.HttpExchange;

import java.io.IOException;

class ExpectGetMissing implements BlockingHttpServer.ExpectedRequest, ResourceExpectation, ResourceHandler {
    private final String path;

    ExpectGetMissing(String path) {
        this.path = SendFixedContent.removeLeadingSlash(path);
    }

    @Override
    public String getMethod() {
        return "GET";
    }

    @Override
    public String getPath() {
        return path;
    }

    @Override
    public ResourceHandler create(WaitPrecondition precondition) {
        return this;
    }

    @Override
    public void writeTo(int requestId, HttpExchange exchange) throws IOException {
        exchange.sendResponseHeaders(404, 0);
    }
}


text:
..
 This work is licensed under a Creative Commons Attribution 3.0 Unported
 License.

 http://creativecommons.org/licenses/by/3.0/legalcode

Neutron QoS Support
===================

Quality of Service (QoS) support is available in GBP using the Neutron API
(via the GBP Neutron Resource Mapping Driver).

This feature can be used by creating Network Service Policies (NSP) with the
following NSP parameter types:
- `qos_maxrate`: maximum bandwidth limiting rate for a Policy Target (in Kbps)
- `qos_burstrate`: burst bandwidth limiting rate for a Policy Target (in Kbps)

When a NSP contains one or both of the previous parameter types, and is
associated to a Policy Target Group (PTG), all Policy Targets part of that PTG
will individually inherit the QoS definitions intended. In other words, each
Policy Target will have their bandwidth limited by the amounts specified in
`qos_maxrate` and `qos_burstrate`, independently of the network activity in
other Policy Targets of the same PTG.

The QoS NSP parameter types expect a numerical value bound by Neutron's QoS.

Resource Mapping Driver
-----------------------
When a NSP contains one or both of the supported parameter types, and a
respective numerical value, the Resource Mapping Driver will automatically be
called to create one QoS Policy resource and one QoS Bandwidth Limit Rule
resource, via Neutron's REST API.

The Resource Mapping Driver includes the NSP Manager as a mixin, which
provides the data model and methods for creating mappings from GBP to QoS
resources in Neutron, as explained in more detail below.

This driver also handles the association of each Policy Target (part of a PTG
having a NSP that includes QoS parameters) to the actual QoS Policies that
have been created in Neutron. The Neutron Ports already mapped to Policy
Targets will be updated to include the correct Neutron QoS Policy that was
previously created and mapped to GBP.

NSP Manager
-----------
A special resource exists in GBP, `ServicePolicyQosPolicyMapping`, which keeps
track of the mapping between NSPs in GBP and QoS Policies in Neutron, and is
specifically defined inside the NSP Manager file (`nsp_manager.py`).

Furthermore, `NetworkServicePolicyMappingMixin` includes the database
operations for creating, deleting and reading these mappings.

DevStack Support
----------------
The GBP DevStack plugin will automatically enable QoS support.


text:
package chapter_8;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

import datastructures.util.InputUtil;

public class TestRecursiveMultiply {
    private static String inputFile = "input_files/chapter_8/recursive_multiply/test_case";
    private static RecursiveMultiply recursiveMultiply;
    private static String[] input = null;

    @BeforeClass
    public static void setup() {
        recursiveMultiply = new RecursiveMultiply();
        input = InputUtil.readContents(inputFile);
    }

    @AfterClass
    public static void teardown() {
        recursiveMultiply = null;
        input = null;
    }

    @Test
    public void testRecursiveMultiplyTestCase1() {
        assertRecursiveMultiply(input[0]);
    }

    @Test
    public void testRecursiveMultiplyTestCase2() {
        assertRecursiveMultiply(input[1]);
    }

    @Test
    public void testRecursiveMultiplyTestCase3() {
        assertRecursiveMultiply(input[2]);
    }

    @Test
    public void testRecursiveMultiplyTestCase4() {
        assertRecursiveMultiply(input[3]);
    }

    @Test
    public void testRecursiveMultiplyTestCase5() {
        assertRecursiveMultiply(input[4]);
    }

    @Test
    public void testRecursiveMultiplyTestCase6() {
        assertRecursiveMultiply(input[5]);
    }

    private void assertRecursiveMultiply(String input) {
        String[] values = input.split(" ");
        assertEquals(Long.parseLong(values[2]),
                recursiveMultiply.multiply(Integer.parseInt(values[0]), Integer.parseInt(values[1])));
    }
}


text:
//  See http://www.boost.org for updates, documentation, and revision history.
//
//  File        : $RCSfile$
//
//  Version     : $Revision: 54633 $
//
//  Description : argument usage printing helpers
// ***************************************************************************

#ifndef BOOST_RT_CLA_ARGUMENT_VALUE_USAGE_HPP_062604GER
#define BOOST_RT_CLA_ARGUMENT_VALUE_USAGE_HPP_062604GER

// Boost.Runtime.Parameter
#include <boost/test/utils/runtime/config.hpp>
#include <boost/test/utils/runtime/cla/argv_traverser.hpp>

// Boost.Test
#include <boost/test/utils/basic_cstring/io.hpp>
#include <boost/test/utils/basic_cstring/compare.hpp>

#include <boost/lexical_cast.hpp>

// STL
// !! can we eliminate these includes?
#include <list>

namespace boost {

namespace BOOST_RT_PARAM_NAMESPACE {

namespace cla {

namespace rt_cla_detail {

// ************************************************************************** //
// **************             argument_value_usage             ************** //
// ************************************************************************** //

// generic case
template<typename T>
inline void
argument_value_usage( format_stream& fs, long, T* = 0 )
{
    fs << BOOST_RT_PARAM_CSTRING_LITERAL( "<value>" );
}

//____________________________________________________________________________//

// specialization for list of values
template<typename T>
inline void
argument_value_usage( format_stream& fs, int, std::list<T>* = 0 )
{
    fs << BOOST_RT_PARAM_CSTRING_LITERAL( "(<value1>, ..., <valueN>)" );
}

//____________________________________________________________________________//

// specialization for type bool
inline void
argument_value_usage( format_stream& fs,  int, bool* = 0 )
{
    fs << BOOST_RT_PARAM_CSTRING_LITERAL( "yes|y|no|n" );
}

//____________________________________________________________________________//

} // namespace rt_cla_detail

} // namespace cla

} // namespace BOOST_RT_PARAM_NAMESPACE

} // namespace boost

#endif // BOOST_RT_CLA_ARGUMENT_VALUE_USAGE_HPP_062604GER


text:
define(
    function (require) {
        function Plain() {
            this.enter = jasmine.createSpy('enter');
            this.leave = jasmine.createSpy('leave');
            Plain.mostRecentInstance = this;
        }

        return Plain;
    }
);


text:
package org.wso2.carbon.dashboard.dashboardpopulator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.registry.core.*;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.session.UserRegistry;
import org.wso2.carbon.registry.core.utils.MediaTypesUtils;
import org.wso2.carbon.user.core.AuthorizationManager;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.ServerConstants;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Arrays;
import java.util.List;

public class GadgetPopulator {

    private static final Log log = LogFactory.getLog(GadgetPopulator.class);

    public static final String SYSTEM_GADGETS_PATH = "/repository/dashboards/gadgets";

    private static final String REGISTRY_SYSTEM_DASHBOARDS_ROOT = "/repository/dashboards";

    static String gadgetsPath = SYSTEM_GADGETS_PATH;

    /**
     * This will not use because of on demand population method
     *
     * @param tenantId
     */
    public static void populateDashboard(int tenantId) {
        try {

            String dashboardDiskRoot = System.getProperty(ServerConstants.CARBON_HOME) + File
                    .separator + "repository" + File.separator + "resources" + File.separator + "dashboard";

            String dashboardConfigFile = dashboardDiskRoot + File.separator + "dashboard.xml";
            String gadgetsDiskLocation = dashboardDiskRoot + File.separator + "gadgets";

            // Check whether the system dashboard is already available if not populate
            UserRegistry registry = DashboardPopulatorContext.getRegistry(tenantId);

            // Set permission for annonymous read. We do it here because it should happen always in order
            // to support mounting a remote registry.
            AuthorizationManager accessControlAdmin =
                    registry.getUserRealm().getAuthorizationManager();

            if (!accessControlAdmin.isRoleAuthorized(CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME, RegistryConstants.CONFIG_REGISTRY_BASE_PATH +
                    GadgetPopulator.SYSTEM_GADGETS_PATH, ActionConstants.GET)) {
                accessControlAdmin.authorizeRole(CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME, RegistryConstants.CONFIG_REGISTRY_BASE_PATH +
                        GadgetPopulator.SYSTEM_GADGETS_PATH, ActionConstants.GET);
            }

            String serverName = CarbonUtils.getServerConfiguration().getFirstProperty("Name");

/*            String serverPrefix = serverName.indexOf("Business Activity Monitor") > -1 ? "bam" : "";

            if (serverName.length() > 0) {
                gadgetsPath = SYSTEM_GADGETS_PATH + "/" + serverPrefix;
            }*/

            if (!registry.resourceExists(REGISTRY_SYSTEM_DASHBOARDS_ROOT + "/" + serverName)) {
                // Creating an OMElement from file
                File dashboardConfigXml = new File(dashboardConfigFile);

                if (dashboardConfigXml.exists()) {
                    FileReader dashboardConfigXmlReader = new FileReader(dashboardConfigXml);

                    // Restoring from file
                    registry.restore(REGISTRY_SYSTEM_DASHBOARDS_ROOT, dashboardConfigXmlReader);

                    log.info("Successfully populated the default Dashboards.");

                } else {
                    log.info("Couldn't find a Dashboard at '" + dashboardConfigFile +
                            "'. Giving up.");
                }

                // Store gadgets
                File gadgetsDir = new File(gadgetsDiskLocation);
                if (gadgetsDir.exists()) {
                    GadgetPopulator.beginFileTansfer(gadgetsDir, tenantId);

                    log.info("Successfully populated the default Gadgets.");
                } else {
                    log.info("Couldn't find contents at '" + gadgetsDiskLocation +
                            "'. Giving up.");
                }
                registry.put(REGISTRY_SYSTEM_DASHBOARDS_ROOT + "/" + serverName, registry.newResource());
            }

        } catch (Exception e) {
            log.debug("Failed to activate Dashboard Populator for Governance bundle ");
        }
    }

    public static void beginFileTansfer(File rootDirectory, int tenantId) throws RegistryException {
        try {

            // Storing the root path for future reference
            String rootPath = rootDirectory.getAbsolutePath();

            UserRegistry registry = DashboardPopulatorContext.getRegistry(tenantId);

            // Creating the default gadget collection resource
            Collection defaultGadgetCollection = registry.newCollection();
            try {
                registry.beginTransaction();
                registry.put(gadgetsPath, defaultGadgetCollection);

                transferDirectoryContentToRegistry(rootDirectory, registry, rootPath, tenantId);
                registry.commitTransaction();
            } catch (Exception e) {
                registry.rollbackTransaction();
                log.error(e.getMessage(), e);
            }

        } catch (DashboardPopulatorException e) {
            log.error(e.getMessage(), e);
        }
    }

    private static void transferDirectoryContentToRegistry(File rootDirectory, Registry registry,
                                                           String rootPath, int tenantId)
            throws FileNotFoundException {

        try {
            File[] filesAndDirs = rootDirectory.listFiles();
            List<File> filesDirs = Arrays.asList(filesAndDirs);

            for (File file : filesDirs) {

                if (!file.isFile()) {
                    // This is a Directory add a new collection
                    // This path is used to store the file resource under registry
                    String directoryRegistryPath =
                            gadgetsPath + file.getAbsolutePath()
                                    .substring(rootPath.length()).replaceAll("[/\\\\]+", "/");
                    Collection newCollection = registry.newCollection();
                    registry.put(directoryRegistryPath, newCollection);

                    // recurse
                    transferDirectoryContentToRegistry(file, registry, rootPath, tenantId);
                } else {
                    // Add this to registry
                    addToRegistry(rootPath, file, tenantId);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

    }

    private static void addToRegistry(String rootPath, File file, int tenantId) {
        try {
            Registry registry = DashboardPopulatorContext.getRegistry(tenantId);

            // This path is used to store the file resource under registry
            String fileRegistryPath =
                    gadgetsPath + file.getAbsolutePath().substring(rootPath.length())
                            .replaceAll("[/\\\\]+", "/");

            // Adding the file to the Registry

            Resource fileResource = registry.newResource();
            String mediaType = MediaTypesUtils.getMediaType(file.getAbsolutePath());
            if (mediaType.equals("application/xml")) {
                fileResource.setMediaType("application/vnd.wso2-gadget+xml");
            } else {
                fileResource.setMediaType(mediaType);
            }
            fileResource.setContentStream(new FileInputStream(file));
            registry.put(fileRegistryPath, fileResource);

        } catch (DashboardPopulatorException e) {
            log.error(e.getMessage(), e);
        } catch (RegistryException e) {
            log.error(e.getMessage(), e);
        } catch (FileNotFoundException e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * This method populates dashboard layout using dashboard.xml
     * Tab Layout and default gadget lists are identified by this population
     *
     * @param tenantId
     * @return status of population
     */
    public static void PopulateDashboardLayout(int tenantId) {

        try {

            String dashboardDiskRoot = System.getProperty(ServerConstants.CARBON_HOME) + File
                    .separator + "repository" + File.separator + "resources" + File.separator + "dashboard";

            String dashboardConfigFile = dashboardDiskRoot + File.separator + "dashboard.xml";

            String serverName = CarbonUtils.getServerConfiguration().getFirstProperty("Name");

            UserRegistry registry = DashboardPopulatorContext.getRegistry(tenantId);

            // Set permission for anonymous read. We do it here because it should happen always in order
            // to support mounting a remote registry.
            AuthorizationManager accessControlAdmin =
                    registry.getUserRealm().getAuthorizationManager();

            if (!accessControlAdmin.isRoleAuthorized(CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME, RegistryConstants.CONFIG_REGISTRY_BASE_PATH +
                    GadgetPopulator.SYSTEM_GADGETS_PATH, ActionConstants.GET)) {
                accessControlAdmin.authorizeRole(CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME, RegistryConstants.CONFIG_REGISTRY_BASE_PATH +
                        GadgetPopulator.SYSTEM_GADGETS_PATH, ActionConstants.GET);
            }

            if (!registry.resourceExists(REGISTRY_SYSTEM_DASHBOARDS_ROOT + "/" + serverName)) {
                // Creating an OMElement from file
                File dashboardConfigXml = new File(dashboardConfigFile);

                if (dashboardConfigXml.exists()) {
                    FileReader dashboardConfigXmlReader = new FileReader(dashboardConfigXml);

                    // Restoring from file
                    registry.restore(REGISTRY_SYSTEM_DASHBOARDS_ROOT, dashboardConfigXmlReader);

                    log.info("Successfully populated the default Dashboard XML for tenant :" + tenantId);

                } else {
                    log.info("Couldn't find a Dashboard XML at '" + dashboardConfigFile +
                            "'. Giving up dashboard population for tenant : " + tenantId);
                }

                // This will prevent re-population of dashboard.xml and tabResources
                registry.put(REGISTRY_SYSTEM_DASHBOARDS_ROOT + "/" + serverName, registry.newResource());
            }

        } catch (Exception e) {
            String errorMsg = "Failed to populate Dashboard Layout (dashboard.xml) for tenant : " + tenantId;
            log.error(errorMsg, e);
        }

    }

}


text:
from bibliopixel.drivers.serial_driver import DriverSerial, LEDTYPE
from bibliopixel import LEDMatrix, log
from BiblioPixelAnimations.matrix.bloom import Bloom
log.setLogLevel(log.DEBUG)

driver = DriverSerial(LEDTYPE.GENERIC, 64, hardwareID="16C0:0483")
led = LEDMatrix(driver)

try:
    anim = Bloom(led, dir=True)
    anim.run(amt=1, fps=15)
except:
    led.all_off()
    led.update()


text:
@class Student;

@interface AddStudentNameViewController : UITableViewController {
	NSString *lastName;
    NSString *firstName;
	Student *student;
	AddStudentNameTableCell *tableCell;
}

@property (nonatomic, retain) NSString *lastName;
@property (nonatomic, retain) NSString *firstName;
@property (nonatomic, retain) IBOutlet AddStudentNameTableCell *tableCell;
@property (nonatomic, retain) Student *student;
- (void)cancel;
- (void)save;

@end


text:
a = "\u0030" #unicode for 0
b = "\u00B2" #unicode for ²
c = "10km2"

print(a.isnumeric())
print(b.isnumeric())
print(c.isnumeric())

txt = "565543"

x = txt.isnumeric()

print(x)

a = "Hello world!"
b = "hello 123"
c = "mynameisPeter"

print(a.islower())
print(b.islower())
print(c.islower())

txt = "hello world!"

x = txt.islower()

print(x)

a = "MyFolder"
b = "Demo002"
c = "2bring"
d = "my demo"

print(a.isidentifier())
print(b.isidentifier())
print(c.isidentifier())
print(d.isidentifier())

txt = "Demo"

x = txt.isidentifier()

print(x)

a = "\u0030" #unicode for 0
b = "\u00B2" #unicode for 2

print(a.isdigit())
print(b.isdigit())

txt = "50800"

x = txt.isdigit()

print(x)

a = "\u0030" #unicode for 0
b = "\u0047" #unicode for G

print(a.isdecimal())
print(b.isdecimal())

txt = "\u0033" #unicode for 3

x = txt.isdecimal()

print(x)

txt = "Company10"

x = txt.isalpha()

print(x)

txt = "CompanyX"

x = txt.isalpha()

print(x)

txt = "Company 12"

x = txt.isalnum()

print(x)

txt = "Company12"

x = txt.isalnum()

print(x)

txt = "Hello, welcome to my world."

print(txt.find("q"))
# print(txt.index("q"))

txt = "Hello, welcome to my world."

x = txt.index("e", 5, 10)

print(x)

txt = "Hello, welcome to my world."

x = txt.index("e")

print(x)

txt = "Hello, welcome to my world."

x = txt.index("welcome")

print(x)

#Use "%" to convert the number into a percentage format:

txt = "You scored {:%}"
print(txt.format(0.25))

#Or, without any decimals:

txt = "You scored {:.0%}"
print(txt.format(0.25))

#Use "X" to convert the number into upper-case Hex format:

txt = "The Hexadecimal version of {0} is {0:X}"

print(txt.format(255))

#Use "x" to convert the number into Hex format:

txt = "The Hexadecimal version of {0} is {0:x}"

print(txt.format(255))

#Use "o" to convert the number into octal format:

txt = "The octal version of {0} is {0:o}"

print(txt.format(10))

#Use "G" to convert the number into upper-case general format:

txt = "The general version of {0} is {0:G}"

print(txt.format(211e11))

#Use "g" to convert the number into general format:

txt = "The general version of {0} is {0:g}"

print(txt.format(211E11))

#Use "F" to convert a number into a fixed point number, but display inf and nan as INF and NAN:

x = float('inf')

txt = "The price is {:F} dollars."
print(txt.format(x))

#same example, but with a lower case f:

txt = "The price is {:f} dollars."
print(txt.format(x))

#Use "f" to convert a number into a fixed point number, default with 6 decimals, but use a period followed by a number to specify the number of decimals:

txt = "The price is {:.2f} dollars."
print(txt.format(45))

#without the ".2" inside the placeholder, this number will be displayed like this:

txt = "The price is {:f} dollars."
print(txt.format(45))

#Use "E" to convert a number into scientific number format (with an upper-case E):

txt = "We have {:E} chickens."
print(txt.format(5))

#Use "e" to convert a number into scientific number format (with a lower-case e):

txt = "We have {:e} chickens."
print(txt.format(5))

#Use "d" to convert a number, in this case a binary number, into decimal number format:

txt = "We have {:d} chickens."
print(txt.format(0b101))

#Use "b" to convert the number into binary format:

txt = "The binary version of {0} is {0:b}"

print(txt.format(5))

#Use "_" to add a underscore character as a thousand separator:

txt = "The universe is {:_} years old."

print(txt.format(13800000000))

#Use "," to add a comma as a thousand separator:

txt = "The universe is {:,} years old."

print(txt.format(13800000000))

#Use " " (a space) to insert a space before positive numbers and a minus sign before negative numbers:

txt = "The temperature is between {: } and {: } degrees celsius."

print(txt.format(-3, 7))

#Use "-" to always indicate if the number is negative (positive numbers are displayed without any sign):

txt = "The temperature is between {:-} and {:-} degrees celsius."

print(txt.format(-3, 7))

#Use "+" to always indicate if the number is positive or negative:

txt = "The temperature is between {:+} and {:+} degrees celsius."

print(txt.format(-3, 7))

#To demonstrate, we insert the number 8 to specify the available space for the value.

#Use "=" to place the plus/minus sign at the left most position:

txt = "The temperature is {:=8} degrees celsius."

print(txt.format(-5))

#To demonstrate, we insert the number 8 to set the available space for the value to 8 characters.

#Use "^" to center-align the value:

txt = "We have {:^8} chickens."
print(txt.format(49))

#To demonstrate, we insert the number 8 to set the available space for the value to 8 characters.

#Use ">" to right-align the value:

txt = "We have {:>8} chickens."
print(txt.format(49))

#To demonstrate, we insert the number 8 to set the available space for the value to 8 characters.

#Use "<" to left-align the value:

txt = "We have {:<8} chickens."
print(txt.format(49))

#named indexes:
txt1 = "My name is {fname}, I'm {age}".format(fname = "John", age = 36)
#numbered indexes:
txt2 = "My name is {0}, I'm {1}".format("John",36)
#empty placeholders:
txt3 = "My name is {}, I'm {}".format("John",36)

print(txt1)
print(txt2)
print(txt3)

txt = "For only {price:.2f} dollars!"
print(txt.format(price = 49))

txt = "Hello, welcome to my world."

print(txt.find("q"))
#print(txt.index("q"))

txt = "Hello, welcome to my world."

x = txt.find("e", 5, 10)

print(x)

txt = "Hello, welcome to my world."

x = txt.find("e")

print(x)

txt = "Hello, welcome to my world."

x = txt.find("welcome")

print(x)