text:
package com.anjlab.eclipse.tapestry5;

import org.apache.commons.lang3.StringUtils;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.ISourceRange;

import com.anjlab.eclipse.tapestry5.internal.TapestryBuiltinJavaScriptModuleConfiguration;

public class JavaScriptModuleReference extends AbstractFileReference
{

    public static final String MARKER_NAME = "ModuleName";

    private static final TapestryBuiltinJavaScriptModuleConfiguration
        builtinModules = new TapestryBuiltinJavaScriptModuleConfiguration();

    private final String moduleName;
    private final String functionName;

    public JavaScriptModuleReference(TapestryFile javaFile, ISourceRange sourceRange, String reference)
    {
        super(javaFile, sourceRange, reference, MARKER_NAME);

        int colonIndex = reference.lastIndexOf(':');

        if (colonIndex < 0)
        {
            moduleName = reference;
            functionName = null;
        }
        else
        {
            moduleName = reference.substring(0, colonIndex);
            functionName = reference.substring(colonIndex + 1);
        }
    }

    public String getModuleName()
    {
        return moduleName;
    }

    public String getFunctionName()
    {
        return functionName;
    }

    @Override
    public IPath getPath()
    {
        String path = builtinModules.getPath(moduleName);

        if (StringUtils.isEmpty(path))
        {
            path = "META-INF/modules/" + moduleName + ".js";
        }

        //  TODO First segment of moduleName holds the name of the library,
        //  also extension name may be different

        path = TapestryUtils.expandSymbols(path);

        return new Path(path);
    }

    @Override
    public String getName()
    {
        return reference;
    }

    @Override
    protected TapestryFile resolveFile() throws UnresolvableReferenceException
    {
        String path = getPath().toOSString();

        Asset asset = new Asset(path);

        AssetResolver assetResolver = TapestryUtils.createAssetResolver(asset.bindingPrefix);

        TapestryFile resolvedFile = assetResolver.resolve(asset.path, javaFile);

        return resolvedFile;
    }

}

redpajama_set_name: RedPajamaGithub


text:
/****** Object:  StoredProcedure [GetG11_CityRoadColl] ******/
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[GetG11_CityRoadColl]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [GetG11_CityRoadColl]
GO

CREATE PROCEDURE [GetG11_CityRoadColl]
    @Parent_City_ID int
AS
    BEGIN

        SET NOCOUNT ON

        /* Get G12_CityRoad from table */
        SELECT
            [6_CityRoads].[CityRoad_ID],
            [6_CityRoads].[CityRoad_Name]
        FROM [6_CityRoads]
        WHERE
            [6_CityRoads].[Parent_City_ID] = @Parent_City_ID AND
            [6_CityRoads].[IsActive] = 'true'

    END
GO


text:
@implementation ZJMMusicTool

static NSArray *_music;
static ZJMMusic *_playingMusic;

+ (void)initialize
{
    _music = [ZJMMusicTool objectArrayWithFilename:@"Musics.plist"];
    _playingMusic = _music[0];
}

+ (NSArray *)music
{
    return _music;
}
+ (ZJMMusic *)playingMusic
{
    return _playingMusic;
}
+ (void)setPlayingMusic:(ZJMMusic *)playingMusic
{
    _playingMusic = playingMusic;
}

@end


text:
Algo package
============

Submodules
----------

Algo.Clustering module
----------------------

.. automodule:: Algo.Clustering
    :members:
    :undoc-members:
    :show-inheritance:

Algo.Supervisor module
----------------------

.. automodule:: Algo.Supervisor
    :members:
    :undoc-members:
    :show-inheritance:

Module contents
---------------

.. automodule:: Algo
    :members:
    :undoc-members:
    :show-inheritance:


text:
<?php
/**
 * 后台通知:由LATIPAY支付平台转发银行支付确认信息。
 *          这种方式是LATIPAY支付平台服务器与商户服务器之间进行通信的,对于持卡买家不可见
 *          参数同前台通知,有返回值
 * 详细说明见API文档 https://merchant.latipay.co.nz/developer/api.action
 */

error_reporting(0);

require_once('../config.php');

// Startup
require_once(DIR_SYSTEM . 'startup.php');

// Registry
$registry = new Registry();

// Loader
$loader = new Loader($registry);
$registry->set('load', $loader);

// Config
$config = new Config();
$registry->set('config', $config);

// Database
$db = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
$registry->set('db', $db);

// Settings
$query = $db->query("SELECT * FROM `" . DB_PREFIX . "setting` WHERE code = 'latipay2' ");
foreach ($query->rows as $result) {
    $config->set($result['key'], $result['value']);
}

$api_key = trim($config->get('latipay2_api_key'));
$user_id = trim($config->get('latipay2_user_id'));
$wallet_id = trim($config->get('latipay2_wallet_id'));
$order_status_id = $config->get('latipay2_order_status_id');

$payment_method = $_POST['payment_method'];
$status = $_POST['status'];
$currency = $_POST['currency'];
$amount = $_POST['amount'];
$merchant_order_id = $_POST['merchant_reference'];

$signature_string = $merchant_order_id . $payment_method . $status . $currency . $amount;
$signature = hash_hmac('sha256', $signature_string, $api_key);
if ($signature == $_POST['signature']) {

    $order_id = substr($merchant_order_id, 0, strripos($merchant_order_id, '_'));
    $sql = $db->query("SELECT * FROM `" . DB_PREFIX . "order` WHERE order_id = '" . $order_id . "' LIMIT 1 ");
    if (!$sql->num_rows) {
        die('No Order ID');
    }

    if ($status == "paid") {
        $db->query("UPDATE `" . DB_PREFIX . "order` SET order_status_id = '" . $order_status_id . "' WHERE order_id = '" . $order_id . "' ");

        //send email
        $url = HTTP_SERVER . "index.php?route=payment/latipay2/callback";
        $post_data = array(
            "order_id" => $order_id,
            "order_status_id" => $order_status_id,
            "latipay_order_id" => isset($_POST['order_id']) ? $_POST['order_id'] : '',
        );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $output = curl_exec($ch);
        curl_close($ch);

        die('sent');
    } else {
        die('error status');
    }
} else {
    die('access denied');
}


text:
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Runtime.Serialization;

namespace GameLogic.GameGenerator
{
    using System;
    using OpenTK;
    using System.Drawing;
    using System.IO;
    using Models;
    using System.Xml;

    public class Item
    {
        public int data;

    }
  public class Level
    {
        private Block[,] grid;
        private string fileName;
        public Point playerStartPos;

        public Block this[int x, int y]
        {
            get
            {
                return grid[x, y];
            }
            set
            {
                grid[x, y] = value;

            }
        }

        public string FileName
        {
            get
            {
                return fileName;
            }
        }

