text:
<?xml version="1.0" encoding="utf-8"?>
<!-- invalid - ttp:processorProfileCombination - all space value -->
<tt xml:lang="en" xmlns="http://www.w3.org/ns/ttml"
  xmlns:ttp="http://www.w3.org/ns/ttml#parameter" ttp:profile="ttml2-transformation"
  ttp:processorProfileCombination="

 "
  xmlns:ttva="http://skynav.com/ns/ttv/annotations" ttva:warnOn="all" ttva:expectedErrors="2" ttva:expectedWarnings="0" ttva:model="ttml2"/>


text:
@interface HCMatchSequence : NSObject
@property (nonatomic, readonly) NSArray *matchers;
@property (nonatomic, readonly) id <HCDescription, NSObject> mismatchDescription;
@property (nonatomic) NSUInteger nextMatchIndex;
@end

@implementation HCMatchSequence

- (instancetype)initWithMatchers:(NSArray *)itemMatchers
             mismatchDescription:(id<HCDescription, NSObject>)description
{
    self = [super init];
    if (self)
    {
        _matchers = [itemMatchers copy];
        _mismatchDescription = description;
    }
    return self;
}

- (BOOL)matches:(id)item
{
    return [self isNotSurplus:item] && [self isMatched:item];
}

- (BOOL)isFinished
{
    if (self.nextMatchIndex < [self.matchers count])
    {
        [[self.mismatchDescription appendText:@"no item matched: "]
                              appendDescriptionOf:self.matchers[self.nextMatchIndex]];
        return NO;
    }
    return YES;
}

- (BOOL)isMatched:(id)item
{
    id <HCMatcher> matcher = self.matchers[self.nextMatchIndex];
    if (![matcher matches:item])
    {
        [self describeMismatchOfMatcher:matcher item:item];
        return NO;
    }
    ++self.nextMatchIndex;
    return YES;
}

- (BOOL)isNotSurplus:(id)item
{
    if ([self.matchers count] <= self.nextMatchIndex)
    {
        [[self.mismatchDescription appendText:@"not matched: "] appendDescriptionOf:item];
        return NO;
    }
    return YES;
}

- (void)describeMismatchOfMatcher:(id <HCMatcher>)matcher item:(id)item
{
    [self.mismatchDescription appendText:[NSString stringWithFormat:@"item %zi: ", self.nextMatchIndex]];
    [matcher describeMismatchOf:item to:self.mismatchDescription];
}

@end

@interface HCIsCollectionContainingInOrder ()
@property (nonatomic, readonly) NSArray *matchers;
@end

@implementation HCIsCollectionContainingInOrder

+ (instancetype)isCollectionContainingInOrder:(NSArray *)itemMatchers
{
    return [[self alloc] initWithMatchers:itemMatchers];
}

- (instancetype)initWithMatchers:(NSArray *)itemMatchers
{
    self = [super init];
    if (self)
        _matchers = [itemMatchers copy];
    return self;
}

- (BOOL)matches:(id)collection
{
    return [self matches:collection describingMismatchTo:nil];
}

- (BOOL)matches:(id)collection describingMismatchTo:(id<HCDescription, NSObject>)mismatchDescription
{
    if (![collection conformsToProtocol:@protocol(NSFastEnumeration)])
    {
        [super describeMismatchOf:collection to:mismatchDescription];
        return NO;
    }

    HCMatchSequence *matchSequence =
        [[HCMatchSequence alloc] initWithMatchers:self.matchers
                              mismatchDescription:mismatchDescription];
    for (id item in collection)
        if (![matchSequence matches:item])
            return NO;

    return [matchSequence isFinished];
}

- (void)describeMismatchOf:(id)item to:(id<HCDescription>)mismatchDescription
{
    [self matches:item describingMismatchTo:mismatchDescription];
}

- (void)describeTo:(id<HCDescription>)description
{
    [[description appendText:@"a collection containing "]
                  appendList:self.matchers start:@"[" separator:@", " end:@"]"];
}

@end

id HC_contains(id itemMatch, ...)
{
    va_list args;
    va_start(args, itemMatch);
    NSArray *matchers = HCCollectMatchers(itemMatch, args);
    va_end(args);

    return [HCIsCollectionContainingInOrder isCollectionContainingInOrder:matchers];
}

redpajama_set_name: RedPajamaGithub


text:
Q2MM stands for quantum (mechanics) to molecular mechanics or quantum guided
molecular mechanics, depending on what you prefer. Q2MM is open source software
for force field optimization.

---

### Python Dependencies

Q2MM uses Python 2.7.4. I'm reluctant to use more recent versions of Python
because as far as I know, Schrödinger still uses 2.7.4.

The following modules are required, but are included in the standard library for
Python 2.7.4.

* argparse
* collections
* copy
* glob
* itertools
* logging
* mmap
* os
* random
* re
* string
* sqlite3
* subprocess
* sys
* textwrap
* time

These are required, but aren't in the standard library.

* numpy

Required for particular features.

* schrodinger

If you'd like to use Schrödinger features, they recommend running external
Python scripts using

```
$SCHRODINGER/run somepythoncode.py
```

---

### Usage

You can get help for most python Q2MM scripts using the command line. Here's an
example.

```
python calculate.py -h
```

### Setting up the Schrödinger MM3* force field

These force field files are labeled `mm3.fld`. Our custom parameters are stored
in substructures towards the end of theses files. For information on these
substructures, see the MacroModel reference manual.

Substructures are marked for optimization by adding the word "OPT" to their
title. For example, you could name your substructure "New Metal Parameters OPT".
Running

```
python parameters.py -f pathtomm3.fld -a -pp
```

will print a list of the parameters that Q2MM identified. You can redirect the
output parameter list to a file using standard Unix redirection.

```
python parameters.py -f pathtomm3fld -a -pp > params.txt
```

Here's an example of what `params.txt` might look like.

```
1854 1 0.0 inf
1854 2 0.0 inf
1854 3 -inf inf
1855 1 0.0 inf
1855 2 0.0 inf
1856 1 -inf inf
1856 2 -inf inf
1856 3 -inf inf
```

The first column refers to the line of the force field file where the parameter
is located. The second column is an index refering to the location of the
parameter in that line. For Schrödinger and `mm3.fld`, equilibrium bond lengths
are found in column 1, force constants in column 2, dipoles in column 3, etc.
See Schrödinger's documentation and the documentation inside
[`parameters`](q2mm/parameters.py).

The 3rd and 4th column in `params.txt` are optional and specify the allowed
parameter range. These values can be any floating points. Also, "inf" is used to
signify the parameter can go to infinity. If the 3rd and 4th column aren't
included, Q2MM will attempt to identify suitable parameter ranges based upon the
parameter type.

Currently, these parameter ranges are hard walls. In other words, if a step
is made to move outside that wall, the step is simply scaled down to not go too
far. Ideally, we should implement soft walls in the future.

To select only certain types of parameters, use

```
python parameters.py -f mm3.fld -pt bf af
```

This command would print the bond and angle force constants in the format
described above. See the help dialogue for
[`parameters`](q2mm/parameters.py) for more information.

### Running an optimization loop

I would always recommend making a backup of your force field before beginning an
optimization.

The loop module uses customized input files to manage the optimization of
parameters. You can supply the input file using the simple command shown below.

```
python loop.py someinputfile
```

Here's an example of what the input file could look like.

```
DIR somedir
FFLD read mm3.fld # This is a comment.
PARM params.txt
RDAT -d somedir -je str_a.mae str_b.mae str_c.mae -je str_d.mae str_e.mae -jb str_a.mae str_b.mae str_c.mae str_d.mae str_e.mae
CDAT -d somedir -me str_a.mae str_b.mae str_c.mae -me str_d.mae str_e.mae -mb str_a.mae str_b.mae str_c.mae str_d.mae str_e.mae
COMP -o opt_start.txt
# Here's another comment.
LOOP 0.15
GRAD
SIMP
END
LOOP 0.05
GRAD
END
FFLD write smm3.fld
CDAT
COMP -o opt_end.txt
```

Let's breakdown each line.

```
DIR somedir
```

This sets the directory where all the data files, `atom.typ`, and `mm3.fld`
files are located. Also, the MacroModel calculations will be run from this
directory, and Q2MM intermediate or temporary files will be written here.

```
FFLD read mm3.fld
```

Read the initial force field.

```
PARM params.txt
```

Select certain parameters from the force field you just read. Without this, all
parameters in the substructre are selected.

```
RDAT -d somedir -je str_a.mae str_b.mae str_c.mae -je str_d.mae str_e.mae -jb str_a.mae str_b.mae str_c.mae str_d.mae str_e.mae
```

This gathers the reference data used throughout the optimization. All of the
arguments following `RDAT` are the same as the arguments used for the calculate
module. See
[`calculate`](q2mm/calculate.py) help for more information. Note that the
directory is still included in the command shown above.

```
CDAT -d somedir -me str_a.mae str_b.mae str_c.mae -me str_d.mae str_e.mae -mb str_a.mae str_b.mae str_c.mae str_d.mae str_e.mae
```

Same as above, except this is for the force field data.

```
COMP -o opt_start.txt
```

