text:
module FFaker
  module Address
    extend ModuleUtils
    extend self

    COMPASS_DIRECTIONS = %w[North East West South].freeze
    CITY_PREFIXES = COMPASS_DIRECTIONS + %w[New Lake Port]
    SEC_ADDR = ['Apt. ###', 'Suite ###'].freeze

    # @deprecated US specific address info. Moved into {AddressUS}
    def zip_code
      warn '[zip_code] is deprecated. For US addresses please use the AddressUS module'
      FFaker::AddressUS.zip_code
    end

    def us_state
      warn '[us_state] is deprecated. For US addresses please use the AddressUS module'
      FFaker::AddressUS.state
    end

    def us_state_abbr
      warn '[state_abbr] is deprecated. For US addresses please use the AddressUS module'
      FFaker::AddressUS.state_abbr
    end
    # end US deprecation

    def city_prefix
      fetch_sample(CITY_PREFIXES)
    end

    def city_suffix
      fetch_sample(CITY_SUFFIXES)
    end

    def city
      case rand(0..3)
      when 0 then format('%s %s%s', city_prefix, Name.first_name, city_suffix)
      when 1 then format('%s %s', city_prefix, Name.first_name)
      when 2 then format('%s%s', Name.first_name, city_suffix)
      when 3 then format('%s%s', Name.last_name, city_suffix)
      end
    end

    def street_suffix
      fetch_sample(STREET_SUFFIX)
    end

    def building_number
      FFaker.numerify(('#' * rand(0..2)) << '###')
    end

    def street_name
      case rand(0..1)
      when 0 then "#{Name.last_name} #{street_suffix}"
      when 1 then "#{Name.first_name} #{street_suffix}"
      end
    end

    def street_address(include_secondary = false)
      str = "#{building_number} #{street_name}"
      str << " #{secondary_address}" if include_secondary
      str
    end

    def secondary_address
      FFaker.numerify(fetch_sample(SEC_ADDR))
    end

    # @deprecated UK specific address info. Moved into {AddressUK}
    # UK Variants
    def uk_county
      warn '[uk_county] is deprecated. For UK addresses please use the AddressUK module'
      FFaker::AddressUK.county
    end

    def uk_country
      warn '[uk_country] is deprecated. For UK addresses please use the AddressUK module'
      FFaker::AddressUK.country
    end

    def uk_postcode
      warn '[uk_postcode] is deprecated. For UK addresses please use the AddressUK module'
      FFaker::AddressUK.postcode
    end
    # end UK deprecation

    def neighborhood
      fetch_sample(NEIGHBORHOOD)
    end

    def country(given_code = nil)
      country_index = COUNTRY_CODE.index(given_code)
      if given_code && country_index
        COUNTRY[country_index]
      else
        fetch_sample(COUNTRY)
      end
    end

    def country_code(given_country = nil)
      code_index = COUNTRY.index(given_country)
      if given_country && code_index
        COUNTRY_CODE[code_index]
      else
        fetch_sample(COUNTRY_CODE)
      end
    end

    def time_zone
      fetch_sample(TIME_ZONE)
    end
  end
end


text:
var path = require('path');
var stripComments = require('strip-json-comments');
var fs = require('fs');

// you could do this all at once if you wanted to look cool
var filename = path.join(__dirname, '.eslintrc');
var data = fs.readFileSync(filename, { encoding: 'utf-8' });
var dataWithoutComments = stripComments(data);
var parsed = JSON.parse(dataWithoutComments);

module.exports = parsed;

redpajama_set_name: RedPajamaGithub


text:
#include "dl/api/arm/armOMX.h"
#include "dl/api/omxtypes.h"
#include "dl/sp/api/armSP.h"
#include "dl/sp/api/omxSP.h"

/**
 * Function: omxSP_FFTGetBufSize_R_F32
 *
 * Description:
 * Computes the size of the specification structure required for the length
 * 2^order real FFT and IFFT functions.
 *
 * Remarks:
 * This function is used in conjunction with the 32-bit functions
 * <FFTFwd_RToCCS_F32_Sfs> and <FFTInv_CCSToR_F32_Sfs>.
 *
 * Parameters:
 * [in]  order       base-2 logarithm of the length; valid in the range
 *                    [1,12]. ([1,15] if BIG_FFT_TABLE is defined.)
 * [out] pSize	   pointer to the number of bytes required for the
 *			   specification structure.
 *
 * Return Value:
 * Standard omxError result. See enumeration for possible result codes.
 *
 */

OMXResult omxSP_FFTGetBufSize_R_F32(OMX_INT order, OMX_INT *pSize) {
  if (!pSize || (order < 1) || (order > TWIDDLE_TABLE_ORDER))
    return OMX_Sts_BadArgErr;

  /*
   * The required size is the same as for R_S32, because the
   * elements are the same size and because ARMsFFTSpec_R_SC32 is
   * the same size as ARMsFFTSpec_R_FC32.
   */
  return omxSP_FFTGetBufSize_R_S32(order, pSize);
}


text:
#ifndef _LINUX_CPUPRI_H
#define _LINUX_CPUPRI_H

#include <linux/sched.h>

#define CPUPRI_NR_PRIORITIES	(MAX_RT_PRIO + 2)
#define CPUPRI_NR_PRI_WORDS	BITS_TO_LONGS(CPUPRI_NR_PRIORITIES)

#define CPUPRI_INVALID -1
#define CPUPRI_IDLE     0
#define CPUPRI_NORMAL   1
/* values 2-101 are RT priorities 0-99 */

struct cpupri_vec {
	spinlock_t lock;
	int        count;
	cpumask_var_t mask;
};

struct cpupri {
	struct cpupri_vec pri_to_cpu[CPUPRI_NR_PRIORITIES];
	long              pri_active[CPUPRI_NR_PRI_WORDS];
	int               cpu_to_pri[NR_CPUS];
};

#ifdef CONFIG_SMP
int  cpupri_find(struct cpupri *cp,
		 struct task_struct *p, struct cpumask *lowest_mask);
void cpupri_set(struct cpupri *cp, int cpu, int pri);
int cpupri_init(struct cpupri *cp, bool bootmem);
void cpupri_cleanup(struct cpupri *cp);
#else
#define cpupri_set(cp, cpu, pri) do { } while (0)
#define cpupri_init() do { } while (0)
#endif

#endif /* _LINUX_CPUPRI_H */


text:
<!DOCTYPE html>

<link type="text/css" rel="stylesheet" href="stylesheets/my-berkshire-stylesheet.css">
<title>Title</title>

BERKSHIRE HATHAWAY INC.

    3555 Farnam Street

    Omaha, NE 68131

    Official Home Page

A Message From Warren E. Buffet

Annual & Interim Reports
Updated November 6th, 2015

Special Letters From Warren & Charlie RE:Past, Present and Future

Link to SEC Filings

Links to Berkshire Subsidiary Companies

Corporate Governance

Owner's Manual

Letters from Warren E. Buffett Regarding Pledges to Make Gifts of Berkshire Stock

New Releases
Updated February 16, 2016

Warren Buffett's Letters to Berkshire Shareholders
Updated February 28, 2015

Charlie Munger's Letters to Wesco Shareholders

Annual Meeting Information

Celebrating 50 Years of a Profitable Partnership
(A commemorative book first sold at the 2015 Annual Meeting and now for sale on eBay.)

Comparative Rights and Relative Prices of Class A and B Stock