        public int Width
        {
            get
            {
                return grid.GetLength(0);
            }
        }
        public int Height
        {
            get
            {
                return grid.GetLength(1);
            }
        }
        public static T ParseJsonObject<T>(string json)
            where T : class, new()
        {
            JObject jobject = JObject.Parse(json);
            return JsonConvert.DeserializeObject<T>(jobject.ToString());
        }
        public Level(string filePath)
        {
            try
            {

               // var jsreader = new JsonTextReader(new StringReader(filePath));
               // var json = (JObject) new JsonSerializer().Deserialize(jsreader);

                //JObject obj=JObject.Parse(File.ReadAllText(filePath));
                using (StreamReader file = new StreamReader(filePath))
                {
                    var str = file.ReadToEnd();
                    JObject search=JObject.Parse(str);
                    IList<JToken> result = search["layers"][0]["data"].Children().ToList();

                    Map root = JsonConvert.DeserializeObject<Map>(str);
                    int width = root.Width;
                    int height = root.Height;

                    grid = new Block[width, height];
                    this.fileName = filePath;
                    playerStartPos = new Point(1, 1);
                    IList<JToken> tileset = search["tilesets"].ToList();

                    Map myObj = JsonConvert.DeserializeObject<Map>(str);

                    Layer lyer = JsonConvert.DeserializeObject<Layer>(str);

                    int x = 0, y = 0;
                    for (int i = 0; i < result.Count; i++)
                    {
                        int gid = int.Parse(result[i].ToString());

                        switch (gid)
                        {
                            default:
                                grid[x, y] = new Block(BlockType.Empty, x, y);
                                break;
                            case 1:
                                grid[x, y] = new Block(BlockType.Ice_Block, x, y);
                                break;
                            case 2:
                                grid[x, y] = new Block(BlockType.Brick_Block, x, y);
                                break;
                            case 3:
                                grid[x, y] = new Block(BlockType.StoneBlocks, x, y);
                                break;
                            case 4:
                                grid[x, y] = new Block(BlockType.diamand, x, y);
                                break;
                            case 5:
                                grid[x, y] = new Block(BlockType.Paper, x, y);
                                break;
                        }
                        x++;
                        if (x >= width)
                        {
                            x = 0;
                            y++;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);

                //int width = 20;
                //int height = 20;
                //grid = new Block[width, height];
                //fileName = "none";

                //playerStartPos = new Point(1, 1);

                //for (int x = 0; x < width; x++)
                //{
                //    for (int y = 0; y < height; y++)
                //    {
                //        if (x == 0 || y == 0 || x == width - 1 || y == height - 1)
                //        {
                //            grid[x, y] = new Block(BlockType.Brick_Block, x, y);

                //        }
                //        else
                //        {
                //            grid[x, y] = new Block(BlockType.Empty, x, y);

                //        }
                //    }
                //}
            }
        }

        public Level(int width, int height)
        {
            grid = new Block[width, height];
            fileName = "none";

            playerStartPos = new Point(1, 1);

            for (int x = 0; x< width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    if (x == 0 || y == 0 || x == width - 1 || y == height - 1)
                    {
                        grid[x, y] = new Block(BlockType.Brick_Block, x, y);

                    }
                    else
                    {
                        grid[x, y] = new Block(BlockType.Empty, x, y);

                    }
                }
            }

        }
    }

    public enum BlockType
    {
        Ice_Block,
        Brick_Block,
        StoneBlocks,
        diamand,
        Paper,
        Empty
    }

    public struct  Block
    {
        private BlockType type;
        private int posX, posY;
        private bool brickBlock, diamond, paper, stoneblock, ice_Block,empty;

        public BlockType Type
        {
            get
            {
                return type;
            }
        }

        public int X
        {
            get { return posX; }
        }

        public int Y
        {
            get { return posY;}
        }

        public bool IsBrickBlock
        {
            get
            {
                return brickBlock;
            }
        }

        public bool IsDiamond
        {
            get
            {
                return diamond;
            }
        }

        public bool IsPaper
        {
            get
            {
                return paper;
            }
        }

        public bool IsStoneBlock
        {
            get
            {
                return stoneblock;
            }
        }

        public bool IsIceBlock
        {
            get { return ice_Block; }
        }

        public bool isEmpty
        {
            get
            {
                return empty;
            }
        }

