text:
#ifndef PageSerializer_h
#define PageSerializer_h

#include "KURL.h"
#include "KURLHash.h"
#include "SharedBuffer.h"
#include <wtf/HashMap.h>
#include <wtf/ListHashSet.h>
#include <wtf/Vector.h>

namespace WebCore {

class CachedImage;
class CSSStyleDeclaration;
class CSSStyleRule;
class CSSStyleSheet;
class Frame;
class Page;

// This class is used to serialize a page contents back to text (typically HTML).
// It serializes all the page frames and retrieves resources such as images and CSS stylesheets.
class PageSerializer {
public:
    struct Resource {
        KURL url;
        String mimeType;
        RefPtr<SharedBuffer> data;
        Resource();
        Resource(const KURL&, const String& mimeType, PassRefPtr<SharedBuffer> data);
    };

    explicit PageSerializer(Vector<Resource>*);

    // Initiates the serialization of the frame's page. All serialized content and retrieved
    // resources are added to the Vector passed to the constructor. The first resource in that
    // vector is the top frame serialized content.
    void serialize(Page*);

    KURL urlForBlankFrame(Frame*);

private:
    void serializeFrame(Frame*);

    // Serializes the stylesheet back to text and adds it to the resources if URL is not-empty.
    // It also adds any resources included in that stylesheet (including any imported stylesheets and their own resources).
    void serializeCSSStyleSheet(CSSStyleSheet*, const KURL&);

    void addImageToResources(CachedImage*, const KURL&);
    void retrieveResourcesForCSSDeclaration(CSSStyleDeclaration*);
    void retrieveResourcesForCSSRule(CSSStyleRule*);

    Vector<Resource>* m_resources;
    ListHashSet<KURL> m_resourceURLs;
    HashMap<Frame*, KURL> m_blankFrameURLs;
    unsigned m_blankFrameCounter;
};

}

#endif


text:
{% extends "projects/base.html" %}
{% set page_id = "projects" %}
{% set active_project = project.short_name %}
{% import "projects/_helpers.html" as helper %}
{% set active_link = 'tasks' %}
{% set section = _('Import tasks') %}

{% from "_formhelpers.html" import render_field %}

{% block main_content %}

{{_('From Youtube')}}

 {{ _('Please provide a URL to a Youtube playlist with videos for') }} {{ active_project }}.

<form class="form-group" method="post" action="{{ url_for(target, short_name=project.short_name) }}">
    <fieldset>
        {{ form.hidden_tag() }}
        {{ render_field(form.playlist_url, placeholder=_("URL of a Youtube Playlist")) }}
    </fieldset>
    <input id="submit" type="submit" value="{{_('Import')}}" class="btn btn-primary" />
</form>
{% endblock %}
{% block script %}

{% endblock %}

redpajama_set_name: RedPajamaGithub


text:
This document outlines the rules we have added to the GitHub Desktop project and how to interact with them.

## About

This project uses rules from a number of sources, but sometimes we need specific rules that aren't available elsewhere. These are added to the `eslint-rules/` directory and are configured in the `.eslintrc.yml` file at the root of the project.

## Adding rules

If you wish to add a new rule specific to the project, ensure that there isn't an existing rule available from one of the existing plugins used in the project:

 - `@typescript-eslint/eslint-plugin`
 - `eslint-plugin-babel`
 - `eslint-plugin-jsdoc`
 - `eslint-plugin-json`
 - `eslint-plugin-prettier`
 - `eslint-plugin-react`

This project supports two different kinds of ESLint plugins, based on what you are interested in linting:

 - Typescript-aware rules, that allow you to inspect the AST and relevant information of the source files - these leverage the `@typescript-eslint` parser
    - example: `react-proper-lifecycle-methods` rule
 - Regular ESLint rules, that do not need to inspect the type information in the source files
    - example: `no-unbound-dispatcher-props` rule

How to write a plugin is out of scope for this documentation, but I've added some resources at the end of this page to help you get started.

## Checking locally

The custom ESLint rules are annotated with TypeScript types wherever available, and can be checked through `yarn`:

```
$ yarn check:eslint
```

The `eslint-rules/tsconfig.json` is setup to guide `tsc` to understand the environment for running the ESlint rules, and each rule is annotated
with `@type` hints wherever possible to appease the typechecker.

## Testing locally

Tests are added alongside each rule in the `eslint-rules/tests/` section, and can be run from the project root through `yarn`:

```
$ yarn test:eslint
```

Each test suite is designed to exercise the relevant rule against code snippets that illustrate both valid and invalid code, and indicate which messages should be reported in case of failure.

If you wish to debug the rules using VSCode, add this action to the `configurations` array of the `.vscode/launch.json` settings:

```json
{
  "command": "yarn test:eslint",
  "name": "Test ESLint scripts",
  "request": "launch",
  "type": "node-terminal"
}
```

Running this command will attach the debugger, and allow you to step through the rule with the available test cases.