Compare the reference data to the force field data to determine the initial
objective function score. Write the data and scores out to
somedir/opt_start.txt.

```
LOOP 0.15
```

This marks the beginning of an optimization loop. All commands located between
this line and the line containg `END` will be repeated until convergence is
reached. In this case, it loops back and forth between
[`gradient`](q2mm/gradient.py) and
[`simplex`](q2mm/simplex.py)
until the objective function changes by less than 15%.

```
GRAD
```

Use the gradient methods to optimize parameters. See the
[`gradient`](q2mm/gradient.py) module for
more information.

```
SIMP
```

Use the simplex method to optimize parameters. See the
[`simplex`](q2mm/simplex.py) module for more information.

```
END
```

Marks the end of the commands being looped.

```
LOOP 0.05
```

Start another loop, but this time with a stricter convergence of 5% change.
Really, you will hardly ever need to include two separate loops. I'm just
showing you that you can if you want to for whatever reason.

```
GRAD
```

In this loop, we're only using the
[`gradient`](q2mm/gradient.py) method.

```
END
```

Marks the end of the second loop.

```
FFLD write mm3.fld
```

Write the optimized force field parammeters to `somedir/mm3.fld`.

```
CDAT
```

Calculate the force field data again. If `CDAT` is used without additional
arguments, as shown here, then it remembers the previously entered arguments and
repeats them. Calculating the force field data again here may seem excessive,
but I wanted to make sure that the FF data stored in memory was calculated using
the most recent optimized parameters. Better safe than sorry!

```
COMP -o opt_end.txt
```

Compare the reference and force field data for the optimized force field. Note
that the reference data remains the same through this entire command file, so
there's no need for me to use another `RDAT` command. Write the data and scores
out to `somedir/opt_end.txt`. At this point, it would be wise to examine
`mm3.fld`. Check that the parameters seem reasonable, and cross-check them with
the backed up original parameters.

### Changes to default settings

#### Maximum parameters for simplex optimization:
The maximum parameters that are used for simplex optimizations is defaulted to
10, but can be changed with the max_params command.
```
SIMP max_params=6
```

#### Control of gradient methods:
Five gradient methods are available: least-squared, lagrange, levenberg,
newton-raphson, and SVD. Changing default settings for these require the use of
the shortened name (lstsq, legrange, levenberg, newton, and svd) followed by "="
and the settings the user wants to use. True and False commands will turn on and
off the optimizers, respectively. Users can also change the factors, cutoffs, and
radii, that are used by including the setting they want to change followed by the
values seperated by "/" nested in brackets.
```
GRAD lstsq=False newton=True,cutoffs[None],radii[0.01/0.1/2.0] svd=True,factor[0.01/0.1]
```

#### Changing default weights and step sizes:
A user may want to change the weights of certain data, or step sizes during
differentiation of parameters. This can be accomplished with the keywords WGHT and
STEP followed by the data/parameter type and value.
```
WGHT b 10.0
STEP be 1.0
```


text:
// Discovery type.
// Copyright (C) 2008-2010 Malcolm Crowe, Lex Li, and other contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