        public Block(BlockType type, int x, int y)
        {
            this.posX = x;
            this.posY = y;
            this.type = type;
            this.brickBlock = false;
            this.diamond = false;
            this.paper = false;
            this.stoneblock = false;
            this.ice_Block = false;
            this.empty = false;
            switch (type)
            {
                    case BlockType.Brick_Block:
                    brickBlock = true;
                    break;
                    case BlockType.Ice_Block:
                    ice_Block = true;
                    break;
                    case BlockType.Paper:
                    paper = true;
                    break;
                    case BlockType.StoneBlocks:
                    stoneblock = true;
                    break;
                    case BlockType.diamand:
                    diamond = true;
                    break;
                    case BlockType.Empty:
                    empty = true;
                    break;
                default:
                    break;
            }
        }
    }
}


text:
layout: post_layout
title: "Automatically create Jekyll posts with Thor"
avatar: /images/posts/jekyll_thor/thor_hammer.png
category: Programming
tags: [Programming - Jekyll - Thor - Ruby - Automation]
identifier: posts
---

**The Problem**

Jekyll is a simple, blog-aware, static site generator so it tracks posts and publication dates to produce the static content.

*The naming convention for post files is important, and must follow the
format:
`YEAR-MONTH-DAY-title.MARKUP`*

So each time you create a new post you have to follow these convention.
In addition to this every post has a `YAML front matter block` which is processed by Jekyll and contains predefined and custom variables.

Hence we have to automate these two things:

1. the creation of the file with the correct name
2. the *YAML front matter block*

**The solution**

I chose [Thor](https://github.com/erikhuda/thor) for this job as it is a very simple but powerful tool.

In my research I have rejected two other solutions

- a simple Rake task
- a simple [ruby script](https://gist.github.com/rpk0/7ef3ba85bff2fbbba342) with [Slop Gem](https://github.com/leejarvis/slop) (lightweight option parsing)

if you have a Gemfile add the following gems

```
gem 'thor'
gem 'stringex'
```

and run `bundle isntall`

if you do not have a gemfile just (`sudo if required`) install the two gems

```
gem install thor
gem install stringex
```

Now create a `post.thor` file in the root directory of the your Jekyll project with the following contents:

```ruby
require "stringex"
require "thor"

class Post < Thor
  desc "new TITLE", "Create a new post"

  method_option :date, aliases: "-d",
                       default: Time.now.strftime('%Y-%m-%d'),
                       desc: "Change the current time to the value provided"
  method_option :category, aliases: "-c",
                           default: "General",
                           type: :string,
                           desc: "Add the post's category, default 'General'"
  method_option :tags, aliases: "-t",
                       type: :string,
                       desc: "Add post tags, comma-separated string"

  def new(*title)
    title = title.join(" ")
    category = options[:category]
    # fomat tags in the way you want them to be displayed
    tags = options[:tags].gsub(/\W+/, " - ") if options[:tags]
    filename = "_posts/#{category.downcase}/#{options[:date]}-#{title.to_url}.md"

    if File.exist?(filename)
      abort("#{filename} already exists!")
    end

    puts "Creating new post: #{filename}"
    open(filename, 'w') do |post|
      post.puts "---"
      post.puts "layout: post_layout"
      post.puts "title: \"#{title.gsub(/&/,'&')}\""
      post.puts "avatar:"
      post.puts "category: #{category}"
      post.puts "tags: #{tags}"
      post.puts "path: posts"
      post.puts "---"
    end

    # opens the md file in your default editor
    system ("#{ENV['EDITOR']} #{filename}")

    puts "New post created: #{filename}"
  end
end
```

Once you have this created, you can run `thor list` from the command line and you should see the following output:

```
post
----
thor post:new TITLE  # Create a new post
```

In this example, the `method_options` have been supplied with several parameters.
The first parameter is the full name of the option, this is translated into a -- option on the command line.
The second is the alias option to provide a short version of this option.
The last one is the `desc` parameter which adds a description for the option,when printing out the full usage for a command.
for example:

If you run `thor post:help new` you should see the following output:

```
Usage:
  thor post:new TITLE

Options:
  -d, [--date=DATE]          # Change the current time to the value provided
                             # Default: 2014-10-16 *the current date*
  -c, [--category=CATEGORY]  # Add the post's category
                             # Default: General
  -t, [--tags=TAGS]          # Add post tags, comma-separated string

Create a new post
```

So that command to generate this post was:

```
thor post:new Automatically create jekyll posts with Thor -c Programming -t "Programming, Jekyll, Thor, Ruby, Automation"
```

which creates the file `_posts/2014-10-16-automatically-create-jekyll-posts-with-thor.md` and opens it in your default editor (`printenv | grep EDITOR`).

**Optional**

You can create an executable file in the current directory and start the simple CLI with a call to `Post.start(ARGV)`

```
#!/usr/bin/env ruby
require './post'

trap('SIGINT') do
  puts "\nInterrupt received exiting..."
  exit
end

Post.start(ARGV)
```

In this configuration, which can be useful in some cases
you have to change the main script to `.rb`

To execute the post task you have to run
`ruby create_post new TITLE, [Options]`

**Future work**

In a future post I'll be writing how I have automated the photo essay posts generation which are not markdown files but complex HTML files.

<sup>*references: https://jonasforsberg.se/2012/12/28/create-jekyll-posts-from-the-command-line*</sup>


text:
001
032
033    package com.jeantessier.dependency;
034
035    import java.util.*;
036
037    public abstract class ClosureLayerSelector extends ClosureSelector {
038        private Node currentNode;
039
040        private Collection<? extends Node> coverage;
041
042        public ClosureLayerSelector() {
043            super();
044        }
045
046        public ClosureLayerSelector(NodeFactory factory, Collection<? extends Node> coverage) {
047            super(factory);
048
049            setCoverage(coverage);
050        }
051
052        public void reset() {
053            super.reset();
054
055            currentNode = null;
056        }
057
058        public Collection<? extends Node> getCoverage() {
059            return coverage;
060        }
061
062        public void setCoverage(Collection<? extends Node> coverage) {
063            this.coverage = coverage;
064        }
065
066        public void visitPackageNode(PackageNode node) {
067            currentNode = getFactory().createPackage(node.getName(), node.isConfirmed());
068        }
069
070        public void visitInboundPackageNode(PackageNode node) {
071            if (!getCoverage().contains(node)) {
072                getSelectedNodes().add(node);
073
074                Node copy = getFactory().createPackage(node.getName(), node.isConfirmed());
075                getCopiedNodes().add(copy);
076                copy.addDependency(currentNode);
077            }
078        }
079
080        public void visitOutboundPackageNode(PackageNode node) {
081            if (!getCoverage().contains(node)) {
082                getSelectedNodes().add(node);
083
084                Node copy = getFactory().createPackage(node.getName(), node.isConfirmed());
085                getCopiedNodes().add(copy);
086                currentNode.addDependency(copy);
087            }
088        }
089
090        public void visitClassNode(ClassNode node) {
091            currentNode = getFactory().createClass(node.getName(), node.isConfirmed());
092        }
093
094        public void visitInboundClassNode(ClassNode node) {
095            if (!getCoverage().contains(node)) {
096                getSelectedNodes().add(node);
097
098                Node copy = getFactory().createClass(node.getName(), node.isConfirmed());
099                getCopiedNodes().add(copy);
100                copy.addDependency(currentNode);
101            }
102        }
103
104        public void visitOutboundClassNode(ClassNode node) {
105            if (!getCoverage().contains(node)) {
106                getSelectedNodes().add(node);
107
108                Node copy = getFactory().createClass(node.getName(), node.isConfirmed());
109                getCopiedNodes().add(copy);
110                currentNode.addDependency(copy);
111            }
112        }
113
114        public void visitFeatureNode(FeatureNode node) {
115            currentNode = getFactory().createFeature(node.getName(), node.isConfirmed());
116        }
117
118        public void visitInboundFeatureNode(FeatureNode node) {
119            if (!getCoverage().contains(node)) {
120                getSelectedNodes().add(node);
121
122                Node copy = getFactory().createFeature(node.getName(), node.isConfirmed());
123                getCopiedNodes().add(copy);
124                copy.addDependency(currentNode);
125            }
126        }
127
128        public void visitOutboundFeatureNode(FeatureNode node) {
129            if (!getCoverage().contains(node)) {
130                getSelectedNodes().add(node);
131
132                Node copy = getFactory().createFeature(node.getName(), node.isConfirmed());
133                getCopiedNodes().add(copy);
134                currentNode.addDependency(copy);
135            }
136        }
137    }


text:
Version 0.8 (unreleased)
-----------

Version 0.7
-----------
- [Fix]		Fixed check for PHP startup-errors

Version 0.6
-----------

- [Fix]		Also check 4er and 7er PHP versions against updates

Version 0.5
-----------

- [Enh]		Enhance documentation
- [Enh]		Add to Icinga/Nagios Exchange

Version 0.4
-----------

- [Enh]		Performance data: min+max values
- [Enh]		Performance data: warn+crit thresholds
- [Enh]		Added ability to check for blacklisted PHP modules
- [Fix]		Performance data: fixed error and warning count

Version 0.3
-----------

- [Enh]		Always display current PHP version in nagios output
- [Enh]		Choose severity level for all checks (error or warning)
- [Enh]		Remote checks now also check for wget, curl or fetch and only require one of them

Version 0.2
-----------

- [Enh]		Warn on PHP startup errors (instead of error) by default if no severity is specified
- [Enh]		Check against PHP startup errors by default (without any arguments)
- [Enh]		Check against compiled modules
- [Enh]		Check for php.ini misconfiguration
- [Enh]		Performance data

Version 0.1
-----------

- [Enh]		Check for PHP startup Errors


text:
    <upload-directive target-url="'rest/v1/plugins'" drag-and-drop-message="'PLUGINS.DRAG_DROP_UPLOAD'" button-message="'PLUGINS.UPLOAD'"
                      upload-success-callback='search()' />

      <form role="search" ng-submit="search()">

          <input type="text" class="form-control" placeholder="..." ng-model="query">
            <button type="submit" class="btn btn-default" data-loading-text="Loading...">

            </button>

      </form>

              {{ 'COMMON.ID' | translate}}
              {{ 'COMMON.VERSION' | translate}}
              {{ 'COMMON.NAME' | translate}}
              {{ 'COMMON.DESCRIPTION' | translate}}
              {{ 'PLUGINS.BEANS' | translate}}

              {{plugin.descriptor.id}}
              {{plugin.descriptor.version}}
              {{plugin.descriptor.name}}
              {{plugin.description}}

                     {{component.name}}

                  <delete-confirm id="delete-plugin_{{plugin.id}}" func="remove(plugin.id)" position="left" bssize="btn-sm" fastyle="fa-trash-o">
                  </delete-confirm>

        <pagination-directive pagination-info="searchService.pagination" />


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.widget;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ListView;

import org.chromium.base.VisibleForTesting;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.compositor.layouts.Layout;
import org.chromium.chrome.browser.compositor.layouts.LayoutRenderHost;
import org.chromium.chrome.browser.compositor.layouts.LayoutUpdateHost;
import org.chromium.chrome.browser.compositor.layouts.content.TabContentManager;
import org.chromium.chrome.browser.compositor.layouts.eventfilter.BlackHoleEventFilter;
import org.chromium.chrome.browser.compositor.layouts.eventfilter.EventFilter;
import org.chromium.chrome.browser.compositor.scene_layer.SceneLayer;
import org.chromium.chrome.browser.tabmodel.TabModel;
import org.chromium.chrome.browser.tabmodel.TabModelSelector;
import org.chromium.chrome.browser.tabmodel.TabModelUtils;
import org.chromium.chrome.browser.util.FeatureUtilities;
import org.chromium.chrome.browser.widget.accessibility.AccessibilityTabModelAdapter.AccessibilityTabModelAdapterListener;
import org.chromium.chrome.browser.widget.accessibility.AccessibilityTabModelWrapper;

/**
 * A {@link Layout} that shows the tabs as two {@link ListView}s, one for each {@link TabModel} to
 * represent.
 */
public class OverviewListLayout extends Layout implements AccessibilityTabModelAdapterListener {
    private AccessibilityTabModelWrapper mTabModelWrapper;
    private final float mDpToPx;
    private final BlackHoleEventFilter mBlackHoleEventFilter;
    private final SceneLayer mSceneLayer;

    public OverviewListLayout(
            Context context, LayoutUpdateHost updateHost, LayoutRenderHost renderHost) {
        super(context, updateHost, renderHost);
        mBlackHoleEventFilter = new BlackHoleEventFilter(context);
        mDpToPx = context.getResources().getDisplayMetrics().density;
        mSceneLayer = new SceneLayer();
    }

    @Override
    public void attachViews(ViewGroup container) {
        if (mTabModelWrapper == null) {
            mTabModelWrapper =
                    (AccessibilityTabModelWrapper) LayoutInflater.from(container.getContext())
                            .inflate(R.layout.accessibility_tab_switcher, null);
            mTabModelWrapper.setup(this);
            mTabModelWrapper.setTabModelSelector(mTabModelSelector);
            adjustForFullscreen();
        }

        if (container == null || mTabModelWrapper.getParent() != null) return;

        ((ViewGroup) container.findViewById(R.id.overview_list_layout_holder))
                .addView(mTabModelWrapper);
    }

    @Override
    public ViewportMode getViewportMode() {
        return ViewportMode.ALWAYS_FULLSCREEN;
    }

    @Override
    protected void notifySizeChanged(float width, float height, int orientation) {
        adjustForFullscreen();
    }

    private void adjustForFullscreen() {
        if (mTabModelWrapper == null) return;
        FrameLayout.LayoutParams params =
                (FrameLayout.LayoutParams) mTabModelWrapper.getLayoutParams();
        if (params == null) return;

        int margin = (int) ((getHeight() - getHeightMinusBrowserControls()) * mDpToPx);
        if (FeatureUtilities.isChromeHomeEnabled()) {
            params.bottomMargin = margin;
        } else {
            params.topMargin = margin;
        }
        mTabModelWrapper.setLayoutParams(params);
    }

    @Override
    public boolean handlesTabClosing() {
        return true;
    }

    @Override
    public boolean handlesTabCreating() {
        return true;
    }

    @Override
    public boolean handlesCloseAll() {
        return true;
    }

    @Override
    public void onTabCreating(int sourceTabId) {
        super.onTabCreating(sourceTabId);
        startHiding(sourceTabId, false);
    }

    @Override
    public void onTabCreated(long time, int tabId, int tabIndex, int sourceTabId,
            boolean newIsIncognito, boolean background, float originX, float originY) {
        super.onTabCreated(
                time, tabId, tabIndex, sourceTabId, newIsIncognito, background, originX, originY);
        startHiding(tabId, false);
    }

    @Override
    public void onTabRestored(long time, int tabId) {
        super.onTabRestored(time, tabId);
        // Call show() so that new tabs and potentially the toggle between incognito and normal
        // lists are created.
        // TODO(twellington): add animation for showing the restored tab.
        show(time, false);
    }

    @Override
    public void onTabModelSwitched(boolean incognito) {
        super.onTabModelSwitched(incognito);
        if (mTabModelWrapper == null) return;
        mTabModelWrapper.setStateBasedOnModel();
    }

    @Override
    public void show(long time, boolean animate) {
        super.show(time, animate);
        if (mTabModelWrapper == null) return;
        mTabModelWrapper.setStateBasedOnModel();

        doneShowing();
    }

    @Override
    public void startHiding(int nextId, boolean hintAtTabSelection) {
        super.startHiding(nextId, hintAtTabSelection);

        doneHiding();
    }

    @Override
    public void detachViews() {
        if (mTabModelSelector != null) mTabModelSelector.commitAllTabClosures();
        if (mTabModelWrapper != null) {
            ViewGroup parent = (ViewGroup) mTabModelWrapper.getParent();
            if (parent != null) parent.removeView(mTabModelWrapper);
        }
    }

    @Override
    public void setTabModelSelector(
            TabModelSelector tabModelSelector, TabContentManager tabContentManager) {
        super.setTabModelSelector(tabModelSelector, tabContentManager);

        if (mTabModelWrapper == null) return;
        mTabModelWrapper.setTabModelSelector(tabModelSelector);
    }

    @VisibleForTesting
    public ViewGroup getContainer() {
        return mTabModelWrapper;
    }

    @Override
    public void onTabsAllClosing(long time, boolean incognito) {
        super.onTabsAllClosing(time, incognito);

        TabModel model = mTabModelSelector.getModel(incognito);
        while (model.getCount() > 0) TabModelUtils.closeTabByIndex(model, 0);

        if (incognito) {
            mTabModelSelector.selectModel(!incognito);
        }
        if (mTabModelWrapper == null) return;
        mTabModelWrapper.setStateBasedOnModel();
    }

    @Override
    public void onTabClosureCommitted(long time, int tabId, boolean incognito) {
        mTabModelWrapper.setStateBasedOnModel();
    }

    @Override
    public void showTab(int tabId) {
        onTabSelecting(0, tabId);
    }

    @Override
    protected EventFilter getEventFilter() {
        return mBlackHoleEventFilter;
    }

    @Override
    protected SceneLayer getSceneLayer() {
        return mSceneLayer;
    }
}


text:
ACCEPTED

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

#### Published in
Mycotaxon 67: 43 (1998)

#### Original name
Uredo flosculorum DC., 1815

### Remarks
null


text:
package com.github.ckwen.je.spring.boot.multi.datasource.model.p;

import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {

}


text:
import type {Placement, Middleware} from '../types';
import {getOppositePlacement} from '../utils/getOppositePlacement';
import {getSide} from '../utils/getSide';
import {
  detectOverflow,
  Options as DetectOverflowOptions,
} from '../detectOverflow';
import {getAlignmentSides} from '../utils/getAlignmentSides';
import {getExpandedPlacements} from '../utils/getExpandedPlacements';

export interface Options {
  /**
   * The axis that runs along the side of the floating element.
   * @default true
   */
  mainAxis: boolean;
  /**
   * The axis that runs along the alignment of the floating element.
   * @default true
   */
  crossAxis: boolean;
  /**
   * Placements to try if the preferred `placement` does not fit.
   * @default [oppositePlacement] (computed)
   */
  fallbackPlacements: Array<Placement>;
  /**
   * What strategy to use when no placements fit.
   * @default 'bestFit'
   */
  fallbackStrategy: 'bestFit' | 'initialPlacement';
  /**
   * Whether to flip to placements with the opposite alignment if they fit
   * better.
   * @default true
   */
  flipAlignment: boolean;
}

/**
 * Changes the placement of the floating element to one that will fit if the
 * initially specified `placement` does not.
 * @see https://floating-ui.com/docs/flip
 */
export const flip = (
  options: Partial<Options & DetectOverflowOptions> = {}
): Middleware => ({
  name: 'flip',
  options,
  async fn(middlewareArguments) {
    const {
      placement,
      middlewareData,
      rects,
      initialPlacement,
      platform,
      elements,
    } = middlewareArguments;

    const {
      mainAxis: checkMainAxis = true,
      crossAxis: checkCrossAxis = true,
      fallbackPlacements: specifiedFallbackPlacements,
      fallbackStrategy = 'bestFit',
      flipAlignment = true,
      ...detectOverflowOptions
    } = options;

    const side = getSide(placement);
    const isBasePlacement = side === initialPlacement;

    const fallbackPlacements =
      specifiedFallbackPlacements ||
      (isBasePlacement || !flipAlignment
        ? [getOppositePlacement(initialPlacement)]
        : getExpandedPlacements(initialPlacement));

    const placements = [initialPlacement, ...fallbackPlacements];

    const overflow = await detectOverflow(
      middlewareArguments,
      detectOverflowOptions
    );

    const overflows = [];
    let overflowsData = middlewareData.flip?.overflows || [];

    if (checkMainAxis) {
      overflows.push(overflow[side]);
    }

    if (checkCrossAxis) {
      const {main, cross} = getAlignmentSides(
        placement,
        rects,
        await platform.isRTL?.(elements.floating)
      );
      overflows.push(overflow[main], overflow[cross]);
    }

    overflowsData = [...overflowsData, {placement, overflows}];

    // One or more sides is overflowing
    if (!overflows.every((side) => side <= 0)) {
      const nextIndex = (middlewareData.flip?.index ?? 0) + 1;
      const nextPlacement = placements[nextIndex];

      if (nextPlacement) {
        // Try next placement and re-run the lifecycle
        return {
          data: {
            index: nextIndex,
            overflows: overflowsData,
          },
          reset: {
            placement: nextPlacement,
          },
        };
      }

      let resetPlacement: Placement = 'bottom';
      switch (fallbackStrategy) {
        case 'bestFit': {
          const placement = overflowsData
            .map(
              (d) =>
                [
                  d,
                  d.overflows
                    .filter((overflow) => overflow > 0)
                    .reduce((acc, overflow) => acc + overflow, 0),
                ] as const
            )
            .sort((a, b) => a[1] - b[1])[0]?.[0].placement;
          if (placement) {
            resetPlacement = placement;
          }
          break;
        }
        case 'initialPlacement':
          resetPlacement = initialPlacement;
          break;
        default:
      }

      if (placement !== resetPlacement) {
        return {
          reset: {
            placement: resetPlacement,
          },
        };
      }
    }

    return {};
  },
});


text:
'use strict';

/**
 * @ngdoc capitalize
 * @name ngCkanApp.filter:formats
 * @function
 * @description
 * # capitalize
 * Filter in the ngCkanApp.
 */
angular.module('ngCkanApp')
  .filter('capitalize', function () {
    return function(input) {
      /* istanbul ignore else */
      if ( !!input ) {
        return input.charAt(0).toUpperCase() + input.substr(1).toLowerCase();
      } else {
        return '';
      }
    };
  });


text:
package main

import (
	"github.com/BurntSushi/toml"
	"io/ioutil"
	"log"
	"os"
)

type Config struct {
	GyazoId       string
	HomeDir       string
	HistDir       string
	IdFilename    string
	Endpoint      string
	BasicUser     string
	BasicPassword string
}

type Toml struct {
	Profile []Profiles `toml:"profile"`
}

type Profiles struct {
	BasicUser     string `toml:"basicUser"`
	BasicPassword string `toml:"basicPassword"`
	Endpoint      string `toml:"endpoint"`
	Name          string `toml:"name"`
}

func NewGyazo() *Gyazo {
	var g Gyazo
	g.Config.IdFilename = "/.gyazo.id"

	g.Config.createHomeDir()
	g.Config.createHistDir()
	g.Config.getGyazoId()

	return &g
}

func (c *Config) createHomeDir() {
	//home directory
	c.HomeDir = os.Getenv("HOME") + "/.gyagoyle"
	err := os.MkdirAll(c.HomeDir, 0777)
	if err != nil {
		log.Fatalf("Make a home directory is failed: %v", err)
	}

	return
}

func (c *Config) createHistDir() {
	//history directory
	c.HistDir = c.HomeDir + "/history"
	err := os.MkdirAll(c.HistDir, 0777)
	if err != nil {
		log.Fatalf("Make a history directory is failed: %v", err)
	}

	return
}

func (c *Config) getGyazoId() {
	filePath := c.HomeDir + c.IdFilename
	if isExist(filePath) == false {
	}

	id, err := ioutil.ReadFile(filePath)
	if err != nil {
		//The ID is blank is no problem
		return
	}

	c.GyazoId = string(id)

	return
}

func isExist(filename string) bool {
	_, err := os.Stat(filename)
	return err == nil
}

func (c *Config) SetGyazoId(id string) {
	if c.GyazoId == "" {
		ioutil.WriteFile(c.HomeDir+c.IdFilename, []byte(id), 0644)
	}

	return
}

func (c *Config) GetToml(profile string) {
	filePath := c.HomeDir + "/config.toml"
	if isExist(filePath) == false {
		log.Fatalf("config.toml not found:")
	}

	var t Toml

	_, err := toml.DecodeFile(filePath, &t)
	if err != nil {
		log.Fatalf("config.toml read error:", err)
	}

	for _, v := range t.Profile {
		if v.Name == profile {
			c.BasicUser = v.BasicUser
			c.BasicPassword = v.BasicPassword
			c.Endpoint = v.Endpoint
		}
	}

}


text:
import axios from 'axios'

export default () => {
  return axios.create({
    baseURL: 'http://localhost:8081'
  })
}


text:
#ifndef SPROKIT_PIPELINE_SCHEDULER_REGISTRY_EXCEPTION_H
#define SPROKIT_PIPELINE_SCHEDULER_REGISTRY_EXCEPTION_H

#include "pipeline-config.h"

#include "scheduler_registry.h"
#include "types.h"

/**
 * \file scheduler_registry_exception.h
 *
 * \brief Header for exceptions used within the \link sprokit::scheduler_registry scheduler registry\endlink.
 */

namespace sprokit
{

/**
 * \class scheduler_registry_exception scheduler_registry_exception.h <sprokit/pipeline/scheduler_registry_exception.h>
 *
 * \brief The base class for all exceptions thrown from a \ref scheduler_registry.
 *
 * \ingroup exceptions
 */
class SPROKIT_PIPELINE_EXPORT scheduler_registry_exception
  : public pipeline_exception
{
  public:
    /**
     * \brief Constructor.
     */
    scheduler_registry_exception() throw();
    /**
     * \brief Destructor.
     */
    virtual ~scheduler_registry_exception() throw();
};

/**
 * \class null_scheduler_ctor_exception scheduler_registry_exception.h <sprokit/pipeline/scheduler_registry_exception.h>
 *
 * \brief Thrown when a \c NULL constructor function is added to the registry.
 *
 * \ingroup exceptions
 */
class SPROKIT_PIPELINE_EXPORT null_scheduler_ctor_exception
  : public scheduler_registry_exception
{
  public:
    /**
     * \brief Constructor.
     *
     * \param type The type the ctor is for.
     */
    null_scheduler_ctor_exception(scheduler_registry::type_t const& type) throw();
    /**
     * \brief Destructor.
     */
    ~null_scheduler_ctor_exception() throw();

    /// The type that was passed a \c NULL constructor.
    scheduler_registry::type_t const m_type;
};

/**
 * \class null_scheduler_registry_config_exception scheduler_registry_exception.h <sprokit/pipeline/scheduler_registry_exception.h>
 *
 * \brief Thrown when a \c NULL \ref config is passed to a scheduler.
 *
 * \ingroup exceptions
 */
class SPROKIT_PIPELINE_EXPORT null_scheduler_registry_config_exception
  : public scheduler_registry_exception
{
  public:
    /**
     * \brief Constructor.
     */
    null_scheduler_registry_config_exception() throw();
    /**
     * \brief Destructor.
     */
    ~null_scheduler_registry_config_exception() throw();
};

/**
 * \class null_scheduler_registry_pipeline_exception scheduler_registry_exception.h <sprokit/pipeline/scheduler_registry_exception.h>
 *
 * \brief Thrown when a \c NULL \link sprokit::pipeline\endlink is passed to a scheduler.
 *
 * \ingroup exceptions
 */
class SPROKIT_PIPELINE_EXPORT null_scheduler_registry_pipeline_exception
  : public scheduler_registry_exception
{
  public:
    /**
     * \brief Constructor.
     */
    null_scheduler_registry_pipeline_exception() throw();
    /**
     * \brief Destructor.
     */
    ~null_scheduler_registry_pipeline_exception() throw();
};

/**
 * \class no_such_scheduler_type_exception scheduler_registry_exception.h <sprokit/pipeline/scheduler_registry_exception.h>
 *
 * \brief Thrown when a type is requested, but does not exist in the registry.
 *
 * \ingroup exceptions
 */
class SPROKIT_PIPELINE_EXPORT no_such_scheduler_type_exception
  : public scheduler_registry_exception
{
  public:
    /**
     * \brief Constructor.
     *
     * \param type The type requested.
     */
    no_such_scheduler_type_exception(scheduler_registry::type_t const& type) throw();
    /**
     * \brief Destructor.
     */
    ~no_such_scheduler_type_exception() throw();

    /// The type that was requested from the \link scheduler_registry scheduler registry\endlink.
    scheduler_registry::type_t const m_type;
};

/**
 * \class scheduler_type_already_exists_exception scheduler_registry_exception.h <sprokit/pipeline/scheduler_registry_exception.h>
 *
 * \brief Thrown when a type is added, but does already exists in the registry.
 *
 * \ingroup exceptions
 */
class SPROKIT_PIPELINE_EXPORT scheduler_type_already_exists_exception
  : public scheduler_registry_exception
{
  public:
    /**
     * \brief Constructor.
     *
     * \param type The type requested.
     */
    scheduler_type_already_exists_exception(scheduler_registry::type_t const& type) throw();
    /**
     * \brief Destructor.
     */
    ~scheduler_type_already_exists_exception() throw();

    /// The type that was requested from the \link scheduler_registry scheduler registry\endlink.
    scheduler_registry::type_t const m_type;
};

}

#endif // SPROKIT_PIPELINE_SCHEDULER_REGISTRY_EXCEPTION_H


text:
package com.kjetland.jackson.jsonSchema.testData.polymorphism4;

public class Child41 extends Parent4 {

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }

        return o != null && getClass() == o.getClass();
    }
}


text:
using System.Collections.Generic;
using Ldme.Models.Dtos;
using Ldme.Models.Models;

namespace Ldme.Abstract.Interfaces
{
    public interface IQuestRepository
    {
        void SaveChanges();
        void DeleteQuest(int id);
        void CreateQuest(Quest quest);
        void CompleteQuest(int id, QuestCompletionDto completionData);