## Additional resources

 - [ESLint - Working with Rules](http://eslint.org/docs/developer-guide/working-with-rules)
 - [`typescript-estree` package](https://github.com/typescript-eslint/typescript-eslint/tree/master/packages/typescript-estree) - this is part of `@typescript-eslint` and allows for interop between Typescript code and the `estree` reference spec that ESLint uses for it's plugins.


text:
package io.enmasse.systemtest.platform.cluster;

import io.enmasse.systemtest.logs.CustomLogger;
import org.slf4j.Logger;

import java.util.Arrays;

public interface KubeCluster {

    boolean isAvailable();

    boolean isClusterUp();

    String getKubeCmd();

    static KubeCluster detect() {
        Logger LOGGER = CustomLogger.getLogger();

        KubeCluster[] clusters = new KubeCluster[]{new MinikubeCluster(), new CRCCluster(), new OpenShiftCluster()};
        KubeCluster cluster = null;
        for (KubeCluster kc : clusters) {
            if (kc.isAvailable()) {
                LOGGER.debug("Cluster {} is installed", kc);
                if (kc.isClusterUp()) {
                    LOGGER.debug("Cluster {} is running", kc);
                    cluster = kc;
                    break;
                } else {
                    LOGGER.debug("Cluster {} is not running", kc);
                }
            } else {
                LOGGER.debug("Cluster {} is not installed", kc);
            }
        }
        if (cluster == null) {
            throw new NoClusterException(
                    "Unable to find a cluster; tried " + Arrays.toString(clusters));
        }
        return cluster;
    }
}


text:
from System.IO import *
from System.Drawing import *
from System.Runtime.Remoting import *
from System.Threading import *
from System.Windows.Forms import *
from System.Xml.Serialization import *
from System import *
from System.Collections.Generic import Dictionary
import time
import itertools
from random import shuffle

# specific EDMSuite stuff
from DAQ.Environment import *
from DAQ import *
from MOTMaster import *

def run_script():
	return 0

def ScanSingleParameter(script_name, parameter_name, values):
	"""
	Generic function to run a MOTMaster script (script_name - note you don't need the path or .cs suffix)
	repeatedly, whilst scanning a single parameter (parameter_name) over a list of values. Can be used
	directly or with one of convenience functions defined below.
	"""
	dic = Dictionary[String, Object]()
	mm.SetScriptPath('C:\\ControlPrograms\\EDMSuite\\MoleculeMOTMasterScripts\\' + script_name + '.cs')
	for value in values:
		start = time.time()
		dic[parameter_name] = value
		mm.Go(dic)
		end = time.time()
		print '{0} : {1} seconds'.format(value, end-start)
	print 'Finished'
	return 0

def ScanMultipleParametersList(script_name, parameter_names, value_tuples):
	dic = Dictionary[String, Object]()
	mm.SetScriptPath('C:\\ControlPrograms\\EDMSuite\\MoleculeMOTMasterScripts\\' + script_name + '.cs')
	row_format = '{:<3} {:<8}' + ' {:<20}' * len(parameter_names)
	print row_format.format('N', 'Time', *parameter_names)
	for value_tuple in value_tuples:
		start = time.time()
		for i in range(len(parameter_names)):
			dic[parameter_names[i]] = value_tuple[i]
		mm.Go(dic)
		end = time.time()
		print row_format.format(i, str(int(round(end-start))) + ' s', *value_tuple)
	print 'Finished'
	return 0

def ScanMultipleParameters(script_name, parameter_names, values):
	"""
	Generic function to run a MOTMaster script (script_name - note you don't need the path or .cs suffix)
	repeatedly, whilst scanning a list of parameters (parameter_names) over a list of lists of values. The number
	lists of values must match the number of parameters. The parameters will be looped over in order of appearance.
	Can be used directly or with one of convenience functions defined below.
	"""
	dic = Dictionary[String, Object]()
	mm.SetScriptPath('C:\\ControlPrograms\\EDMSuite\\MoleculeMOTMasterScripts\\' + script_name + '.cs')
	if not all(isinstance(item, list) for item in values):
		raise ValueError('Values must be a list of lists (even if only single valued!).')
	num_params = len(parameter_names)
	num_values_lists = len(values)
	if not num_params == num_values_lists:
		raise ValueError('The number of lists of values must match the number of parameters')
	row_format = '{:<3} {:<8}' + ' {:<20}' * num_params
	print row_format.format('N', 'Time', *parameter_names)
	i=0
	start = time.time()
	for combination in itertools.product(*values):
		iter_start = time.time()
		for j in range(0,num_params):
			dic[parameter_names[j]] = combination[j]
		mm.Go(dic)
		iter_end = time.time()
		i+=1
		print row_format.format(i, str(int(round(iter_end-iter_start))) + ' s', *combination)
	end = time.time()
	print 'Finished, total time was {} s.'.format(int(round(end-start)))

def ScanSingleParameter2(script_name, parameter_name, values):
	ScanMultipleParameters(script_name, [parameter_name], [values])

def ScanMicrowaveFrequency(script_name, centre_freq, num_steps, freq_range, channel):
	lowest_freq = centre_freq - freq_range/2
	spacing = freq_range/(num_steps - 1)
	values = [lowest_freq + spacing * x for x in range(0, num_steps)]
	shuffle(values)
	mm.SetScriptPath('C:\\ControlPrograms\\EDMSuite\\MoleculeMOTMasterScripts\\' + script_name + '.cs')
	for value in values:
		start = time.time()
		if channel=='G1':
			hc.tabs['Gigatronics Synthesizer 1'].SetFrequency(value)
		elif channel=='G2':
			hc.tabs['Gigatronics Synthesizer 2'].SetFrequency(value)
		elif channel=='WA':
			hc.tabs['Windfreak Synthesizer'].SetFrequency(value, False)
		elif channel=='WB':
			hc.tabs['Windfreak Synthesizer'].SetFrequency(value, True)
		mm.Go()
		end = time.time()
		print '{0} : {1} seconds'.format(value, int(round(end-start)))
	print 'Finished'

def ScanMicrowaveAmplitude(script_name, values, channel):
	mm.SetScriptPath('C:\\ControlPrograms\\EDMSuite\\MoleculeMOTMasterScripts\\' + script_name + '.cs')
	for value in values:
		start = time.time()
		if channel=='G1':
			hc.tabs['Gigatronics Synthesizer 1'].SetAmplitude(value)
		elif channel=='G2':
			hc.tabs['Gigatronics Synthesizer 2'].SetAmplitude(value)
		elif channel=='WA':
			hc.tabs['Windfreak Synthesizer'].SetAmplitude(value, False)
		elif channel=='WB':
			hc.tabs['Windfreak Synthesizer'].SetAmplitude(value, True)
		mm.Go()
		end = time.time()
		print '{0} : {1} seconds'.format(value, int(round(end-start)))
	print 'Finished'

def ScanExpansionTime(values=[50, 650, 150, 750, 550, 350, 250, 450, 800]):
	script_name = 'MOTBlueMolassesShimSwitch'
	parameter_name = 'ExpansionTime'
	return ScanSingleParameter(script_name, parameter_name, values)
def ScanExpansionTimeShort(values=[50, 650, 150, 750, 550, 350, 250, 450, 800]):
	script_name = 'MOTBlueMolassesShimSwitchShort'
	parameter_name = 'ExpansionTime'
	return ScanSingleParameter(script_name, parameter_name, values)
def ScanExpansionTimeHot(values=[50, 260, 180, 140, 300, 220, 100]):
	script_name = 'MOTRampIntensity'
	parameter_name = 'ExpansionTime'
	return ScanSingleParameter(script_name, parameter_name, values)

def ScanMolassesHoldTime(values=[500,1000]):
	script_name = 'MOTBlueMolassesLifetime'
	parameter_name = 'MolassesHoldTime'
	return ScanSingleParameter(script_name, parameter_name, values)

def ScanOscillationTime(values=[0, 1200, 500, 900, 200, 1000, 300, 700, 400, 100, 600, 1100, 800, 1300]):
	script_name = 'MOTOscillation'
	parameter_name = 'OscillationTime'
	return ScanSingleParameter(script_name, parameter_name, values)

def PokeVelocityMeasurement(values=[0,20,30,10]):
	script_name = 'PokeNoRecapture'
	parameter_name = 'FreeFlightTime'
	return ScanSingleParameter(script_name, parameter_name, values)

def ScanSlowingAOMOff(values=[1500, 900, 1300, 1100]):
	script_name = 'MOTBasicExperimental'
	parameter_name = 'SlowingAOMOffStart'
	return ScanSingleParameter(script_name, parameter_name, values)

def ScanFrame0Trigger(values=[250, 850, 1450, 1050, 450, 1250, 650]):
	script_name = 'MOTBasic'
	parameter_name = 'Frame0Trigger'
	return ScanSingleParameter(script_name, parameter_name, values)

def ScanPokeDetuning(values=[ -1.4,-1.35,-1.38,-1.31,-1.36,-1.33,-1.37,-1.32,-1.34,-1.39]):
	script_name = 'MOTOscillation'
	parameter_name = 'PokeDetuningValue'
	return ScanSingleParameter(script_name, parameter_name, values)

def ScanMolassesField(values=[0.05, -0.05, 0.25, 0.15, 0.35]):
	script_name = 'MOTBlueMolassesShimSwitch'
	parameter_name = 'MOTBOPCoilsCurrentMolassesValue'
	return ScanSingleParameter(script_name, parameter_name, values)

def ScanRedMolassesTime(values=[8200, 8300, 8400, 8500, 8600, 8800, 9200]):
	script_name = 'MOTBlueMolassesRedMolasses'
	parameter_name = 'Frame0Trigger'
	return ScanSingleParameter(script_name, parameter_name, values)

def ScanDetuningv0(values=[0.0,5.0,10.0,15.0,20.0,25.0,30.0,35.0]):
	script_name = 'MOTBlueMolassesShimSwitch'
	parameter_name = 'v0FrequencyNewValue'
	return ScanSingleParameter(script_name, parameter_name, values)

def MagTrapLifetime(values=[ 2000, 3000, 4000, 5000]):
	script_name = 'MOTMagTrapLifetime'
	parameter_name = 'magTrapLifetime'
	return ScanSingleParameter(script_name, parameter_name, values)

def ChirpAmplitudeScan(values=[ -1.9, -1.95, -2.0, -2.05, -2.1]):
	script_name = 'MOTBasic'
	parameter_name = 'SlowingChirpEndValue'
	return ScanSingleParameter(script_name, parameter_name, values)

def RunExperimentWithTrackMovement(script_name, StartPosition, EndPosition, numRuns):
	mm.SetScriptPath('C:\\ControlPrograms\\EDMSuite\\MoleculeMOTMasterScripts\\' + script_name + '.cs')

	for i in range(numRuns):
		hc.tabs['XPS Track'].TCLscript(StartPosition, EndPosition)
		mm.Go()

def ScanTurningPoint(script_name, StartPosition, values, numRuns):
	for value in values:
		RunExperimentWithTrackMovement(script_name, StartPosition, value, numRuns)


text:
const logger = require('winston');
const { customAlphabet } = require('nanoid');
const moment = require('moment');
const FD = require('./frontdata');
const Contract = require('./contract');
const occupantModel = require('../models/occupant');
const propertyModel = require('../models/property');

const nanoid = customAlphabet('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', 12);

function _buildPropertyMap(realm, callback) {
  propertyModel.findAll(realm, (errors, properties) => {
    const propertyMap = {};
    if (properties) {
      properties.reduce((acc, property) => {
        acc[property._id.toString()] = property;
        return acc;
      }, propertyMap);
    }
    callback(errors, propertyMap);
  });
}

////////////////////////////////////////////////////////////////////////////////
// Exported functions
////////////////////////////////////////////////////////////////////////////////
function add(req, res) {
  const realm = req.realm;
  const occupant = occupantModel.schema.filter(req.body);

  if (!occupant.isCompany) {
    occupant.company = null;
    occupant.legalForm = null;
    occupant.siret = null;
    occupant.capital = null;
    occupant.name = occupant.name || occupant.manager;
  } else {
    occupant.name = occupant.company;
  }

  occupant.reference = occupant.reference || nanoid();

  if (!occupant.name) {
    return res.status(422).json({
      errors: ['Missing tenant name'],
    });
  }

  _buildPropertyMap(realm, (errors, propertyMap) => {
    if (errors && errors.length > 0) {
      return res.status(404).json({
        errors: errors,
      });
    }

    // Resolve proprerties
    if (occupant.properties) {
      occupant.properties.forEach((item) => {
        item.property = propertyMap[item.propertyId];
        item.entryDate = item.entryDate || occupant.beginDate;
        item.exitDate = item.exitDate || occupant.endDate;
        item.rent = item.rent || item.property.price;
        item.expenses =
          item.expenses ||
          (item.property.expense && [
            { title: 'general expense', amount: item.property.expense },
          ]) ||
          [];
      });
    }

    // Build rents from contract
    occupant.rents = [];
    if (occupant.beginDate && occupant.endDate && occupant.properties) {
      const contract = Contract.create({
        begin: occupant.beginDate,
        end: occupant.endDate,
        frequency: occupant.frequency || 'months',
        properties: occupant.properties,
      });

      occupant.rents = contract.rents;
    }

    occupantModel.add(realm, occupant, (errors, occupant) => {
      if (errors) {
        return res.status(500).json({
          errors: errors,
        });
      }
      res.json(FD.toOccupantData(occupant));
    });
  });
}

function update(req, res) {
  const realm = req.realm;
  const occupantId = req.params.id;
  const occupant = occupantModel.schema.filter(req.body);

  if (!occupant.isCompany) {
    occupant.company = null;
    occupant.legalForm = null;
    occupant.siret = null;
    occupant.capital = null;
    occupant.name = occupant.name || occupant.manager;
  } else {
    occupant.name = occupant.company;
  }

  occupant.reference = occupant.reference || nanoid();

  if (!occupant.name) {
    return res.status(422).json({
      errors: ['Missing tenant name'],
    });
  }

  occupantModel.findOne(realm, occupantId, (errors, dbOccupant) => {
    if (errors && errors.length > 0) {
      return res.status(404).json({
        errors: errors,
      });
    }

    if (dbOccupant.documents) {
      occupant.documents = dbOccupant.documents;
    }

    _buildPropertyMap(realm, (errors, propertyMap) => {
      if (errors && errors.length > 0) {
        return res.status(404).json({
          errors: errors,
        });
      }

      // Resolve proprerties
      if (occupant.properties) {
        occupant.properties = occupant.properties.map((item) => {
          let itemToKeep;
          if (dbOccupant.properties) {
            dbOccupant.properties.forEach((dbItem) => {
              if (dbItem.propertyId === item.propertyId) {
                itemToKeep = dbItem;
              }
            });
          }
          if (!itemToKeep) {
            itemToKeep = {
              propertyId: item.propertyId,
              property: propertyMap[item.propertyId],
            };
          }
          itemToKeep.entryDate = item.entryDate || occupant.beginDate;
          itemToKeep.exitDate = item.exitDate || occupant.endDate;
          itemToKeep.rent = item.rent || itemToKeep.property.price;
          itemToKeep.expenses =
            item.expenses ||
            (itemToKeep.property.expense && [
              { title: 'general expense', amount: itemToKeep.property.expense },
            ]) ||
            [];
          return itemToKeep;
        });
      }

      // Build rents from contract
      occupant.rents = [];
      if (occupant.beginDate && occupant.endDate && occupant.properties) {
        try {
          const contract = {
            begin: dbOccupant.beginDate,
            end: dbOccupant.endDate,
            frequency: occupant.frequency || 'months',
            terms: Math.ceil(
              moment(dbOccupant.endDate, 'DD/MM/YYYY').diff(
                moment(dbOccupant.beginDate, 'DD/MM/YYYY'),
                'months',
                true
              )
            ),
            properties: dbOccupant.properties,
            vatRate: dbOccupant.vatRatio,
            discount: dbOccupant.discount,
            rents: dbOccupant.rents,
          };

          const modification = {
            begin: occupant.beginDate,
            end: occupant.endDate,
            termination: occupant.terminationDate,
            properties: occupant.properties,
          };
          if (occupant.vatRatio !== undefined) {
            modification.vatRate = occupant.vatRatio;
          }
          if (occupant.discount !== undefined) {
            modification.discount = occupant.discount;
          }

          const newContract = Contract.update(contract, modification);
          occupant.rents = newContract.rents;
        } catch (e) {
          logger.error(e);
          return res.sendStatus(500);
        }
      }

      occupantModel.update(realm, occupant, (errors) => {
        if (errors) {
          return res.status(500).json({
            errors: errors,
          });
        }
        res.json(FD.toOccupantData(occupant));
      });
    });
  });
}

function remove(req, res) {
  const realm = req.realm;
  const occupantIds = req.params.ids.split(',');

  function releaseRent(callback) {
    const occupantfilters = occupantIds.map((_id) => {
      return { _id };
    });

    occupantModel.findFilter(
      realm,
      {
        $query: {
          $or: occupantfilters,
        },
      },
      (errors, occupants) => {
        if (errors) {
          return res.status(500).json({
            errors,
          });
        }

        if (!occupants || !occupants.length) {
          return res.sendStatus(404);
        }

        if (occupants) {
          const occupantsWithPaidRents = occupants.filter((occupant) => {
            return occupant.rents.some(
              (rent) =>
                (rent.payments &&
                  rent.payments.some((payment) => payment.amount > 0)) ||
                rent.discounts.some(
                  (discount) => discount.origin === 'settlement'
                )
            );
          });
          if (occupantsWithPaidRents.length > 0) {
            return res.status(422).json({
              errors: [
                `impossible to remove ${occupantsWithPaidRents[0].name}. Rents have been recorded.`,
              ],
            });
          }
          occupantModel.remove(
            realm,
            occupants.map((occupant) => occupant._id.toString()),
            (errors) => {
              if (errors) {
                return res.status(500).json({
                  errors,
                });
              }
              callback();
            }
          );
        }
      }
    );
  }

  releaseRent(() => {
    occupantModel.remove(realm, occupantIds, (errors) => {
      if (errors) {
        return res.status(500).json({
          errors,
        });
      }
      res.sendStatus(200);
    });
  });
}

function all(req, res) {
  const realm = req.realm;
  occupantModel.findAll(realm, (errors, occupants) => {
    if (errors && errors.length > 0) {
      return res.status(500).json({
        errors: errors,
      });
    }

    res.json(occupants.map((occupant) => FD.toOccupantData(occupant)));
  });
}

function one(req, res) {
  const realm = req.realm;
  const occupantId = req.params.id;
  occupantModel.findOne(realm, occupantId, (errors, dbOccupant) => {
    if (errors && errors.length > 0) {
      return res.status(404).json({
        errors: errors,
      });
    }

    res.json(FD.toOccupantData(dbOccupant));
  });
}

function overview(req, res) {
  const realm = req.realm;
  let result = {
    countAll: 0,
    countActive: 0,
    countInactive: 0,
  };
  const currentDate = moment();

  occupantModel.findAll(realm, (errors, occupants) => {
    if (errors && errors.length > 0) {
      return res.status(404).json({
        errors: errors,
      });
    }

    if (occupants) {
      result.countAll = occupants.length;
      result = occupants.reduce((acc, occupant) => {
        const endMoment = moment(
          occupant.terminationDate || occupant.endDate,
          'DD/MM/YYYY'
        );
        if (endMoment.isBefore(currentDate, 'day')) {
          acc.countInactive++;
        } else {
          acc.countActive++;
        }
        return acc;
      }, result);
    }
    res.json(result);
  });
}

module.exports = {
  add,
  update,
  remove,
  one,
  all,
  overview,
};


text:
/** Filter inputs by id */
define(function (require) {
  'use strict';

  var modules = require('modules');
  var angular = require('angular');

  var excludedInputs = ['loc_meta_', 'app_meta_', 'app_tags_', 'env_meta_', 'env_tags_'];

  modules.get('a4c-common').filter('internalInputs', function() {
    return function(items) {
      var filtered = {};
      var foundStart = false;
      angular.forEach(items, function(inputValue, inputId) {
        excludedInputs.forEach(function(inputStart) {
          // start by one reserved tag ?
          if (inputId.indexOf(inputStart) === 0) {
            foundStart = true;
          }
        });
        if (!foundStart) {
          filtered[inputId] = inputValue;
        }
        foundStart = false;
      });
      return filtered;
    };
  });
});


text:
mongoroo
========

MongoDB and Spring Roo Integration


text:
@interface RegisterViewController ()<UITableViewDataSource, UITableViewDelegate, TTTAttributedLabelDelegate>
@property (nonatomic, assign) RegisterMethodType medthodType;

@property (nonatomic, strong) Register *myRegister;

@property (strong, nonatomic) TPKeyboardAvoidingTableView *myTableView;
@property (strong, nonatomic) UIButton *footerBtn;
@property (strong, nonatomic) EaseInputTipsView *inputTipsView;

@property (assign, nonatomic) BOOL captchaNeeded;

@property (strong, nonatomic) NSString *phoneCodeCellIdentifier;
@property (strong, nonatomic) NSDictionary *countryCodeDict;

@end

@implementation RegisterViewController

+ (instancetype)vcWithMethodType:(RegisterMethodType)methodType registerObj:(Register *)obj{
    RegisterViewController *vc = [self new];
    vc.medthodType = methodType;
    vc.myRegister = obj;
    return vc;
}

- (void)viewDidLoad{
    [super viewDidLoad];
    self.phoneCodeCellIdentifier = [Input_OnlyText_Cell randomCellIdentifierOfPhoneCodeType];
    _captchaNeeded = NO;
    self.title = @"注册";
    if (!_myRegister) {
        self.myRegister = [Register new];
    }
    //    添加myTableView
    _myTableView = ({
        TPKeyboardAvoidingTableView *tableView = [[TPKeyboardAvoidingTableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        [tableView registerClass:[Input_OnlyText_Cell class] forCellReuseIdentifier:kCellIdentifier_Input_OnlyText_Cell_Text];
        [tableView registerClass:[Input_OnlyText_Cell class] forCellReuseIdentifier:kCellIdentifier_Input_OnlyText_Cell_Password];
        [tableView registerClass:[Input_OnlyText_Cell class] forCellReuseIdentifier:kCellIdentifier_Input_OnlyText_Cell_Captcha];
        [tableView registerClass:[Input_OnlyText_Cell class] forCellReuseIdentifier:kCellIdentifier_Input_OnlyText_Cell_Phone];
        [tableView registerClass:[Input_OnlyText_Cell class] forCellReuseIdentifier:self.phoneCodeCellIdentifier];
        tableView.backgroundColor = kColorTableSectionBg;
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:tableView];
        [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
        tableView;
    });
    [self setupNav];
    self.myTableView.tableHeaderView = [self customHeaderView];
    self.myTableView.tableFooterView=[self customFooterView];
    [self configBottomView];
}

- (void)refreshCaptchaNeeded{
    __weak typeof(self) weakSelf = self;
    [[Coding_NetAPIManager sharedManager] request_CaptchaNeededWithPath:@"api/captcha/register" andBlock:^(id data, NSError *error) {
        if (data) {
            NSNumber *captchaNeededResult = (NSNumber *)data;
            if (captchaNeededResult) {
                weakSelf.captchaNeeded = captchaNeededResult.boolValue;
            }
            [weakSelf.myTableView reloadData];
        }
    }];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [self refreshCaptchaNeeded];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.view endEditing:YES];
}

- (EaseInputTipsView *)inputTipsView{
    if (!_inputTipsView) {
        _inputTipsView = ({
            EaseInputTipsView *tipsView = [EaseInputTipsView tipsViewWithType:EaseInputTipsViewTypeRegister];
            tipsView.valueStr = nil;

            __weak typeof(self) weakSelf = self;
            tipsView.selectedStringBlock = ^(NSString *valueStr){
                [weakSelf.view endEditing:YES];
                weakSelf.myRegister.email = valueStr;
                [weakSelf.myTableView reloadData];
            };
            UITableViewCell *cell = [_myTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
            [tipsView setY:CGRectGetMaxY(cell.frame)];

            [_myTableView addSubview:tipsView];
            tipsView;
        });
    }
    return _inputTipsView;
}

#pragma mark - Nav
- (void)setupNav{
    if (self.navigationController.childViewControllers.count <= 1) {
        self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithBtnTitle:@"取消" target:self action:@selector(dismissSelf)];
    }
}

- (void)dismissSelf{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - Top Bottom Header Footer
- (void)configBottomView{
    UIView *bottomView = [UIView new];
    bottomView.backgroundColor = self.myTableView.backgroundColor;

    UIButton *bottomBtn = ({
        UIButton *button = [UIButton new];
        button.titleLabel.font = [UIFont systemFontOfSize:15];
        [button setTitleColor:kColorBrandGreen forState:UIControlStateNormal];
        [button setTitle:_medthodType == RegisterMethodEamil? @"手机号注册": @"邮箱注册" forState:UIControlStateNormal];
        [button addTarget:self action:@selector(changeMethodType) forControlEvents:UIControlEventTouchUpInside];
        button;
    });

    [bottomView addSubview:bottomBtn];
    [bottomBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(bottomView).insets(UIEdgeInsetsMake(0, 0, 30, 0));
    }];

    [self.view addSubview:bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.height.mas_equalTo(50);
    }];
}

- (void)changeMethodType{
    if (_medthodType == RegisterMethodPhone) {
        RegisterViewController *vc = [RegisterViewController vcWithMethodType:RegisterMethodEamil registerObj:_myRegister];
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}
- (UIView *)customHeaderView{
    UIView *headerV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, 0.15*kScreen_Height)];
    headerV.backgroundColor = [UIColor clearColor];
    UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, 50)];
    headerLabel.backgroundColor = [UIColor clearColor];
    headerLabel.font = [UIFont boldSystemFontOfSize:18];
    headerLabel.textColor = kColor222;
    headerLabel.textAlignment = NSTextAlignmentCenter;
    headerLabel.text = @"加入Coding,体验云端开发之美!";
    [headerLabel setCenter:headerV.center];
    [headerV addSubview:headerLabel];
    return headerV;
}
- (UIView *)customFooterView{
    UIView *footerV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, 150)];
    //button
    _footerBtn = [UIButton buttonWithStyle:StrapSuccessStyle andTitle:@"注册" andFrame:CGRectMake(kLoginPaddingLeftWidth, 20, kScreen_Width-kLoginPaddingLeftWidth*2, 45) target:self action:@selector(sendRegister)];
    [footerV addSubview:_footerBtn];

    __weak typeof(self) weakSelf = self;
    RAC(self, footerBtn.enabled) = [RACSignal combineLatest:@[RACObserve(self, myRegister.global_key),
                                                              RACObserve(self, myRegister.phone),
                                                              RACObserve(self, myRegister.email),
                                                              RACObserve(self, myRegister.password),
                                                              RACObserve(self, myRegister.code),
                                                              RACObserve(self, myRegister.j_captcha),
                                                              RACObserve(self, captchaNeeded)]
                                                     reduce:^id(NSString *global_key,
                                                                NSString *phone,
                                                                NSString *email,
                                                                NSString *password,
                                                                NSString *code,
                                                                NSString *j_captcha,
                                                                NSNumber *captchaNeeded){
                                                         BOOL enabled = (global_key.length > 0 &&
                                                                         password.length > 0 &&
                                                                         (!captchaNeeded.boolValue || j_captcha.length > 0) &&
                                                                         ((weakSelf.medthodType == RegisterMethodEamil && email.length > 0) ||
                                                                          (weakSelf.medthodType == RegisterMethodPhone && phone.length > 0 && code.length > 0)));
                                                         return @(enabled);
                                                     }];
    //label
    UITTTAttributedLabel *lineLabel = ({
        UITTTAttributedLabel *label = [[UITTTAttributedLabel alloc] init];
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:12];
        label.textColor = kColor999;
        label.numberOfLines = 0;
        label.linkAttributes = kLinkAttributes;
        label.activeLinkAttributes = kLinkAttributesActive;
        label.delegate = self;
        label;
    });
    NSString *tipStr = @"注册 Coding 账号表示您已同意《Coding 服务条款》";
    lineLabel.text = tipStr;
    [lineLabel addLinkToTransitInformation:@{@"actionStr" : @"gotoServiceTermsVC"} withRange:[tipStr rangeOfString:@"《Coding 服务条款》"]];
    CGRect footerBtnFrame = _footerBtn.frame;
    lineLabel.frame = CGRectMake(CGRectGetMinX(footerBtnFrame), CGRectGetMaxY(footerBtnFrame) +12, CGRectGetWidth(footerBtnFrame), 12);
    [footerV addSubview:lineLabel];

    return footerV;
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSInteger num = _medthodType == RegisterMethodEamil? 3: 4;
    return _captchaNeeded? num +1 : num;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *cellIdentifier;
    if (_medthodType == RegisterMethodEamil) {
        cellIdentifier = (indexPath.row == 3? kCellIdentifier_Input_OnlyText_Cell_Captcha:
                          indexPath.row == 2? kCellIdentifier_Input_OnlyText_Cell_Password:
                          kCellIdentifier_Input_OnlyText_Cell_Text);
    }else{
        cellIdentifier = (indexPath.row == 4? kCellIdentifier_Input_OnlyText_Cell_Captcha:
                          indexPath.row == 3? self.phoneCodeCellIdentifier:
                          indexPath.row == 2? kCellIdentifier_Input_OnlyText_Cell_Password:
                          indexPath.row == 1? kCellIdentifier_Input_OnlyText_Cell_Phone:
                          kCellIdentifier_Input_OnlyText_Cell_Text);
    }
    Input_OnlyText_Cell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];

    __weak typeof(self) weakSelf = self;
    if (_medthodType == RegisterMethodEamil) {
        if (indexPath.row == 0) {
            [cell setPlaceholder:@" 用户名(个性后缀)" value:self.myRegister.global_key];
            cell.textValueChangedBlock = ^(NSString *valueStr){
                weakSelf.myRegister.global_key = valueStr;
            };
        }else if (indexPath.row == 1){
            cell.textField.keyboardType = UIKeyboardTypeEmailAddress;
            [cell setPlaceholder:@" 邮箱" value:self.myRegister.email];
            cell.textValueChangedBlock = ^(NSString *valueStr){
                weakSelf.inputTipsView.valueStr = valueStr;
                weakSelf.inputTipsView.active = YES;
                weakSelf.myRegister.email = valueStr;
            };
            cell.editDidEndBlock = ^(NSString *textStr){
                weakSelf.inputTipsView.active = NO;
            };
        }else if (indexPath.row == 2){
            [cell setPlaceholder:@" 设置密码" value:self.myRegister.password];
            cell.textValueChangedBlock = ^(NSString *valueStr){
                weakSelf.myRegister.password = valueStr;
            };
        }else{
            [cell setPlaceholder:@" 验证码" value:self.myRegister.j_captcha];
            cell.textValueChangedBlock = ^(NSString *valueStr){
                weakSelf.myRegister.j_captcha = valueStr;
            };
        }
    }else{
        if (indexPath.row == 0) {
            [cell setPlaceholder:@" 用户名(个性后缀)" value:self.myRegister.global_key];
            cell.textValueChangedBlock = ^(NSString *valueStr){
                weakSelf.myRegister.global_key = valueStr;
            };
        }else if (indexPath.row == 1){
            if (!_countryCodeDict) {
                _countryCodeDict = @{@"country": @"China",
                                     @"country_code": @"86",
                                     @"iso_code": @"cn"};
            }
            cell.textField.keyboardType = UIKeyboardTypeNumberPad;
            [cell setPlaceholder:@" 手机号" value:self.myRegister.phone];
            cell.countryCodeL.text = [NSString stringWithFormat:@"+%@", _countryCodeDict[@"country_code"]];
            cell.countryCodeBtnClickedBlock = ^(){
                [weakSelf goToCountryCodeVC];
            };
            cell.textValueChangedBlock = ^(NSString *valueStr){
                weakSelf.myRegister.phone = valueStr;
            };
        }else if (indexPath.row == 2){
            [cell setPlaceholder:@" 设置密码" value:self.myRegister.password];
            cell.textValueChangedBlock = ^(NSString *valueStr){
                weakSelf.myRegister.password = valueStr;
            };
        }else if (indexPath.row == 3){
            cell.textField.keyboardType = UIKeyboardTypeNumberPad;
            [cell setPlaceholder:@" 手机验证码" value:self.myRegister.code];
            cell.textValueChangedBlock = ^(NSString *valueStr){
                weakSelf.myRegister.code = valueStr;
            };
            cell.phoneCodeBtnClckedBlock = ^(PhoneCodeButton *btn){
                [weakSelf phoneCodeBtnClicked:btn];
            };
        }else{
            [cell setPlaceholder:@" 验证码" value:self.myRegister.j_captcha];
            cell.textValueChangedBlock = ^(NSString *valueStr){
                weakSelf.myRegister.j_captcha = valueStr;
            };
        }
    }
    [tableView addLineforPlainCell:cell forRowAtIndexPath:indexPath withLeftSpace:kLoginPaddingLeftWidth];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44.0;
}