/*
 * Created by SharpDevelop.
 * User: lextm
 * Date: 5/24/2009
 * Time: 11:56 AM
 *
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using Lextm.SharpSnmpLib.Security;

namespace Lextm.SharpSnmpLib.Messaging
{
    /// <summary>
    /// Discovery class that participates in SNMP v3 discovery process.
    /// </summary>
    public sealed class Discovery
    {
        private readonly ISnmpMessage _discovery;
        private static readonly UserRegistry Empty = new UserRegistry();
        private static readonly SecurityParameters DefaultSecurityParameters =
            new SecurityParameters(
                OctetString.Empty,
                Integer32.Zero,
                Integer32.Zero,
                OctetString.Empty,
                OctetString.Empty,
                OctetString.Empty);

        /// <summary>
        /// Initializes a new instance of the <see cref="Discovery"/> class.
        /// </summary>
        /// <param name="requestId">The request id.</param>
        /// <param name="messageId">The message id.</param>
        /// <param name="maxMessageSize">The max size of message.</param>
        public Discovery(int messageId, int requestId, int maxMessageSize)
        {
            _discovery = new GetRequestMessage(
                VersionCode.V3,
                new Header(
                    new Integer32(messageId),
                    new Integer32(maxMessageSize),
                    Levels.Reportable),
                DefaultSecurityParameters,
                new Scope(
                    OctetString.Empty,
                    OctetString.Empty,
                    new GetRequestPdu(requestId, new List<Variable>())),
                DefaultPrivacyProvider.DefaultPair,
                null);
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Discovery"/> class.
        /// </summary>
        /// <param name="requestId">The request id.</param>
        /// <param name="messageId">The message id.</param>
        /// <param name="maxMessageSize">The max size of message.</param>
        /// <param name="type">Message type.</param>
        public Discovery(int messageId, int requestId, int maxMessageSize, SnmpType type)
        {
            switch (type)
            {
                case SnmpType.GetRequestPdu:
                    {
                        _discovery = new GetRequestMessage(
                            VersionCode.V3,
                            new Header(
                            new Integer32(messageId),
                            new Integer32(maxMessageSize),
                            Levels.Reportable),
                            DefaultSecurityParameters,
                            new Scope(
                            OctetString.Empty,
                            OctetString.Empty,
                            new GetRequestPdu(requestId, new List<Variable>())),
                            DefaultPrivacyProvider.DefaultPair,
                            null);
                        break;
                    }

                case SnmpType.GetNextRequestPdu:
                    {
                        _discovery = new GetNextRequestMessage(
                            VersionCode.V3,
                            new Header(
                            new Integer32(messageId),
                            new Integer32(maxMessageSize),
                            Levels.Reportable),
                            DefaultSecurityParameters,
                            new Scope(
                            OctetString.Empty,
                            OctetString.Empty,
                            new GetNextRequestPdu(requestId, new List<Variable>())),
                            DefaultPrivacyProvider.DefaultPair,
                            null);
                        break;
                    }

                case SnmpType.GetBulkRequestPdu:
                    {
                        _discovery = new GetBulkRequestMessage(
                            VersionCode.V3,
                            new Header(
                            new Integer32(messageId),
                            new Integer32(maxMessageSize),
                            Levels.Reportable),
                            DefaultSecurityParameters,
                            new Scope(
                            OctetString.Empty,
                            OctetString.Empty,
                            new GetBulkRequestPdu(requestId, 0, 0, new List<Variable>())),
                            DefaultPrivacyProvider.DefaultPair,
                            null);
                        break;
                    }

                case SnmpType.SetRequestPdu:
                    {
                        _discovery = new SetRequestMessage(
                            VersionCode.V3,
                            new Header(
                            new Integer32(messageId),
                            new Integer32(maxMessageSize),
                            Levels.Reportable),
                            DefaultSecurityParameters,
                            new Scope(
                            OctetString.Empty,
                            OctetString.Empty,
                            new SetRequestPdu(requestId, new List<Variable>())),
                            DefaultPrivacyProvider.DefaultPair,
                            null);
                        break;
                    }

                case SnmpType.InformRequestPdu:
                    {
                        _discovery = new InformRequestMessage(
                            VersionCode.V3,
                            new Header(
                            new Integer32(messageId),
                            new Integer32(maxMessageSize),
                            Levels.Reportable),
                            DefaultSecurityParameters,
                            new Scope(
                            OctetString.Empty,
                            OctetString.Empty,
                            new InformRequestPdu(requestId)),
                            DefaultPrivacyProvider.DefaultPair,
                            null);
                        break;
                    }

                default:
                    throw new ArgumentException("discovery message must be a request", "type");
            }
        }

        /// <summary>
        /// Gets the response.
        /// </summary>
        /// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
        /// <param name="receiver">The receiver.</param>
        /// <returns></returns>
        public ReportMessage GetResponse(int timeout, IPEndPoint receiver)
        {
            if (receiver == null)
            {
                throw new ArgumentNullException("receiver");
            }

            using (var socket = receiver.GetSocket())
            {
                return (ReportMessage)_discovery.GetResponse(timeout, receiver, Empty, socket);
            }
        }

        /// <summary>
        /// Converts to the bytes.
        /// </summary>
        /// <returns></returns>
        public byte[] ToBytes()
        {
            return _discovery.ToBytes();
        }

        /// <summary>
        /// Returns a <see cref="System.String"/> that represents this instance.
        /// </summary>
        /// <returns>
        /// A <see cref="System.String"/> that represents this instance.
        /// </returns>
        public override string ToString()
        {
            return string.Format(CultureInfo.InvariantCulture, "discovery class: message id: {0}; request id: {1}", _discovery.MessageId(), _discovery.RequestId());
        }
    }
}


text:
from django.urls import re_path

import sahara_dashboard.content.data_processing. \
    jobs.views as views
import sahara_dashboard.content.data_processing. \
    jobs.job_binaries.views as job_binary_views
import sahara_dashboard.content.data_processing. \
    jobs.data_sources.views as data_source_views
import sahara_dashboard.content.data_processing. \
    jobs.job_templates.views as job_templates_views
import sahara_dashboard.content.data_processing. \
    jobs.wizard.views as job_wizard_views
import sahara_dashboard.content.data_processing. \
    jobs.jobs.views as jobs_views

urlpatterns = [re_path(r'^$', views.IndexView.as_view(), name='index'),
               re_path(r'^$', views.IndexView.as_view(), name='jobs'),
               re_path(r'^\?tab=job_tabs__jobs_tab$',
                       views.IndexView.as_view(),
                       name='jobs-tab'),
               re_path(r'^create-job$',
                       job_templates_views.CreateJobView.as_view(),
                       name='create-job'),
               re_path(r'^launch-job$',
                       job_templates_views.LaunchJobView.as_view(),
                       name='launch-job'),
               re_path(r'^launch-job-new-cluster$', job_templates_views.
                       LaunchJobNewClusterView.as_view(),
                       name='launch-job-new-cluster'),
               re_path(r'^choose-plugin$',
                       job_templates_views.ChoosePluginView.as_view(),
                       name='choose-plugin'),
               re_path(r'^job-template/(?P<job_id>[^/]+)$',
                       job_templates_views.
                       JobTemplateDetailsView.as_view(), name='jt-details'),
               re_path(r'^job-execution/(?P<job_execution_id>[^/]+)$',
                       jobs_views.JobDetailsView.as_view(), name='details'),
               re_path(r'^create-job-binary$',
                       job_binary_views.CreateJobBinaryView.as_view(),
                       name='create-job-binary'),
               re_path(r'^job-binary/(?P<job_binary_id>[^/]+)$',
                       job_binary_views.JobBinaryDetailsView.as_view(),
                       name='jb-details'),
               re_path(r'^job-binary/(?P<job_binary_id>[^/]+)/edit$',
                       job_binary_views.EditJobBinaryView.as_view(),
                       name='edit-job-binary'),
               re_path(r'^job-binary/(?P<job_binary_id>[^/]+)/download/$',
                       job_binary_views.DownloadJobBinaryView.as_view(),
                       name='download'),
               re_path(r'^create-data-source$',
                       data_source_views.CreateDataSourceView.as_view(),
                       name='create-data-source'),
               re_path(r'^data-source/(?P<data_source_id>[^/]+)/edit$',
                       data_source_views.EditDataSourceView.as_view(),
                       name='edit-data-source'),
               re_path(r'^data-source/(?P<data_source_id>[^/]+)$',
                       data_source_views.DataSourceDetailsView.as_view(),
                       name='ds-details'),
               re_path(r'^jobex_guide$',
                       job_wizard_views.JobExecutionGuideView.as_view(),
                       name='jobex_guide'),
               re_path(r'^jobex_guide/(?P<reset_jobex_guide>[^/]+)/$',
                       job_wizard_views.ResetJobExGuideView.as_view(),
                       name='reset_jobex_guide'),
               re_path(r'^job_type_select$',
                       job_wizard_views.JobTypeSelectView.as_view(),
                       name='job_type_select'),
               ]


text:
var through = require('through'),

	Handlebars = require('yui/handlebars').Handlebars,

	Engines = require('./engines'),

	yuiModuleStart = Handlebars.compile("YUI.add('{{moduleName}}', function(Y) {\n\n"),
	yuiModuleEnd = Handlebars.compile("}, '{{version}}', { requires: ['template-base'{{#each dependencies}}, '{{.}}'{{/each}}] });"),

	ENGINE_DECLARATION = /var\s+(\w+?)Engine\s+=\s+new\s+Y\.Template\(/g;

// templateModuleData = {
//   name: {String} module name,
//   dependencies: {Array} additional module dependencies (optional),
//   version: {String} version of the module (or of the code the module belongs to)
// }

// codeBuffer = {Buffer|String} contents to write to the YUI module file (excluding module stamp)

function generateYuiModuleForTemplates(templateModuleData) {
	var engineModules = [],
		yuiModuleDeclared = false;

	function declareModule() {
		if (!yuiModuleDeclared) {
			this.queue(yuiModuleStart({
				moduleName: templateModuleData.name
			}));

			yuiModuleDeclared = true;
		}
	}

	return through(function(code) {
		var engineDeclMatch,
			engineId;

		declareModule.apply(this);

		engineDeclMatch = new RegExp(ENGINE_DECLARATION).exec(code);

		if (engineDeclMatch) {
			engineId = engineDeclMatch[1];
			engineModules.push(Engines[engineId].moduleName);
		}

		this.queue(code);
	}, function() {
		var moduleDependencies = engineModules;

		declareModule.apply(this);

		if (templateModuleData.dependencies) {
			moduleDependencies = moduleDependencies.concat(templateModuleData.dependencies);
		}

		this.queue(yuiModuleEnd({
			dependencies: moduleDependencies,
			version: templateModuleData.version
		}));

		this.queue(null);
	});
}
exports = module.exports = generateYuiModuleForTemplates;


text:
namespace operations_research {
namespace glop {

// This class is used to decompose an existing LinearProgram into several
// independent LinearPrograms. Problems are independent when none of their
// variables are connected, i.e. appear in the same constraints.
// Consider for instance the following problem:
//    min: x + 2 y + 3 z + 4 t + 5 u
//    c1: 0 <= x + z <= 1;
//    c2: 0 <= y + t <= 1;
//    c3: 0 <= x + u <= 1;
//    int: x, y, z, t, u
// Variables x, z and u are connected by constraints c1 and c3.
// Variables y and t are connected by constraints c2.
// The problem can be decomposed into two independent problems:
//    min: x + 3 z + 5 u
//    c1: 0 <= x + z <= 1;
//    c3: 0 <= x + u <= 1;
//    int: x, z, u
// and
//    min: 2 y + 4 t
//    c2: 0 <= y + t <= 1;
//    int: y, t
//
// Note that a solution to those two independent problems is a solution to the
// original problem.
class LPDecomposer {
 public:
  LPDecomposer();

  // Decomposes the problem into independent problems.
  // Note that a pointer is kept (no copy) on the linear_problem, so the problem
  // should not change during the life of the LPDecomposer object.
  void Decompose(const LinearProgram* linear_problem) LOCKS_EXCLUDED(mutex_);

  // Returns the number of independent problems generated by Decompose().
  int GetNumberOfProblems() const LOCKS_EXCLUDED(mutex_);

  // Returns the original problem, i.e. as it was before any decomposition.
  const LinearProgram& original_problem() const LOCKS_EXCLUDED(mutex_);

  // Fills lp with the problem_index^th independent problem generated by
  // Decompose().
  // Note that this method runs in O(num-entries-in-generated-problem).
  void ExtractLocalProblem(int problem_index, LinearProgram* lp)
      LOCKS_EXCLUDED(mutex_);

  // Returns an assignment to the original problem based on the assignments
  // to the independent problems. Requires Decompose() to have been called.
  DenseRow AggregateAssignments(const std::vector<DenseRow>& assignments) const
      LOCKS_EXCLUDED(mutex_);

  // Returns an assignment to the given subproblem based on the assignment to
  // the original problem. Requires Decompose() to have been called.
  DenseRow ExtractLocalAssignment(int problem_index, const DenseRow& assignment)
      LOCKS_EXCLUDED(mutex_);

 private:
  const LinearProgram* original_problem_;
  std::vector<std::vector<ColIndex>> clusters_;

  mutable Mutex mutex_;

  DISALLOW_COPY_AND_ASSIGN(LPDecomposer);
};

}  // namespace glop
}  // namespace operations_research

#endif  // OR_TOOLS_LP_DATA_LP_DECOMPOSER_H_


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using TVS.API;
using static TVS.API.Episode;

namespace TVSPlayer {
    /// <summary>
    /// Interaction logic for SeriesEpisodes.xaml
    /// </summary>
    public partial class SeriesEpisodes : Page {
        public SeriesEpisodes(Series series) {
            InitializeComponent();
            this.series = series;
        }
        public Series series;

        bool hasBackground = false;

        Dictionary<Episode, string> searchValues = new Dictionary<Episode, string>();

        private void BackButton_MouseUp(object sender, MouseButtonEventArgs e) {
            Window main = Application.Current.MainWindow;
            ((MainWindow)main).SetLibrary();
        }

        private async void Grid_Loaded(object sender, RoutedEventArgs e) {
            PageCustomization pg = new PageCustomization();
            pg.Buttons = new EpisodeButtons(this);
            pg.SearchBarEvent += async (s, ev) => { Search(); };
            pg.MainTitle = series.seriesName;
            MainWindow.SetPageCustomization(pg);
            await ShowNextEp();
            Task.Run(() => LoadBackground());
            Task.Run(() => LoadSeasons());
        }

        private async void LoadBackground() {
            if (!Settings.PerformanceMode) {
                BitmapImage bmp = await Database.GetFanArt(series.id);
                Dispatcher.Invoke(() => {
                    if (bmp != null) {
                        hasBackground = true;
                        BackgroundImage.Source = bmp;
                        Darkener.Visibility = Visibility.Visible;
                        var sb = (Storyboard)FindResource("BlurImage");
                        sb.Begin();
                        var sboard = (Storyboard)FindResource("OpacityUp");
                        sboard.Begin(BackgroundImage);
                    } else {
                        BackButton.SetResourceReference(Image.SourceProperty, "BackIcon");
                    }
                }, DispatcherPriority.Send);
            }
        }

        public void LoadSeasons() {
            List<Episode> eps = Database.GetEpisodes(series.id);
            GenerateSearch(eps);
            List<List<Episode>> sorted = new List<List<Episode>>();
            for (int i = 1; ; i++) {
                List<Episode> list = eps.Where(a => a.airedSeason == i && !String.IsNullOrEmpty(a.firstAired) && Helper.ParseAirDate(a.firstAired).AddDays(1) < DateTime.Now).ToList();
                if (Properties.Settings.Default.EpisodeSort) list.Reverse();
                if (list.Count != 0) {
                    sorted.Add(list);
                } else {
                    break;
                }
            }
            if (Properties.Settings.Default.EpisodeSort) {
                sorted.Reverse();
            }
            Dispatcher.Invoke(() => {
                SecondPanel.Children.RemoveRange(0, SecondPanel.Children.Count);
                foreach (var list in sorted) {
                    SeasonView sv = new SeasonView(list, series, this);
                    sv.ScrollView.PreviewMouseWheel += (s, ev) => Scroll(ev);
                    sv.Height = 195;
                    sv.Margin = new Thickness(0, 0, 35, 20);
                    SecondPanel.Children.Add(GenerateText("Season " + list[0].airedSeason));
                    SecondPanel.Children.Add(sv);
                }
            }, DispatcherPriority.Send);
        }

        private void ShowNextEpAnimated() {
            Storyboard sb = (Storyboard)FindResource("OpacityDown");
            var clone = sb.Clone();
            clone.Completed += async (s, ev) => {
                await ShowNextEp();
                Storyboard up = (Storyboard)FindResource("OpacityUp");
                up.Begin(DetailsGrid);
            };
            clone.Begin(DetailsGrid);

        }

        private async Task ShowNextEp() {
            DetailsGrid.Children.RemoveRange(0, DetailsGrid.Children.Count);
            await Task.Run(async () => {
                List<Episode> episodes = Database.GetEpisodes(series.id);
                var eps = episodes.Where(x => x.airedSeason > 0 && !String.IsNullOrEmpty(x.firstAired) && Helper.ParseAirDate(x.firstAired).AddDays(-1) < DateTime.Now).ToList().OrderBy(x => x.airedSeason).ThenBy(x => x.airedEpisodeNumber).ToList();
                if (eps != null) {
                    var ep = eps.Where(x => !x.finished).ToList().FirstOrDefault();
                    if (ep != null) {
                        ep = Database.GetEpisode(series.id, ep.id, true);
                        await Dispatcher.Invoke(async () => {
                            var details = new EpisodeDetails(ep, false);
                            details.EpisodeThumb.Source = await Database.GetEpisodeThumbnail(Int32.Parse(ep.seriesId.ToString()), ep.id);
                            DetailsGrid.Children.Add(details);
                        }, DispatcherPriority.Send);
                    } else {
                        ep = eps.Where(x => x.airedSeason == eps.Max(y => y.airedSeason)).MaxBy(x => x.airedEpisodeNumber);
                        await Dispatcher.Invoke(async () => {
                            var details = new EpisodeDetails(ep, false);
                            details.EpisodeThumb.Source = await Database.GetEpisodeThumbnail(Int32.Parse(ep.seriesId.ToString()), ep.id);
                            DetailsGrid.Children.Add(details);
                        }, DispatcherPriority.Send);
                    }
                }
            });
        }

        private void Scroll(MouseWheelEventArgs ev) {
            if (ev.Delta > 0) {
                ScrollView.LineUp();
                ScrollView.LineUp();
                ScrollView.LineUp();
            } else {
                ScrollView.LineDown();
                ScrollView.LineDown();
                ScrollView.LineDown();
            }
        }

        private TextBlock GenerateText(string textblockText) {
            TextBlock text = new TextBlock();
            text.FontSize = 24;
            text.Foreground = (Brush)FindResource("TextColor");
            text.Margin = new Thickness(0, 0, 0, 10);
            text.Text = textblockText;
            return text;
        }

        public static ScannedFile GetFileToPlay(Episode episode, Series series) {
            List<Episode.ScannedFile> list = new List<Episode.ScannedFile>();
            foreach (var item in episode.files) {
                if (item.Type == Episode.ScannedFile.FileType.Video) {
                    list.Add(item);
                }
            }
            List<FileInfo> infoList = new List<FileInfo>();
            foreach (var item in list) {
                infoList.Add(new FileInfo(item.NewName));
            }
            FileInfo info = infoList.OrderByDescending(ex => ex.Length).FirstOrDefault();
            if (info != null) {
                return list.Where(x => x.NewName == info.FullName).FirstOrDefault();
            }
            return null;
        }
        public static void TryRefresh() {
            if (MainWindow.GetCurrentFrameContentName() == "SeriesEpisodes") {
                Window main = Application.Current.MainWindow;
                ((SeriesEpisodes)((MainWindow)main).ActiveContent.Content).ShowNextEpAnimated();
            }
        }

        public static void SetDetails(Episode episode) {
            Window main = Application.Current.MainWindow;
            ((SeriesEpisodes)((MainWindow)main).ActiveContent.Content).SetDetailsPrivate(episode);

        }

        private void SetDetailsPrivate(Episode episode) {
            Storyboard sb = (Storyboard)FindResource("OpacityDown");
            var clone = sb.Clone();
            clone.Completed += (s, ev) => {
                DetailsGrid.Children.RemoveRange(0, DetailsGrid.Children.Count);
                DetailsGrid.Children.Add(new EpisodeDetails(episode));
                Storyboard up = (Storyboard)FindResource("OpacityUp");
                up.Begin(DetailsGrid);
            };
            clone.Begin(DetailsGrid);

        }

        bool isRunning = false;
        Task searchTask;
        private async void Search() {
            SearchResultPanel.Children.Clear();
            string text = MainWindow.GetSearchBarText().ToLower();
            if (searchTask != null && searchTask.Status != TaskStatus.RanToCompletion) {
                isRunning = true;
                await Task.Run(() => {
                    Thread.Sleep(10);
                });
            }
            isRunning = false;
            searchTask = Task.Run(async () => {
                text = text.Trim();
                if (!String.IsNullOrEmpty(text)) {
                    Dispatcher.Invoke(() => {
                        SearchResultPanel.Visibility = Visibility.Visible;
                        SecondPanel.Visibility = Visibility.Collapsed;
                    });
                    var eps = GoThroughValues(text);
                    List<UIElement> list = new List<UIElement>();
                    foreach (var ep in eps) {
                        if (isRunning) {
                            list = new List<UIElement>();
                            Dispatcher.Invoke(() => {
                                SearchResultPanel.Children.Clear();
                            }, DispatcherPriority.Send);
                            break;
                        }
                        Episode episode = Database.GetEpisode(series.id, ep.id, true);
                        Dispatcher.Invoke(() => {
                            EpisodeSearchResult esr = new EpisodeSearchResult(episode);
                            esr.PlayIcon.PreviewMouseLeftButtonUp += (s, ev) => SearchClickEvent(episode);
                            esr.Clickable.PreviewMouseUp += (s, ev) => SearchClickEvent(episode);
                            esr.QuestionIcon.PreviewMouseUp += (s, ev) => EpisodeView.RightClickEvent(this, episode);
                            esr.Height = 60;
                            SearchResultPanel.Children.Add(esr);
                        }, DispatcherPriority.Send);
                    }
                } else {
                    Dispatcher.Invoke(() => {
                        SearchResultPanel.Visibility = Visibility.Collapsed;
                        SecondPanel.Visibility = Visibility.Visible;
                    });
                }
            });
        }

        private async void SearchClickEvent(Episode episode) {
            if (!(await SeasonView.EpisodeViewMouseLeftUp(series, episode))) {
                EpisodeView.RightClickEvent(this, episode);
            }
        }

        private List<Episode> GoThroughValues(string text) {
            List<Episode> eps = searchValues.Keys.ToList();
            var result = new List<Episode>();
            Match seasonRgx = new Regex("s[0-9]?[0-9]", RegexOptions.IgnoreCase).Match(text);
            Match episodeRgx = new Regex("e[0-9]?[0-9]", RegexOptions.IgnoreCase).Match(text);
            if (seasonRgx.Success) {
                result = eps.Where(x => GetSeasonsOrEpisodes(seasonRgx.Value).Contains((int)x.airedSeason)).ToList();
                eps = result.Count > 0 ? result : eps;
                text = text.Replace(seasonRgx.Value, "");
            }
            if (episodeRgx.Success) {
                result = eps.Where(x => GetSeasonsOrEpisodes(episodeRgx.Value).Contains((int)x.airedEpisodeNumber)).ToList();
                eps = result.Count > 0 ? result : eps;
                text = text.Replace(episodeRgx.Value, "");
            }
            //Removes whitespace at start and end. Replaces all other whitespaces with single space
            text = text.Trim();
            text = Regex.Replace(text, @"\s+", " ");
            eps = eps.Where(x => x.episodeName.ToLower().Contains(text)).ToList();
            return eps;
        }

        private List<int> GetSeasonsOrEpisodes(string text) {
            List<int> seasons = new List<int>();
            int season = Int32.Parse(text.Remove(0, 1));
            if (text.Length >= 3) {
                return new List<int>() { season };
            }
            if (season == 0) {
                return new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            }
            for (int i = 0; i < 100; i++) {
                if (i.ToString()[0] == season.ToString()[0]) {
                    seasons.Add(i);
                }
            }
            return seasons;
        }

        private void GenerateSearch(List<Episode> episodes) {
            episodes = episodes.Where(x => x.airedSeason.ToString() != "0" && !String.IsNullOrEmpty(x.airedSeason.ToString()) && !String.IsNullOrEmpty(x.firstAired) && Helper.ParseAirDate(x.firstAired).AddDays(1) < DateTime.Now).ToList();
            foreach (var episode in episodes) {
                searchValues.Add(episode, episode.episodeName);
            }
        }

        private void Image_MouseEnter(object sender, MouseEventArgs e) {
            Mouse.OverrideCursor = Cursors.Hand;
        }

        private void Image_MouseLeave(object sender, MouseEventArgs e) {
            Mouse.OverrideCursor = null;
        }
    }
}


text:
<!-- modified from http://alex.dojotoolkit.org/08/jscript/lettable.html -->
<html>
<head>
  <title>A Crazy Getter/Setter Hack</title>
</head>
<body>
  <script language="VBScript" type="text/VBScript">
    Function exec_vb_global(code)
      ExecuteGlobal(code)
    End Function
  </script>
  <script type="text/javascript">

    // Create the main default thing object, we will proxy this later
    function ThingBase() {
      // Private
      var space = 'something about the awesome';

      this.getSpace = function() {
        console.log('getting');
        return space;
      }
      this.setSpace = function(value) {
        console.log('setting');
        space = value;
      }
      this.groove = function() {
        console.log('nn ts nn ts nn ts nn ts');
      }
    }

    // We need a factory to build this becuase we can't call 'new' from vbscript
    function ThingBaseFactory() {
      return new ThingBase();
    }

    // Eventually this text construction will be automated for the proxy
    // All you need to do is build the proxy for each property set*, get*
    // and stub each method
    var obj = ""+
      "Class ThingProxy\n"+
      "  Private obj__\n"+
      "  Public Property Get space\n"+
      "    space = obj__.getSpace()\n"+
      "  End Property\n"+
      "  Public Property Let space(value)\n"+
      "    obj__.setSpace(value)\n"+
      "  End Property\n"+
      "  Public Function groove\n"+
      "    obj__.groove()\n"+
      "  End Function\n"+
      "  Private Sub Class_Initialize()\n"+
      "    Set obj__ = ThingBaseFactory()\n"+
      "  End Sub\n"+
      "End Class\n"+
      "' We need a factory because we can't call 'New' from javascript\n"+
      "Function thingProxyFactory()\n"+
      "  Dim tmp\n"+
      "  Set tmp = New ThingProxy\n"+
      "  Set thingProxyFactory = tmp\n"+
      "End Function\n";

    // Register the proxy class in the global context, make the factory global
    exec_vb_global(obj);

    // The actual thing constructor
    var Thing = function() { return (window["thingProxyFactory"]()) }

    console.log(Thing);
    console.log(Thing.prototype);
    // function ThingProto(){
    //   this.hoho = 293;
    // }

    // Use the thing

    function YamaComponent(desc){
      for (var k in desc){
        var t = new Thing();
      }

    }

    var comp = new YamaComponent({
      'toto':9523
    });

    //t.prototype = new ThingProto();
    t.groove();
    console.log(t.space);
    t.space = "Imma let you finish";
    console.log(t.space);
    console.log(t.hoho);

  </script>
</body>
</html>


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
Bull. Soc. bot. Fr. 71: 382 (1924)

#### Original name
Lichen chlorinus Ach.

### Remarks
null


text:
/*global define*/
define(['jquery'], function ($) {
    "use strict";
    var TriggerAction;

    TriggerAction = function () {
        return $(this).each(function () {
            // Edit mode toggle
            if ($(this).data('trigger') === 'ping') {
                $(this)
                    .click(function () {
                        var $that = $(this),
                            location = $that.data('href');
                        if (location) {
                            $.ajax({
                                url: location
                            });
                        }
                    });
            }
        });
    };

    $.fn.TriggerAction = TriggerAction;
});