        Quest GetQuest(int id);

        IEnumerable<Quest> GetCreatedBy(int playerId);
        IEnumerable<Quest> GetOwnedBy(int playerId);
    }
}


text:
sudo add-apt-repository ppa:webupd8team/y-ppa-manager
sudo apt-get update
sudo apt-get install y-ppa-manager


text:
require_relative 'test_base'

require 'dl/struct'

module DL
  class TestCUnionEntity < TestBase
    def test_class_size
      size = CUnionEntity.size([TYPE_DOUBLE, TYPE_CHAR])

      assert_equal SIZEOF_DOUBLE, size
    end

    def test_class_size_with_count
      size = CUnionEntity.size([[TYPE_DOUBLE, 2], [TYPE_CHAR, 20]])

      assert_equal SIZEOF_CHAR * 20, size
    end

    def test_set_ctypes
      union = CUnionEntity.malloc [TYPE_INT, TYPE_LONG]
      union.assign_names %w[int long]

      # this test is roundabout because the stored ctypes are not accessible
      union['long'] = 1
      assert_equal 1, union['long']

      union['int'] = 1
      assert_equal 1, union['int']
    end
  end
end


text:
<!doctype html>

    <meta charset="UTF-8">
    <title>JavaScript Event Model - Capturing and Bubbling Events</title>
    <link rel="stylesheet" href="styles/styles.css" />