#pragma mark TTTAttributedLabelDelegate
- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithTransitInformation:(NSDictionary *)components{
    [self gotoServiceTermsVC];
}
#pragma mark Btn Clicked
- (void)phoneCodeBtnClicked:(PhoneCodeButton *)sender{
    if (![_myRegister.phone isPhoneNo]) {
        [NSObject showHudTipStr:@"手机号码格式有误"];
        return;
    }
    sender.enabled = NO;
    NSDictionary *params = @{@"phone": _myRegister.phone,
                             @"phoneCountryCode": [NSString stringWithFormat:@"+%@", _countryCodeDict[@"country_code"]]};
    [[CodingNetAPIClient sharedJsonClient] requestJsonDataWithPath:@"api/account/register/generate_phone_code" withParams:params withMethodType:Post andBlock:^(id data, NSError *error) {
        if (data) {
            [NSObject showHudTipStr:@"验证码发送成功"];
            [sender startUpTimer];
        }else{
            [sender invalidateTimer];
        }
    }];
}

- (void)sendRegister{
    if (![_myRegister.global_key isGK]) {
        [NSObject showHudTipStr:@"个性后缀仅支持英文字母、数字、横线(-)以及下划线(_)"];
        return;
    }
    __weak typeof(self) weakSelf = self;
    NSMutableDictionary *params = @{@"channel": [Register channel],
                                    @"global_key": _myRegister.global_key,
                                    @"password": [_myRegister.password sha1Str],
                                    @"confirm": [_myRegister.password sha1Str]}.mutableCopy;
    if (_medthodType == RegisterMethodEamil) {
        params[@"email"] = _myRegister.email;
    }else{
        params[@"phone"] = _myRegister.phone;
        params[@"code"] = _myRegister.code;
        params[@"country"] = _countryCodeDict[@"iso_code"];
        params[@"phoneCountryCode"] = [NSString stringWithFormat:@"+%@", _countryCodeDict[@"country_code"]];
    }
    if (_captchaNeeded) {
        params[@"j_captcha"] = _myRegister.j_captcha;
    }
    [self.footerBtn startQueryAnimate];
    [[Coding_NetAPIManager sharedManager] request_Register_V2_WithParams:params andBlock:^(id data, NSError *error) {
        [weakSelf.footerBtn stopQueryAnimate];
        if (data) {
            [self.view endEditing:YES];
            [Login setPreUserEmail:self.myRegister.global_key];//记住登录账号
            [((AppDelegate *)[UIApplication sharedApplication].delegate) setupTabViewController];
            if (weakSelf.medthodType == RegisterMethodEamil) {
                kTipAlert(@"欢迎注册 Coding,请尽快去邮箱查收邮件并激活账号。如若在收件箱中未看到激活邮件,请留意一下垃圾邮件箱(T_T)。");
            }
        }else{
            [weakSelf refreshCaptchaNeeded];
        }
    }];
}