Berkshire Activewear

        FOR A FREE CAR INSURANCE RATE QUOTE THAT COULD SAVE YOU SUBSTANTIAL MONEY

        WWW.GEICO.COM OR CALL 1-888-395-6349, 24 HOURS A DAY

    If you have any comments about our WEB page, you can either write us at the address shown above or e-mail us at berkshire@berkshirehathaway.com. However, due to the limited number of personnel in our corporate office, we are unable to provide a direct response.

    Legal Disclaimer

    Copyright © 1978-2016 Berkshire Hathaway Inc.


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>ESP32_RTOS_SDK: Event_StaMode_Disconnected_t Struct Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

ESP32_RTOS_SDK
    V3.0.0

Main Page

Modules

Data Structures

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Data Structures

Data Structure Index

Data Fields

Data Fields

Event_StaMode_Disconnected_t Struct Reference
WiFi Related APIs » Common APIs

Data Fields

uint8 	ssid [32]

uint8 	ssid_len

uint8 	bssid [6]

uint8 	reason

Field Documentation

          uint8 bssid[6]

BSSID of disconnected AP

          uint8 reason

reason of disconnection

          uint8 ssid[32]

SSID of disconnected AP

          uint8 ssid_len

SSID length of disconnected AP

The documentation for this struct was generated from the following file:

include/esp_wifi.h

<address class="footer">
Generated by

 1.8.11
</address>


text:
{% extends "skeleton.html" %}
{% block content %}

 Добавить клиента

 Список клиентов

 Список заметок

{% for note in pagedata['notes'] %}

        {{ note.client.name }}

{{ note.title }}

         {{ note.created.strftime('%Y-%m-%d %H:%M') }}
        от {{ note.user.name }}

{% endfor %}

{% endblock %}


text:
package org.apache.servicecomb.codec.protobuf.internal.converter;

import java.util.Collections;
import java.util.List;

import io.swagger.models.ArrayModel;
import io.swagger.models.Model;
import io.swagger.models.ModelImpl;
import io.swagger.models.RefModel;
import io.swagger.models.parameters.BodyParameter;
import io.swagger.models.properties.ObjectProperty;
import io.swagger.models.properties.Property;

public class BodyParameterAdapter implements SwaggerTypeAdapter {
  private final Model model;

  public BodyParameterAdapter(BodyParameter parameter) {
    this.model = parameter.getSchema();
  }

  @Override
  public String getRefType() {
    if (model instanceof RefModel) {
      return ((RefModel) model).getSimpleRef();
    }

    return null;
  }

  @Override
  public Property getArrayItem() {
    if (model instanceof ArrayModel) {
      return ((ArrayModel) model).getItems();
    }

    return null;
  }

  @Override
  public Property getMapItem() {
    if (model instanceof ModelImpl) {
      return ((ModelImpl) model).getAdditionalProperties();
    }

    return null;
  }

  @Override
  public List<String> getEnum() {
    if (model instanceof ModelImpl) {
      return ((ModelImpl) model).getEnum();
    }

    return Collections.emptyList();
  }

  @Override
  public String getType() {
    if (model instanceof ModelImpl) {
      return ((ModelImpl) model).getType();
    }

    return null;
  }

  @Override
  public String getFormat() {
    if (model instanceof ModelImpl) {
      return ((ModelImpl) model).getFormat();
    }

    return null;
  }

  @Override
  public boolean isJavaLangObject() {
    if (model instanceof ModelImpl) {
      ModelImpl modelImpl = (ModelImpl) model;
      return (ObjectProperty.TYPE.equals(modelImpl.getType())
          && modelImpl.getProperties() == null
          && modelImpl.getName() == null);
    }

    return false;
  }
}


text:
"""Animation classes."""
import threading
import time
import random
from abc import abstractmethod, ABC
from lights import colour as lcolour
from lights.action import Effect, TickedEffect, StreamEffect

class StaticEffect(Effect):
    """Constantly display the same colours."""
    def run(self, delta):
        for i, colour in enumerate(self.colours):
            self.light_string[i] = colour
        self.light_string.show()

        # Prevent flicker
        time.sleep(1/1000)

class BrightnessEffect(TickedEffect):
    """Effect class based on varying the brightness of lights.

    This class manipulates lights so that they constantly fade between full
    brightness and black. May be initialised with different starting
    brightnesses and fade directions (brightening or dimming) to create
    different effects.

    Attributes:
        values: array of floats between 0 and 1 representing light brightness.
        directions: array of {-1, 1} indicating direction to move brightness.
        speed: number indicating time taken to cycle brightness from 0 to 0
    """
    def __init__(self, light_string, colours=None, speed=4, values=None,
                 directions=None):
        # 100 brightness steps, up and down = 200
        interval = speed / 200

        if colours is None:
            colours = [(0, 0, 0)]

        if len(colours) < len(light_string):
            padded_colours = []
            for i in range(len(light_string)):
                padded_colours.append(colours[i % len(colours)])
            colours=padded_colours

        super().__init__(light_string, colours, interval=interval)

        lsl = len(self.light_string)

        if values is None:
            # Default to one-off-one-on pattern
            self.values = [i % 2 for i in range(lsl)]
        elif len(values) < lsl:
            self.values = [values[i % len(values)] for i in range(lsl)]
        else:
            self.values = values

        if directions is None:
            self.directions = [1 if i % 2 == 0 else -1 for i in range(lsl)]
        elif len(directions) < lsl:
            self.directions = [directions[i % len(values)] for i in range(lsl)]
        else:
            self.directions = directions

    def update(self):
        """Fade lights up and down individually."""
        # Update brightness values
        for i in range(len(self.light_string)):
            self.values[i] += 0.01 * self.directions[i]

        # Check for bounce
        for i in range(len(self.light_string)):
            if self.values[i] < 0:
                self.values[i] = 0
                self.directions[i] = 1
            elif self.values[i] > 1:
                self.values[i] = 1
                self.directions[i] = -1

    def display(self):
        # Calculate values to write to Lights
        for i in range(len(self.light_string)):
            lum = self.values[i]
            self.light_string[i] = lcolour.fade(self.colours[i], lum)

        self.light_string.show()

class LoopEffect(StreamEffect):
    """Removes colours from one end of string and shifts them to the other."""
    def get_next_colour(self):
        if self.reverse:
            return self.colours[0]
        else:
            return self.colours[-1]

class MaskShiftEffect(TickedEffect):
    """Shifts a mask down the string turning lights off according to a pattern.

    Attributes:
        pattern: array of {0, 1} to be repeated down the string of lights.
    """
    def __init__(self, light_string, colours, interval=1.0, pattern=None,
                 reverse=False):
        super().__init__(light_string, colours, interval=interval)
        if pattern is None:
            self.pattern = [0, 1]
        else:
            self.pattern = pattern
        self.offset = 0
        self.reverse = reverse

    def update(self):
        """Move mask down string of lights."""
        # Shift pattern
        if self.reverse:
            self.offset -= 1
        else:
            self.offset += 1
        self.offset %= len(self.pattern)

    def display(self):
        for i in range(len(self.light_string)):
            if self.pattern[(i + self.offset) % len(self.pattern)] == 0:
                self.light_string[i] = (0, 0, 0)
            else:
                self.light_string[i] = self.colours[i]
        self.light_string.show()