text:
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'spec_helper'))
require 'data_objects/spec/typecast/datetime_spec'

describe 'DataObjects::Mysql with DateTime' do
  behaves_like 'supporting DateTime'
  behaves_like 'supporting DateTime autocasting'
end


text:
@implementation WTChain

+ (id (^)(id))createImageBlockWithView:(UIView *)view action:(void (^)(UIImage *))action
{
    return ^id(id image){

        UIImage *img;
        if([image isKindOfClass:[NSString class]])
        {
            img = [UIImage imageFromString:image];
        }
        else if([image isKindOfClass:[UIImage class]])
        {
            img = image;
        }

        action(img);
        return view;
    };
}

+ (id (^)(id))createColorBlockWithView:(UIView *)view action:(void (^)(UIColor *))action
{
    return ^id(id color){

        UIColor *c;
        if([color isKindOfClass:[NSString class]])
        {
            c = [UIColor colorWithString:color];
        }
        else if([color isKindOfClass:[UIColor class]])
        {
            c = color;
        }

        action(c);
        return view;
    };
}

+ (id (^)(CGFloat, BOOL))createFontBlockWithView:(UIView *)view action:(void (^)(UIFont *))action
{
    id block = ^id(CGFloat size, BOOL bold){

        action(bold ? [UIFont boldSystemFontOfSize:size] : [UIFont systemFontOfSize:size]);
        return view;
    };
    return block;
}