#pragma mark VC
- (void)gotoServiceTermsVC{
    NSString *pathForServiceterms = [[NSBundle mainBundle] pathForResource:@"service_terms" ofType:@"html"];
    WebViewController *vc = [WebViewController webVCWithUrlStr:pathForServiceterms];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)goToCountryCodeVC{
    __weak typeof(self)  weakSelf = self;
    CountryCodeListViewController *vc = [CountryCodeListViewController new];
    vc.selectedBlock = ^(NSDictionary *countryCodeDict){
        weakSelf.countryCodeDict = countryCodeDict;
    };
    [self.navigationController pushViewController:vc animated:YES];
}

@end


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

<title>CreateStaticLibrary (Gradle API 1.12)</title>
<meta name="date" content="2014-04-29">
<link href="../../../../groovy.ico" type="image/x-icon" rel="shortcut icon">
<link href="../../../../groovy.ico" type="image/x-icon" rel="icon">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

      Overview

      Package
    Class

      Deprecated
      Index
      Help

Groovy Documentation

  FRAMES
 NO FRAMES

  All Classes

SUMMARY: NESTED | FIELD | PROPERTY | CONSTR | METHOD

DETAIL: FIELD | PROPERTY | CONSTR | METHOD

org.gradle.nativebinaries.tasks

[Groovy] Class CreateStaticLibrary

java.lang.Object
  org.gradle.api.internal.AbstractTask
      org.gradle.api.DefaultTask
          org.gradle.nativebinaries.tasks.CreateStaticLibrary

All Implemented Interfaces:

BuildBinaryTask

@Incubating
class CreateStaticLibrary
extends DefaultTask

 Assembles a static library from object files.

    Property Summary

        File

            outputFile

The file where the output binary will be located.

        List

            staticLibArgs

Additional arguments passed to the archiver.

        Platform

            targetPlatform

The platform being targeted.

        ToolChain

            toolChain

The tool chain used for creating the static library.

    Constructor Summary

            CreateStaticLibrary()

    Method Summary

            def

            getOutputType()

            FileCollection

            getSource()

The source object files to be passed to the archiver.

            void

            link()

            void

            source(Object source)

Adds a set of object files to be linked.

    Property Detail

outputFile

@OutputFile
File outputFile

 The file where the output binary will be located.

staticLibArgs

@Input
List staticLibArgs

 Additional arguments passed to the archiver.

targetPlatform

Platform targetPlatform

 The platform being targeted.

toolChain

ToolChain toolChain

 The tool chain used for creating the static library.

    Constructor Detail

        CreateStaticLibrary

@Inject
CreateStaticLibrary()

    Method Detail

        getOutputType

@Input
def getOutputType()

        getSource

@InputFiles
@SkipWhenEmpty // Can't use field due to GRADLE-2026
FileCollection getSource()

 The source object files to be passed to the archiver.

        link

@TaskAction
void link()

        source

void source(Object source)

 Adds a set of object files to be linked.

 The provided source object is evaluated as per Project.files.

Gradle API 1.12


text:
data:extend({
--Arms
{
	type = 'item',
	flags= { "goes-to-main-inventory" },
	name = 'burner-inserter-arm',
	icon = '__complicated-recipes__/graphics/inserters/inserter-hand-0.png',
	subgroup = 'intermediates',
	inventory_order = 'd-a-a',
	stack_size = 50
},
{
	type = 'item',
	flags= { "goes-to-main-inventory" },
	name = 'inserter-arm',
	icon = '__complicated-recipes__/graphics/inserters/inserter-hand-1.png',
	subgroup = 'intermediates',
	inventory_order = 'd-a-b',
	stack_size = 50
},
{
	type = 'item',
	flags= { "goes-to-main-inventory" },
	name = 'long-armed-inserter-arm',
	icon = '__complicated-recipes__/graphics/inserters/inserter-hand-2.png',
	subgroup = 'intermediates',
	inventory_order = 'd-a-c',
	stack_size = 50
},
{
	type = 'item',
	flags= { "goes-to-main-inventory" },
	name = 'fast-inserter-arm',
	icon = '__complicated-recipes__/graphics/inserters/inserter-hand-3.png',
	subgroup = 'intermediates',
	inventory_order = 'd-a-d',
	stack_size = 50
},
{
	type = 'item',
	flags= { "goes-to-main-inventory" },
	name = 'filter-inserter-arm',
	icon = '__complicated-recipes__/graphics/inserters/inserter-hand-4.png',
	subgroup = 'intermediates',
	inventory_order = 'd-a-e',
	stack_size = 50
},
{
	type = 'item',
	flags= { "goes-to-main-inventory" },
	name = 'stack-inserter-arm',
	icon = '__complicated-recipes__/graphics/inserters/inserter-hand-5.png',
	subgroup = 'intermediates',
	inventory_order = 'd-a-f',
	stack_size = 50
},
{
	type = 'item',
	flags= { "goes-to-main-inventory" },
	name = 'stack-filter-inserter-arm',
	icon = '__complicated-recipes__/graphics/inserters/inserter-hand-6.png',
	subgroup = 'intermediates',
	inventory_order = 'd-a-g',
	stack_size = 50
},
--Platform
{
	type = 'item',
	flags= { "goes-to-main-inventory" },
	name = 'burner-inserter-platform',
	icon = '__complicated-recipes__/graphics/inserters/inserter-platform-0.png',
	subgroup = 'intermediates',
	inventory_order = 'd-b-a',
	stack_size = 50
},
{
	type = 'item',
	flags= { "goes-to-main-inventory" },
	name = 'inserter-platform',
	icon = '__complicated-recipes__/graphics/inserters/inserter-platform-1.png',
	subgroup = 'intermediates',
	inventory_order = 'd-b-b',
	stack_size = 50
},
{
	type = 'item',
	flags= { "goes-to-main-inventory" },
	name = 'long-armed-inserter-platform',
	icon = '__complicated-recipes__/graphics/inserters/inserter-platform-2.png',
	subgroup = 'intermediates',
	inventory_order = 'd-b-c',
	stack_size = 50
},
{
	type = 'item',
	flags= { "goes-to-main-inventory" },
	name = 'fast-inserter-platform',
	icon = '__complicated-recipes__/graphics/inserters/inserter-platform-3.png',
	subgroup = 'intermediates',
	inventory_order = 'd-b-d',
	stack_size = 50
},
{
	type = 'item',
	flags= { "goes-to-main-inventory" },
	name = 'filter-inserter-platform',
	icon = '__complicated-recipes__/graphics/inserters/inserter-platform-4.png',
	subgroup = 'intermediates',
	inventory_order = 'd-b-e',
	stack_size = 50
},
{
	type = 'item',
	flags= { "goes-to-main-inventory" },
	name = 'stack-inserter-platform',
	icon = '__complicated-recipes__/graphics/inserters/inserter-platform-5.png',
	subgroup = 'intermediates',
	inventory_order = 'd-b-f',
	stack_size = 50
},
{
	type = 'item',
	flags= { "goes-to-main-inventory" },
	name = 'stack-filter-inserter-platform',
	icon = '__complicated-recipes__/graphics/inserters/inserter-platform-6.png',
	subgroup = 'intermediates',
	inventory_order = 'd-b-g',
	stack_size = 50
}
})