                    Click me!


text:
"""Routines for accessing fuel datasets."""
import numpy as np
import uuid
from fuel.datasets.hdf5 import H5PYDataset
from fuel.utils import find_in_data_path
from fuel.transformers.defaults import uint8_pixels_to_floatX
from fuel.schemes import SequentialExampleScheme, ShuffledScheme, SequentialScheme
from fuel.streams import DataStream
from fuel.transformers import AgnosticSourcewiseTransformer

# hack: added return_length. maybe refactor
def get_dataset_iterator(dataset, split, include_features=True, include_targets=False, unit_scale=True, label_transforms=False, return_length=False):
    """Get iterator for dataset, split, targets (labels) and scaling (from 255 to 1.0)"""
    sources = []
    sources = sources + ['features'] if include_features else sources
    sources = sources + ['targets'] if include_targets else sources
    if split == "all":
        splits = ('train', 'valid', 'test')
    elif split == "nontrain":
        splits = ('valid', 'test')
    else:
        splits = (split,)

    dataset_fname = find_in_data_path("{}.hdf5".format(dataset))
    h5_dataset = H5PYDataset(dataset_fname, which_sets=splits,
                             sources=sources)
    if unit_scale:
        h5_dataset.default_transformers = uint8_pixels_to_floatX(('features',))