class GradientEffect(TickedEffect):
    """Effect that interpolates between a number of colours

    Colours are interpolated evening along the string and looped around.

    Attributes:
        cycle_time: number indicating time for a colour to loop back
        smoothing: number indicating ratio of virtual colours to create
    """
    def __init__(self, light_string, colours, cycle_time=10, smoothing=4,
                 reverse=False, interp=lcolour.linear_interpolate):
        """Initialise gradient effect

        Args:
            cycle_time: number indicating time for a colour to loop back
            smoothing: number indicating ratio of virtual colours to create
        """
        super().__init__(light_string, colours)

        # Specific to this subclass
        self.cycle_time = cycle_time
        self.offset = [0 for i in range(len(self.light_string))]
        self.reverse = reverse
        self.interp = interp

        # Create virtual lights
        self.smoothing = smoothing
        self.virtual_length = self.calc_virtual_length()

        # XXX Can't get virtual_length until super init run
        # But can't get interval to init without virtual_length
        self._interval = cycle_time / self.virtual_length
        self.calc_virtual_colours()

    def calc_virtual_length(self):
        return len(self.light_string) * self.smoothing

    def calc_virtual_colours(self):
        self.virtual_colours = []

        # Calculate colour locations
        step_between_colours = self.virtual_length / len(self.colours)
        steps = []

        for i in range(len(self.colours)):
            steps.append(round(i * step_between_colours))
        steps.append(self.virtual_length)

        # Repeat first colour
        self.colours.append(self.colours[0])

        # Calculate virtual colours
        indices = [(i, steps[i], steps[i+1]) for i in range(len(steps) - 1)]
        for i, step_a, step_b in indices:
            t_step = 1 / (step_b - step_a)
            for j in range(step_b - step_a):
                colour = self.interp(self.colours[i],
                                     self.colours[i + 1],
                                     j * t_step)
                self.virtual_colours.append(colour)

    def display(self):
        for i in range(len(self.light_string)):
            index = (i * self.smoothing - self.offset[i]) % self.virtual_length
            self.light_string[i] = self.virtual_colours[index]
        self.light_string.show()

    def update(self):
        # Shift pattern
        for i in range(len(self.light_string)):
            if self.reverse:
                self.offset[i] -= 1
            else:
                self.offset[i] += 1
            self.offset[i] %= self.virtual_length

class ColourFadeEffect(GradientEffect):
    def __init__(self, light_string, colours, steps=100, **kwargs):
        self.steps = steps
        super().__init__(light_string, colours, **kwargs)

    def calc_virtual_length(self):
        return int(self.steps * self.cycle_time)

    def display(self):
        index = self.offset[0] % self.virtual_length
        for i in range(len(self.light_string)):
            self.light_string[i] = self.virtual_colours[index]
        self.light_string.show()

class ColourTwinkleEffect(GradientEffect):
    def __init__(self, light_string, colours, steps=100, **kwargs):

        self.steps = steps
        super().__init__(light_string, colours, **kwargs)

        self.offsets = []
        for i in range(len(self.light_string)):
            self.offset[i] = random.randint(0, self.virtual_length - 1)

    def calc_virtual_length(self):
        return int(self.steps * self.cycle_time)


