text:
Create a blurred images, take a screenshot, make a image with color...

[![Build Status](https://api.travis-ci.org/NZN/UIImage-Helpers.png)](https://api.travis-ci.org/NZN/UIImage-Helpers.png)
[![Cocoapods](https://cocoapod-badges.herokuapp.com/v/UIImage-Helpers/badge.png)](http://beta.cocoapods.org/?q=UIImage-Helpers)
[![Cocoapods](https://cocoapod-badges.herokuapp.com/p/UIImage-Helpers/badge.png)](http://beta.cocoapods.org/?q=UIImage-Helpers)

## Requirements

UIImage-Helpers works on iOS 5.0+ version and is compatible with ARC projects. It depends on the following Apple frameworks, which should already be included with most Xcode templates:

* Accelerate.framework
* Foundation.framework
* QuartzCore.framework

You will need LLVM 3.0 or later in order to build UIImage-Helpers.

## Adding UIImage-Helpers to your project

### Cocoapods

[CocoaPods](http://cocoapods.org) is the recommended way to add UIImage-Helpers to your project.

* Add a pod entry for UIImage-Helpers to your Podfile:

```
pod 'UIImage-Helpers', '~> 0.0.1'
```

* Install the pod(s) by running:

```
pod install
```

### Source files

Alternatively you can directly add source files to your project.

1. Download the [latest code version](https://github.com/NZN/UIImage-Helpers/archive/master.zip) or add the repository as a git submodule to your git-tracked project.
2. Open your project in Xcode, then drag and drop all files at `UIImage-Helpers` folder onto your project (use the "Product Navigator view"). Make sure to select Copy items when asked if you extracted the code archive outside of your project.

## Usage

* Make a blurred image with another image

```objective-c
#import "UIImage+Blur.h"
...

// jpeg quality image data
float quality = .00001f;

// intensity of blurred
float blurred = .5f;

NSData *imageData = UIImageJPEGRepresentation([self.imageViewNormal image], quality);
UIImage *blurredImage = [[UIImage imageWithData:imageData] blurredImage:blurred];
self.imageViewBlurred.image = blurredImage;
```

* Take a screenshot

```objective-c
#import "UIImage+Screenshot.h"
...

UIImage *image = [UIImage screenshot];
self.imageView.image = image;
```

* Generate a image with color

```objective-c
#import "UIImage+ImageWithColor.h"
...
UIColor *purpleColor = [UIColor colorWithRed:.927f green:.264f blue:.03f alpha:1];
UIImage *image = [UIImage imageWithColor:purpleColor];

[self.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
```

## License

This code is distributed under the terms and conditions of the [MIT license](LICENSE).

## Change-log

A brief summary of each UIImage-Helpers release can be found on the [wiki](https://github.com/NZN/UIImage-Helpers/wiki/Change-log).


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

public class ControleConsCocaina : MonoBehaviour {
	public Animator AnimConsCocaina;
	public EscolhasManager esco;

	public void IniciaAnimacao(){
		AnimConsCocaina.gameObject.SetActive (true);
		AnimConsCocaina.SetBool ("start", true);
		AnimConsCocaina.SetBool ("aceita", true);
	}

	public void FinalAnimacao(){
		if (AnimConsCocaina.GetBool ("final")) {
			esco.CarregaFase3 ();
			gameObject.SetActive (false);
		} else {
			AnimConsCocaina.SetBool ("final", true);
		}
	}
	/*Criar um estado para final da animação em que apresentará todos os textos e a label informando clique para ir à próxima tela
	 * Usar o click do botão para mudar o state da animação para a final, caso a variavel de controle final não seja true
	 * se a variavel de controle final for true, retira da animação e volta para o jogo
	 * No método de voltar para o jogo, será feito uma verificação da fase e das drogas aceitas antes de ir para a próxima fase.
	*/
}

redpajama_set_name: RedPajamaGithub


text:
from common.config import config
from common.controller import Controller

class ReportController(Controller):

    def Process(self, section):
        self.mimetype = 'text/xsl'

        self.output = '<?xml version="1.0" encoding="UTF-8"?>'
        self.output += '<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">'
        self.output += '<xsl:output method="html" />'
        self.RenderFile('reports/' + section + '.xsl', {'_': config.i18n, 'CompanyName': config.CompanyName})
        self.RenderFile('reports/report-footer.xsl', {'_': config.i18n})


text:
[fiplog](https://fipress.org/project/fiplog) simple golang log lib with basic configurable log level, output format and location.

A typical config file could be:
```
level: Debug
file: fip.log
pattern: %date [%level] <%file> %msg
```

**Usage**
The usage is simple:
```
logger := fiplog.GetLogger()
logger.Debug("debug")
logger.Info("info")
logger.Error("error:",err)
```

For detailed usage, please refer to the [project page](https://fipress.org/project/fiplog)


text:
module Favorites
  def self.included(base)
    base.extend(ClassMethods)
  end

  module ClassMethods
    def favorite(finder, shortcuts)
      singleton = (class << self; self; end)

      shortcuts.each do |name, value|
        singleton.send(:define_method, name, lambda{ send("find_by_#{finder}", value) })
      end
    end
  end
end


text:
using System.Runtime.Serialization;

namespace GoogleApi.Entities.Maps.Roads.Common.Enums;

/// <summary>
/// Speed Units.
/// </summary>
public enum Units
{
    /// <summary>
    /// Miles per hour.
    /// </summary>
    [EnumMember(Value = "MPH")]
    Mph,

    /// <summary>
    /// Kilometers per hour.
    /// </summary>
    [EnumMember(Value = "KPH")]
    Kph
}


text:
package xsd4ld.types;

import xsd4ld.ValueClass;
import xsd4ld.XSDConst;
import xsd4ld.XSDDatatype;

public class XSD_AnyType extends XSDDatatype {

    public XSD_AnyType() {
        super(XSDConst.xsd_anyType, null, ValueClass.ANY, null);
    }

    @Override
    protected Object valueOrException(String lex) {
        return lex;
    }
}


text:
from orderedset import OrderedSet

from notifications_utils.insensitive_dict import InsensitiveDict

class TemplateChange:
    def __init__(self, old_template, new_template):
        self.old_placeholders = InsensitiveDict.from_keys(old_template.placeholders)
        self.new_placeholders = InsensitiveDict.from_keys(new_template.placeholders)

    @property
    def has_different_placeholders(self):
        return bool(self.new_placeholders.keys() ^ self.old_placeholders.keys())

    @property
    def placeholders_added(self):
        return OrderedSet(
            [self.new_placeholders.get(key) for key in self.new_placeholders.keys() - self.old_placeholders.keys()]
        )

    @property
    def placeholders_removed(self):
        return OrderedSet(
            [self.old_placeholders.get(key) for key in self.old_placeholders.keys() - self.new_placeholders.keys()]
        )


text:
Dir.glob(File.join(File.dirname(__FILE__), *%w[primitives *.rb])) do |file|
  require file.sub(/\.rb$/, '')
end

module DeferrableGratification
  # Trivial operations which return Deferrables.
  #
  # Used internally by the library, and may be useful in cases where you need
  # to return a Deferrable to keep API compatibility but the result is already
  # available.
  #
  # {DeferrableGratification} extends this module, and thus the methods here
  # are accessible via the {DG} alias.
  module Primitives
    # Return a Deferrable which immediately succeeds, passing 0 or more values
    # to callbacks.
    def success(*values)
      blank.tap {|d| d.succeed(*values) }
    end

    # Return a Deferrable which immediately succeeds, passing a constant value
    # to callbacks.
    def const(value)
      success(value)
    end

    # Return a Deferrable which immediately fails with an exception.
    #
    # @overload failure(message)
    #   Passes +RuntimeError.new(message)+ to errbacks.
    # @overload failure(exception_class)
    #   Passes +exception_class.new+ to errbacks.
    # @overload failure(exception_class, message)
    #   Passes +exception_class.new(message)+ to errbacks.
    # @overload failure(exception)
    #   Passes +exception+ to errbacks.
    def failure(exception_class_or_message, message_or_nil = nil)
      blank.tap do |d|
        d.fail(
          case exception_class_or_message
          when Exception
            raise ArgumentError, "can't specify both exception and message" if message_or_nil
            exception_class_or_message
          when Class
            exception_class_or_message.new(message_or_nil)
          else
            RuntimeError.new(exception_class_or_message.to_s)
          end)
      end
    end

    # Return a completely uninteresting Deferrable.
    def blank
      DeferrableGratification::DefaultDeferrable.new
    end
  end
end


text:
**Banner Zen** is a Banner Starter Kit is a somewhat opinionated boilerplate for HTML5 Rich Banner Development that takes the stress out and peace in. Included are tools for building across Google AdWords, DoubleClick Studio, DoubleClick Rich Media and Sizmek in the most relaxing, peaceful and heartwarming way possible.

### Features

> Latest Ecmascript [ES6] Features

Practice the basics of ES6 today!

> Multi-platform boilerplate

Although a work in progress, this repo aims to contain a major template from each ad provider as listed above. Just swap out bits and pieces. Currently the repo only includes importable stylesheet includes for various banner sizes.

> Cross-device Synchronisation

Synchronise clicks, scrolls, forms and live-reload across multiple devices on the fly as you code. Powered by [BrowserSync](http://browsersync.io).

> Built in HTTP Server

Test pages easily in your local environment with one command: `gulp`.

> Performance Optimisation with a build process powered by [Gulp](http://gulpjs.com/).

Minify and concatenate JavaScript, CSS, HTML and images to keep your pages lean and your code readable.

> Stylus Support

Compile [Stylus](https://learnboost.github.io/stylus/) into CSS with ease, with support for variables, mixins and more.
Stylus has been chosen for its ability to incorporate syntax of most other preprocessors. This means that if you start to work on a project where the previous developer has used Sass indented syntax, but you like Less syntax, you can do so and it will just work.

Also, performance-wise Stylus performs really well, and it is natively created in NodeJS.

> Local Area Network Sharing

Ever been in a situation where a producer, designer, creative, janitor, Bob, Anthony's cat or your Aunty sends an email asking for `thing x` to be moved to the right by `x pixels`, so you do it, zip up the files, send them over and wait an hour for a response? Well, that just wont do. From now on, send them the external link [ which will look something like http://192.168.130.81:7878/] to your current project, get them on the phone if you have to, make the amends and have them watch it happen from their end. No more emails, no more firebreathing, just zen.

### Quickstart
- Clone or [download](https://gitlab.mcsaatchi.com.au/MAKE/banner-zen/repository/archive.zip) this repository and build on what is included in the `source` directory.
- ` git clone git@gitlab.mcsaatchi.com.au:MAKE/banner-zen.git`
- `cd banner-zen` (or whatever you named the folder)
- `npm install`

And you are ready to go, run with `gulp` to start the built in HTTP server in a new browser page.

### Workflow
- Put on some sound-blocking headphones, and switch to [3 Hours of Healing Zen Music](https://www.youtube.com/watch?v=LGiH6oUDXVg)
- `gulp` will start a HTTP server with browser-sync
- `gulp build` will clean the build directory and then build the project and create an archive of the project ready for dispatch

[I'm working on it!]

### Gulp Tasks
#### `npm run gulp -- build`
Clean `build` dir and rebuild project.

#### `npm run gulp`
Build project and initialise BrowserSync session which will open a new tab and
live reload in that tab.

#### `gulp images`
Minify images with: imagemin-pngquant, imagemin-svgo, imagemin-gifsicle, imagemin-jpegtran

## [GreenSock](http://greensock.com/) Guides
- [Jump Start](https://greensock.com/jump-start-js)
- [Ease Visualizer](http://greensock.com/ease-visualizer)
- [TimeLine Lite Tuts+ Guide](http://code.tutsplus.com/tutorials/timelinelite-ultimate-starter-guide-working-with-labels--active-10240)

### Ad Platform Build Guides & Spec Sheets
- [DoubleClick](https://support.google.com/richmedia/answer/3369501?hl=en&ref_topic=3369390&rd=1)
  - [How to prepare HTML5 assets for DCM] (https://support.google.com/dcm/partner/answer/3145300?hl=en&vid=1-635790097211926859-3253088437#1&2&2a&3&4&5&6&7&8&9&10&11&12&13&14&15&16&17)
  - [Hosted libraries](https://support.google.com/richmedia/answer/6307288?hl=en)

- [AdWords](https://support.google.com/adwordspolicy/answer/176108)
- [Sizmek](https://support.sizmek.com/hc/en-us/categories/200103329-Creating-HTML5-Ads)
  - Specifically [this link](https://support.sizmek.com/hc/en-us/articles/202732315-HTML5-Formats-and-Features)
- [AdRoll](https://help.adroll.com/hc/en-us/articles/201975690-Creative-Guidelines)

##NOTES

* I used this project as an opportunity to showcase many of my current skills:
  * front-end build tools (Gulp)
  * JS templating tools (nunjucks)
  * ES6/7
  * Modular JS
  * CSS preprocessor (Stylus)
  * NPM
  * external data source used while templating (./source/data.json)
  * optimisation (css/js/image minification)

##TODO
- [ ] Implement ES6 imports, which will require bundling of output js to bundle.js


text:
'use strict';

var test = require('../../../src');

describe('Asserter string()', function(){

  describe('string() behavior', function(){

    it('Does not contains assertions from the assertions containers', function(){

      test
        .value(test.string('').hasHeader)
          .isUndefined()

        .value(test.string('').hasProperty)
          .isUndefined()

        .value(test.string('').hasMessage)
          .isUndefined()

        .value(test.string('').isInfinite)
          .isUndefined()
      ;

    });

    it('Assert that the tested value is a `string`', function(){

      test
        .string('')
        .string('Hello')

        .case('Test failure', function(){

          test
            .exception(function(){
              test.string();
            })

            .exception(function(){
              test.string({});
            })

            .exception(function(){
              test.string([]);
            })

            .exception(function(){
              test.string(1);
            })

            .exception(function(){
              test.string(/foobar/);
            })

            .exception(function(){
              test.string(true);
            })

            .exception(function(){
              test.string(false);
            })

            .exception(function(){
              test.string(null);
            })

            .exception(function(){
              test.string(undefined);
            })
          ;
        })
      ;
    });
  });

  describe('Assertions of string()', function(){

    it('is(expected)', function(){

      var str = 'Hello world !';

      test
        .string(str)
          .is('Hello world !')

        .exception(function(){
          test.string(str).is('foo');
        })
      ;

    });

    it('isNot(expected)', function(){

      var str = 'Hello world !';

      test
        .string(str)
          .isNot('hello world !')

        .exception(function(){
          test.string(str).isNot('Hello world !');
        })
      ;

    });

    it('isIdenticalTo(expected)', function(){

      var str = 'Hello world !';

      test
        .string(str)
          .isIdenticalTo('Hello world !')

        .exception(function(){
          test.string(str).isIdenticalTo('Hello World !');
        })
      ;

    });

    it('isNotIdenticalTo(expected)', function(){

      var str = 'Hello world !';

      test
        .string(str)
          .isNotIdenticalTo('hello world !')

        .exception(function(){
          test.string(str).isNotIdenticalTo('Hello world !');
        })
      ;

    });

    it('isEqualTo(expected)', function(){

      var str = 'Hello world !';

      test
        .string(str)
          .isEqualTo('Hello world !')

        .exception(function(){
          test.string(str).isEqualTo('Hello World !');
        })
      ;

    });

    it('isNotEqualTo(expected)', function(){

      var str = 'Hello world !';

      test
        .string(str)
          .isNotEqualTo('hello world !')

        .exception(function(){
          test.string(str).isNotEqualTo('Hello world !');
        })
      ;

    });

    it('match(expected)', function(){

      // Assert a string value with a expected string
      test.string('Hello').match('Hello');

      // Assert a string value with a RegExp
      test.string('Hello world !').match(/world/i);

      // Assert a string with a function
      test.string('hello').match(function(it){
        return it === 'hello';
      });

      test.exception(function(){
        test.string('hello').match(/foo/);
      });

    });

    it('notMatch(expected)', function(){

      test
        .string('foobar')
          .notMatch('some value')
          .notMatch(/[foo]+bazzz$/)

        .string('foo')
          .notMatch(function(it){
            return it === 'bar';
          })

        .exception(function(){
          test.string('Hello Nico!').notMatch(/nico/i);
        })
      ;

    });

    it('isValid(expected)', function(){

      // Assert a string value with a expected string
      test.string('Hello').isValid('Hello');

      // Assert a string value with a RegExp
      test.string('Hello world !').isValid(/world/i);

      // Assert a string with a function
      test.string('hello').isValid(function(it){
        return it === 'hello';
      });

      test.exception(function(){
        test.string('hello').isValid(/foo/);
      });

    });

    it('isNotValid(expected)', function(){

      test
        .string('foobar')
          .isNotValid('some value')
          .isNotValid(/[foo]+bazzz$/)

        .string('foo')
          .isNotValid(function(it){
            return it === 'bar';
          })

        .exception(function(){
          test.string('Hello Nico!').notMatch(/nico/i);
        })
      ;

    });

    it('matchEach(expected)', function(){

      var str = 'Hello Nico!';

      test
        .string(str)
          .matchEach([/hello/i, 'Nico', function(it){
            return it === 'Hello Nico!';
          }])

        .case('Test failure', function(){

          test
            .exception(function(){
              test.string(str).matchEach([/hello/i, 'nico', function(it){
                return it === 'Hello Nico!';
              }]);
            })

            .exception(function(){
              test.string(str).matchEach([/hello/i, 'Nico', function(it){
                return it === 'Hello nico!';
              }]);
            })
          ;
        })
      ;
    });

    it('notMatchEach(expected)', function(){

      var str = 'Hello Nico!';

      test
        .string(str)
          .notMatchEach([/foo/i, 'bad word', function(it){
            return it === 'Bye';
          }])

        .case('Test failure', function(){

          test
            .exception(function(){
              test.string(str).notMatchEach([/hello/, 'Nico', function(it){
                return it === 'Hello !';
              }]);
            })

            .exception(function(){
              test.string(str).notMatchEach([/hello/, 'nico', function(it){
                return it === 'Hello Nico!';
              }]);
            })
          ;
        })
      ;

    });

    it('isEmpty()', function(){
      test
        .string('')
          .isEmpty()

        .exception(function(){
          test.string(str).isEmpty();
        })
      ;
    });

    it('isNotEmpty()', function(){
      test
        .string('a')
          .isNotEmpty()

        .exception(function(){
          test.string('').isNotEmpty();
        })
      ;
    });

    it('hasLength(expected)', function(){
      test
        .string('Hello Nico')
          .hasLength(10)

        .exception(function(){
          test.string('abc').hasLength(4);
        })
      ;
    });

    it('hasNotLength(expected)', function(){
      test
        .string('Hello Nico')
          .hasNotLength(11)

        .exception(function(){
          test.string('abc').hasNotLength(3);
        })
      ;
    });

    it('hasValue(expected)', function(){
      test
        .string('Hello, Nico!')
          .hasValue('Nico')

        .exception(function(){
          test.string('Hello').hasValue('hello');
        })
      ;
    });

    it('notHasValue(expected)', function(){
      test
        .string('Hello, Nico!')
          .notHasValue('Bye')

        .exception(function(){
          test.string('Hello').notHasValue('Hello');
        })
      ;
    });

    it('hasValues(expected)', function(){
      test
        .string('Hello Nico!')
          .hasValues(['Hello', 'Nico'])

        .exception(function(){
          test.string('Hello Nico!').hasValues(['Hi', 'Nico']);
        })
      ;
    });

    it('notHasValues(expected)', function(){
      test
        .string('Sarah Connor ?')
          .notHasValues(['next', 'door'])

        .exception(function(){
          test.string('Hello Nico!').notHasValues(['Hi', 'Nico']);
        })

      ;
    });

    it('contains(expected [, ...])', function(){
      test
        .string('hello boy')
          .contains('boy')

        .string('KISS principle : Keep it Simple, Stupid')
          .contains('Simple', 'principle', ':')

        .exception(function(){
          test.string('Hello').contains('hello');
        })
      ;
    });

    it('notContains(expected [, ...])', function(){
      test
        .string('hello boy')
          .notContains('bye')

        .exception(function(){
          test.string('Hello').notContains('Hello');
        })
      ;
    });

    it('startsWith(str)', function(){
      test
        .string('foobar')
          .startsWith('foo')

        .exception(function(){
          test.string('Hello the world').startsWith('world');
        })
      ;
    });

    it('notStartsWith(str)', function(){
      test
        .string('foobar')
          .notStartsWith('bar')

        .exception(function(){
          test.string('Hello the world').notStartsWith('Hello');
        })
      ;
    });

    it('endsWith(str)', function(){
      test
        .string('foobar')
          .endsWith('bar')

        .exception(function(){
          test.string('Hello the world').endsWith('Hello');
        })
      ;
    });

    it('notEndsWith(str)', function(){
      test
        .string('foobar')
          .notEndsWith('foo')

        .exception(function(){
          test.string('Hello the world').notEndsWith('world');
        })
      ;
    });

  });
});


text:
namespace CrowdChat.Web.Account
{
    using System;
    using System.Web;
    using System.Web.UI;

    using CrowdChat.Models;
    using CrowdChat.Web.Models;

    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.Owin;
    using Microsoft.Owin.Security;

    /// <summary>
    /// The manage.
    /// </summary>
    public partial class Manage : Page
    {
        #region Public Properties

        /// <summary>
        /// Gets a value indicating whether has phone number.
        /// </summary>
        public bool HasPhoneNumber { get; private set; }

        /// <summary>
        /// Gets or sets the logins count.
        /// </summary>
        public int LoginsCount { get; set; }

        /// <summary>
        /// Gets a value indicating whether two factor browser remembered.
        /// </summary>
        public bool TwoFactorBrowserRemembered { get; private set; }

        /// <summary>
        /// Gets a value indicating whether two factor enabled.
        /// </summary>
        public bool TwoFactorEnabled { get; private set; }

        #endregion

        #region Properties

        /// <summary>
        /// Gets the success message.
        /// </summary>
        protected string SuccessMessage { get; private set; }

        #endregion

        #region Methods

        /// <summary>
        /// The page_ load.
        /// </summary>
        protected void Page_Load()
        {
            var manager = this.Context.GetOwinContext().GetUserManager<UserManager>();

            this.HasPhoneNumber = string.IsNullOrEmpty(manager.GetPhoneNumber(this.User.Identity.GetUserId()));

            // Enable this after setting up two-factor authentientication
            // PhoneNumber.Text = manager.GetPhoneNumber(User.Identity.GetUserId()) ?? String.Empty;
            this.TwoFactorEnabled = manager.GetTwoFactorEnabled(this.User.Identity.GetUserId());

            this.LoginsCount = manager.GetLogins(this.User.Identity.GetUserId()).Count;

            IAuthenticationManager authenticationManager = HttpContext.Current.GetOwinContext().Authentication;

            if (!this.IsPostBack)
            {
                // Determine the sections to render
                if (this.HasPassword(manager))
                {
                    this.ChangePassword.Visible = true;
                }
                else
                {
                    this.CreatePassword.Visible = true;
                    this.ChangePassword.Visible = false;
                }

                // Render success message
                string message = this.Request.QueryString["m"];
                if (message != null)
                {
                    // Strip the query string from action
                    this.Form.Action = this.ResolveUrl("~/Account/Manage");

                    this.SuccessMessage = message == "ChangePwdSuccess"
                                              ? "Your password has been changed."
                                              : message == "SetPwdSuccess"
                                                    ? "Your password has been set."
                                                    : message == "RemoveLoginSuccess"
                                                          ? "The account was removed."
                                                          : message == "AddPhoneNumberSuccess"
                                                                ? "Phone number has been added"
                                                                : message == "RemovePhoneNumberSuccess"
                                                                      ? "Phone number was removed"
                                                                      : string.Empty;
                    this.successMessage.Visible = !string.IsNullOrEmpty(this.SuccessMessage);
                }
            }
        }

        protected void RemovePhone_Click(object sender, EventArgs e)
        {
            var manager = this.Context.GetOwinContext().GetUserManager<UserManager>();
            IdentityResult result = manager.SetPhoneNumber(this.User.Identity.GetUserId(), null);
            if (!result.Succeeded)
            {
                return;
            }

            User user = manager.FindById(this.User.Identity.GetUserId());
            if (user != null)
            {
                IdentityHelper.SignIn(manager, user, false);
                this.Response.Redirect("/Account/Manage?m=RemovePhoneNumberSuccess");
            }
        }

        // DisableTwoFactorAuthentication
        /// <summary>
        /// The two factor disable_ click.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        protected void TwoFactorDisable_Click(object sender, EventArgs e)
        {
            var manager = this.Context.GetOwinContext().GetUserManager<UserManager>();
            manager.SetTwoFactorEnabled(this.User.Identity.GetUserId(), false);

            this.Response.Redirect("/Account/Manage");
        }

        protected void TwoFactorEnable_Click(object sender, EventArgs e)
        {
            var manager = this.Context.GetOwinContext().GetUserManager<UserManager>();
            manager.SetTwoFactorEnabled(this.User.Identity.GetUserId(), true);

            this.Response.Redirect("/Account/Manage");
        }

        /// <summary>
        /// The add errors.
        /// </summary>
        /// <param name="result">
        /// The result.
        /// </param>
        private void AddErrors(IdentityResult result)
        {
            foreach (string error in result.Errors)
            {
                this.ModelState.AddModelError(string.Empty, error);
            }
        }

        /// <summary>
        /// The has password.
        /// </summary>
        /// <param name="manager">
        /// The manager.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        private bool HasPassword(UserManager manager)
        {
            return manager.HasPassword(this.User.Identity.GetUserId());
        }

        #endregion
    }
}


text:
package org.loader.glin.helper;

/**
 * Created by qibin on 2016/7/13.
 */
public class LogHelper {
    private boolean isDebugMode;
    private LogPrinter mLogPrinter;
    private StringBuilder mLogAppender;

    public static LogHelper get(boolean debug, LogPrinter logPrinter) {
        LogHelper helper = new LogHelper(logPrinter);
        helper.isDebugMode(debug);
        return helper;
    }

    private LogHelper(LogPrinter logPrinter) {
        mLogPrinter = logPrinter;
    }

    public void isDebugMode(boolean debug) {
        isDebugMode = debug;
    }

    public boolean isDebugMode() {
        return isDebugMode;
    }

    public StringBuilder getLogAppender() {
        if (mLogAppender == null) {
            mLogAppender = new StringBuilder();
        }
        return mLogAppender;
    }

    public void print() {
        if (!isDebugMode || mLogAppender == null || mLogAppender.length() == 0) { return;}
        print(mLogAppender.toString());
    }

    public void print(String content) {
        if (!isDebugMode) { return;}

        mLogPrinter.print("Glin", "*******************--BEGIN--*******************");
        mLogPrinter.print("Glin", content);
        mLogPrinter.print("Glin", "********************--END--********************");
    }

    public interface LogPrinter {
        void print(String tag, String content);
    }
}


text:
#ifndef LIBMINIFI_INCLUDE_EVENTDRIVENSCHEDULINGAGENT_H_
#define LIBMINIFI_INCLUDE_EVENTDRIVENSCHEDULINGAGENT_H_

#include <memory>
#include <string>

#define DEFAULT_TIME_SLICE_MS 500

#include "core/logging/Logger.h"
#include "core/Processor.h"
#include "core/ProcessContext.h"
#include "core/ProcessSessionFactory.h"
#include "ThreadedSchedulingAgent.h"

namespace org {
namespace apache {
namespace nifi {
namespace minifi {

// EventDrivenSchedulingAgent Class
class EventDrivenSchedulingAgent : public ThreadedSchedulingAgent {
 public:
  // Constructor
  /*!
   * Create a new event driven scheduling agent.
   */
  EventDrivenSchedulingAgent(const gsl::not_null<core::controller::ControllerServiceProvider*> controller_service_provider, std::shared_ptr<core::Repository> repo,
                             std::shared_ptr<core::Repository> flow_repo, std::shared_ptr<core::ContentRepository> content_repo, std::shared_ptr<Configure> configuration,
                             utils::ThreadPool<utils::TaskRescheduleInfo> &thread_pool)
      : ThreadedSchedulingAgent(controller_service_provider, repo, flow_repo, content_repo, configuration, thread_pool) {
    int slice = configuration->getInt(Configure::nifi_flow_engine_event_driven_time_slice, DEFAULT_TIME_SLICE_MS);
    if (slice < 10 || 1000 < slice) {
      throw Exception(FLOW_EXCEPTION, std::string(Configure::nifi_flow_engine_event_driven_time_slice) + " is out of reasonable range!");
    }
    time_slice_ = std::chrono::milliseconds(slice);
  }

  void schedule(core::Processor* processor) override;

  // Run function for the thread
  utils::TaskRescheduleInfo run(core::Processor* processor, const std::shared_ptr<core::ProcessContext> &processContext,
      const std::shared_ptr<core::ProcessSessionFactory> &sessionFactory) override;

 private:
  // Prevent default copy constructor and assignment operation
  // Only support pass by reference or pointer
  EventDrivenSchedulingAgent(const EventDrivenSchedulingAgent &parent);
  EventDrivenSchedulingAgent &operator=(const EventDrivenSchedulingAgent &parent);

  std::chrono::milliseconds time_slice_;
};

}  // namespace minifi
}  // namespace nifi
}  // namespace apache
}  // namespace org
#endif  // LIBMINIFI_INCLUDE_EVENTDRIVENSCHEDULINGAGENT_H_


text:
public class SelectedOrder {

    private static long nextId = 0;

    private final long id;
    private final Planet source;
    private final Planet destination;
    private final int shipCount;

    public SelectedOrder(final Planet source, final Planet destination, final int shipCount) {
        super();
        this.id = nextId++;
        this.source = source;
        this.destination = destination;
        this.shipCount = shipCount;
    }

    public Planet getSource() {
        return source;
    }

    public Planet getDestination() {
        return destination;
    }

    public int getShipCount() {
        return shipCount;
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        final SelectedOrder that = (SelectedOrder) o;
        return id == that.id;
    }

    @Override
    public int hashCode() {
        return (int) (id ^ (id >>> 32));
    }

    @Override
    public String toString() {
        return "SelectedOrder(" + source + " -> " + destination + " #" + shipCount + ")";
    }
}


text:
name: John
---

# In Progress

* [Project A] Lipsum dolor sit amet

# Pipeline

* [Project B] Veggie ipsum dolor sit amet
* [Project B] Dolor ipsum sit lipsum

# Next week

* [Project C] Dolor ipsum sit lipsum


text:
<input id="updateItem" type="button" value="Update Item" onclick="updateItem();" />

<textarea readonly id= "textarea" style="width:400px; height:800px"></textarea>


text:
{-| Types and path helpers.
    This is re-exported in the main `Shikensu` module.

-}
module Shikensu.Internal.Types where

import Data.Aeson ((.=), toJSON)
import Data.Aeson.KeyMap (KeyMap)
import Data.ByteString (ByteString)
import Data.Monoid ((<>))
import System.FilePath (joinPath)

import qualified Data.Aeson as Aeson (ToJSON, Value, object)

{-| A file definition, along with some additional properties.
-}
data Definition =
    Definition
        { basename :: String
        , dirname :: FilePath
        , extname :: String
        , pattern :: String
        , rootDirname :: FilePath
        , workingDirname :: FilePath

        -- Additional properties
        , content :: Maybe ByteString
        , metadata :: Metadata
        , parentPath :: Maybe FilePath
        , pathToRoot :: FilePath
        } deriving (Eq, Show)

instance Aeson.ToJSON Definition where
    toJSON def =
        Aeson.object
            [ "basename"        .= basename def
            , "dirname"         .= dirname def
            , "extname"         .= extname def
            , "pattern"         .= pattern def
            , "workingDirname"  .= workingDirname def
            , "parentPath"      .= parentPath def
            , "pathToRoot"      .= pathToRoot def
            ]

-- Type aliases

type Dictionary = [Definition]
type Metadata = KeyMap Aeson.Value

-- Path functions

absolutePath :: Definition -> String
absolutePath def =
    joinPath [rootDirname def, workspacePath def]

localPath :: Definition -> String
localPath def =
    joinPath [dirname def, basename def <> extname def]

workspacePath :: Definition -> String
workspacePath def =
    joinPath [workingDirname def, localPath def]


text:
package org.drools.benchmarks.turtle.runtime;

import org.drools.benchmarks.model.Account;
import org.kie.api.runtime.KieSession;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.Benchmark;

import java.util.ArrayList;
import java.util.List;

@Warmup(iterations = 100000)
@Measurement(iterations = 10000)
public class DTable1Benchmark extends AbstractSimpleRuntimeBenchmark {

    private static int from = 999;
    private static int to = 3102;

    @Setup
    public void addResources() {
        addClassPathResource("kbase-creation/dtable1-kbase-creation.xls");
    }

    @Benchmark
    public KieSession timeFactsInsertionAndRulesFiring() {
        return insertFactsAndFireAllRules();
    }

    @Override
    protected List<Object> generateFacts() {
        List<Object> facts = new ArrayList<Object>();
        for (int i = from; i < to; i++) {
            Account account = new Account();
            account.setNumber(i);
            facts.add(account);
        }
        return facts;
    }

}


text:
package com.yueny.demo.job.scheduler.demo;

import org.springframework.scheduling.annotation.Scheduled;

import com.yueny.demo.job.scheduler.base.BaseSuperScheduler;

/**
 * @author yueny09 <deep_blue_yang@163.com>
 *
 * @DATE 2017年4月18日 下午6:26:57
 *
 */
// @Component
public class ExampleJob extends BaseSuperScheduler {
	// @Value("${aaaa:0}")
	// private String aaaa;
	// @Value(value = "${memcached.serverlist}")
	// private String memcachedAddress;
	// @Value("${zookeeper.address}")
	// private String zookeeperAddress;

	/**
	 *
	 */
	@Scheduled(cron = "0/30 * * * * ?")
	public void processData() {
		System.out.println("ExampleJob");

		// logger.info("ExampleJob with memcachedAddress {} and {} ...",
		// memcachedAddress, zookeeperAddress);
		// System.out.println(aaaa);
	}

}


text:
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.api.ads.dfp.axis;

import com.google.api.ads.common.lib.client.HeaderHandler;
import com.google.api.ads.common.lib.soap.ProductFrameworkModule;
import com.google.api.ads.common.lib.soap.axis.AxisModule;
import com.google.api.ads.dfp.lib.DfpModule;
import com.google.api.ads.dfp.lib.DfpProductFrameworkModule;
import com.google.api.ads.dfp.lib.DfpSoapModule;
import com.google.inject.TypeLiteral;

/**
 * Guice module to bind DFP's SOAP header handler to an Axis-friendly
 * implementation.
 */
@DfpProductFrameworkModule
public class DfpAxisModule extends ProductFrameworkModule {

  @SuppressWarnings("rawtypes") /* Guice lacks support for template type literals.*/
  @Override
  public void configure() {
    bind(new TypeLiteral<HeaderHandler>() {}).to(new TypeLiteral<DfpAxisHeaderHandler>() {});
    install(new AxisModule());
    install(new DfpModule());
    install(new DfpSoapModule());
    configureConfigurations(this.getClass().getResource("conf/props/build.properties"));
  }
}


text:
require_relative "context"
require_relative "registry"

module RDG
  module Analysis
    class Analyser
      extend Forwardable
      def_delegators :@context, :graph, :equivalences, :registry

      def self.register_analyser(*types)
        Registry.register_by_type(self, *types)
      end

      def self.register_default_analyser
        Registry.register_default(self)
      end

      def initialize(ast_node)
        @ast_node = ast_node
        prepare
      end

      def analyse(context = Context.new)
        @context = context
      end

      private

      def prepare
        # do nothing
      end

      def remove_all_successors
        graph.each_successor(@ast_node) { |s| graph.remove_edge(@ast_node, s) }
      end
    end
  end
end


text:
/**
 * (created at 2012-6-15)
 */
package com.alibaba.cobar.config.loader.xml;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.alibaba.cobar.config.model.ClusterConfig;
import com.alibaba.cobar.config.model.QuarantineConfig;
import com.alibaba.cobar.config.model.SystemConfig;
import com.alibaba.cobar.config.model.UserConfig;
import com.alibaba.cobar.config.util.ConfigException;
import com.alibaba.cobar.config.util.ConfigUtil;
import com.alibaba.cobar.config.util.ParameterMapping;
import com.alibaba.cobar.util.SplitUtil;

/**
 * @author QIU Shuo
 */
@SuppressWarnings("unchecked")
public class XMLServerLoader {
    private final SystemConfig system;
    private final Map<String, UserConfig> users;
    private final QuarantineConfig quarantine;
    private ClusterConfig cluster;

    public XMLServerLoader() {
        this.system = new SystemConfig();
        this.users = new HashMap<String, UserConfig>();
        this.quarantine = new QuarantineConfig();
        this.load();
    }

    public SystemConfig getSystem() {
        return system;
    }

    public Map<String, UserConfig> getUsers() {
        return (Map<String, UserConfig>) (users.isEmpty() ? Collections.emptyMap() : Collections.unmodifiableMap(users));
    }

    public QuarantineConfig getQuarantine() {
        return quarantine;
    }

    public ClusterConfig getCluster() {
        return cluster;
    }

    private void load() {
        InputStream dtd = null;
        InputStream xml = null;
        try {
            dtd = XMLServerLoader.class.getResourceAsStream("/server.dtd");
            xml = XMLServerLoader.class.getResourceAsStream("/server.xml");
            Element root = ConfigUtil.getDocument(dtd, xml).getDocumentElement();
            loadSystem(root);
            loadUsers(root);
            this.cluster = new ClusterConfig(root, system.getServerPort());
            loadQuarantine(root);
        } catch (ConfigException e) {
            throw e;
        } catch (Throwable e) {
            throw new ConfigException(e);
        } finally {
            if (dtd != null) {
                try {
                    dtd.close();
                } catch (IOException e) {
                }
            }
            if (xml != null) {
                try {
                    xml.close();
                } catch (IOException e) {
                }
            }
        }
    }

    private void loadQuarantine(Element root) {
        NodeList list = root.getElementsByTagName("host");
        for (int i = 0, n = list.getLength(); i < n; i++) {
            Node node = list.item(i);
            if (node instanceof Element) {
                Element e = (Element) node;
                String host = e.getAttribute("name").trim();
                if (quarantine.getHosts().containsKey(host)) {
                    throw new ConfigException("host duplicated : " + host);
                }

                Map<String, Object> props = ConfigUtil.loadElements(e);
                String[] users = SplitUtil.split((String) props.get("user"), ',', true);
                HashSet<String> set = new HashSet<String>();
                if (null != users) {
                    for (String user : users) {
                        UserConfig uc = this.users.get(user);
                        if (null == uc) {
                            throw new ConfigException("[user: " + user + "] doesn't exist in [host: " + host + "]");
                        }

                        if (null == uc.getSchemas() || uc.getSchemas().size() == 0) {
                            throw new ConfigException("[host: " + host + "] contains one root privileges user: " + user);
                        }
                        if (set.contains(user)) {
                            throw new ConfigException("[host: " + host + "] contains duplicate user: " + user);
                        } else {
                            set.add(user);
                        }
                    }
                }
                quarantine.getHosts().put(host, set);
            }
        }
    }

    private void loadUsers(Element root) {
        NodeList list = root.getElementsByTagName("user");
        for (int i = 0, n = list.getLength(); i < n; i++) {
            Node node = list.item(i);
            if (node instanceof Element) {
                Element e = (Element) node;
                String name = e.getAttribute("name");
                UserConfig user = new UserConfig();
                user.setName(name);
                Map<String, Object> props = ConfigUtil.loadElements(e);
                user.setPassword((String) props.get("password"));
                String schemas = (String) props.get("schemas");
                if (schemas != null) {
                    String[] strArray = SplitUtil.split(schemas, ',', true);
                    user.setSchemas(new HashSet<String>(Arrays.asList(strArray)));
                }
                if (users.containsKey(name)) {
                    throw new ConfigException("user " + name + " duplicated!");
                }
                users.put(name, user);
            }
        }
    }

    private void loadSystem(Element root) throws IllegalAccessException, InvocationTargetException {
        NodeList list = root.getElementsByTagName("system");
        for (int i = 0, n = list.getLength(); i < n; i++) {
            Node node = list.item(i);
            if (node instanceof Element) {
                Map<String, Object> props = ConfigUtil.loadElements((Element) node);
                ParameterMapping.mapping(system, props);
            }
        }
    }

}


text:
Widget support the following options that are additionally recognized over and above the configuration options in the InputWidget.

## Base options

**theme** _string_: specify the theme of the widget. Available 2 themes:

* `default` with only widget css classes
* `bs` \(twitter bootstrap\) theme with additional BS ccs classes\).

Default value is `bs`

**max** _integer_: maximum number of rows. If not set will default to unlimited

**min** _integer_: minimum number of rows. Set to `0` if you need the empty list in case you don't have any data

**prepend** _boolean_: add a new row to the beginning of the list, not to the end

**attributeOptions** _array_: client-side attribute options, e.g. enableAjaxValidation. You may use this property in case when you use widget without a model, since in this case widget is not able to detect client-side options automatically

**addButtonPosition** _integer\|array_: the position\(s\) of `add` button. This can be `MultipleInput::POS_HEADER`, `MultipleInput::POS_ROW`, `MultipleInput::POS_ROW_BEGIN` or `MultipleInput::POS_FOOTER`.

**addButtonOptions** _array_: the HTML options for `add` button. Can contains `class` and `label` keys

**removeButtonOptions** _array_: the HTML options for `remove` button. Can contains `class` and `label` keys

**cloneButton** _bool_: whether need to enable clone buttons or not

**cloneButtonOptions** _array_: the HTML options for `remove` button. Can contains `class` and `label` keys

**data** _array_: array of values in case you use widget without model

**models** _array_: the list of models. Required in case you use `TabularInput` widget

**allowEmptyList** _boolean_: whether to allow the empty list. **Deprecateed** use the `min` option instead

**columnClass** _string_: the name of column class. You can specify your own class to extend base functionality. Defaults to `unclead\multipleinput\MultipleInputColumn` for `MultipleInput` and `unclead\multipleinput\TabularColumn` for `TabularInput`.

**rendererClass** _string_: the name of renderer class. You can specify your own class to extend base functionality. Defaults to `unclead\multipleinput\renderers\TableRenderer`.

**columns** _array_: the row columns configuration where you can set the properties which is described below

**rowOptions** _array\|\Closure_: the HTML attributes for the table body rows. This can be either an array specifying the common HTML attributes for all body rows, or an anonymous function that returns an array of the HTML attributes. It should have the following signature:

```php
function ($model, $index, $context)
```

* `$model`: the current data model being rendered
* `$index`: the zero-based index of the data model in the model array
* `$context`: the widget object

**sortable** _bool_: whether need to enable sorting or not

**modelClass** _string_: a class of model which is used to render `TabularInput`. You must specify this property when a list of `models` is empty. If this property is not specified the widget will detect it based on a class of `models`

**extraButtons** _string\|\Closure_: the HTML content that will be rendered after the buttons. It can be either string or an anonymous function that returns a string which will be treated as HTML content. It should have the following signature:

```php
function ($model, $index, $context)
```

* `$model`: the current data model being rendered
* `$index`: the zero-based index of the data model in the model array
* `$context`: the MultipleInput widget object

**layoutConfig** _array_: CSS grid classes for horizontal layout \(only supported for `ListRenderer` class\). This must be an array with these keys:

* `'offsetClass'`: the offset grid class to append to the wrapper if no label is rendered
* `'labelClass'`: the label grid class
* `'wrapperClass'`: the wrapper grid class
* `'errorClass'`: the error grid class

**showGeneralError** _bool_: whether need to show error message for main attribute, when you don't want to validate particular input and want to validate a filed in general.

## Column options

**name** _string_: input name. _Required options_

**type** _string_: type of the input. If not set will default to `textInput`. Read more about the types described below

**title** _string_: the column title

**value** _Closure_: you can set it to an anonymous function with the following signature:

```php
function($data) {}
```

**defaultValue** _string_: default value of input

**items** _array_\|_Closure_: the items for input with type dropDownList, listBox, checkboxList, radioList or anonymous function which return array of items and has the following signature:

```php
function($data) {}
```

**options** _array_\|_Closure_: the HTML attributes for the input, you can set it as array or an anonymous function with the following signature:

```php
function($data) {}
```

**headerOptions** _array_: the HTML attributes for the header cell

**enableError** _boolean_: whether to render inline error for the input. Default to `false`

**errorOptions** _array_: the HTMl attributes for the error tag

**nameSuffix** _string_: the unique prefix for attribute's name to avoid id duplication e.g. in case of using several copies of the widget on a page and one column is a Select2 widget

**tabindex** _integer_: use it to customize a form element `tabindex`

**attributeOptions** _array_: client-side options of the attribute, e.g. enableAjaxValidation. You can use this property for custom configuration of the column (attribute). By default, the column will use options which are defined on widget level.

_Supported versions >= 2.1.0

**columnOptions** _array|\Closure_: the HTML attributes for the indivdual table body column. This can be either an array specifying the common HTML attributes for indivdual body column, or an anonymous function that returns an array of the HTML attributes.

It should have the following signature:
```php
function ($model, $index, $context)
```
* `$model`: the current data model being rendered
* `$index`: the zero-based index of the data model in the model array
* `$context`: the widget object

_Supported versions >= 2.18.0_

**inputTemplate** _string_: the template of input for customize view. Default is `{input}`.

**Example**

`<div class="input-group"><span class="input-group-addon"><i class="fas fa-mobile-alt"></i></span>{input}</div>`

## Input types

Each column in a row can has their own type. Widget supports:

* all yii2 html input types:
  * `textInput`
  * `dropDownList`
  * `radioList`
  * `textarea`
  * For more detail look at [Html helper class](http://www.yiiframework.com/doc-2.0/yii-helpers-html.html)
* input widget \(widget that extends from `InputWidget` class\). For example, `yii\widgets\MaskedInput`
* `static` to output a static HTML content

For using widget as column input you may use the following code:

```php
echo $form->field($model, 'phones')->widget(MultipleInput::className(), [
...
    'columns' => [
        ...
        [
            'name'  => 'phones',
            'title' => $model->getAttributeLabel('phones'),
            'type' => \yii\widgets\MaskedInput::className(),
            'options' => [
                'class' => 'input-phone',
                'mask' => '999-999-99-99',
            ],
        ],
    ],
])->label(false);
```


text:
title: "Standigm ranked third in the AstraZeneca-Sanger drug Combination Prediction Dream Challenge"
date: May 11, 2016
categories:
  - News
---

Standigm had participated in the AstraZeneca-Sanger Drug Combination Prediction Dream Challenge hosted by one of the leading pharmaceutical companies, AstraZeneca. Standigm team ranked third among 71 international teams. Standigm will apply the methods to precision medicine, patient stratification, and therapeutic/diagnostic design.

[Read result](https://www.synapse.org/#!Synapse:syn4231880/wiki/247607)

Read from Korean press
* [etnews](http://www.etnews.com/20160511000290)


text:
import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { OePage } from './oe';

@NgModule({
  declarations: [
    OePage,
  ],
  imports: [
    IonicPageModule.forChild(OePage),
  ],
  exports: [
    OePage
  ]
})
export class OePageModule {}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <!-- Content Descriptions -->
    <string name="cd_web_button">Click to open sellers web page.</string>
    <string name="cd_navigation_button">Click to navigate to seller.</string>

</resources>


text:
#ifndef FLEXIMAGE_H
#define FLEXIMAGE_H

#if defined(HAVE_CONFIG_H)
# include "config.h"
#endif

#include <string>
#include "FlexDefs.h"
#include "FlexDataExchange.h"
#include "FlexImageStore.h"

template <class T, int C>
class FlexImage {

protected:

	FlexImageStore<T,C> *mStore;	//Pointer to FlexImageStore object owning pixel data
	T *mData;						//Pointer to image data
	int mBpp;						//Size in bytes of pixel   (step x)
	int mStepBytes;					//Stride in bytes per line (step y)
	FISize mSize;					//Image dimensions
	FlexImageStatus mStatus;		//Error status for image object

protected:

	///Allocate image store object according to width, height, and channel data members
	void Allocate();
	///Decrement reference and destroy image store if necessary
	void DecReference();

public:

	//-------------------------- Constructors --------------------------------
	///Default Constructor
	FlexImage();
	///Constructor specifying width, height - allocates a new FlexImageStore
	FlexImage(int width, int height);
	///Constructor specifying FISize - allocates a new FlexImageStore
	FlexImage(FISize size);
	///Constructor specifying width, height, and initial value - allocates a new FlexImageStore
	FlexImage(int width, int height, T InitVal);
	///Constructor specifying FISize and initial value - allocates a new FlexImageStore
	FlexImage(FISize size, T InitVal);
	///Copy Constructor
	FlexImage(const FlexImage<T,C> &src);
	///Creates a sub-image from an FlexImage referencing the same memory
	FlexImage(const FlexImage<T,C> &src, int x, int y, int width, int height);
	///Sub image constructor specifying an IppRect
	FlexImage(const FlexImage<T,C> &src, const FIRect &r);

	///Destructor - frees image store if object has last reference to it
	~FlexImage();

	//-------------------------- Member Functions -----------------------------

	///Reallocate to a given size - creates new image store
	bool Reallocate(int width, int height);
	bool Reallocate(FISize size);

	///Get function for pixel data pointer
	inline T *Data()					{ return(mData); };
	inline const T *Data()		const	{ return(mData); };

	//various get functions
	inline int StepBytes()		const	{ return(mStepBytes); };
	inline int BytesPerPixel()	const	{ return(mBpp); };
	inline FISize Size()		const	{ return(mSize); };
	inline int Width()			const	{ return(mSize.width); };
	inline int Height()			const	{ return(mSize.height); };
	inline bool Empty()			const	{ return(mSize.width == 0 && mSize.height == 0); };

	///Convenience function for image rect ( 0,0,w,h )
	inline FIRect ImgRect() const;

	///Equals operator - sets image to refer to same memory as source image
	void operator=(const FlexImage<T,C> &src);

	///Create Sub Image of a given image - points to same memory
	void CreateSubImage(const FlexImage<T,C> &img, int x, int y, int width, int height);
	void CreateSubImage(const FlexImage<T,C> &img, const FIRect &r);

	///Convert image to another data type
	template<class T2>
	FIStatus ConvertFrom(const FlexImage<T2,C> &src, bool allocate = true);
	template<class T2>
	FIStatus ConvertTo(FlexImage<T2,C> &dst, bool allocate = true) const;

	///Deep copy of a given image
	FIStatus CopyTo(FlexImage<T,C> &dst, bool allocate = true) const;
	FIStatus CopyFrom(const FlexImage<T,C> &src, bool allocate = true);

	///Pixel access through () operator for given plane
	inline T &operator ()(int x, int y, int c) {return( *(T *)((char *)mData + mStepBytes * y + mBpp * x + c*sizeof(T) )); };
	inline T &operator ()(int x, int y, int c) const {return( *(T *)((char *)mData + mStepBytes * y + mBpp * x + c*sizeof(T) )); };
	///Pixel access through () operator into plane 0
	inline T &operator ()(int x, int y) { return (operator()(x, y, 0)); };
	inline T &operator ()(int x, int y) const { return (operator()(x, y, 0)); };

	///() operator returns a sub image with 4 parameters
	FlexImage<T,C> operator ()(int x, int y, int width, int height);

	///Fill ROI of image specifying a value for each channel
	FIStatus Set(T value[C+1]);
	///Fill ROI of image specifying a single value for all channels
	FIStatus Set(T value)
	{	T colors[C+1];
		for(int i=0; i < C; i++)
			colors[i] = value;
		return(Set(colors));
	};

	//set a pixel to a color given as an array sized to the number of channels
	void SetPixel(int x, int y, T *color);

	///reallocate to given dimensions if not already equal.  If equal, do nothing. Returns true if resized.
	bool ReallocateNE(int w, int h);

	///reallocate to given dimensions if not already of equal or greater size in both dimensions
	bool ReallocateGE(int w, int h);

	///determine if another image is of equal size
	bool EqualSize(const FlexImage<T,C> &img);

	///Return Error/Warning status
	FlexImageStatus Status() { return mStatus; };

	///Print contents of image to standard out
	void Print();

	// --------------------------------------------------------------------------------------
	//Advanced functions - most users will never need these

	///Get function for Image store object
	inline FlexImageStore<T,C> *ImageStore() { return(mStore); };
	inline const FlexImageStore<T,C> *ImageStore() const { return(mStore); };

	///Create Sub Image from a given image store
	void CreateSubImage(FlexImageStore<T,C> &store, int x, int y, int width, int height);
	void CreateSubImage(FlexImageStore<T,C> &store, FIRect &r);

	///Creates a sub-image from an FlexImagestore
	FlexImage(FlexImageStore<T,C> &store, int x, int y, int width, int height);

};

//------------------------Implementation required to be in header -------------------

template<class T, int C>
template<class T2>
FIStatus FlexImage<T,C>::ConvertFrom(const FlexImage<T2,C> &src, bool allocate)
{	return( FlexConvert<T2,T,C>(src, *this, allocate) );
}

template<class T, int C>
template<class T2>
FIStatus FlexImage<T,C>::ConvertTo(FlexImage<T2,C> &dst, bool allocate) const
{	return( FlexConvert<T,T2,C>(*this, dst, allocate) );
}

#endif


text:
package com.intellij.ide.util.gotoByName;

import org.jetbrains.annotations.NotNull;

/**
 * @author Roman.Chernyatchik
 * @date Mar 11, 2009
 */
public interface CustomMatcherModel {
  /**
   * Allows to implement custom matcher for matching items from ChooseByName popup
   * with user pattern
   * @param popupItem Item from list
   * @param userPattern Pattern defined by user in Choose by name popup
   * @return True if matches
   */
  boolean matches(@NotNull final String popupItem, @NotNull final String userPattern);
}


text:
/** Binary connection of two sub formulas. */
public class Bin extends Formula {

  /** Left sub formula. */
  public final Formula left;

  /** The connective. */
  public final Conn connective;

  /** Right sub formula. */
  public final Formula right;

  Bin (Formula left, Conn connective, Formula right) {
    this.left       = left;
    this.connective = connective;
    this.right      = right;
  }

  public String toString() {
    return "(" + left.toString() +
           " " + connective.toString() +
           " " + right.toString() + ")";
  }

  public boolean eval (boolean[] valuation) {
    final boolean l = left.eval(valuation);
    final boolean r = right.eval(valuation);
    switch (connective) {
    case AND     : return l && r;
    case OR      : return l || r;
    case IMPLIES : return !l || r;
    case IFF     : return l == r;
    default      : throw new UnsupportedOperationException();
    }
  }
}


text:
<?php

namespace Balongo\UserBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('user');

        // Here you should define the parameters that are allowed to
        // configure your bundle. See the documentation linked above for
        // more information on that topic.

        return $treeBuilder;
    }
}


text:
> responsive graphical weekly scheduler component with drag/expand functionality to fill time blocks

## Install

```console
$ npm install react-week-scheduler
```

## Usage

```js
import WeeklyScheduler from 'react-week-scheduler';
import 'react-week-scheduler/react-week-scheduler.css';
```

### Properties

```js
return (
  <div>
    <WeeklyScheduler
      defaultEvent={startingDefault} selectedEvent={blockingEvent} events={eventList}
      currentSchedule={currentSchedule}
      ref={(scheduler) => { this.scheduler = scheduler; }}
    />
  </div>
);
```
Event objects follow the format: { event: 'myEventName', color '#999'}. Any format of CSS color string including hsl should be valid.

`defaultEvent` - event that by default will fill the week

`selectedEvent` - default event selected for filling scheduler

`events` - array of events to select from to fill scheduler

`currentSchedule` - 7 x 96 timeblock matrix corresponding to 7 weekdays and 96 15-minute blocks per day. Stores Event objects.

### Accessing Scheduler state

To access and return current Scheduler state just use a `ref` callback:

  `ref={(scheduler) => { this.scheduler = scheduler }}`

Current timeblock matrix will be stored in `this.scheduler.state.days` corresponding to above ref

##Demo

[https://wrleskovec.github.io/react-week-scheduler/](https://wrleskovec.github.io/react-week-scheduler/)