    datastream = DataStream.default_stream(
        dataset=h5_dataset,
        iteration_scheme=SequentialExampleScheme(h5_dataset.num_examples))

    if label_transforms:
        # TODO: maybe refactor this common bit with get_custom_streams below
        datastream = AddLabelUncertainty(datastream,
                                         chance=0,
                                         which_sources=('targets',))

        datastream = RandomLabelStrip(datastream,
                                         chance=0,
                                         which_sources=('targets',))

        # HACK: allow variable stretch
        datastream = StretchLabels(datastream,
                                         length=128,
                                         which_sources=('targets',))

    it = datastream.get_epoch_iterator()
    if return_length:
        return it, h5_dataset.num_examples
    else:
        return it

# get images from dataset. numanchors=None to get all. image_size only needed for color conversion
def get_anchor_images(dataset, split, offset=0, stepsize=1, numanchors=150, allowed=None, prohibited=None, image_size=64, color_convert=False, include_targets=True, unit_scale=True):
    """Get images in np array with filters"""
    it = get_dataset_iterator(dataset, split, include_targets=include_targets, unit_scale=unit_scale)

    anchors = []
    for i in range(offset):
        cur = it.next()
    try:
        while numanchors == None or len(anchors) < numanchors:
            cur = it.next()
            for s in range(stepsize-1):
                it.next()
            candidate_passes = True
            if allowed:
                for p in allowed:
                    if(cur[1][p] != 1):
                        candidate_passes = False
            if prohibited:
                for p in prohibited:
                    if(cur[1][p] != 0):
                        candidate_passes = False

            if candidate_passes:
                if color_convert:
                    anchors.append(np.tile(cur[0].reshape(1, image_size, image_size), (3, 1, 1)))
                else:
                    anchors.append(cur[0])
    except StopIteration:
        if numanchors is not None:
            print("Warning: only read {} of {} requested anchor images".format(len(anchors), numanchors))

    return np.array(anchors)

# TODO / HACK: refactor with above
def get_anchor_labels(dataset, split, offset=0, stepsize=1, numanchors=150, unit_scale=True):
    """Get images in np array with filters"""
    it = get_dataset_iterator(dataset, split, include_features=False, include_targets=True, unit_scale=unit_scale, label_transforms=True)