text:
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class SMTPServer { // Ö÷º¯Êý£¬Ã»Ê²Ã´ºÃ˵µÄ
	public static void main(String[] args) {
		try {
			ServerSocket ss = new ServerSocket(25);
			while (true) {
				Socket s = ss.accept();
				new SMTPSession(s).start();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}


text:
SparkFun LSM303C 6 DOF IMU Arduino Library
========================================

![LSM303C Breakout](https://cdn.sparkfun.com/r/600-600/assets/learn_tutorials/4/1/8/LSM303C_BOB.jpg)

[*LSM303C Breakout (BOB-13303)*](https://www.sparkfun.com/products/13303)

This is an arduino IDE library to control the LSM303C.  It can be configured to use I2C or half-duplex SPI.

This has been tested with Arduino Pro Mini.

Repository Contents
-------------------

* **/examples** - Example sketches for the library (.ino). Run these from the Arduino IDE.
* **/src** - Source files for the library (.cpp, .h).
* **keywords.txt** - Keywords from this library that will be highlighted in the Arduino IDE.
* **library.properties** - General library properties for the Arduino package manager.

Example Briefs
--------------

* MinimalistExample - The **easiest** configuration.  Prints out sensor data with some sane default configuration parameters
* ConfigureExample - Same as MinimalistExample, except all of the configuration is exposed with easy to change options all spelled out

Documentation
--------------

* **[Installing an Arduino Library Guide](https://learn.sparkfun.com/tutorials/installing-an-arduino-library)** - Basic information on how to install an Arduino library.
* **[Product Repository](https://github.com/sparkfun/LSM303C_6_DOF_IMU_Breakout)** - Main repository (including hardware files) for the LSM6DS3 Breakout.
* **[Hookup Guide](https://learn.sparkfun.com/tutorials/lsm303c-hookup-guide)** - Basic hookup guide for the LSM303C Breakout.

Products that use this Library
---------------------------------

* [BOB-13303](https://www.sparkfun.com/products/13339)- LSM303C Breakout board

Version History
---------------

* [V 1.0.0](https://github.com/sparkfun/SparkFun_LSM303C_6_DOF_IMU_Breakout_Arduino_Library/releases/tag/V_1.0.0) -- Initial commit of Arduino 1.5+ compatible library.

SparkFun IMU Interface
---
Arduino libraries that implement this interface are guaranteed to to work interchangeably in sketches. If a project is started with 6-DOF IMU, but one realizes that the project really needs a 9-DOF sensor, the change is simple.  Include the new header file, & change the type of the IMU object(s).  All of the code written to the interface will still function.  Here is a list of the functions provided by this interface:
* `status_t begin()` - initialize IMU to sane default values
* `float readGyroX()` - read value from the gyroscope about x-axis
* `float readGyroY()` - read value from the gyroscope about y-axis
* `float readGyroZ()` - read value from the gyroscope about z-axis
* `float readAccelX()` - read value from the accelerometer in x-axis
* `float readAccelY()` - read value from the accelerometer in y-axis
* `float readAccelZ()` - read value from the accelerometer in z-axis
* `float readMagX()` - read value from the magnetometer in x-axis
* `float readMagY()` - read value from the magnetometer in y-axis
* `float readMagZ()` - read value from the magnetometer in z-axis
* `float readTempC()` - read temperature of sensor in ˚C
* `float readTempF()` - read temperature of sensor in ˚F
* `status_t getStatus()` - read the status code of the previous operation

All functions other than `getStatus()` will update the status code depending on how their operation went.  Errors in the read functions can be detected by them returning `NAN` or calling `getStatus()`.

If an IMU doesn't support a set of functions, they will always return `NAN` and set the status to `IMU_NOT_SUPPORTED`.

Other, more advanced features may be available depending on the sensor.  See the documentation for the particular sensor for information on advanced feature support.

Using as a Template
---

* Create your repo
* pull [/src/SparkFunIMU.h](https://github.com/sparkfun/SparkFun_LSM303C_6_DOF_IMU_Breakout_Arduino_Library/blob/master/src/SparkFunIMU.h) into it

License Information
-------------------

This product is _**open source**_!

Please review the LICENSE.md file for license information.

If you have any questions or concerns on licensing, please contact techsupport@sparkfun.com.

Distributed as-is; no warranty is given.

- Your friends at SparkFun.


text:
class CrcInterface
{
  public:
    virtual ~CrcInterface() = default;

    virtual std::uint16_t
        generateCrc(const std::vector<std::uint8_t>& data) const = 0;
};

class CrcMock : public CrcInterface
{
  public:
    virtual ~CrcMock() = default;
    MOCK_METHOD(std::uint16_t, generateCrc, (const std::vector<std::uint8_t>&),
                (const, override));
};


text:
#ifndef FIREBASE_FIRESTORE_SRC_JNI_ARRAY_H_
#define FIREBASE_FIRESTORE_SRC_JNI_ARRAY_H_

#include "firestore/src/jni/env.h"
#include "firestore/src/jni/jni_fwd.h"
#include "firestore/src/jni/object.h"
#include "firestore/src/jni/traits.h"

namespace firebase {
namespace firestore {
namespace jni {

template <typename T>
class Array : public Object {
 public:
  using jni_type = JniType<Array<T>>;

  Array() = default;
  explicit Array(jni_type array) : Object(array) {}

  jni_type get() const override { return static_cast<jni_type>(Object::get()); }

  size_t Size(Env& env) const { return env.GetArrayLength(*this); }

  Local<T> Get(Env& env, size_t i) const {
    return env.GetArrayElement<T>(*this, i);
  }

  void Set(Env& env, size_t i, const T& value) {
    env.SetArrayElement<T>(*this, i, value);
  }
};

}  // namespace jni
}  // namespace firestore
}  // namespace firebase

#endif  // FIREBASE_FIRESTORE_SRC_JNI_ARRAY_H_


text:
using System;
using VCSJones.FiddlerCertGen.Interop;

namespace VCSJones.FiddlerCertGen
{
    internal class CngKeyProvider : KeyProviderBase
    {
        internal static CngKeyProvider Instance { get; } = new CngKeyProvider();
        private static readonly NCryptStorageProvider _storageProvider = NCryptStorageProvider.MicrosoftSoftwareKeyStorageProvider;
        public override string Name { get; } = "CNG";

        internal override NCryptKeyOrCryptProviderSafeHandle CreateKey(string keyName, int keySize, Algorithm algorithm, bool overwrite, KeyUsage keyUsage, out KeySpec keySpec)
        {
            NCryptKeyOrCryptProviderSafeHandle keyHandle;
            var flags = overwrite ? NCryptCreatePersistedKeyFlags.NCRYPT_OVERWRITE_KEY_FLAG : NCryptCreatePersistedKeyFlags.NONE;
            var result = NCrypt.NCryptCreatePersistedKey(_storageProvider.Handle, out keyHandle, algorithm.Name, keyName, KeySpec.NONE, flags);
            if (result != SECURITY_STATUS.ERROR_SUCCESS)
            {
                throw new InvalidOperationException("Failed to generate a key.");
            }
            if (algorithm == Algorithm.RSA)
            {
                NCryptPropertyWriter.WriteUInt32(keyHandle, CngProperties.NCRYPT_LENGTH_PROPERTY, (uint) keySize);
            }
            NCryptPropertyWriter.WriteEnum(keyHandle, CngProperties.NCRYPT_EXPORT_POLICY_PROPERTY, CngExportPolicy.NCRYPT_ALLOW_EXPORT_FLAG);
            var finalizeResult = NCrypt.NCryptFinalizeKey(keyHandle, 0u);
            if (finalizeResult != SECURITY_STATUS.ERROR_SUCCESS)
            {
                throw new InvalidOperationException("Failed to finalize key.");
            }
            keySpec = KeySpec.NONE;
            return keyHandle;
        }

        internal override string GetProviderName()
        {
            return _storageProvider.Name;
        }

        internal override string GetName(NCryptKeyOrCryptProviderSafeHandle handle)
        {
            return NCryptPropertyReader.ReadStringUni(handle, CngProperties.NCRYPT_NAME_PROPERTY);
        }

        internal override string GetAlgorithmGroup(NCryptKeyOrCryptProviderSafeHandle handle)
        {
            return NCryptPropertyReader.ReadStringUni(handle, CngProperties.NCRYPT_ALGORITHM_GROUP_PROPERTY);
        }

        internal override NCryptKeyOrCryptProviderSafeHandle OpenExisting(string keyName, out KeySpec keySpec)
        {
            keySpec = KeySpec.NONE;
            NCryptKeyOrCryptProviderSafeHandle keyHandle;
            var result = NCrypt.NCryptOpenKey(_storageProvider.Handle, out keyHandle, keyName, KeySpec.NONE, 0u);
            if (result == SECURITY_STATUS.ERROR_SUCCESS)
            {
                return keyHandle;
            }
            if (result == SECURITY_STATUS.NTE_BAD_KEYSET)
            {
                return null;
            }
            throw new InvalidOperationException("Failed to open key.");
        }
    }
}


text:
package ai.bot.botkit.slackbot.core.models;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

/**
 * Created by ramswaroop on 14/06/2016.
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class Profile {
    private String firstName;
    private String lastName;
    private String realName;
    private String email;
    private String skype;
    private String phone;
    private String image24;
    private String image32;
    private String image48;
    private String image72;
    private String image192;
    private String image512;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getRealName() {
        return realName;
    }

    public void setRealName(String realName) {
        this.realName = realName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getSkype() {
        return skype;
    }

    public void setSkype(String skype) {
        this.skype = skype;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getImage24() {
        return image24;
    }

    public void setImage24(String image24) {
        this.image24 = image24;
    }

    public String getImage32() {
        return image32;
    }

    public void setImage32(String image32) {
        this.image32 = image32;
    }

    public String getImage48() {
        return image48;
    }

    public void setImage48(String image48) {
        this.image48 = image48;
    }

    public String getImage72() {
        return image72;
    }

    public void setImage72(String image72) {
        this.image72 = image72;
    }

    public String getImage192() {
        return image192;
    }

    public void setImage192(String image192) {
        this.image192 = image192;
    }

    public String getImage512() {
        return image512;
    }

    public void setImage512(String image512) {
        this.image512 = image512;
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Algorithm Tutorials</title>

<link type="image/x-icon" rel="shortcut icon" href="http://community.topcoder.com/i/favicon.ico">

<link type="text/css" rel="stylesheet" href="./complexity1_files/style.css">
<link type="text/css" rel="stylesheet" href="./complexity1_files/coders.css">
<link type="text/css" rel="stylesheet" href="./complexity1_files/tcStyles20080219.css">
<link type="text/css" rel="stylesheet" href="./complexity1_files/jobsRemix.css">

Member Count: 316,431 -

October 24, 2011

 [Get Time]

                Login

Competitions

Overview

Reliability

Ratings

How to Get Paid

Administrative Overview

Copilot Opportunities

Overview

Track Information

How to Compete

Documentation

Tutorial

Active Contests

Past Contests

Copilot Pool

Design

Studio

Conceptualization

Overview

Track Information

How to Compete

Documentation

Tutorial

Active Contests

Contest Status

Past Contests

Review Opportunities

Meet the Review Board

Specification

Overview

Track Information

How to Compete

Active Contests

Contest Status

Past Contests

Review Opportunities

Meet the Review Board

Architecture

Overview

Track Information

How to Compete

Active Contests

Contest Status

Past Contests

Review Opportunities

Meet the Review Board

Component Design

Overview

Track Information

How to Compete

Documentation

Recent Color Changes

Data Feeds

Active Contests

Contest Status

Past Contests

Review Opportunities

Meet the Review Board

Development

Component Development

Overview

Track Information

How to Compete

Documentation

Recent Color Changes

Data Feeds

Active Contests

Contest Status

Past Contests

Review Opportunities

Meet the Review Board

Assembly

Overview

Track Information

How to Compete

Tutorial

Documentation

Active Contests

Contest Status

Past Contests

Review Opportunities

Meet the Review Board

Test Suites

Overview

Track Information

How to Compete

Tutorial

Documentation

Active Contests

Contest Status

Past Contests

Review Opportunities

Meet the Review Board

UI Development

UI Prototype

Overview

Track Information

How to Compete

Active Contests

Contest Status

Past Contests

Review Opportunities

Meet the Review Board

RIA Build

Overview

Track Information

How to Compete

Active Contests

Contest Status

Past Contests

Review Opportunities

Meet the Review Board

Content Creation

Overview

Track Information

How to Compete

Active Contests

Contest Status

Past Contests

Review Opportunities

Meet the Review Board

QA and Maintenance

Test Scenarios

Overview

Track Information

How to Compete

Tutorial

Documentation

Active Contests

Contest Status

Past Contests

Review Opportunities

Meet the Review Board

Bug Race

Overview

Track Information

How to Compete

Active Contests

Review Opportunities

Algorithm

Single Round Matches (SRM)

Overview

Track Information

How to Compete

FAQs

Rating System

Write Problems

Statistics

Match Archive

Match Overviews

Match Winners

Match Results

Match Editorials

Problem Archive

Recent Color Changes

Data Feeds

Launch Arena

Marathon Match

Overview

Track Information

How to Compete

Rating System

Statistics

Match Archive

Match Overview

Match Winners

Match Editorials

Data Feeds

Active Contests

Practice

Queue Status

High School

Overview

Statistics

Match Overview

Match Results (Team)

Match Results (Indiv.)

Match Editorials

Recent Color Changes

Data Feeds

Spotlight Sessions

Launch Arena

The Digital Run

Submit & Review

TopCoder Networks

Alcatel Lucent

AMD OpenCL

DARPA CS-STEM

NASA Tournament Lab

PayPalX

Events

Event Calendar

Tournaments

TopCoder

Powered by TopCoder

Charity

Statistics

The Tops

Top Ranked

Algorithm

High School

Marathon Match

Conceptualization

Specification

Architecture

Design

Development

Assembly

Test Suites

Record Book

Algorithm

Component

Marathon Match

Coder of the Month

Algorithm

Design

Development

Tutorials

Overview

Algorithm Tutorials

Component Tutorials

Marathon Tutorials

Wiki

Forums

Surveys

My TopCoder

Help Center

About TopCoder

Overview

Why Join TopCoder?

Working at TopCoder

Leadership

Press Room

Member Search:
<form action="http://www.topcoder.com/tc" method="get" name="simpleSearchForm" class="noSpace" id="simpleSearchForm">
   <input class="noSpace" type="hidden" name="module" value="SimpleSearch">
   <input class="noSpace" type="text" name="ha" value="Handle:" size="12" maxlength="15" onfocus="javascript: if (document.simpleSearchForm.ha.value=='Handle:') document.simpleSearchForm.ha.value = '';" onblur="javascript:if (document.simpleSearchForm.ha.value == '')document.simpleSearchForm.ha.value = 'Handle:';">
   Go

   Advanced Search
</form>

                Archive

                Printable view

                Normal view

                Discuss this article

                Write for TopCoder

Computational Complexity: Section 1

By misof

TopCoder Member

In this article I'll try to introduce you to the area of computation
complexity. The article will be a bit long before we get to the actual
formal definitions because I feel that the rationale behind these
definitions needs to be explained as well - and that understanding the
rationale is even more important than the definitions alone.

Why is it important?

Example 1. Suppose you were assigned to write a program to process some records
your company receives from time to time. You implemented two different algorithms
and tested them on several sets of test data. The processing times you obtained
are in Table 1.

# of records
10
20
50
100
1000
5000

algorithm 1
0.00s
0.01s
0.05s
0.47s
23.92s
47min

algorithm 2
0.05s
0.05s
0.06s
0.11s
0.78s
14.22s

Table 1. Runtimes of two fictional algorithms.

In praxis, we probably could tell which of the two implementations
is better for us (as we usually can estimate the amount of data we
will have to process). For the company this solution may be fine. But from the
programmer's point of view, it would be much better if he could estimate
the values in Table 1 before writing the actual code - then he
could only implement the better algorithm.

The same situation occurs during programming contests: The size of
the input data is given in the problem statement. Suppose I found an
algorithm. Questions I have to answer before I start to type should be:
Is my algorithm worth implementing? Will it solve the largest test
cases in time? If I know more algorithms solving the problem,
which of them shall I implement?

This leads us to the question: How to compare algorithms?
Before we answer this question in general, let's return to our simple
example. If we extrapolate the data in Table 1, we may assume that
if the number of processed records is larger than 1000, algorithm
2 will be substantially faster. In other words, if we consider all
possible inputs, algorithm 2 will be better for almost all of them.

It turns out that this is almost always the case - given two algorithms,
either one of them is almost always better, or they are approximately
the same. Thus, this will be our definition of a better algorithm.
Later, as we define everything formally, this will be the
general idea behind the definitions.

A neat trick

If you thing about Example 1 for a while, it shouldn't be
too difficult to see that there is an algorithm with runtimes similar
to those in Table 2:

# of records
10
20
50
100
1000
5000

algorithm 3
0.00s
0.01s
0.05s
0.11s
0.78s
14.22s

Table 2. Runtimes of a new fictional algorithm.

The idea behind this algorithm: Check the number of records. If it is small
enough, run algorithm 1, otherwise run algorithm 2.

Similar ideas are often used in praxis. As an example consider most of
the sort() functions provided by various libraries. Often this function
is an implementation of QuickSort with various improvements, such as:

if the number of elements is too small, run InsertSort instead
  (as InsertSort is faster for small inputs)

if the pivot choices lead to poor results, fall back to MergeSort

What is efficiency?

Example 2. Suppose you have a concrete implementation of some algorithm.
(The example code presented below is actually an implementation of
MinSort - a slow but simple sorting algorithm.)

for (int i=0; i<N; i++)
  for (int j=i+1; j<N; j++)
    if (A[i] > A[j])
      swap( A[i], A[j] );

If we are given an input to this algorithm (in our case, the array A
and its size N), we can exactly compute the number of steps our
algorithm does on this input. We could even count the processor
instructions if we wanted to. However, there are too many possible
inputs for this approach to be practical.

And we still need to answer one important question: What is it exactly
we are interested in? Most usually it is the behavior of our program
in the worst possible case - we need to look at the input
data and to determine an upper bound on how long will it take
if we run the program.

But then, what is the worst possible case? Surely we can always make the program
run longer simply by giving it a larger input. Some of the more important
questions are: What is the worst input with 700 elements?
How fast does the maximum runtime grow when we increase the input
size?

Formal notes on the input size

What exactly is this "input size" we started to talk about?
In the formal definitions this is the size of the input written in some
fixed finite alphabet (with at least 2 "letters"). For our needs, we may consider
this alphabet to be
the numbers 0..255. Then the "input size" turns out to be exactly
the size of the input file in bytes.

Usually a part of the input is a number (or several numbers) such that
the size of the input is proportional to the number.

E.g. in Example 2 we are given an int N and an array containing N ints.
The size of the input file will be roughly 5N (depending on the OS and
architecture, but always linear in N).

In such cases, we may choose that this number will represent the size of
the input. Thus when talking about problems on arrays/strings, the input size
is the length of the array/string, when talking about graph problems, the
input size depends both on the number of vertices (N) and the number of
edges (M), etc.

We will adopt this approach and use N as the input size in the following
parts of the article.

There is one tricky special case you sometimes need to be aware of. To write
a (possibly large) number we need only logarithmic space. (E.g. to write
123456, we need only roughly
log10(123456) digits.)
This is why the naive primality test does not run in polynomial time -
its runtime is polynomial in the size of the number, but not
in its number of digits!
If you didn't understand the part about polynomial time, don't worry,
we'll get there later.

How to measure efficiency?

We already mentioned that given an input we are able to count the
number of steps an algorithm makes simply by simulating it.
Suppose we do this for all inputs of size at most N and
find the worst of these inputs (i.e. the one that causes
the algorithm to do the most steps). Let f (N) be this number
of steps.
We will call this function the time complexity, or shortly the runtime
of our algorithm.

In other words, if we have any input of size N, solving it will
require at most f (N) steps.

Let's return to the algorithm from Example 2. What is the worst
case of size N? In other words, what array with N elements
will cause the algorithm to make the most steps? If we take a
look at the algorithm, we can easily see that:

the first step is executed exactly N times

the second and third step are executed exactly N(N - 1)/2 times

the fourth step is executed at most N(N - 1)/2 times

Clearly, if the elements in A are in descending order at the beginning, the fourth
step will always be executed. Thus in this case the algorithm
makes
3N(N - 1)/2 + N = 1.5N2 - 0.5N steps.
Therefore our algorithm has
f (N) = 1.5N2 - 0.5N.

As you can see, determining the exact function f for more complicated
programs is painful. Moreover, it isn't even necessary. In our case, clearly
the -0.5N term can be neglected. It will usually be much smaller than
the 1.5N2 term and it won't affect the runtime significantly.
The result "f (N) is roughly equal to 1.5N2" gives
us all the information we need. As we will show now, if we want
to compare this algorithm with some other algorithm solving the
same problem, even the constant 1.5 is not that important.

Consider two algorithms, one with the runtime N2, the other with the
runtime 0.001N3. One can easily see that for N greater than 1 000 the first
algorithm is faster - and soon this difference becomes apparent. While
the first algorithm is able to solve inputs with N = 20 000 in a matter
of seconds, the second one will already need several minutes on current
machines.

Clearly this will occur always when one of the runtime functions grows
asymptotically faster than the other (i.e. when N grows beyond
all bounds the limit of their quotient is zero or infinity).
Regardless of the constant factors, an algorithm
with runtime proportional to N2 will always be better than an algorithm
with runtime proportional to N3 on almost all inputs.
And this observation is exactly what we base our
formal definition on.

Finally, formal definitions

Let f, g be positive non-decreasing functions defined on positive integers.
(Note that all runtime functions satisfy these conditions.)
We say that f (N) is O(g(N)) (read: f is big-oh of g)
if for some c and N0 the following condition holds:

N > N0; f (N) < c.g(N)

In human words, f (N) is O(g(N)), if for some c almost the entire graph
of the function f is below the graph of the function c.g.
Note that this means that f grows at most as fast as c.g does.

Instead of "f (N) is O(g(N))" we usually write
f (N) = O(g(N)).
Note that this "equation" is not symmetric -
the notion "
O(g(N)) = f (N)" has no sense and
"
g(N) = O(f (N))" doesn't have to be true (as we will see later).
(If you are not comfortable with this notation, imagine O(g(N))
to be a set of functions and imagine that there is a  instead
of =.)

What we defined above is known as the big-oh notation and is conveniently
used to specify upper bounds on function growth.

E.g. consider the function
f (N) = 3N(N - 1)/2 + N = 1.5N2 - 0.5N from
Example 2. We may say that
f (N) = O(N2) (one possibility for the constants
is c = 2 and N0 = 0). This means that f doesn't grow (asymptotically)
faster than N2.

Note that even the exact runtime function f doesn't give an exact
answer to the question "How long will the program run on my machine?"
But the important observation in the example case is that the runtime function is
quadratic. If we double the input size, the runtime will increase
approximately to four times the current runtime, no matter how fast our
computer is.

The
f (N) = O(N2) upper bound gives us almost the same - it guarantees that
the growth of the runtime function is at most quadratic.

Thus, we will use the O-notation to describe the time (and sometimes also
memory) complexity of algorithms. For the algorithm from Example 2 we would say
"The time complexity of this algorithm is O(N2)"
or shortly
"This algorithm is O(N2)".

In a similar way we defined O we may define  and .

We say that f (N) is
(g(N)) if
g(N) = O(f (N)), in other words if f grows at least as fast as g.

We say that
f (N) = (g(N)) if
f (N) = O(g(N)) and
g(N) = O(f (N)),
in other words if both functions have approximately the same rate of growth.

As it should be obvious,  is used to specify lower bounds and
 is used to give a tight asymptotic bound on a function.
There are other similar bounds, but these are the ones you'll encounter
most of the time.

Some examples of using the notation

1.5N2 -0.5N = O(N2).

47N log N = O(N2).

N log N + 1 000 047N = (N log N).

All polynomials of order k are O(Nk).

The time complexity of the algorithm in Example 2 is
(N2).

If an algorithm is O(N2), it is also O(N5).

Each comparision-based sorting algorithm is
(N log N).

MergeSort run on an array with N elements does roughly N log N comparisions.
Thus the time complexity of MergeSort is
(N log N).
If we trust the previous statement, this means that MergeSort is an
asymptotically optimal general sorting algorithm.

The algorithm in Example 2 uses (N) bytes of memory.

The function giving my number of teeth in time is O(1).

A naive backtracking algorithm trying to solve chess is O(1) as the tre
of positions it will examine is finite. (But of course in this case the constant hidden behind
the O(1) is unbelievably large.)

The statement "Time complexity of this algorithm is at least O(N2)" is meaningless.
(It says: "Time complexity of this algorithm is at least at most roughly quadratic."
The speaker probably wanted to say: "Time complexity of this algorithm is
(N2).")

When speaking about the time/memory complexity of an algorithm, instead of using the
formal
(f (n))-notation we may simply state the class of functions f belongs to.
E.g. if
f (N) = (N), we call the algorithm linear. More examples:

f (N) = (log N): logarithmic

f (N) = (N2): quadratic

f (N) = (N3): cubic

f (N) = O(Nk) for some k: polynomial

f (N) = (2N): exponential

For graph problems, the complexity
(N + M) is known as "linear in the graph size".

Determining execution time from an asymptotic bound

For most algorithms you may encounter in praxis, the constant hidden behind the O
(or ) is usually relatively small. If an algorithm is
(N2), you
may expect that the exact time complexity is something like 10N2, not 107N2.

The same observation in other words: if the constant is large, it is usually somehow related to some
constant in the problem statement. In this case it is good practice to give this constant
a name and to include it in the asymptotic notation.

An example: The problem is to count occurences of each letter in a string of N letters. A naive algorithm
passes through the whole string once for each possible letter. The size of alphabet is fixed (e.g.
at most 255 in C), thus the algorithm is linear in N. Still, it is better to write that its
time complexity is
(| S|.N), where S is the alphabet used.
(Note that there is a better algorithm solving this problem in
(| S| + N).)

In a TopCoder contest, an algorithm doing
1 000 000 000 multiplications runs barely in time.
This fact together with the above observation and some experience with TopCoder problems
can help us fill the following table:

complexity
maximum N

(N)

100 000 000

(N log N)

40 000 000

(N2)
10 000

(N3)
500

(N4)
90

(2N)
20

(N!)
11

Table 3. Approximate maximum problem size solvable in 8 seconds.

A note on algorithm analysis

Usually if we present an algorithm, the best way to present its time complexity
is to give a -bound. However, it is common practice to only give an O-bound
- the other bound is usually trivial, O is much easier to type and better known.
Still, don't forget that O represents only an upper bound. Usually we try to find
an O-bound that's as good as possible.

Example 3.
Given is a sorted
array A. Determine whether it contains two elements with the difference D.
Consider the following code solving this problem:

int j=0;
for (int i=0; i<N; i++) {
  while ( (j<N-1) && (A[i]-A[j] > D) )
    j++;
  if (A[i]-A[j] == D) return 1;
}

It is easy to give an O(N2) bound for the time complexity of this algorithm - the
inner while-cycle is called N times, each time we increase j at most N times.
But a more careful analysis shows that in fact we can give an O(N) bound on the
time complexity of this algorithm - it is sufficient to realize that during the
whole execution of the algorithm the command "<tt>j++;</tt>" is executed no more than N times.

If we said "this algorithm is O(N2)", we would have been right.
But by saying "this algorithm is O(N)" we give more information
about the algorithm.

Conclusion

We have shown how to write bounds on the time complexity of algorithms.
We have also demonstrated why this way of characterizing algorithms is natural
and (usually more-or-less) sufficient.

The next logical step is to show how to estimate the time complexity of a given
algorithm. As we have already seen in Example 3, sometimes this can be messy.
It gets really messy when recursion is involved.
We will address these issues in the second part of this article.

...continue to Section 2

            Home  |
            About TopCoder  |
            Press Room  |
            Contact Us  |
            Careers  |
            Privacy  |
            Terms

            Competitions  |
            Cockpit

      Copyright TopCoder, Inc. 2001-2011


text:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-manage',
  templateUrl: './manage.component.html',
  styleUrls: ['./manage.component.scss']
})
export class ManageComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}


text:
def stub_users_expired_token(options = {})
  stub_request(:get, "https://apps-apis.google.com/a/feeds/cnm.edu/user/2.0?startUsername=znelson1").
      with(:headers => {'Authorization' => "OAuth #{options[:token]}", 'Content-Type' => 'application/atom+xml'}).
      to_return(:status => 401, :body => File.read('spec/fixtures/invalid_token.html'))
end

def stub_refresh_token
  stub_request(:post, "https://accounts.google.com/o/oauth2/token").
      to_return(:status => 200, :body => File.read('spec/fixtures/refreshed_token_response.json'))
end

def stub_users_ok(options = {})
  stub_request(:get, "https://apps-apis.google.com/a/feeds/cnm.edu/user/2.0?startUsername=znelson1").
      with(:headers => {'Authorization' => "OAuth #{options[:token]}", 'Content-Type' => 'application/atom+xml'}).
      to_return(:status => 200, :body => File.read('spec/fixtures/users_feed.xml'))
end


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE bindings SYSTEM "chrome://hatenabookmark/locale/sidebar.dtd">
<bindings xmlns="http://www.mozilla.org/xbl"
          xmlns:xbl="http://www.mozilla.org/xbl"
          xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">

    <binding id="searchbar">
        <resources>


text:
package org.kuali.kfs.module.bc.document.validation.event;

import org.kuali.kfs.module.bc.document.BudgetConstructionDocument;
import org.kuali.kfs.module.bc.document.validation.BudgetExpansionRule;
import org.kuali.rice.krad.document.Document;
import org.kuali.rice.krad.rules.rule.BusinessRule;
import org.kuali.rice.krad.rules.rule.event.KualiDocumentEventBase;

/**
 * Base class for expansion rule events.
 */
public abstract class BudgetExpansionEvent extends KualiDocumentEventBase {
    private BudgetConstructionDocument budgetConstructionDocument;

    /**
     * Constructs a BudgetExpansionEvent.java.
     */
    public BudgetExpansionEvent(String description, String errorPathPrefix, Document document) {
        super(description, errorPathPrefix, document);
        this.budgetConstructionDocument = (BudgetConstructionDocument) document;
    }

    /**
     * @see org.kuali.rice.krad.rule.event.KualiDocumentEvent#getRuleInterfaceClass()
     */
    public Class getRuleInterfaceClass() {
        return BudgetExpansionRule.class;
    }

    /**
     * @see org.kuali.rice.krad.rule.event.KualiDocumentEvent#invokeRuleMethod(org.kuali.rice.krad.rule.BusinessRule)
     */
    public boolean invokeRuleMethod(BusinessRule rule) {
        return ((BudgetExpansionRule) rule).processExpansionRule(this);
    }

    public abstract Class getExpansionRuleInterfaceClass();

    public abstract boolean invokeExpansionRuleMethod(BusinessRule rule);

    /**
     * Gets the budgetConstructionDocument attribute.
     *
     * @return Returns the budgetConstructionDocument.
     */
    public BudgetConstructionDocument getBudgetConstructionDocument() {
        return budgetConstructionDocument;
    }

    /**
     * Sets the budgetConstructionDocument attribute value.
     *
     * @param budgetConstructionDocument The budgetConstructionDocument to set.
     */
    public void setBudgetConstructionDocument(BudgetConstructionDocument budgetConstructionDocument) {
        this.budgetConstructionDocument = budgetConstructionDocument;
    }

}


text:
var User = require('../proxy/user');
var Message = require('../proxy/message');
var JPush = require("jpush-sdk");
var eventproxy = require('eventproxy');
var config = require('../config');
var client = null;
if (config.jpush && config.jpush.secretKey !== 'your secret key') {
  client = JPush.buildClient(config.jpush.appKey, config.jpush.secretKey);
}

/**
 * 通过极光推送发生消息通知
 * @param {String} type 消息类型
 * @param {String} author_id 消息作者ID
 * @param {String} master_id 被通知者ID
 * @param {String} topic_id 相关主题ID
 */
exports.send = function (type, author_id, master_id, topic_id) {
  if (client !== null) {
    var ep = new eventproxy();
    User.getUserById(author_id, ep.done('author'));
    Message.getMessagesCount(master_id, ep.done('count'));
    ep.all('author', 'count', function (author, count) {
      var msg = author.loginname + ' ';
      var extras = {
        topicId: topic_id
      };
      switch (type) {
      case 'at':
        msg += '@了你';
        break;
      case 'reply':
        msg += '回复了你的主题';
        break;
      default:
        break;
      }
      client.push()
        .setPlatform(JPush.ALL)
        .setAudience(JPush.alias(master_id.toString()))
        .setNotification(msg,
          JPush.ios(msg, null, count, null, extras),
          JPush.android(msg, null, null, extras)
        )
        .setOptions(null, null, null, !config.debug)
        .send(function (err, res) {
          if (config.debug) {
            if (err) {
              console.log(err.message);
            } else {
              console.log('Sendno: ' + res.sendno);
              console.log('Msg_id: ' + res.msg_id);
            }
          }
        });
    })
  }
};


text:
title: Overview
weight: 1
type: docs
bookToc: false
aliases:
  - /dev/table/streaming/
---
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you 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.
-->

# Streaming Concepts

Flink's [Table API]({{< ref "docs/dev/table/tableApi" >}}) and [SQL support]({{< ref "docs/dev/table/sql/overview" >}}) are unified APIs for batch and stream processing.
This means that Table API and SQL queries have the same semantics regardless whether their input is bounded batch input or unbounded stream input.

The following pages explain concepts, practical limitations, and stream-specific configuration parameters of Flink's relational APIs on streaming data.

State Management
----------------

Table programs that run in streaming mode leverage all capabilities of Flink as a stateful stream
processor.

In particular, a table program can be configured with a [state backend]({{< ref "docs/ops/state/state_backends" >}})
and various [checkpointing options]({{< ref "docs/dev/datastream/fault-tolerance/checkpointing" >}})
for handling different requirements regarding state size and fault tolerance. It is possible to take
a savepoint of a running Table API & SQL pipeline and to restore the application's state at a later
point in time.

### State Usage

Due to the declarative nature of Table API & SQL programs, it is not always obvious where and how much
state is used within a pipeline. The planner decides whether state is necessary to compute a correct
result. A pipeline is optimized to claim as little state as possible given the current set of optimizer
rules.

{{< hint info >}}
Conceptually, source tables are never kept entirely in state. An implementer deals with logical tables
(i.e. [dynamic tables]({{< ref "docs/dev/table/concepts/dynamic_tables" >}})). Their state requirements
depend on the used operations.
{{< /hint >}}

Queries such as `SELECT ... FROM ... WHERE` which only consist of field projections or filters are usually
stateless pipelines. However, operations such as joins, aggregations, or deduplications require keeping
intermediate results in a fault-tolerant storage for which Flink's state abstractions are used.

{{< hint info >}}
Please refer to the individual operator documentation for more details about how much state is required
and how to limit a potentially ever-growing state size.
{{< /hint >}}

For example, a regular SQL join of two tables requires the operator to keep both input tables in state
entirely. For correct SQL semantics, the runtime needs to assume that a matching could occur at any
point in time from both sides. Flink provides [optimized window and interval joins]({{< ref "docs/dev/table/sql/queries/joins" >}})
that aim to keep the state size small by exploiting the concept of [watermarks]({{< ref "docs/dev/table/concepts/time_attributes" >}}).

Another example is the following query that computes the number of clicks per session.

```sql
SELECT sessionId, COUNT(*) FROM clicks GROUP BY sessionId;
```

The `sessionId` attribute is used as a grouping key and the continuous query maintains a count
for each `sessionId` it observes. The `sessionId` attribute is evolving over time and `sessionId`
values are only active until the session ends, i.e., for a limited period of time. However, the
continuous query cannot know about this property of `sessionId` and expects that every `sessionId`
value can occur at any point of time. It maintains a count for each observed `sessionId` value.
Consequently, the total state size of the query is continuously growing as more and more `sessionId`
values are observed.

#### Idle State Retention Time

The *Idle State Retention Time* parameter [`table.exec.state.ttl`]({{< ref "docs/dev/table/config" >}}#table-exec-state-ttl)
defines for how long the state of a key is retained without being updated before it is removed.
For the previous example query, the count of a`sessionId` would be removed as soon as it has not
been updated for the configured period of time.

By removing the state of a key, the continuous query completely forgets that it has seen this key
before. If a record with a key, whose state has been removed before, is processed, the record will
be treated as if it was the first record with the respective key. For the example above this means
that the count of a `sessionId` would start again at `0`.

### Stateful Upgrades and Evolution

Table programs that are executed in streaming mode are intended as *standing queries* which means they
are defined once and are continuously evaluated as static end-to-end pipelines.

In case of stateful pipelines, any change to both the query or Flink's planner might lead to a completely
different execution plan. This makes stateful upgrades and the evolution of table programs challenging
at the moment. The community is working on improving those shortcomings.

For example, by adding a filter predicate, the optimizer might decide to reorder joins or change the
schema of an intermediate operator. This prevents restoring from a savepoint due to either changed
topology or different column layout within the state of an operator.

The query implementer must ensure that the optimized plans before and after the change are compatible.
Use the `EXPLAIN` command in SQL or `table.explain()` in Table API to [get insights]({{< ref "docs/dev/table/common" >}}#explaining-a-table).

Since new optimizer rules are continuously added, and operators become more efficient and specialized,
also the upgrade to a newer Flink version could lead to incompatible plans.

{{< hint warning >}}
Currently, the framework cannot guarantee that state can be mapped from a savepoint to a new table
operator topology.

In other words: Savepoints are only supported if both the query and the Flink version remain constant.
{{< /hint >}}

Since the community rejects contributions that modify the optimized plan and the operator topology
in a patch version (e.g. from `1.13.1` to `1.13.2`), it should be safe to upgrade a Table API & SQL
pipeline to a newer bug fix release. However, major-minor upgrades from (e.g. from `1.12` to `1.13`)
are not supported.

For both shortcomings (i.e. modified query and modified Flink version), we recommend to investigate
whether the state of an updated table program can be "warmed up" (i.e. initialized) with historical
data again before switching to real-time data. The Flink community is working on a [hybrid source]({{< ref "docs/connectors/datastream/hybridsource" >}})
to make this switching as convenient as possible.

Where to go next?
-----------------

* [Dynamic Tables]({{< ref "docs/dev/table/concepts/dynamic_tables" >}}): Describes the concept of dynamic tables.
* [Time attributes]({{< ref "docs/dev/table/concepts/time_attributes" >}}): Explains time attributes and how time attributes are handled in Table API & SQL.
* [Versioned Tables]({{< ref "docs/dev/table/concepts/versioned_tables" >}}): Describes the Temporal Table concept.
* [Joins in Continuous Queries]({{< ref "docs/dev/table/sql/queries/joins" >}}): Different supported types of Joins in Continuous Queries.
* [Determinism in Continuous Queries]({{< ref "docs/dev/table/concepts/determinism" >}}): Determinism in Continuous Queries.
* [Query configuration]({{< ref "docs/dev/table/config" >}}): Lists Table API & SQL specific configuration options.

{{< top >}}


text:
require "rails_helper"

RSpec.describe "Edit shipping details" do
  let(:order) { FactoryBot.create(:order) }

  before do
    FactoryBot.create(:website)
    sign_in_as_admin
  end

  scenario "Edit shipping method and amount" do
    visit edit_admin_order_path(order)
    fill_in "Shipping method", with: "Long distance courier"
    fill_in "Shipping amount", with: "8"
    fill_in "Shipping VAT amount", with: "1.6"
    click_save
    order.reload
    expect(order.shipping_method).to eq "Long distance courier"
    expect(order.shipping_amount).to eq 8
    expect(order.shipping_vat_amount).to eq BigDecimal("1.6")
    expect(order.total).to eq BigDecimal("9.6")
  end

  scenario "Edit delivery instructions" do
    visit edit_admin_order_path(order)
    fill_in "Delivery instructions", with: "Leave in shed"
    click_save
    order.reload
    expect(order.delivery_instructions).to eq "Leave in shed"
  end

  def click_save
    find(".cancel-save").click_button "Save"
  end
end


text:
namespace mojo {
namespace view_manager {

class View;

// A ViewEventDispatcher is provided by the application rendering at the root
// of a Node hierarchy. It is responsible for targeting input events to the
// relevant Views. This allows window manager features like focus, activation,
// modality, etc. to be implemented.
class ViewEventDispatcher {
 public:
  virtual void DispatchEvent(View* target, EventPtr event) = 0;

 protected:
  virtual ~ViewEventDispatcher() {}
};

}  // namespace view_manager
}  // namespace mojo

#endif  // MOJO_SERVICES_PUBLIC_CPP_VIEW_MANAGER_VIEW_EVENT_DISPATCHER_H_


text:
#pragma once
#include <aws/s3outposts/S3Outposts_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace S3Outposts
{
namespace Model
{
  enum class EndpointStatus
  {
    NOT_SET,
    Pending,
    Available,
    Deleting
  };

namespace EndpointStatusMapper
{
AWS_S3OUTPOSTS_API EndpointStatus GetEndpointStatusForName(const Aws::String& name);

AWS_S3OUTPOSTS_API Aws::String GetNameForEndpointStatus(EndpointStatus value);
} // namespace EndpointStatusMapper
} // namespace Model
} // namespace S3Outposts
} // namespace Aws


text:
var args = arguments[0] || {};

function goHomeSet()
{
	$.settingsWindow.close();
}


text:
/* global atom */
'use strict';

var BeautifyCommand = require('./commands/beautify');
var ConvertCommand = require('./commands/convert');

var plugin = module.exports;

/**
 * Default package options.
 * @type {Object}
 */
plugin.configDefaults = {
  indent: 4,
  dasherize: false,
  old: false,
  path: ''
};

/**
 * Set the commands.
 */
plugin.activate = function() {

  var beautifyCommand = new BeautifyCommand(this);
  var convertCommand = new ConvertCommand(this);

  atom.workspaceView.command('SassBeautify',
    beautifyCommand.init.bind(beautifyCommand));

  atom.workspaceView.command('SassBeautify:Convert-from-SASS',
    convertCommand.init.bind(convertCommand, {
      from: 'sass'
    }));

  atom.workspaceView.command('SassBeautify:Convert-from-SCSS',
    convertCommand.init.bind(convertCommand, {
      from: 'scss'
    }));

  atom.workspaceView.command('SassBeautify:Convert-from-CSS',
    convertCommand.init.bind(convertCommand, {
      from: 'css'
    }));
};


text:
Tamaño máximo de un mensaje

<tt>message_size_limit</tt>

Este parámetro limita el tamaño total en octetos de un mensaje, incluyendo
al información del sobre.


text:
module Softlayer
  class Network
    class Subnet
      class Registration
        class Arin < Softlayer::Network::Subnet::Registration

          class Representer < Softlayer::Network::Subnet::Registration::Representer
            include Representable::Hash
            include Representable::Coercion
          end
        end
      end
    end
  end
end


text:
<md-content layout-fill >

Login

        <form name="loginForm" novalidate="" ng-submit="vm.doLogin()">
          <md-input-container class="md-has-icon md-block">

            <ng-md-icon icon="person" placeholder="Email"></ng-md-icon>
            <input ng-model="vm.user.email" name="email" required type="email" >

This is required.

          </md-input-container>
          <md-input-container  md-no-float class="md-has-icon md-block">

            <ng-md-icon icon="lock"></ng-md-icon>
            <input type="password" required name="password" placeholder="Password" ng-model="vm.user.password">

This is required.

          </md-input-container>
           <md-button  type="sumbit" class="md-raised md-accent" >Login</md-button>
        </form>
        <button ng-click="vm.authenticate('facebook')">Sign in with Facebook</button>
      </md-content>


text:
package org.tntstudio.interfaces;

public interface Identifiable {
	public String Name();
}