@end


text:
from ....testing import assert_equal
from ..base import AFNICommand

def test_AFNICommand_inputs():
    input_map = dict(args=dict(argstr='%s',
    ),
    environ=dict(nohash=True,
    usedefault=True,
    ),
    ignore_exception=dict(nohash=True,
    usedefault=True,
    ),
    out_file=dict(argstr='-prefix %s',
    name_source=['in_file'],
    name_template='%s_afni',
    ),
    outputtype=dict(),
    terminal_output=dict(nohash=True,
    ),
    )
    inputs = AFNICommand.input_spec()

    for key, metadata in list(input_map.items()):
        for metakey, value in list(metadata.items()):
            yield assert_equal, getattr(inputs.traits()[key], metakey), value


text:
/* dui.Calendar */
.duiCalendar thead {
  background-repeat: repeat-x;
  background-image: url(compat/calendar-month-bg.png);
}
.duiCalendarSelectedDate .duiCalendarDateLabel {
  background-repeat: repeat-x;
  background-image: url(compat/calendar-datelabel-sel-bg.png);
}
.duiCalendarDate:active .duiCalendarDateLabel {
  background-repeat: repeat-x;
  background-image: url(compat/calendar-datelabel-sel-bg.png);
}
.duiCalendarYearLabel {
  background-repeat: repeat-x;
  background-image: url(compat/calendar-year-bg.png);
}
.dj_gecko .duiCalendar .duiDropDownButton .duiButtonNode {
  -moz-box-shadow: 0 0 0 transparent;
}
.dj_gecko .duiCalendar thead {
  background-image: -moz-linear-gradient(top, #63696b 0%, #182021 100%);
}
.dj_gecko .duiCalendarSelectedDate .duiCalendarDateLabel {
  background-image: -moz-linear-gradient(top, #088eef 0%, #0869c6 50%, #0851ad 100%);
}
.dj_gecko .duiCalendarDate:active .duiCalendarDateLabel {
  background-image: -moz-linear-gradient(top, #088eef 0%, #0869c6 50%, #0851ad 100%);
}
.dj_gecko .duiCalendarYearLabel {
  background-image: -moz-linear-gradient(top, #63696b 0%, #182021 100%);
}
.dj_ff3 .duiCalendar {
  -moz-border-radius: 0;
}
.dj_ff3 .duiCalendarMonthMenu {
  -moz-border-radius: 6px;
}


text:
package com.b2international.snowowl.snomed.cis.action;

import com.b2international.snowowl.core.domain.RepositoryContext;

/**
 * @since 4.5
 */
abstract class AbstractIdAction<I> implements IdAction<I> {

	private I result;

	@Override
	public final I execute(final RepositoryContext context) {
		if (result != null) {
			throw new IllegalStateException("Action was already executed.");
		}

		try {
			result = doExecute(context);
			LOGGER.debug("Action {} executed successfully, result: {}.", this, result);
			return result;
		} catch (final Exception e) {
			LOGGER.debug("Exception caught while executing action {}.", this, e);
			throw e;
		}
	}

	@Override
	public final void commit(final RepositoryContext context) {
		if (result != null) {
			doCommit(context, result);
		}
	}

	@Override
	public final void rollback(final RepositoryContext context) {
		if (result != null) {
			doRollback(context, result);
		}
	}

	protected abstract I doExecute(RepositoryContext context);

	protected void doCommit(final RepositoryContext context, final I storedResult) {
		// Empty by default, subclasses should override
	}

	protected void doRollback(final RepositoryContext context, final I storedResult) {
		// There's usually an insufficient amount of information to roll back most of the actions, so the default
		// implementation just adds a warning to the log.
		LOGGER.warn("Action {} can not be rolled back.", this);
	}

}


text:
char* read_file(char* file_name, long* file_size);

char** split_lines(char* buffer, size_t* n_lines);

byte_string** read_lines_hex(char* file_name, size_t* n_lines);

char* strip_newlines(char* buffer);

byte_string* read_file_base64(char* file_name);

size_t random_range(size_t min, size_t max);

char* replace_all(const char* input, const char* from, const char* to);

#endif


text:
package mgr

import (
	"bytes"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"sync"
	"time"

	"github.com/json-iterator/go"
	"github.com/labstack/echo"
	"github.com/qiniu/log"
	"github.com/qiniu/logkit/utils"
	. "github.com/qiniu/logkit/utils/models"
)

type ClusterConfig struct {
	MasterUrl []string `json:"master_url"`
	IsMaster  bool     `json:"is_master"`
	Enable    bool     `json:"enable"`
	Address   string   `json:"address"`
	Tag       string   `json:"tag"`
}

type Cluster struct {
	ClusterConfig
	slaves       []Slave
	mutex        *sync.RWMutex
	statusUpdate time.Time
}

type Slave struct {
	Url       string    `json:"url"`
	Tag       string    `json:"tag"`
	Status    string    `json:"status"`
	LastTouch time.Time `json:"last_touch"`
}

type ClusterStatus struct {
	Status map[string]RunnerStatus `json:"status"`
	Tag    string                  `json:"tag"`
	Err    string                  `json:"error"`
}

type SlaveConfig struct {
	Configs map[string]RunnerConfig `json:"configs"`
	Tag     string                  `json:"tag"`
	Err     string                  `json:"error"`
}

type respRunnersNameList struct {
	Code string   `json:"code"`
	Data []string `json:"data"`
}

type respRunnerStatus struct {
	Code string                  `json:"code"`
	Data map[string]RunnerStatus `json:"data"`
}

type respRunnerConfig struct {
	Code string       `json:"code"`
	Data RunnerConfig `json:"data"`
}

type respRunnerConfigs struct {
	Code string                  `json:"code"`
	Data map[string]RunnerConfig `json:"data"`
}

const (
	StatusOK   = "ok"
	StatusBad  = "bad"
	StatusLost = "lost"
)

const DefaultMyTag = "default"

func NewCluster(cc *ClusterConfig) *Cluster {
	cl := new(Cluster)
	cl.ClusterConfig = *cc
	if cl.Tag == "" {
		cl.Tag = DefaultMyTag
	}
	cl.slaves = make([]Slave, 0)
	cl.mutex = new(sync.RWMutex)
	return cl
}

func (cc *Cluster) RunRegisterLoop() error {
	if err := Register(cc.MasterUrl, cc.Address, cc.Tag); err != nil {
		return fmt.Errorf("master %v is unavaliable", cc.MasterUrl)
	}
	go func() {
		for {
			time.Sleep(15 * time.Second)
			if err := Register(cc.MasterUrl, cc.Address, cc.Tag); err != nil {
				log.Errorf("master %v is unavaliable", cc.MasterUrl)
			}
		}
	}()
	return nil
}

func (cc *Cluster) AddSlave(url, tag string) {
	cc.mutex.Lock()
	defer cc.mutex.Unlock()
	for idx, v := range cc.slaves {
		if v.Url == url {
			v.Tag = tag
			v.LastTouch = time.Now()
			v.Status = StatusOK
			cc.slaves[idx] = v
			return
		}
	}
	cc.slaves = append(cc.slaves, Slave{url, tag, StatusOK, time.Now()})
	return
}

func (cc *Cluster) UpdateSlaveStatus() {
	now := time.Now()
	if now.Sub(cc.statusUpdate) < 15*time.Second {
		return
	}
	cc.mutex.Lock()
	defer cc.mutex.Unlock()
	for idx, v := range cc.slaves {
		if now.Sub(v.LastTouch) < 31*time.Second {
			v.Status = StatusOK
		} else if now.Sub(v.LastTouch) <= time.Minute {
			v.Status = StatusBad
		} else {
			v.Status = StatusLost
		}
		cc.slaves[idx] = v
	}
	cc.statusUpdate = now
}

// master API
// GET /logkit/cluster/ping
func (rs *RestService) Ping() echo.HandlerFunc {
	return func(c echo.Context) error {
		return RespSuccess(c, nil)
	}
}

// master API
// GET /logkit/cluster/ismaster
func (rs *RestService) IsMaster() echo.HandlerFunc {
	return func(c echo.Context) error {
		isMaster := true
		if rs.cluster == nil || !rs.cluster.Enable || !rs.cluster.IsMaster {
			isMaster = false
		}
		return RespSuccess(c, isMaster)
	}
}

// master API
// GET /logkit/cluster/slaves?tag=tagValue&url=urlValue
func (rs *RestService) Slaves() echo.HandlerFunc {
	return func(c echo.Context) error {
		_, tag, url, _, err := rs.checkClusterRequest(c)
		if err != nil {
			return RespError(c, http.StatusBadRequest, ErrClusterSlaves, err.Error())
		}
		rs.cluster.UpdateSlaveStatus()
		rs.cluster.mutex.RLock()
		slaves, _ := getQualifySlaves(rs.cluster.slaves, tag, url)
		rs.cluster.mutex.RUnlock()
		return RespSuccess(c, slaves)
	}
}

// master API
// GET /logkit/cluster/runners?tag=tagValue&url=urlValue
func (rs *RestService) GetClusterRunners() echo.HandlerFunc {
	return func(c echo.Context) error {
		_, tag, url, _, err := rs.checkClusterRequest(c)
		if err != nil {
			return RespError(c, http.StatusBadRequest, ErrClusterSlaves, err.Error())
		}
		rs.cluster.UpdateSlaveStatus()
		rs.cluster.mutex.RLock()
		slaves, _ := getQualifySlaves(rs.cluster.slaves, tag, url)
		rs.cluster.mutex.RUnlock()
		mutex := new(sync.Mutex)
		wg := new(sync.WaitGroup)
		runnerNameSet := utils.NewHashSet()
		for _, v := range slaves {
			wg.Add(1)
			go func(v Slave) {
				defer wg.Done()
				var respRss respRunnersNameList
				url := fmt.Sprintf("%v/logkit/runners", v.Url)
				respCode, respBody, err := executeToOneCluster(url, http.MethodGet, []byte{})
				if err != nil || respCode != http.StatusOK {
					log.Errorf("get slave(tag='%v', url='%v') runner name list failed, resp is %v, error is %v", v.Tag, v.Url, string(respBody), err.Error())
					return
				} else {
					if err = jsoniter.Unmarshal(respBody, &respRss); err != nil {
						log.Errorf("unmarshal slave(tag='%v', url='%v') runner name list failed, error is %v", v.Tag, v.Url, err.Error())
					} else {
						mutex.Lock()
						runnerNameSet.AddStringArray(respRss.Data)
						mutex.Unlock()
					}
				}

			}(v)
		}
		wg.Wait()
		return RespSuccess(c, runnerNameSet.Elements())
	}
}

// master API
// GET /logkit/cluster/status?tag=tagValue&url=urlValue
func (rs *RestService) ClusterStatus() echo.HandlerFunc {
	return func(c echo.Context) error {
		_, tag, url, _, err := rs.checkClusterRequest(c)
		if err != nil {
			return RespError(c, http.StatusBadRequest, ErrClusterStatus, err.Error())
		}
		rs.cluster.mutex.RLock()
		slaves, _ := getQualifySlaves(rs.cluster.slaves, tag, url)
		rs.cluster.mutex.RUnlock()
		mutex := new(sync.Mutex)
		wg := new(sync.WaitGroup)
		allStatus := make(map[string]ClusterStatus)
		for _, v := range slaves {
			wg.Add(1)
			go func(v Slave) {
				defer wg.Done()
				var cs ClusterStatus
				cs.Tag = v.Tag
				var respRss respRunnerStatus
				if v.Status != StatusOK {
					cs.Status = map[string]RunnerStatus{}
					mutex.Lock()
					allStatus[v.Url] = cs
					mutex.Unlock()
					return
				}
				url := fmt.Sprintf("%v/logkit/status", v.Url)
				respCode, respBody, err := executeToOneCluster(url, http.MethodGet, []byte{})
				if err != nil || respCode != http.StatusOK {
					errInfo := fmt.Errorf("%v %v", string(respBody), err)
					cs.Err = errInfo.Error()
				} else {
					if err = jsoniter.Unmarshal(respBody, &respRss); err != nil {
						cs.Err = fmt.Sprintf("unmarshal query result error %v, body is %v", err, string(respBody))
					} else {
						cs.Status = respRss.Data
					}
				}
				mutex.Lock()
				allStatus[v.Url] = cs
				mutex.Unlock()
			}(v)
		}
		wg.Wait()
		return RespSuccess(c, allStatus)
	}
}

// master API
// Get /logkit/cluster/configs:name?tag=tagValue&url=urlValue
func (rs *RestService) GetClusterConfig() echo.HandlerFunc {
	return func(c echo.Context) error {
		runnerName, tag, url, _, err := rs.checkClusterRequest(c)
		if err != nil {
			return RespError(c, http.StatusBadRequest, ErrClusterConfig, err.Error())
		}
		rs.cluster.mutex.RLock()
		slaves, _ := getQualifySlaves(rs.cluster.slaves, tag, url)
		rs.cluster.mutex.RUnlock()
		var config RunnerConfig
		var lastErrMsg string
		for _, v := range slaves {
			var respRss respRunnerConfig
			if v.Status != StatusOK {
				lastErrMsg = "the slaves(tag = '" + tag + "', url = '" + url + "') status is " + v.Status
				continue
			}
			url := fmt.Sprintf("%v/logkit/configs/"+runnerName, v.Url)
			respCode, respBody, err := executeToOneCluster(url, http.MethodGet, []byte{})
			if err != nil || respCode != http.StatusOK {
				lastErrMsg = fmt.Sprintf("get slave(tag = '%v'', url = '%v') config failed resp is %v, error is %v", tag, url, string(respBody), err)
				continue
			} else {
				if err = jsoniter.Unmarshal(respBody, &respRss); err != nil {
					lastErrMsg = fmt.Sprintf("get slave(tag = '%v'', url = '%v') config unmarshal failed, resp is %v, error is %v", tag, url, string(respBody), err)
					continue
				} else {
					config = respRss.Data
					return RespSuccess(c, config)
				}
			}
		}
		return RespError(c, http.StatusBadRequest, ErrClusterConfig, lastErrMsg)
	}
}

// master API
// Get /logkit/cluster/configs?tag=tagValue&url=urlValue
func (rs *RestService) GetClusterConfigs() echo.HandlerFunc {
	return func(c echo.Context) error {
		_, tag, url, _, err := rs.checkClusterRequest(c)
		if err != nil {
			return RespError(c, http.StatusBadRequest, ErrClusterConfigs, err.Error())
		}
		rs.cluster.mutex.RLock()
		slaves, _ := getQualifySlaves(rs.cluster.slaves, tag, url)
		rs.cluster.mutex.RUnlock()
		mutex := new(sync.Mutex)
		wg := new(sync.WaitGroup)
		allConfigs := make(map[string]SlaveConfig)
		for _, v := range slaves {
			wg.Add(1)
			go func(v Slave) {
				defer wg.Done()
				var sc SlaveConfig
				sc.Tag = v.Tag
				var respRss respRunnerConfigs
				if v.Status != StatusOK {
					sc.Configs = map[string]RunnerConfig{}
					mutex.Lock()
					allConfigs[v.Url] = sc
					mutex.Unlock()
					return
				}
				url := fmt.Sprintf("%v/logkit/configs", v.Url)
				respCode, respBody, err := executeToOneCluster(url, http.MethodGet, []byte{})
				if err != nil || respCode != http.StatusOK {
					errInfo := fmt.Errorf("%v %v", string(respBody), err)
					sc.Err = errInfo.Error()
				} else {
					if err = jsoniter.Unmarshal(respBody, &respRss); err != nil {
						sc.Err = fmt.Sprintf("unmarshal query result error %v, body is %v", err, string(respBody))
					} else {
						sc.Configs = respRss.Data
					}
				}
				mutex.Lock()
				allConfigs[v.Url] = sc
				mutex.Unlock()
			}(v)
		}
		wg.Wait()
		return RespSuccess(c, allConfigs)
	}
}

type RegisterReq struct {
	Url string `json:"url"`
	Tag string `json:"tag"`
}

// master API
// POST /logkit/cluster/register
func (rs *RestService) PostRegister() echo.HandlerFunc {
	return func(c echo.Context) error {
		var req RegisterReq
		if err := c.Bind(&req); err != nil {
			return RespError(c, http.StatusBadRequest, ErrClusterRegister, err.Error())
		}
		req.Url = utils.AddHttpProtocal(req.Url)
		if rs.cluster == nil || !rs.cluster.Enable {
			errMsg := "this is not master"
			return RespError(c, http.StatusBadRequest, ErrClusterRegister, errMsg)
		}
		rs.cluster.AddSlave(req.Url, req.Tag)
		return RespSuccess(c, nil)
	}
}

type TagReq struct {
	Tag string `json:"tag"`
}

// slave API
// POST /logkit/cluster/tag
func (rs *RestService) PostTag() echo.HandlerFunc {
	return func(c echo.Context) error {
		var req TagReq
		if err := c.Bind(&req); err != nil {
			return RespError(c, http.StatusBadRequest, ErrClusterTag, err.Error())
		}
		if rs.cluster == nil || !rs.cluster.Enable {
			errMsg := "cluster function not configed"
			return RespError(c, http.StatusBadRequest, ErrClusterTag, errMsg)
		}
		if err := Register(rs.cluster.MasterUrl, rs.cluster.Address, req.Tag); err != nil {
			return RespError(c, http.StatusServiceUnavailable, ErrClusterTag, err.Error())
		}
		rs.cluster.mutex.Lock()
		rs.cluster.Tag = req.Tag
		rs.cluster.mutex.Unlock()
		return RespSuccess(c, nil)
	}
}

// POST /logkit/cluster/configs/<name>?tag=tagValue&url=urlValue
func (rs *RestService) PostClusterConfig() echo.HandlerFunc {
	return func(c echo.Context) error {
		configName, tag, url, configBytes, err := rs.checkClusterRequest(c)
		if err != nil {
			return RespError(c, http.StatusBadRequest, ErrClusterRunnerAdd, err.Error())
		}
		rs.cluster.mutex.RLock()
		slaves, err := getQualifySlaves(rs.cluster.slaves, tag, url)
		rs.cluster.mutex.RUnlock()
		if err != nil {
			return RespError(c, http.StatusBadRequest, ErrClusterRunnerAdd, err.Error())
		}
		method := http.MethodPost
		mgrType := "add runner " + configName
		urlPattern := "%v" + PREFIX + "/configs/" + configName
		if err := executeToClusters(slaves, urlPattern, method, mgrType, configBytes); err != nil {
			return RespError(c, http.StatusServiceUnavailable, ErrClusterRunnerAdd, err.Error())
		}
		return RespSuccess(c, nil)
	}
}

// PUT /logkit/cluster/configs/<name>?tag=tagValue&url=urlValue
func (rs *RestService) PutClusterConfig() echo.HandlerFunc {
	return func(c echo.Context) error {
		configName, tag, url, configBytes, err := rs.checkClusterRequest(c)
		if err != nil {
			return RespError(c, http.StatusBadRequest, ErrClusterRunnerUpdate, err.Error())
		}
		rs.cluster.mutex.RLock()
		slaves, err := getQualifySlaves(rs.cluster.slaves, tag, url)
		rs.cluster.mutex.RUnlock()
		if err != nil {
			return RespError(c, http.StatusBadRequest, ErrClusterRunnerUpdate, err.Error())
		}
		method := http.MethodPut
		mgrType := "update runner " + configName
		urlPattern := "%v" + PREFIX + "/configs/" + configName
		if err := executeToClusters(slaves, urlPattern, method, mgrType, configBytes); err != nil {
			return RespError(c, http.StatusServiceUnavailable, ErrClusterRunnerUpdate, err.Error())
		}
		return RespSuccess(c, nil)
	}
}

// DELETE /logkti/cluster/configs/<name>?tag=tagValue&url=urlValue
func (rs *RestService) DeleteClusterConfig() echo.HandlerFunc {
	return func(c echo.Context) error {
		configName, tag, url, configBytes, err := rs.checkClusterRequest(c)
		if err != nil {
			return RespError(c, http.StatusBadRequest, ErrClusterRunnerDelete, err.Error())
		}
		rs.cluster.mutex.RLock()
		slaves, err := getQualifySlaves(rs.cluster.slaves, tag, url)
		rs.cluster.mutex.RUnlock()
		if err != nil {
			return RespError(c, http.StatusBadRequest, ErrClusterRunnerDelete, err.Error())
		}
		method := http.MethodDelete
		mgrType := "delete runner " + configName
		urlPattern := "%v" + PREFIX + "/configs/" + configName
		if err := executeToClusters(slaves, urlPattern, method, mgrType, configBytes); err != nil {
			return RespError(c, http.StatusServiceUnavailable, ErrClusterRunnerDelete, err.Error())
		}
		return RespSuccess(c, nil)
	}
}

// POST /logkit/cluster/configs/<name>/stop?tag=tagValue&url=urlValue
func (rs *RestService) PostClusterConfigStop() echo.HandlerFunc {
	return func(c echo.Context) error {
		configName, tag, url, configBytes, err := rs.checkClusterRequest(c)
		if err != nil {
			return RespError(c, http.StatusBadRequest, ErrClusterRunnerStop, err.Error())
		}
		rs.cluster.mutex.RLock()
		slaves, err := getQualifySlaves(rs.cluster.slaves, tag, url)
		rs.cluster.mutex.RUnlock()
		if err != nil {
			return RespError(c, http.StatusBadRequest, ErrClusterRunnerStop, err.Error())
		}
		method := http.MethodPost
		mgrType := "stop runner " + configName
		urlPattern := "%v" + PREFIX + "/configs/" + configName + "/stop"
		if err := executeToClusters(slaves, urlPattern, method, mgrType, configBytes); err != nil {
			return RespError(c, http.StatusServiceUnavailable, ErrClusterRunnerStop, err.Error())
		}
		return RespSuccess(c, nil)
	}
}

// POST /logkit/cluster/configs/<name>/start?tag=tagValue&url=urlValue
func (rs *RestService) PostClusterConfigStart() echo.HandlerFunc {
	return func(c echo.Context) error {
		configName, tag, url, configBytes, err := rs.checkClusterRequest(c)
		if err != nil {
			return RespError(c, http.StatusBadRequest, ErrClusterRunnerStart, err.Error())
		}
		rs.cluster.mutex.RLock()
		slaves, err := getQualifySlaves(rs.cluster.slaves, tag, url)
		rs.cluster.mutex.RUnlock()
		if err != nil {
			return RespError(c, http.StatusBadRequest, ErrClusterRunnerStart, err.Error())
		}
		method := http.MethodPost
		mgrType := "start runner " + configName
		urlPattern := "%v" + PREFIX + "/configs/" + configName + "/start"
		if err := executeToClusters(slaves, urlPattern, method, mgrType, configBytes); err != nil {
			return RespError(c, http.StatusServiceUnavailable, ErrClusterRunnerStart, err.Error())
		}
		return RespSuccess(c, nil)
	}
}

// POST /logkit/cluster/configs/<name>/reset?tag=tagValue&url=urlValue
func (rs *RestService) PostClusterConfigReset() echo.HandlerFunc {
	return func(c echo.Context) error {
		configName, tag, url, configBytes, err := rs.checkClusterRequest(c)
		if err != nil {
			return RespError(c, http.StatusBadRequest, ErrClusterRunnerReset, err.Error())
		}
		rs.cluster.mutex.RLock()
		slaves, err := getQualifySlaves(rs.cluster.slaves, tag, url)
		rs.cluster.mutex.RUnlock()
		if err != nil {
			return RespError(c, http.StatusBadRequest, ErrClusterRunnerReset, err.Error())
		}
		method := http.MethodPost
		mgrType := "reset runner " + configName
		urlPattern := "%v" + PREFIX + "/configs/" + configName + "/reset"
		if err := executeToClusters(slaves, urlPattern, method, mgrType, configBytes); err != nil {
			return RespError(c, http.StatusServiceUnavailable, ErrClusterRunnerReset, err.Error())
		}
		return RespSuccess(c, nil)
	}
}

// DELETE /logkit/cluster/slaves?tag=tagValue&url=urlValue
func (rs *RestService) DeleteSlaves() echo.HandlerFunc {
	return func(c echo.Context) error {
		_, tag, url, _, err := rs.checkClusterRequest(c)
		if err != nil {
			return RespError(c, http.StatusBadRequest, ErrClusterSlavesDelete, err.Error())
		}
		rs.cluster.mutex.RLock()
		slaves := make([]Slave, 0)
		for _, s := range rs.cluster.slaves {
			if ("" == tag || tag == s.Tag) && ("" == url || url == s.Url) {
				continue
			}
			slaves = append(slaves, s)
		}
		rs.cluster.mutex.RUnlock()
		rs.cluster.mutex.Lock()
		rs.cluster.slaves = slaves
		rs.cluster.mutex.Unlock()
		return RespSuccess(c, nil)
	}
}

// POST /logkit/cluster/slaves/tag?tag=tagValue&url=urlValue
func (rs *RestService) PostSlaveTag() echo.HandlerFunc {
	return func(c echo.Context) error {
		_, tag, url, configBytes, err := rs.checkClusterRequest(c)
		if err != nil {
			return RespError(c, http.StatusBadRequest, ErrClusterSlavesTag, err.Error())
		}
		rs.cluster.mutex.RLock()
		slaves, err := getQualifySlaves(rs.cluster.slaves, tag, url)
		rs.cluster.mutex.RUnlock()
		if err != nil {
			return RespError(c, http.StatusBadRequest, ErrClusterSlavesTag, err.Error())
		}
		mgrType := "change tag"
		method := http.MethodPost
		urlPattern := "%v" + PREFIX + "/cluster/tag"
		if err := executeToClusters(slaves, urlPattern, method, mgrType, configBytes); err != nil {
			return RespError(c, http.StatusServiceUnavailable, ErrClusterSlavesTag, err.Error())
		}
		return RespSuccess(c, nil)
	}
}

func getQualifySlaves(slaves []Slave, tag, url string) ([]Slave, error) {
	errInfo := make([]string, 0)
	slave := make([]Slave, 0)
	//(u == "" && t == "") || (u == "" && s.t == t) || (u == s.u && t == "") || (u == s.u && t == s.t)
	for _, s := range slaves {
		if (url == "" || url == s.Url) && (tag == "" || tag == s.Tag) {
			if s.Status != StatusOK {
				errMsg := "the slaves(tag = '" + tag + "', url = '" + url + "') status is " + s.Status + ", options are terminated"
				errInfo = append(errInfo, errMsg)
			}
			slave = append(slave, s)
		}
	}
	// 没有找到 slave 的错误只有当没有其他错误的时候才报
	if len(slave)+len(errInfo) <= 0 {
		errMsg := "the slaves(tag = '" + tag + "', url = '" + url + "') is not found"
		errInfo = append(errInfo, errMsg)
	}
	if len(errInfo) > 0 {
		return slave, errors.New(strings.Join(errInfo, "\n"))
	}
	return slave, nil
}

func (rs *RestService) checkClusterRequest(c echo.Context) (name, tag, url string, configBytes []byte, err error) {
	if rs.cluster == nil || !rs.cluster.Enable {
		err = errors.New("cluster function not configed")
		return
	}
	var tmpErr error
	req := c.Request()
	if tmpErr := req.ParseForm(); tmpErr != nil {
		err = errors.New("can not get form from request, err is " + tmpErr.Error())
		return
	}
	if configBytes, tmpErr = ioutil.ReadAll(req.Body); tmpErr != nil {
		err = errors.New("get response body failed, err is " + tmpErr.Error())
		return
	}
	name = c.Param("name")
	tag = req.Form.Get("tag")
	url = req.Form.Get("url")
	return
}

func executeToClusters(slaves []Slave, urlP, method, mgr string, reqBd []byte) (err error) {
	mutex := new(sync.Mutex)
	wg := new(sync.WaitGroup)
	errInfo := make([]string, 0)
	for _, slave := range slaves {
		wg.Add(1)
		go func(v Slave) {
			defer wg.Done()
			url := fmt.Sprintf(urlP, v.Url)
			respCode, respBody, err := executeToOneCluster(url, method, reqBd)
			if respCode != http.StatusOK || err != nil {
				log.Errorf("url %v %v occurred an error, resp is %v, err is %v", v.Url, mgr, string(respBody), err)
				errMsg := fmt.Sprintf("url %v %v occurred an error, resp is %v, err is %v", v.Url, mgr, string(respBody), err)
				mutex.Lock()
				errInfo = append(errInfo, errMsg)
				mutex.Unlock()
			}
		}(slave)
	}
	wg.Wait()
	if len(errInfo) == 0 {
		return nil
	}
	return errors.New(strings.Join(errInfo, "\n"))
}

func executeToOneCluster(url, method string, configBytes []byte) (respCode int, respBody []byte, err error) {
	config := bytes.NewReader(configBytes)
	req, err := http.NewRequest(method, url, config)
	if err != nil {
		return
	}
	req.Header.Set(ContentTypeHeader, ApplicationJson)
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return
	}
	defer resp.Body.Close()
	respCode = resp.StatusCode
	respBody, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		return
	}
	return
}

func Register(masters []string, myhost, tag string) error {
	var msg string
	hasSuccess := false
	for _, master := range masters {
		err := registerOne(master, myhost, tag)
		if err != nil {
			msg += "register " + master + " error " + err.Error()
		} else {
			hasSuccess = true
		}
	}
	if msg != "" {
		if hasSuccess {
			log.Error(msg)
			return nil
		}
		return errors.New(msg)
	}
	return nil
}

func registerOne(master, myhost, tag string) error {
	if master == "" {
		return errors.New("master host is not configed")
	}
	req := RegisterReq{Url: myhost, Tag: tag}
	data, err := jsoniter.Marshal(req)
	if err != nil {
		return err
	}
	resp, err := http.Post(master+"/logkit/cluster/register", ApplicationJson, bytes.NewReader(data))
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode == http.StatusOK {
		return nil
	}
	bd, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	return errors.New(string(bd))
}


text:
#import <AppKit/NSNibOutletConnector.h>
#import <objc/runtime.h>

@implementation NSNibOutletConnector

-(void)establishConnection {
   NSString *methodName=[NSString stringWithFormat:@"set%@:",[_label capitalizedString]];
   SEL       selector=NSSelectorFromString(methodName);

   if(selector!=NULL)
    if([_source respondsToSelector:selector]){
     [_source performSelector:selector withObject:_destination];
     return;
    }

   object_setInstanceVariable(_source,[_label UTF8String],&_destination);
}

@end