    anchors = []
    for i in range(offset):
        cur = it.next()
    try:
        while numanchors == None or len(anchors) < numanchors:
            cur = it.next()
            for s in range(stepsize-1):
                it.next()
            candidate_passes = True

            if candidate_passes:
                anchors.append(cur[0])
    except StopIteration:
        if numanchors is not None:
            print("Warning: only read {} of {} requested anchor images".format(len(anchors), numanchors))

    return np.array(anchors)

class Colorize(AgnosticSourcewiseTransformer):
    """Triples a grayscale image to convert it to color.

    This transformer can be used to adapt a one one-channel
    grayscale image to a network that expects three color
    channels by simply replictaing the single channel
    three times.
    """
    def __init__(self, data_stream, **kwargs):
        super(Colorize, self).__init__(
             data_stream=data_stream,
             produces_examples=data_stream.produces_examples,
             **kwargs)

    def transform_any_source(self, source, _):
        iters, dim, height, width = source.shape
        return np.tile(source.reshape(iters*dim, 1, 64, 64), (1, 3, 1, 1))

class Scrubber(AgnosticSourcewiseTransformer):
    """Used to whitelist selected labels for training.

    This transformer zeros out all but selected attribute
    labels for training. This allows custom classifiers to
    be built on a subset of available features

    Parameters
    ----------
    allowed : list of int
        Whitelist of indexes to allow in training. For example,
        passing [4, 7] means only labels at positions 4 and 7
        will be used for training, and all others will be
        zeroed out.
    """
    def __init__(self, data_stream, allowed, **kwargs):
        super(Scrubber, self).__init__(
             data_stream=data_stream,
             produces_examples=data_stream.produces_examples,
             **kwargs)
        self.allowed = [0] * 40
        for a in allowed:
            self.allowed[a] = 1

    def transform_any_source(self, source, _):
        return [a*b for a, b in zip(self.allowed, source)]

class StretchLabels(AgnosticSourcewiseTransformer):
    """Used to stretch a set of vectors by zero-padding.

    This transformer appends zeros to a vector to get it
    to a predefined length.

    Parameters
    ----------
    length : int
        Target lenth of vector.
    """
    def __init__(self, data_stream, length=64, **kwargs):
        super(StretchLabels, self).__init__(
             data_stream=data_stream,
             produces_examples=data_stream.produces_examples,
             **kwargs)
        self.length = length

    def transform_any_source(self, source, _):
        final_flatten = False
        if(len(source.shape) == 1):
            final_flatten = True
            iters, dim = 1, source.shape[0]
            source = source.reshape((1, dim))
        else:
            iters, dim = source.shape
        newdim = self.length

        in_len = len(source[0])
        fixed = np.zeros((iters, newdim), dtype=np.uint8)
        fixed[:,:in_len] = source

        # print("IN/OUT: {}, {}".format(source[0], fixed[0]))

        if final_flatten:
            fixed = fixed.reshape((newdim,))
        return fixed

        # if len(source > 0):
        #     npad = self.length - len(source[0])
        #     return [np.pad(a, pad_width=(0, npad), mode='constant',
        #                    constant_values=0) for a in source]
        # else:
        #     return source

class RandomLabelOptionalSpreader(AgnosticSourcewiseTransformer):
    """Used to stretch a set of vectors making labels optional.

    Input is is clipped to a dim-64 vector, output is dim-128 vector.

    20% of time vector passes unchanged, but with 1s for top 64.
    20% of time vector passes completely zeroed out.
    10% of time vector passes with 1 label enabled, others zeroed.
    50% of time vector passes through with 2-64 labels enabled, others zeroed

    Parameters
    ----------
    config : []
        Placeholder to allow future configuration of behavior.
    """
    def __init__(self, data_stream, config=[20, 20, 10, 50], **kwargs):
        super(RandomLabelOptionalSpreader, self).__init__(
             data_stream=data_stream,
             produces_examples=data_stream.produces_examples,
             **kwargs)
        self.config = config

    def transform_any_source(self, source, _):
        if not len(source > 0):
            return source

        iters, dim = source.shape

        orig_source = source
        # first pad to 64 with 0s (if not already)
        npad = 64 - dim
        if npad > 0:
            source = [np.pad(a, pad_width=(0, npad), mode='constant',
                       constant_values=0) for a in source]
        # now pad to 128 with 1s
        npad = 64
        source = [np.pad(a, pad_width=(0, npad), mode='constant',
                   constant_values=1) for a in source]

        fixed = np.zeros((iters, 128), dtype=np.uint8)
        # now decimate probalisticly
        for i in range(iters):
            choice = np.random.uniform(0,100)
            if choice < self.config[0]:
                # if i == 0:
                #     print("KEEP")
                fixed[i] = source[i]

            elif choice < 40:
                # if i == 0:
                #     print("Zero")
                # leave at 0
                pass

            else:
                if choice < 50:
                    mask = np.zeros(shape=(64,), dtype=np.uint8)
                    which = np.random.randint(low=0,high=64)
                    # if i == 0:
                    #     print("mask {}".format(which))
                    mask[which] = 1
                else:
                    mask = np.random.randint(low=0, high=2, size=(64,), dtype=np.uint8)
                    # if i == 0:
                    #     print("multimask")
                fixed[i][0:64] = source[i][0:64] * mask
                fixed[i][64:128] = mask
        # print("COMPARE")
        # print(orig_source[0])
        # print(fixed[0])
        return np.array(fixed)

### LEGACY FOR STORED MDOELS
class RandomLabelDropping(AgnosticSourcewiseTransformer):
    def __init__(self, data_stream, chance=50, **kwargs):
        super(RandomLabelDropping, self).__init__(
             data_stream=data_stream,
             produces_examples=data_stream.produces_examples,
             **kwargs)
        self.chance = chance

    def transform_any_source(self, source, _):
        if not len(source > 0):
            return source

        # orig_source0 = np.copy(source[0])
        iters, dim = source.shape
        newdim = dim+1

        choice = np.random.uniform(0,100)
        if choice < self.chance:
            source = np.zeros((iters, newdim), dtype=np.uint8)
            source[:,0] = 1
        else:
            source = np.pad(source, pad_width=((0, 0), (1, 0)), mode='constant', constant_values=0)
        # print("COMPARE")
        # print(orig_source0)
        # print(source[0])
        return source

class RandomLabelStrip(AgnosticSourcewiseTransformer):
    """a label vector abcde is randomly replaced with either
       0abcde or
       100000
    """
    def __init__(self, data_stream, chance=50, **kwargs):
        super(RandomLabelStrip, self).__init__(
             data_stream=data_stream,
             produces_examples=data_stream.produces_examples,
             **kwargs)
        self.chance = chance

    def transform_any_source(self, source, _):
        if not len(source > 0):
            return source

        # orig_source0 = np.copy(source[0])
        final_flatten = False
        if(len(source.shape) == 1):
            final_flatten = True
            iters, dim = 1, source.shape[0]
            source = source.reshape((1, dim))
        else:
            iters, dim = source.shape
        newdim = dim+1

        choice = np.random.uniform(0,100)
        if choice < self.chance:
            source = np.zeros((iters, newdim), dtype=np.uint8)
            source[:,0] = 1
        else:
            source = np.pad(source, pad_width=((0, 0), (1, 0)), mode='constant', constant_values=0)
        # print("COMPARE")
        # print(orig_source0)
        # print(source[0])
        if final_flatten:
            source = source.reshape((newdim,))
        return source

class AddLabelUncertainty(AgnosticSourcewiseTransformer):
    """a label vector abcde is randomly replaced with either
       0abcde or
       100000
    """
    def __init__(self, data_stream, chance=50, **kwargs):
        super(AddLabelUncertainty, self).__init__(
             data_stream=data_stream,
             produces_examples=data_stream.produces_examples,
             **kwargs)
        self.chance = chance