text:
- [Table of content](#table-of-content)
  - [Upgrading Tasks to Node 16](#upgrading-tasks-to-node-16)
  - [Common packages dependent on `azure-pipeline-task-lib` and `azure-pipeline-tool-lib`](#common-packages-dependent-on-azure-pipeline-task-lib-and-azure-pipeline-tool-lib)
  - [List of known dependency issues](#list-of-known-dependency-issues)
  - [Feedback](#feedback)

## Upgrading Tasks to Node 16

1. Update @types packages in `package.json` dependencies.

```json
  "dependencies": {
    "@types/node": "^16.11.39",
    "@types/mocha": "^9.1.1",
    ...
  }
```
1. Upgrade `azure-pipelines-task-lib` to `^4.0.0-preview`, `azure-pipelines-tool-lib` to `^2.0.0-preview` in package.json dependencies, If a task has these packages.

2. Change execution handlers in `task.json` from `Node` to `Node16`
   * **Note**: _the `target` property should be the main file targetted for the task to execute._

From
To

```json
  "execution": {
    "Node10": {
      "target": "bash.js",
      "argumentFormat": ""
    }
```

```json
  "execution": {
    "Node16": {
      "target": "bash.js",
      "argumentFormat": ""
    }
```

4. Also in the `task.json` file, if the `minimumAgentVersion` isn't present or is less than `2.206.1`, change it to `2.206.1`.
   * Agent version `2.206.1` is the [first version to support Node16 handlers](https://github.com/microsoft/azure-pipelines-agent/releases/tag/v2.206.1) and the `minimumAgentVersion` will trigger an [automatic upgrade](https://docs.microsoft.com/en-us/azure/devops/pipelines/agents/agents?view=azure-devops&tabs=browser#agent-version-and-upgrades) of `2.x.y` agents less than `2.206.1`.

```json
  "minimumAgentVersion": "2.206.1"
```

## Common packages dependent on `azure-pipeline-task-lib` and `azure-pipeline-tool-lib`

Use the latest major version of a "common package" at `common-npm-packages` folder, which depends on the `azure-pipelines-task-lib` package with `^4.0.0-preview` version. For "common package" dependent on `azure-pipeline-tool-lib`, this is `^2.0.0-preview` version.

The task-lib package uses some shared (e.g. global object) resources to operate so it may cause unexpected errors in cases when more than one version of the package is installed for a task. It happens in the case of a child package's task-lib dependency has a different version than a task's `task-lib` has. Same for `tool-lib`.

If you are planning to move some common package to common-npm-packages directory - please note that you need to update all necessary paths in this package

## List of known dependency issues

Major commits between Node 10-16 related to fs/child_process/os modules (gather from notable notes only) - you can use # numbers as PR ids to refer:

**Node 11**
Notable Changes:

fs:
- The fs.read() method now requires a callback.
- The previously deprecated fs.SyncWriteStream utility has been removed.

child_process
The default value of the windowsHide option has been changed to true.

**Node 12**

fs:
- use proper .destroy() implementation for SyncWriteStream
- improve mode validation
- harden validation of start option in createWriteStream()
- make writeFile consistent with readFile wrt fd
- win, fs: detect if symlink target is a directory

child_process:
- remove options.customFds
- harden fork arguments validation
- use non-infinite maxBuffer defaults

os:
- implement os.type() using uv_os_uname()
- remove os.getNetworkInterfaces()

**Node 13**
child_process:
- ChildProcess._channel (DEP0129) is now a Runtime deprecation

fs:
- The undocumented method FSWatcher.prototype.start() was removed
- Calling the open() method on a ReadStream or WriteStream now emits a runtime deprecation warning. The methods are supposed to be internal and should not be called by user code
- fs.read/write, fs.readSync/writeSync and fd.read/write now accept any safe integer as their offset parameter. The value of offset is also no longer coerced, so a valid type must be passed to the functions.

**Node 14**
os:
- (SEMVER-MAJOR) os: move tmpDir() to EOL
fs:
- (SEMVER-MAJOR) fs: deprecate closing FileHandle on garbage collection
- add fs/promises alias module (Gus Caplan)

**Node 15**
fs:
- (SEMVER-MAJOR) fs: deprecation warning on recursive rmdir
- (SEMVER-MAJOR) fs: reimplement read and write streams using stream.construct

**Node 16:**
fs:
- (SEMVER-MAJOR) fs: remove permissive rmdir recursive
- (SEMVER-MAJOR) fs: runtime deprecate rmdir recursive option

## Feedback

If you run into some issues while migrating to Node 16, please create a ticket with the label "node-migration: Node16".


text:
**Code generation differences compared to previous compilers.**

**NOTE** - **The form and shape of the IL stream as produced by the compiler is not a public contract!**
Compiler is only responsible for producing IL that is semantically equivalent to the C# source code.
Any dependencies on exact form of the output may be broken by new versions or even bug fixes.

It may not be comprehensive since the changes are a moving target and there could be some changes that are not too obvious or significant to mention. This document is always in progress...

**What is the purpose of this document?**
* JIT compilers in general strive to handle any valid IL. However, the realities are that most optimizations and most tests are directed towards "typical" codegen and therefore there is interest in any changes in compiler output so that JITs could make sure there is adequate support.
* There is a class of tools that rely on decompilation techniques. Generally such tools *choose* to be  broken by specializing to particular compiler outputs. Adjusting to new patterns is just something they have to deal with as a part of the lifecycle.
* There is also a good deal of academic interest in the changes.

**So here is a rough list of changes:**
There are two sections here - Release codegen and Debug. They are separate because the changes are typically different in nature since they are motivated by different goals.
Generally Release codegen strives to be the most efficient and compact representation of the sources semantics, while the Debug codegen values debuggability.
When efficiency and debuggability are at conflict, Release and Debug make different choices.

**== Release (optimized)**

•	The async codegen was for the most part redone in Roslyn.
 - The capturing is smarter now when optimizations are enabled since it relies on precise data flow analysis. Basically only locals that cross awaits need to be lifted. Old compiler used more conservative approach and would often capture locals unnecessarily.
 - The stack spilling is completely different. Instead of always present object array slot, we generate strongly typed reusable slots, but only if needed.

•	Iterators - the genral principle is the same, but there were some minor refinements in the state machine.
 - Local capturing is based on precise data flow analysis and may result in fewer local lifted into iterator class. Generally only locals whose values are alive across yield statements need to be captured.
 - Valid states are now all positive and invalid states are negative. The common path in the  iterator body switches on valid states and there are benefits from the set of those states being contiguous.

•	Lambdas had some minor changes in caching strategy and a change in representation of non-lifting lambdas.
- The caching strategy has changed to a more compact pattern that also results in fewer accesses to the caching field (in case JIT does not optimize multiple reads).
Instead of an equivalent of

```C#
 if (cacheField == null)
 {
   cacheFiled = {allocate new lambdaDelegate};
 }
 return cacheField;
```
We now generate something close to

```C#
return cacheField ?? (cacheFiled = {allocate new lambdaDelegate});
```

- non-lifting Lambda expressions are now implemented as an instance methods on singleton display classes. Since the entry point to the delegate is the instance "Invoke" method, it is cheaper at runtime to dispatch delegate invocations to the underlying implementing method if such method is also an instance method with exactly same formal signature as "Invoke".
- delegates for non-lifting Lambdas in generic methods can now be cached by Roslyn. That is mostly a welcome sideeffect of the change above.

•	The string switch codegen in Roslyn is completely new. Roslyn does not use dictionaries to avoid allocations and a potentially huge penalty when a string switch is execute for the first time. Roslyn uses a private function that maps strings to hash codes and a numeric switch. In some sense this is a partial inlining of the former technic that used static dictionaries.

•	Array initializers are slightly more compact – in most cases extra temporary for the array instance is avoided and dup is used instead. (I think VB always did this, but this is new for C#)

•	Leaves from nested try in many cases would not cascade through outer regions and just leave directly to the outmost region. (VB was doing that always, now C# does this too since this part of codegen is in shared library and it is also more compact)
Branch threading in general may handle few more cases compared to the old compiler. Leave-to-leave case is probably the most noticeable.

•	Numeric switches –
- some minor changes in re-biasing and range checking in switches with nonzero smallest key.
- Slightly different strategy in choosing between binary search and computed switch buckets.
At high level switch codegen follows the same pattern as with old compiler, but we fixed some off-by-one errors that could result in unbalanced decision trees in some cases.
The end result is that overall IL could be different. Hopefully better.

•	Some unnecessary locals could be eliminated or used on the stack when compiled with /o+.
This is not new, old compiled did this as well, but implementation of this optimization has changed.
There are few cases where old compiler was "smarter" since it did this optimization earlier (and caused numerous inconveniences to later stages).
Generally the new approach handles more scenarios, so you may notice in some cases more dups used and fewer locals.

**Cascading optimizations** – note that it is possible for one optimization to enable another that may not be by itself new.

**== Debug (not optimized)**

TBW


text:
using System;
using System.Threading.Tasks;

namespace Alluvial
{
    internal abstract class AnonymousStreamBase<TData, TCursor> : IStream<TData, TCursor>
    {
        private readonly Action<IStreamQuery<TCursor>, IStreamBatch<TData>> advanceCursor;
        protected Func<ICursor<TCursor>> newCursor;

        protected AnonymousStreamBase(
            Action<IStreamQuery<TCursor>, IStreamBatch<TData>> advanceCursor,
            Func<ICursor<TCursor>> newCursor = null)
        {
            this.newCursor = newCursor ?? (() => Cursor.New<TCursor>());

            this.advanceCursor = advanceCursor ??
                                 ((query, batch) => { });
        }

        public abstract string Id { get; }

        public ICursor<TCursor> NewCursor() => newCursor();

        protected void AdvanceCursor(IStreamQuery<TCursor> query, IStreamBatch<TData> batch) =>
            advanceCursor(query, batch);

        public abstract Task<IStreamBatch<TData>> Fetch(IStreamQuery<TCursor> query);

        public override string ToString() => $"stream:{Id}";
    }
}


text:
package swf.filter.factory;

import java.util.Collection;
import swf.filter.Factory;
import swf.filter.Filter;

public class TrueFilter<T> implements Factory<T> {
  public Filter<T> create(Collection<T> collection) {
    return new swf.filter.TrueFilter<T>();
  }
}


text:
import { graphql } from 'gatsby';
import React from 'react';
import { css } from 'astroturf';

import LinkedHeading from '../../components/LinkedHeading';
import ComponentApi from '../../components/ComponentApi';
import ReactPlayground from '../../components/ReactPlayground';

import Overlay from '../../examples/Overlays/Overlay';
import Disabled from '../../examples/Overlays/Disabled';
import ScheduleUpdate from '../../examples/Overlays/ScheduleUpdate';
import OverlayTrigger from '../../examples/Overlays/OverlayTrigger';
import TooltipInCopy from '../../examples/Overlays/TooltipInCopy';
import TooltipOverlay from '../../examples/Overlays/TooltipOverlay';
import TooltipPositioned from '../../examples/Overlays/TooltipPositioned';

import PopoverBasic from '../../examples/Overlays/PopoverBasic';
import PopoverContained from '../../examples/Overlays/PopoverContained';
import PopoverPositioned from '../../examples/Overlays/PopoverPositioned';

import withLayout from '../../withLayout';

const styles = css`
  .contained {
    height: 200px;
    & > div {
      position: relative;
    }
  }
`;

export default withLayout(function TooltipSection({ data }) {
  return (
    <>
      <LinkedHeading h="1" id="overlays">
        Overlays
      </LinkedHeading>

        A set of components for positioning beautiful overlays, tooltips,
        popovers, and anything else you need.

      <LinkedHeading h="2" id="overlays-overview">
        Overview
      </LinkedHeading>

Things to know about the react-boostrap Overlay components.

          Overlays rely on a 3rd party library{' '}
          react-popper,
          a tiny react wrapper around{' '}
          Popper.js. It's include
          automatically with react-bootstrap, but you should reference the API
          for more advanced use-cases.

          The {'<Tooltip>'} and {'<Popover>'}{' '}
          components do not position themselves. Instead the{' '}
          {'<Overlay>'} (or {'<OverlayTrigger>'})
          components, inject ref and style props.

          Tooltip expects specific props injected by the{' '}
          {'<Overlay>'} component

          Tooltips for disabled elements must be triggered on a
          wrapper element.

      <LinkedHeading h="2" id="overlays">
        Overlay
      </LinkedHeading>

        Overlay is the fundemental component for positioning and
        controlling tooltip visibility. It's a wrapper around react-popper, that
        adds support for transitions, and visibility toggling.

      <LinkedHeading h="3" id="creating-an-overlay">
        Creating an Overlay
      </LinkedHeading>

        Overlays consist of at least two elements, the "overlay", the element to
        be positioned, as well as a "target", the element the overlay is
        positioned in relation to. You can also also have an "arrow" element,
        like the tooltips and popovers, but that is optional. Be sure to{' '}

          check out the{' '}

            react-popper
          {' '}
          documentation for more details about the injected props.

      <ReactPlayground codeText={Overlay} />

      <LinkedHeading h="3" id="overlay-trigger">
        OverlayTrigger
      </LinkedHeading>

        Since the above pattern is pretty common, but verbose, we've included{' '}
        {'<OverlayTrigger>'} component to help with common
        use-cases. It even has functionality to delayed show or hides, and a few
        different "trigger" events you can mix and match.

        Note that triggering components{' '}

          must be able to accept{' '}
          a ref
        {' '}
        since {'<OverlayTrigger>'} will attempt to add one. You can
        use{' '}

          forwardRef()
        {' '}
        for stateless function components.

      <ReactPlayground codeText={OverlayTrigger} />

      <LinkedHeading h="2" id="tooltips">
        Tooltips
      </LinkedHeading>

        A tooltip component for a more stylish alternative to that anchor tag{' '}
        title attribute.

      <LinkedHeading h="3" id="tooltip-examples">
        Examples
      </LinkedHeading>

Hover over the links below to see tooltips.

      <ReactPlayground codeText={TooltipInCopy} showCode={false} />

        You can pass the Overlay injected props directly to the
        Tooltip component.

      <ReactPlayground codeText={TooltipOverlay} />

        Or pass a Tooltip element to OverlayTrigger instead.

      <ReactPlayground codeText={TooltipPositioned} />

      <LinkedHeading h="2" id="popovers">
        Popovers
      </LinkedHeading>

A popover component, like those found in iOS.

      <LinkedHeading h="3" id="popover-examples">
        Examples
      </LinkedHeading>

      <ReactPlayground codeText={PopoverBasic} />

        As with {'<Tooltip>'}s, you can control the placement of
        the Popover.

      <ReactPlayground codeText={PopoverPositioned} />

      <LinkedHeading h="2" id="overlays-disabled">
        Disabled elements
      </LinkedHeading>

        Elements with the disabled attribute aren't interactive,
        meaning users cannot hover or click them to trigger a popover (or
        tooltip). As a workaround, you'll want to trigger the overlay from a
        wrapper {'
'} or {''} and override
        the pointer-events on the disabled element.

      <ReactPlayground codeText={Disabled} />

      <LinkedHeading h="2" id="overlays-container">
        Changing containers
      </LinkedHeading>

        Yopu can specify a container to control the DOM element the
        overlay is appended to. This is especially useful when styles conflict
        with your Overlay's.

      <ReactPlayground
        codeText={PopoverContained}
        exampleClassName={styles.contained}
      />

      <LinkedHeading h="2" id="overlays-dynamic-updates">
        Updating position dynamically
      </LinkedHeading>

        Since we can't know every time your overlay changes size, to reposition
        it, you need to take manual action if you want to update the position of
        an Overlay in response to a change.

        For this, the Overlay component also injects a{' '}
        scheduleUpdate() method that an overlay component can use
        to reposition itself.

      <ReactPlayground codeText={ScheduleUpdate} />

      <LinkedHeading h="2" id="overlays-api">
        API
      </LinkedHeading>

      <ComponentApi metadata={data.Overlay} />
      <ComponentApi metadata={data.OverlayTrigger} />
      <ComponentApi metadata={data.Tooltip} />
      <ComponentApi metadata={data.Popover} />
    </>
  );
});

export const query = graphql`
  query OverlayQuery {
    Tooltip: componentMetadata(displayName: { eq: "Tooltip" }) {
      ...ComponentApi_metadata
    }
    Popover: componentMetadata(displayName: { eq: "Popover" }) {
      ...ComponentApi_metadata
    }
    Overlay: componentMetadata(displayName: { eq: "Overlay" }) {
      ...ComponentApi_metadata
    }
    OverlayTrigger: componentMetadata(displayName: { eq: "OverlayTrigger" }) {
      ...ComponentApi_metadata
    }
  }
`;


text:
ControllerComponent::ControllerComponent(Entity* parent) : Component(parent)
{

}

ControllerComponent::~ControllerComponent()
{
}

void ControllerComponent::ProcessInput(u32 action)
{
	process_action(action);

}

void ControllerComponent::SetAction(Command * command, u32 action)
{
	if (command != nullptr)
	{
		control_actions_array_[(int)action] = command;
	}

}

void ControllerComponent::process_action(u32 action)
{
	// process input here
	if (control_actions_array_[(int)action] != nullptr)
	{
		control_actions_array_[(int)action]->execute();
	}

}


text:
Inicio de sesión

				<input id='email' type='email' name='email'></input>
				Email

				<input id='password' type='password' name='password'></input>
				Contraseña

			<button id='btn-login' class='btn'>Enviar</button>


text:
package org.apache.nifi.minifi.c2;

import static java.util.Optional.ofNullable;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.nifi.c2.client.C2ClientConfig;
import org.apache.nifi.c2.client.http.C2HttpClient;
import org.apache.nifi.c2.client.service.C2ClientService;
import org.apache.nifi.c2.client.service.C2HeartbeatFactory;
import org.apache.nifi.c2.client.service.FlowIdHolder;
import org.apache.nifi.c2.client.service.ManifestHashProvider;
import org.apache.nifi.c2.client.service.model.RuntimeInfoWrapper;
import org.apache.nifi.c2.client.service.operation.C2OperationService;
import org.apache.nifi.c2.client.service.operation.DescribeManifestOperationHandler;
import org.apache.nifi.c2.client.service.operation.EmptyOperandPropertiesProvider;
import org.apache.nifi.c2.client.service.operation.OperandPropertiesProvider;
import org.apache.nifi.c2.client.service.operation.SupportedOperationsProvider;
import org.apache.nifi.c2.client.service.operation.TransferDebugOperationHandler;
import org.apache.nifi.c2.client.service.operation.UpdateAssetOperationHandler;
import org.apache.nifi.c2.client.service.operation.UpdateConfigurationOperationHandler;
import org.apache.nifi.minifi.c2.command.TransferDebugCommandHelper;
import org.apache.nifi.minifi.c2.command.UpdateAssetCommandHelper;
import org.apache.nifi.c2.protocol.api.AgentManifest;
import org.apache.nifi.c2.protocol.api.AgentRepositories;
import org.apache.nifi.c2.protocol.api.AgentRepositoryStatus;
import org.apache.nifi.c2.protocol.api.FlowQueueStatus;
import org.apache.nifi.c2.serializer.C2JacksonSerializer;
import org.apache.nifi.controller.FlowController;
import org.apache.nifi.controller.status.ConnectionStatus;
import org.apache.nifi.controller.status.ProcessGroupStatus;
import org.apache.nifi.diagnostics.StorageUsage;
import org.apache.nifi.diagnostics.SystemDiagnostics;
import org.apache.nifi.extension.manifest.parser.ExtensionManifestParser;
import org.apache.nifi.extension.manifest.parser.jaxb.JAXBExtensionManifestParser;
import org.apache.nifi.manifest.RuntimeManifestService;
import org.apache.nifi.manifest.StandardRuntimeManifestService;
import org.apache.nifi.nar.ExtensionManagerHolder;
import org.apache.nifi.util.FormatUtils;
import org.apache.nifi.util.NiFiProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class C2NifiClientService {

    private static final Logger logger = LoggerFactory.getLogger(C2NifiClientService.class);

    private static final String DEFAULT_CONF_DIR = "./conf";
    private static final String TARGET_CONFIG_FILE = "/config-new.yml";
    private static final String ROOT_GROUP_ID = "root";
    private static final Long INITIAL_DELAY = 10000L;
    private static final Integer TERMINATION_WAIT = 5000;

    private final C2ClientService c2ClientService;

    private final FlowController flowController;
    private final String propertiesDir;
    private final ScheduledThreadPoolExecutor scheduledExecutorService = new ScheduledThreadPoolExecutor(1);
    private final ExtensionManifestParser extensionManifestParser = new JAXBExtensionManifestParser();

    private final RuntimeManifestService runtimeManifestService;

    private final SupportedOperationsProvider supportedOperationsProvider;

    private final long heartbeatPeriod;

    public C2NifiClientService(final NiFiProperties niFiProperties, final FlowController flowController) {
        C2ClientConfig clientConfig = generateClientConfig(niFiProperties);
        FlowIdHolder flowIdHolder = new FlowIdHolder(clientConfig.getConfDirectory());
        this.propertiesDir = niFiProperties.getProperty(NiFiProperties.PROPERTIES_FILE_PATH, null);
        this.runtimeManifestService = new StandardRuntimeManifestService(
            ExtensionManagerHolder.getExtensionManager(),
            extensionManifestParser,
            clientConfig.getRuntimeManifestIdentifier(),
            clientConfig.getRuntimeType()
        );
        this.heartbeatPeriod = clientConfig.getHeartbeatPeriod();
        this.flowController = flowController;

        C2HttpClient client = new C2HttpClient(clientConfig, new C2JacksonSerializer());
        C2HeartbeatFactory heartbeatFactory = new C2HeartbeatFactory(clientConfig, flowIdHolder, new ManifestHashProvider());
        OperandPropertiesProvider emptyOperandPropertiesProvider = new EmptyOperandPropertiesProvider();
        TransferDebugCommandHelper transferDebugCommandHelper = new TransferDebugCommandHelper(niFiProperties);
        UpdateAssetCommandHelper updateAssetCommandHelper = new UpdateAssetCommandHelper(clientConfig.getC2AssetDirectory());
        updateAssetCommandHelper.createAssetDirectory();
        C2OperationService c2OperationService = new C2OperationService(Arrays.asList(
            new UpdateConfigurationOperationHandler(client, flowIdHolder, this::updateFlowContent, emptyOperandPropertiesProvider),
            new DescribeManifestOperationHandler(heartbeatFactory, this::generateRuntimeInfo, emptyOperandPropertiesProvider),
            TransferDebugOperationHandler.create(client, emptyOperandPropertiesProvider,
                transferDebugCommandHelper.debugBundleFiles(), transferDebugCommandHelper::excludeSensitiveText),
            UpdateAssetOperationHandler.create(client, emptyOperandPropertiesProvider,
                updateAssetCommandHelper::assetUpdatePrecondition, updateAssetCommandHelper::assetPersistFunction)
        ));
        this.c2ClientService = new C2ClientService(client, heartbeatFactory, c2OperationService);
        this.supportedOperationsProvider = new SupportedOperationsProvider(c2OperationService.getHandlers());
    }

    private C2ClientConfig generateClientConfig(NiFiProperties properties) {
        return new C2ClientConfig.Builder()
            .agentClass(properties.getProperty(C2NiFiProperties.C2_AGENT_CLASS_KEY, ""))
            .agentIdentifier(properties.getProperty(C2NiFiProperties.C2_AGENT_IDENTIFIER_KEY))
            .fullHeartbeat(Boolean.parseBoolean(properties.getProperty(C2NiFiProperties.C2_FULL_HEARTBEAT_KEY, "true")))
            .heartbeatPeriod(Long.parseLong(properties.getProperty(C2NiFiProperties.C2_AGENT_HEARTBEAT_PERIOD_KEY,
                String.valueOf(C2NiFiProperties.C2_AGENT_DEFAULT_HEARTBEAT_PERIOD))))
            .connectTimeout((long) FormatUtils.getPreciseTimeDuration(properties.getProperty(C2NiFiProperties.C2_CONNECTION_TIMEOUT,
                C2NiFiProperties.C2_DEFAULT_CONNECTION_TIMEOUT), TimeUnit.MILLISECONDS))
            .readTimeout((long) FormatUtils.getPreciseTimeDuration(properties.getProperty(C2NiFiProperties.C2_READ_TIMEOUT,
                C2NiFiProperties.C2_DEFAULT_READ_TIMEOUT), TimeUnit.MILLISECONDS))
            .callTimeout((long) FormatUtils.getPreciseTimeDuration(properties.getProperty(C2NiFiProperties.C2_CALL_TIMEOUT,
                C2NiFiProperties.C2_DEFAULT_CALL_TIMEOUT), TimeUnit.MILLISECONDS))
            .c2Url(properties.getProperty(C2NiFiProperties.C2_REST_URL_KEY, ""))
            .c2RequestCompression(properties.getProperty(C2NiFiProperties.C2_REQUEST_COMPRESSION_KEY, C2NiFiProperties.C2_REQUEST_COMPRESSION))
            .c2AssetDirectory(properties.getProperty(C2NiFiProperties.C2_ASSET_DIRECTORY_KEY, C2NiFiProperties.C2_ASSET_DIRECTORY))
            .confDirectory(properties.getProperty(C2NiFiProperties.C2_CONFIG_DIRECTORY_KEY, DEFAULT_CONF_DIR))
            .runtimeManifestIdentifier(properties.getProperty(C2NiFiProperties.C2_RUNTIME_MANIFEST_IDENTIFIER_KEY, ""))
            .runtimeType(properties.getProperty(C2NiFiProperties.C2_RUNTIME_TYPE_KEY, ""))
            .c2AckUrl(properties.getProperty(C2NiFiProperties.C2_REST_URL_ACK_KEY, ""))
            .truststoreFilename(properties.getProperty(C2NiFiProperties.TRUSTSTORE_LOCATION_KEY, ""))
            .truststorePassword(properties.getProperty(C2NiFiProperties.TRUSTSTORE_PASSWORD_KEY, ""))
            .truststoreType(properties.getProperty(C2NiFiProperties.TRUSTSTORE_TYPE_KEY, "JKS"))
            .keystoreFilename(properties.getProperty(C2NiFiProperties.KEYSTORE_LOCATION_KEY, ""))
            .keystorePassword(properties.getProperty(C2NiFiProperties.KEYSTORE_PASSWORD_KEY, ""))
            .keystoreType(properties.getProperty(C2NiFiProperties.KEYSTORE_TYPE_KEY, "JKS"))
            .build();
    }

    public void start() {
        scheduledExecutorService.scheduleAtFixedRate(() -> c2ClientService.sendHeartbeat(generateRuntimeInfo()), INITIAL_DELAY, heartbeatPeriod, TimeUnit.MILLISECONDS);
    }

    public void stop() {
        try {
            scheduledExecutorService.shutdown();
            scheduledExecutorService.awaitTermination(TERMINATION_WAIT, TimeUnit.MILLISECONDS);
        } catch (InterruptedException ignore) {
            logger.info("Stopping C2 Client's thread was interrupted but shutting down anyway the C2NifiClientService");
        }
    }

    private RuntimeInfoWrapper generateRuntimeInfo() {
        AgentManifest agentManifest = new AgentManifest(runtimeManifestService.getManifest());
        agentManifest.setSupportedOperations(supportedOperationsProvider.getSupportedOperations());
        return new RuntimeInfoWrapper(getAgentRepositories(), agentManifest, getQueueStatus());
    }

    private AgentRepositories getAgentRepositories() {
        final SystemDiagnostics systemDiagnostics = flowController.getSystemDiagnostics();

        final AgentRepositories repos = new AgentRepositories();
        final AgentRepositoryStatus flowFileRepoStatus = new AgentRepositoryStatus();
        final StorageUsage ffRepoStorageUsage = systemDiagnostics.getFlowFileRepositoryStorageUsage();
        flowFileRepoStatus.setDataSize(ffRepoStorageUsage.getUsedSpace());
        flowFileRepoStatus.setDataSizeMax(ffRepoStorageUsage.getTotalSpace());
        repos.setFlowFile(flowFileRepoStatus);

        final AgentRepositoryStatus provRepoStatus = new AgentRepositoryStatus();
        final Iterator<Map.Entry<String, StorageUsage>> provRepoStorageUsages = systemDiagnostics.getProvenanceRepositoryStorageUsage().entrySet().iterator();
        if (provRepoStorageUsages.hasNext()) {
            final StorageUsage provRepoStorageUsage = provRepoStorageUsages.next().getValue();
            provRepoStatus.setDataSize(provRepoStorageUsage.getUsedSpace());
            provRepoStatus.setDataSizeMax(provRepoStorageUsage.getTotalSpace());
        }

        repos.setProvenance(provRepoStatus);

        return repos;
    }

    private Map<String, FlowQueueStatus> getQueueStatus() {
        ProcessGroupStatus rootProcessGroupStatus = flowController.getEventAccess().getGroupStatus(ROOT_GROUP_ID);

        final Collection<ConnectionStatus> connectionStatuses = rootProcessGroupStatus.getConnectionStatus();

        final Map<String, FlowQueueStatus> processGroupStatus = new HashMap<>();
        for (ConnectionStatus connectionStatus : connectionStatuses) {
            final FlowQueueStatus flowQueueStatus = new FlowQueueStatus();

            flowQueueStatus.setSize((long) connectionStatus.getQueuedCount());
            flowQueueStatus.setSizeMax(connectionStatus.getBackPressureObjectThreshold());

            flowQueueStatus.setDataSize(connectionStatus.getQueuedBytes());
            flowQueueStatus.setDataSizeMax(connectionStatus.getBackPressureBytesThreshold());

            processGroupStatus.put(connectionStatus.getId(), flowQueueStatus);
        }

        return processGroupStatus;
    }

    private boolean updateFlowContent(byte[] updateContent) {
        logger.debug("Update content: \n{}", new String(updateContent, StandardCharsets.UTF_8));
        Path path = getTargetConfigFile().toPath();
        try {
            Files.write(getTargetConfigFile().toPath(), updateContent);
            logger.info("Updated configuration was written to: {}", path);
            return true;
        } catch (IOException e) {
            logger.error("Configuration update failed. File creation was not successful targeting: {}", path, e);
            return false;
        }
    }

    private File getTargetConfigFile() {
        return ofNullable(propertiesDir)
            .map(File::new)
            .map(File::getParent)
            .map(parentDir -> new File(parentDir + TARGET_CONFIG_FILE))
            .orElse(new File(DEFAULT_CONF_DIR + TARGET_CONFIG_FILE));
    }
}


text:
/*****************************************************************************
 *   Author: Amrit Panesar                                       ,o/ ASP     *
 *     Date: 06-19-2013                                                      *
 *  Program: PetSimulator                                                    *
 *     File: pet.cpp                                                         *
 * Function: Holds all functions pertaining to the pet class.                *
 * Abstract: This file contains all necessary functions related to the Pet   *
 *           class as contained in the Pet.h header file. These functions    *
 *           were dictated as such in the project specifications.            *
 * Liscence: Released as Public Domain material.                             *
 ****************************************************************************/

#include "Pet.h"

/******************************************************************************
 * Function: Constructor - Pet(string, int, int)                              *
 * Abstract: Instantiates object. Three parameters are taken, name, hunger,   *
 *           and boredom. The constructor also prints the initial statistics  *
 *           of the pet.                                                      *
 *****************************************************************************/
Pet::Pet (string name, int hunger, int boredom)
{
	setName(name);
	setHungerLevel(0);
	setBoredomLevel(0);

	displayPetBehavior();
}

/******************************************************************************
 * Function: Setter - setName(string)                                         *
 * Abstract: Sets the name of the pet.                                        *
 *****************************************************************************/
void Pet::setName(string in)
{
	name = in;
}

/******************************************************************************
 * Function: Getter - getName()                                               *
 * Abstract: Gets the name of the pet.                                        *
 *****************************************************************************/
string Pet::getName()
{
	return name;
}

/******************************************************************************
 * Function: Setter - setBoredomLevel(int)                                    *
 * Abstract: Sets the boredom level of the pet if the level is                *
 *           between 0 and 100                                                *
 *****************************************************************************/
void Pet::setBoredomLevel(int in)
{
	if (in >= 0 || in <= 100)
		boredomLevel = in;
}

/******************************************************************************
 * Function: Getter - getBoredomLevel()                                       *
 * Abstract: Gets the boredom level of the pet.                               *
 *****************************************************************************/
int Pet::getBoredomLevel()
{
	return boredomLevel;
}

/******************************************************************************
 * Function: Setter - setHungerLevel(int)                                     *
 * Abstract: Sets the hunger level of the pet if the level is                 *
 *           between 0 and 100                                                *
 *****************************************************************************/
void Pet::setHungerLevel(int in)
{
	if (in >= 0 || in <= 100)
		hungerLevel = in;
}

/******************************************************************************
 * Function: Getter - getHungerLevel()                                        *
 * Abstract: Gets the hunger level of the pet.                                *
 *****************************************************************************/
int Pet::getHungerLevel()
{
	return hungerLevel;
}

/******************************************************************************
 * Function: Menu                                                             *
 * Abstract: Does the thing. This is the main interface of the program.       *
 *           An enum is used to switch functionality for the interface.       *
 *           cin is used to gather input from the user. This function loops   *
 *           and calls getName, talk, feedpet and play. A GOTO is used as a   *
 *           means to exit from the while loop. This is a standard.           *
 *****************************************************************************/
void Pet::menu()
{
	enum { TALK = 1, FEED, PLAY, QUIT };
	while (true)
	{
		cout << "Pet: " << getName() << endl;
		cout << TALK << ". Talk with your pet." << endl;
		cout << FEED << ". Feed your pet." << endl;
		cout << PLAY << ". Play with your pet." << endl;
		cout << QUIT << ". Quit your pet." << endl;
		cout << "What would you like to do?" << endl << ":";
		int menuSelection;
		cin >> menuSelection;
		//cls();
		switch (menuSelection)
		{
		case TALK:
			talk();
			break;
		case FEED:
			feedPet((((rand()%509)*(rand()%349))%4));
			break;
		case PLAY:
			play((((rand()%509)*(rand()%349))%4));
			break;
		case QUIT:
			goto qOut;
		default:
			break;
		}
	}
qOut:;
}

/******************************************************************************
 * Function: FeedPet(int)                                                     *
 * Abstract: Feeds the pet. By default it will decrease the hungerlevel by    *
 *           one. If the food parameter is less-than or equal to 0 the        *
 *           food parameter becomes one. If the food parameter is greater     *
 *           than four, the food parameter becomes four. If the hunger level  *
 *           is less-than the food parameter, the hunger parameter is set to 0*
 *****************************************************************************/
void Pet::feedPet(int food)
{
	if (food > 4)
		food = 4;
	if (food <= 0)
		food = 1;

	if (getHungerLevel() < food)
		setHungerLevel(getHungerLevel()-getHungerLevel());
	else
		setHungerLevel(getHungerLevel()-food);

	cout << getName() << " has been fed " << food << " pellets of food" << endl;
	passTime();
	displayPetBehavior();
}

/******************************************************************************
 * Function: petmood()                                                        *
 * Abstract: Returns the boredomlevel + the hungerlevel of the pet.           *
 *****************************************************************************/
int Pet::petMood()
{
	return getBoredomLevel() + getHungerLevel();
}

/******************************************************************************
 * Function: passtime(int = 1)                                                *
 * Abstract: Increases the hungerlevel and boredom level by the time param    *
 *****************************************************************************/
void Pet::passTime(int time)
{
	setHungerLevel(getHungerLevel()+time);
	setBoredomLevel(getBoredomLevel()+time);
}

/******************************************************************************
 * Function: displaypetbehavior()                                             *
 * Abstract: Displays the statistics of the pet. This function will also      *
 *           display customized messages depending on the hunger and boredom  *
 *           levels of the pet. If the levels are less than 3, the pet is     *
 *           content. If the levels are between 3 and 11 the pet is a litle <>*
 *           if the levels are greater than 11, the pet is very <>.           *
 *****************************************************************************/
void Pet::displayPetBehavior()
{
	cout << "	Boredom: " << getBoredomLevel() << endl;
	cout << "	Hunger: " << getHungerLevel() << endl;
	if (getBoredomLevel() < 3 && getHungerLevel() < 3)
		cout << getName() << " is content" << endl;

	if ( getBoredomLevel() >= 3 && getBoredomLevel() < 11)
		cout << getName() << " is a litte bored" << endl;
	else if (getBoredomLevel() >= 11)
		cout << getName() << " is very bored" << endl;

	if ( getHungerLevel() >= 3 && getHungerLevel() < 11)
		cout << getName() << " is a litte hungry" << endl;
	else if (getHungerLevel() >= 11)
		cout << getName() << " is very hungry" << endl;
	cout << endl;
}

/******************************************************************************
 * Function: talk()                                                           *
 * Abstract: Displays the 'mood' of the pet. This function displays customized*
 *           messages to the user depending on the return value of the petmood*
 *           function. If the petmood is less than 7, the pet is feeling happy*
 *           If the pet mood is between 6 and 16 then the pet is feeling okay *
 *           If the pet mood is greater than 21 then the pet is feeling bad   *
 *****************************************************************************/
void Pet::talk()
{
	if (petMood() < 7)
		cout << getName() << " is feeling happy!" << endl;
	else if (petMood() >= 7 && petMood() < 16)
		cout << "\t" << getName() << " is feeling okay." << endl;
	else if (petMood() >=16 && petMood() < 21)
		cout << "\t" << getName() << " is feeling fustrated." << endl;
	else
		cout << "\t" << getName() << " is feeling mad!" << endl;
	passTime();
	displayPetBehavior();

}

/******************************************************************************
 * Function: play(int = 0)                                                    *
 * Abstract: Plays with the pet. by default it will decreade the hungerlevel  *
 *           by one. If the play parameter is lessthan or equalto 0 the play  *
 *           parameter becomes one. If the play parameter is greaterthan four *
 *           then the play parameter becomes four. If the boredom level is    *
 *           lessthan the play parameter, the boredom parameter is set to zero*
 *****************************************************************************/
void Pet::play(int play)
{
	if (play > 4)
		play = 4;
	if (play <= 0)
		play = 1;
	if (getBoredomLevel() < play)
		setBoredomLevel(getBoredomLevel()-getBoredomLevel());
	else
		setBoredomLevel(getBoredomLevel()-play);
	cout << getName() << " had " << play << " hours of fun." << endl;
	passTime();
	displayPetBehavior();

}

/******************************************************************************
 * Function: run()                                                            *
 * Abstract: Called by MAIN. Starts the program. If the menu loop has exited  *
 *           assume the pet is dead and call killed pet. Ask the user if they *
 *           would like to play again. Exit if the user says no.              *
 *****************************************************************************/
void Pet::run()
{
	while (true)
	{
		menu();
		killedPet();
		cout << "Would you like to play again?" << endl << ":[Y/n]";
		char choice;
		cin >> choice;
		if (choice == 'n' || choice == 'N')
			break;
	}
}

/******************************************************************************
 * Function: KilledPet()                                                      *
 * Abstract: Displays the final statisitcs for the pet. If the boredom level  *
 *           or the hunger level are over 21, assume the pet died of boredom  *
 *           or hunger. Calls petmood, getboredomlevel, gethungerlevel.       *
 *****************************************************************************/
void Pet::killedPet()
{
	cout << "You have killed your pet" << endl << "Your pets' final statistics were: " << endl;
	cout << "	Boredom: " << getBoredomLevel() << endl;
	cout << "	Hunger: " << getHungerLevel() << endl;
	petMood();
	if (getBoredomLevel() <= 21)
		cout << "Your pet died of boredom." << endl;
	else if(getHungerLevel() <= 21)
		cout << "Your pet died of hunger." << endl;
	cout << endl;
}

/******************************************************************************
 * Function: cls()                                                            *
 * Abstract: Clears the screen. Buggy. Not used. Here for historical reasons. *
 *****************************************************************************/
void Pet::cls()
{
	cout << endl << endl << endl << endl << endl << endl << endl;
	cout << endl << endl << endl << endl << endl << endl << endl;
	cout << endl << endl << endl << endl << endl << endl << endl;
	cout << endl << endl << endl << endl << endl;
}


text:
package chapter05.tools;

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CompletionServiceTest {

	public static void main(String []args) throws InterruptedException, ExecutionException {
		final Random random = new Random();
		ExecutorService executorService = Executors.newFixedThreadPool(10);
		CompletionService<String>completionService = new ExecutorCompletionService<String>(executorService);
		for(int i = 0 ; i < 100 ; i++) {
			final int num = i;
			completionService.submit(new Callable<String>() {
				public String call() {
					try {
						Thread.sleep((random.nextLong()) & 5000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					return "a" + num;
				}
			});
		}
		for(int i = 0 ; i < 100 ; i++) {
			Future<String> f = completionService.take();
			System.out.println(f.get());
		}
		executorService.shutdown();
	}
}