    def transform_any_source(self, source, _):
        if not len(source > 0):
            return source

        final_flatten = False
        if(len(source.shape) == 1):
            final_flatten = True
            iters, dim = 1, source.shape[0]
            source = source.reshape((1, dim))
        else:
            iters, dim = source.shape
        newdim = dim*2

        fixed = np.zeros((iters, newdim), dtype=np.uint8)
        # start with random numbers 0-100
        mask_nums = np.random.randint(low=0, high=100, size=(dim,), dtype=np.uint8)
        # decide on the fields to be zeroed out (marked by 1)
        mask = (mask_nums < self.chance).astype(int)
        # multiply existing fields by the inverse (0 1 swapped)
        fixed[:,:dim] = source * (1 - mask)
        # store the same mask across the batch
        fixed[:,dim:] = mask
        # print("COMPARE")
        # print(source[0])
        # print(fixed[0])
        if final_flatten:
            fixed = fixed.reshape((newdim,))
        return fixed

def uuid_to_vector(uuid_str):
    u = uuid.UUID(uuid_str)
    uuid_int = u.int
    encoded = []
    high_mask = 0x80000000000000000000000000000000
    for n in range(128):
        bit = uuid_int & high_mask
        uuid_int = uuid_int << 1
        if bit != 0:
            encoded.append(1)
        else:
            encoded.append(0)
    return np.array(encoded, dtype=np.uint8)

def uuid_pad_vector(v, uuid_vector, zero_vector):
    all_zeros = not v.any()
    if all_zeros:
        pad = zero_vector
    else:
        pad = uuid_vector
    return np.concatenate((v, pad))

class UUIDStretch(AgnosticSourcewiseTransformer):
    """Append 128 dimensional uuid to all labels.
    """
    def __init__(self, data_stream, uuid_str, **kwargs):
        super(UUIDStretch, self).__init__(
             data_stream=data_stream,
             produces_examples=data_stream.produces_examples,
             **kwargs)
        self.uuid_pad = uuid_to_vector(uuid_str)
        self.zero_pad = np.zeros((128,), dtype=np.uint8)

    def transform_any_source(self, source, _):
        output = [uuid_pad_vector(a, self.uuid_pad, self.zero_pad)
            for a in source]
        # print("UUID: {}".format(output[0]))
        return output

#copied from discgen.utils
def create_streams(train_set, valid_set, test_set, training_batch_size,
                   monitoring_batch_size):
    """Creates data streams for training and monitoring.

    Parameters
    ----------
    train_set : :class:`fuel.datasets.Dataset`
        Training set.
    valid_set : :class:`fuel.datasets.Dataset`
        Validation set.
    test_set : :class:`fuel.datasets.Dataset`
        Test set.
    monitoring_batch_size : int
        Batch size for monitoring.
    include_targets : bool
        If ``True``, use both features and targets. If ``False``, use
        features only.

    Returns
    -------
    rval : tuple of data streams
        Data streams for the main loop, the training set monitor,
        the validation set monitor and the test set monitor.

    """
    main_loop_stream = DataStream.default_stream(
        dataset=train_set,
        iteration_scheme=ShuffledScheme(
            train_set.num_examples, training_batch_size))
    train_monitor_stream = DataStream.default_stream(
        dataset=train_set,
        iteration_scheme=ShuffledScheme(
            train_set.num_examples, monitoring_batch_size))
    valid_monitor_stream = DataStream.default_stream(
        dataset=valid_set,
        iteration_scheme=SequentialScheme(
            valid_set.num_examples, monitoring_batch_size))
    test_monitor_stream = DataStream.default_stream(
        dataset=test_set,
        iteration_scheme=SequentialScheme(
            test_set.num_examples, monitoring_batch_size))

    return (main_loop_stream, train_monitor_stream, valid_monitor_stream,
            test_monitor_stream)

def create_custom_streams(filename, training_batch_size, monitoring_batch_size,
                          include_targets=False, color_convert=False,
                          allowed=None, stretch=None, random_spread=False,
                          random_label_strip=False, add_label_uncertainty=False,
                          uuid_str=None,
                          split_names=['train', 'valid', 'test']):
    """Creates data streams from fuel hdf5 file.

    Currently features must be 64x64.

    Parameters
    ----------
    filename : string
        basename to hdf5 file for input
    training_batch_size : int
        Batch size for training.
    monitoring_batch_size : int
        Batch size for monitoring.
    include_targets : bool
        If ``True``, use both features and targets. If ``False``, use
        features only.
    color_convert : bool
        If ``True``, input is assumed to be one-channel, and so will
        be transformed to three-channel by duplication.

    Returns
    -------
    rval : tuple of data streams
        Data streams for the main loop, the training set monitor,
        the validation set monitor and the test set monitor.

    """
    sources = ('features', 'targets') if include_targets else ('features',)

    dataset_fname = find_in_data_path(filename+'.hdf5')
    data_train = H5PYDataset(dataset_fname, which_sets=[split_names[0]],
                             sources=sources)
    data_valid = H5PYDataset(dataset_fname, which_sets=[split_names[1]],
                             sources=sources)
    data_test = H5PYDataset(dataset_fname, which_sets=[split_names[2]],
                            sources=sources)
    data_train.default_transformers = uint8_pixels_to_floatX(('features',))
    data_valid.default_transformers = uint8_pixels_to_floatX(('features',))
    data_test.default_transformers = uint8_pixels_to_floatX(('features',))

    results = create_streams(data_train, data_valid, data_test,
                             training_batch_size, monitoring_batch_size)

    if color_convert:
        results = tuple(map(
                    lambda s: Colorize(s, which_sources=('features',)),
                    results))

    if add_label_uncertainty:
        results = tuple(map(
                    lambda s: AddLabelUncertainty(s, chance=add_label_uncertainty,
                                       which_sources=('targets',)),
                    results))

    if random_label_strip:
        results = tuple(map(
                    lambda s: RandomLabelStrip(s, chance=random_label_strip,
                                       which_sources=('targets',)),
                    results))

    # wrap labels in stretcher if requested
    if stretch is not None:
        results = tuple(map(
                    lambda s: StretchLabels(s, which_sources=('targets',), length=stretch),
                    results))

    # wrap labels in scrubber if not all labels are allowed
    if allowed:
        results = tuple(map(
                    lambda s: Scrubber(s, allowed=allowed,
                                       which_sources=('targets',)),
                    results))

    if random_spread:
        results = tuple(map(
                    lambda s: RandomLabelOptionalSpreader(s,
                                       which_sources=('targets',)),
                    results))

    if uuid_str is not None:
        results = tuple(map(
                    lambda s: UUIDStretch(s, uuid_str=uuid_str,
                                       which_sources=('targets',)),
                    results))

    return results


text:
//
//  DNTag.h
//  DonkyCore
//
//  Created by Donky Networks on 12/04/2015.
//  Copyright (c) 2015 Donky Networks Ltd. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface DNTag : NSObject

/*!
 Initialiser method to create a new tag object.

 @param value    the value of the tag.
 @param selected if the tag is selected or not.

 @return a new instance of DNTag.

 @since 2.0.0.0
 */
- (instancetype)initWithValue:(NSString *)value isSelected:(BOOL)selected;

/*!
 The value of the tag.

 @since 2.0.0.0
 */
@property (nonatomic, readonly) NSString *value;

/*!
 Whether the tag has been selected by the user.

 @since 2.0.0.0
 */
@property (nonatomic, getter=isSelected) BOOL selected;

@end