text:
<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_activated="false"
        android:drawable="@drawable/ic_expert_settings_black"
        />
    <item
        android:state_activated="true"
        android:drawable="@drawable/ic_expert_settings_white"
        />
</selector>


text:
import { Map, fromJS } from 'immutable'

export const initialState = Map()

export const set = (state, { payload }) => fromJS(payload)

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace TypetalkSharp
{
    public interface IGetParameter
    {
        string ToEncodedParameter();
    }

    public interface IFormParameter
    {
        FormUrlEncodedContent ToFormUrlEncodedContent();
    }
}


text:
void vd::Debug::Log(const std::string &message) {
    std::cout << message << std::endl;
}


text:
package org.spongepowered.api.stats;

/**
 * An enumeration of all available {@link Statistic}s from the vanilla game.
 */
public final class Statistics {

    public static final Statistic ANIMALS_BRED = null;
    public static final Statistic ARMOR_CLEANED = null;
    public static final Statistic BANNER_CLEANED = null;
    public static final Statistic BEACON_INTERACTION = null;
    public static final Statistic BOAT_DISTANCE = null;
    public static final Statistic BREWINGSTAND_INTERACTION = null;
    public static final Statistic CAKE_SLICES_EATEN = null;
    public static final Statistic CAULDRON_FILLED = null;
    public static final Statistic CAULDRON_USED = null;
    public static final Statistic CHEST_OPENED = null;
    public static final Statistic CLIMB_DISTANCE = null;
    public static final Statistic CRAFTING_TABLE_INTERACTION = null;
    public static final Statistic CROUCH_DISTANCE = null;
    public static final Statistic DAMAGE_DEALT = null;
    public static final Statistic DAMAGE_TAKEN = null;
    public static final Statistic DEATHS = null;
    public static final Statistic DISPENSER_INSPECTED = null;
    public static final Statistic DIVE_DISTANCE = null;
    public static final Statistic DROPPER_INSPECTED = null;
    public static final Statistic ENDERCHEST_OPENED = null;
    public static final Statistic FALL_DISTANCE = null;
    public static final Statistic FISH_CAUGHT = null;
    public static final Statistic FLOWER_POTTED = null;
    public static final Statistic FURNACE_INTERACTION = null;
    public static final Statistic FLY_DISTANCE = null;
    public static final Statistic HOPPER_INSPECTED = null;
    public static final Statistic HORSE_DISTANCE = null;
    public static final Statistic ITEMS_DROPPED = null;
    public static final Statistic ITEMS_ENCHANTED = null;
    public static final Statistic NOTEBLOCK_PLAYED = null;
    public static final Statistic NOTEBLOCK_TUNED = null;
    public static final Statistic JUMP = null;
    public static final Statistic JUNK_FISHED = null;
    public static final Statistic LEAVE_GAME = null;
    public static final Statistic MINECART_DISTANCE = null;
    public static final Statistic MOB_KILLS = null;
    public static final Statistic PIG_DISTANCE = null;
    public static final Statistic PLAYER_KILLS = null;
    public static final Statistic TIME_PLAYED = null;
    public static final Statistic RECORD_PLAYED = null;
    public static final Statistic SPRINT_DISTANCE = null;
    public static final Statistic SWIM_DISTANCE = null;
    public static final Statistic TALKED_TO_VILLAGER = null;
    public static final Statistic TIME_SINCE_DEATH = null;
    public static final Statistic TRADED_WITH_VILLAGER = null;
    public static final Statistic TRAPPED_CHEST_TRIGGERED = null;
    public static final Statistic TREASURE_FISHED = null;
    public static final Statistic WALK_DISTANCE = null;

    private Statistics() {
    }

    /**
     * Checks if this is a flowerpot.
     *
     * @return Whether this is a flowerpot
     */
    public static boolean isFlowerPot() {
        return false;
    }
}


text:
import {getLengthNumeral, isLayoutSizeDefined} from '../../../src/layout';
import * as st from '../../../src/style';

class AmpFitText extends AMP.BaseElement {

  /** @override */
  isLayoutSupported(layout) {
    return isLayoutSizeDefined(layout);
  }

  /** @override */
  isReadyToBuild() {
    return this.element.firstChild != null;
  }

  /** @override */
  buildCallback() {
    var childNodes = this.getRealChildNodes();

    /** @private @const */
    this.content_ = document.createElement('div');
    this.applyFillContent(this.content_);
    this.content_.classList.add('-amp-fit-text-content');
    st.setStyles(this.content_, {zIndex: 2});

    /** @private @const */
    this.measurer_ = document.createElement('div');
    // Note that "measurer" cannot be styled with "bottom:0".
    st.setStyles(this.measurer_, {
      position: 'absolute',
      top: 0,
      left: 0,
      right: 0,
      zIndex: 1,
      visibility: 'hidden'
    });

    this.getRealChildNodes().forEach((node) => {
      this.content_.appendChild(node);
    });
    this.measurer_./*OK*/innerHTML = this.content_./*OK*/innerHTML;
    this.element.appendChild(this.content_);
    this.element.appendChild(this.measurer_);

    /** @private @const {number} */
    this.minFontSize_ = getLengthNumeral(this.element.getAttribute(
        'min-font-size')) || 6;

    /** @private @const {number} */
    this.maxFontSize_ = getLengthNumeral(this.element.getAttribute(
        'max-font-size')) || 72;
  }

  /** @override */
  prerenderAllowed() {
    return true;
  }

  /** @override */
  isRelayoutNeeded() {
    return true;
  }

  /** @override */
  layoutCallback() {
    this.updateFontSize_();
    return Promise.resolve();
  }

  /** @private */
  updateFontSize_() {
    // TODO(dvoytenko): Add ellipsis if the content is still bigger than
    // the available size. Ensure that basic tags are supported when
    // doing the truncation?
    this.content_.style.fontSize = st.px(calculateFontSize_(this.measurer_,
        this.element.offsetHeight, this.minFontSize_, this.maxFontSize_));
  }
}

/**
 * @param {!Element} measurer
 * @param {number} expectedHeight
 * @param {number} minFontSize
 * @param {number} maxFontSize
 * @private  Visible for testing only!
 */
export function calculateFontSize_(measurer, expectedHeight,
    minFontSize, maxFontSize) {
  maxFontSize++;
  // Binomial search for the best font size.
  while (maxFontSize - minFontSize > 1) {
    let mid = Math.floor((minFontSize + maxFontSize) / 2);
    measurer.style.fontSize = st.px(mid);
    let height = measurer.offsetHeight;
    if (height > expectedHeight) {
      maxFontSize = mid;
    } else {
      minFontSize = mid;
    }
  }
  return minFontSize;
}

AMP.registerElement('amp-fit-text', AmpFitText, $CSS$);


text:
package org.bosphorus.core.expression.aggregate.executor.math;

import org.bosphorus.core.expression.aggregate.executor.IAggregateExecutor;

public class SumFloatExecutor implements IAggregateExecutor<Number, Float> {
	private Float sum;

	public SumFloatExecutor() {
		this.reset();
	}

	@Override
	public void execute(Number input) throws Exception {
		sum += input.floatValue();
	}

	@Override
	public Float getValue() {
		return sum;
	}

	@Override
	public void reset() {
		sum = 0.0F;
	}

	@Override
	public Object getState() {
		return this.sum;
	}

	@Override
	public void setState(Object state) throws Exception {
		this.sum = (Float)state;
	}

}


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>org.apache.taverna.scufl2.rdfxml.impl (Apache Taverna Language APIs (Scufl2, Databundle) 0.16.1-incubating-SNAPSHOT API)</title>
<meta name="date" content="2015-01-22">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

org.apache.taverna.scufl2.rdfxml.impl

Classes

NamespacePrefixMapperJAXB_RI


text:
function saveFeedback()  {
	var feedback = new FHQFeedback();
	// alert(createUrlFromObj(feedback.params()));
	send_request_post(
		'api/feedback/update.php',
		createUrlFromObj(feedback.params()),
		function (obj) {
			if (obj.result == "ok") {
				closeModalDialog();
				loadFeedback();
			} else {
				alert(obj.error.message);
			}
		}
	);
}

function formInsertFeedbackMessage(feedbackid) {
	var pt = new FHQParamTable();
	pt.row('Message:', fhqgui.textedit('newfeedbackmessage_text', ''));
	pt.right(fhqgui.btn('Add', 'insertFeedbackMessage(' + feedbackid + ');'));
	fhqgui.showModalDialog(pt.render());
}

function insertFeedbackMessage(feedbackid)
{
	var params = {};
	params["feedbackid"] = feedbackid;
	params["text"] = document.getElementById("newfeedbackmessage_text").value;
// 	alert(createUrlFromObj(params));
	send_request_post(
		'api/feedback/insertmessage.php',
		createUrlFromObj(params),
		function (obj) {
			if (obj.result == "ok") {
				closeModalDialog();
				loadFeedback();
			} else {
				alert(obj.error.message);
			}
		}
	);
};

function deleteFeedback(id)  {
	var params = {};
	params["id"] = id;
	// 	alert(createUrlFromObj(params));
	send_request_post(
		'api/feedback/delete.php',
		createUrlFromObj(params),
		function (obj) {
			if (obj.result == "ok") {
				closeModalDialog();
				loadFeedback();
			} else {
				alert(obj.error.message);
			}
		}
	);
}

function deleteConfirmFeedback(id) {
	var content = 'Are you sure that want remove this Feedback (and all answers)?
';
	content += '
YES!!!
';
	showModalDialog(content);
};

function formEditFeedback(id)  {
	var params = {};
	params["id"] = id;
	// 	alert(createUrlFromObj(params));
	send_request_post(
		'api/feedback/get.php',
		createUrlFromObj(params),
		function (obj) {
			if (obj.result == "ok") {
				FHQFeedback.type = 'error';
				var feedback = new FHQFeedback();
				feedback.show(obj.data);
			} else {
				alert(obj.error.message);
			}
		}
	);
}

function deleteFeedbackMessage(id)  {
	var params = {};
	params["id"] = id;
	// 	alert(createUrlFromObj(params));
	send_request_post(
		'api/feedback/deletemessage.php',
		createUrlFromObj(params),
		function (obj) {
			if (obj.result == "ok") {
				closeModalDialog();
				loadFeedback();
			} else {
				alert(obj.error.message);
			}
		}
	);
}

function deleteConfirmFeedbackMessage(id) {
	var content = 'Are you sure that want remove this Feedback Message?
';
	content += '
YES!!!
';
	showModalDialog(content);
};

function saveFeedbackMessage(id)  {
	var params = {};
	params["id"] = id;
	params["text"] = document.getElementById("editfeedbackmessage_text").value;

	// 	alert(createUrlFromObj(params));
	send_request_post(
		'api/feedback/updatemessage.php',
		createUrlFromObj(params),
		function (obj) {
			if (obj.result == "ok") {
				closeModalDialog();
				loadFeedback();
			} else {
				alert(obj.error.message);
			}
		}
	);
}

function formEditFeedbackMessage(id)  {
	var params = {};
	params["id"] = id;
	// 	alert(createUrlFromObj(params));
	send_request_post(
		'api/feedback/getmessage.php',
		createUrlFromObj(params),
		function (obj) {
			if (obj.result == "ok") {
				var pt = new FHQParamTable();
				pt.row('Message:', fhqgui.textedit('editfeedbackmessage_text', obj.data.text));
				pt.right(fhqgui.btn('Save', 'saveFeedbackMessage(' + id + ');'));
				fhqgui.showModalDialog(pt.render());
			} else {
				alert(obj.error.message);
			}
		}
	);
}


text:
Copyright 2014 Google Inc. All rights reserved.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

# Image resizing in IOSched

Minimizing data traffic is an important requirement for any mobile app, in
special those used in an environment where Internet access is limited, like
a packed conference. But, on the other hand, rich session and speaker images
can make an app like IOSched easier to navigate and more beautiful, and even
help the conference attendees to identify speakers on the conference floor.

To satisfy those conflicting requirements, we implemented a scheme to serve
images in multiple sizes (defined by width, maintaining the aspect ratio).
One server-side script compresses, optimizes and resizes images to specific
buckets, saving them on computable variants of the original URL. On the
client side, an image loader detects a specially crafted pattern in the
image URL and requests the best image depending on the width of the
container where it will be rendered.

## Decoupling

To avoid high coupling between the image resizing scheme on the server and
the Android app, the image URL is crafted in a way that the information
about the available buckets is carried in it, allowing the server to
dynamically change the buckets of images without requiring changes to the
Android side. Also, if the client has no knowledge of this special URL, for
example an old version of the Android app, the URL without any special
handling should serve the full size image.

## Adaptive image URL format

Any image URL that matches the following (simplified) regexp is considered
an adaptive image URL: `.*__w(-\d+)+__.*`

For example:

myserver.com/images/__w-200-400-600-800-1000__/session1.jpg

As mentioned before, by convention this encoded URL will serve the full size
image. To get the image restricted to width 200px, replace `__w-...__` by
"**w200**":

myserver.com/images/w200/session1.jpg

And for 400px of width:

myserver.com/images/w400/session1.jpg

As one can guess, the widths that an image has been resized to are the numbers
delimited by dashes between `__w-` and `__`. The URL

myserver.com/images/__w-200-400-600-800-1000__/session1.jpg

Means that this image can be fetched at any of the following URLs:

URL | Image size
--- | ----------
myserver.com/images/**__w-200-400-600-800-1000__**/session1.jpg | original
myserver.com/images/w200/session1.jpg | 200px wide
myserver.com/images/w400/session1.jpg | 400px wide
myserver.com/images/w600/session1.jpg | 600px wide
myserver.com/images/w800/session1.jpg | 800px wide
myserver.com/images/w1000/session1.jpg | 1000px wide

## On the server side

We decided to process the images offline and serve them statically, in order
to improve scalability and reliability, but a dynamic server would also
work.

Every new or changed session has its image converted to JPG, compressed at
0.8 quality factor, resized to the appropriate buckets and then saved to
Cloud Storage. This is all achieved by a simple Bash script running as a
cron job.  The result is a directory structure like:

    /__w-200-400-600__/session1.jpg
    /__w-200-400-600__/session2.jpg
    /__w-200-400-600__/session3.jpg
    /w200/session1.jpg
    /w200/session2.jpg
    /w200/session3.jpg
    /w400/session1.jpg
    /w400/session2.jpg
    /w400/session3.jpg
    /w600/session1.jpg
    /w600/session2.jpg
    /w600/session3.jpg

We save this directory structure to Google Cloud Storage and update whenever
a session or a speaker changes its photo.

# On the Android app

Every remote image in IOSched is loaded through a special library, [Glide](https://github.com/bumptech/glide),
that appropriately handles asynchronous loading and caching. We extended
Glide with a custom [ImageLoader](../android/src/main/java/com/google/samples/apps/iosched/util/ImageLoader.java) that understands our
adaptive URL format. In particular, the inner class VariableWidthImageLoader
contains the following snippet:

```Java
private static final Pattern PATTERN =
      Pattern.compile("__w-((?:-?\\d+)+)__");

@Override
protected String getUrl(String model, int width, int height) {
    Matcher m = PATTERN.matcher(model);
    int bestBucket = 0;
    if (m.find()) {
        String[] found = m.group(1).split("-");
        for (String bucketStr : found) {
            bestBucket = Integer.parseInt(bucketStr);
            if (bestBucket >= width) {
                // the best bucket is the first immediately
                // bigger than the requested width
                break;
            }
        }
        if (bestBucket > 0) {
            model = m.replaceFirst("w"+bestBucket);
        }
    }
    return model;
}
```

The logic is very simple: whenever an image is about to
be loaded, this code checks if the image URL contains the specific pattern.
If so, it is broken into pieces to find the available bucket widths that the
image is available on, and the first bucket bigger than or equals to the
container width (represented by the parameter `width`) is used. The URL
is changed to the w<bucket> version and the async loading continues as usual.


text:
// .NAME vtkArcSource - create a circular arc

// .SECTION Description
// vtkArcSource is a source object that creates an arc defined by two
// endpoints and a center. The number of segments composing the polyline
// is controlled by setting the object resolution.
// Alternatively, one can use a better API (that does not allow for
// inconsistent nor ambiguous inputs), using a starting point (polar vector,
// measured from the arc's center), a normal to the plane of the arc,
// and an angle defining the arc length.
// Since the default API remains the original one, in order to use
// the improved API, one must switch the UseNormalAndAngle flag to TRUE.

// The development of an improved, consistent API (based on point, normal,
// and angle) was supported by CEA/DIF - Commissariat a l'Energie Atomique,
// Centre DAM Ile-De-France, BP12, F-91297 Arpajon, France, and implemented
// by Philippe Pebay, Kitware SAS 2012.

// .SECTION See Also
// vtkEllipseArcSource

#ifndef vtkArcSource_h
#define vtkArcSource_h

#include "vtkFiltersSourcesModule.h" // For export macro
#include "vtkPolyDataAlgorithm.h"

class VTKFILTERSSOURCES_EXPORT vtkArcSource : public vtkPolyDataAlgorithm
{
public:
  static vtkArcSource *New();
  vtkTypeMacro(vtkArcSource,vtkPolyDataAlgorithm);
  void PrintSelf(ostream& os, vtkIndent indent);

  // Description:
  // Set position of the first end point.
  vtkSetVector3Macro(Point1,double);
  vtkGetVectorMacro(Point1,double,3);

  // Description:
  // Set position of the other end point.
  vtkSetVector3Macro(Point2,double);
  vtkGetVectorMacro(Point2,double,3);

  // Description:
  // Set position of the center of the circle that defines the arc.
  // Note: you can use the function vtkMath::Solve3PointCircle to
  // find the center from 3 points located on a circle.
  vtkSetVector3Macro(Center,double);
  vtkGetVectorMacro(Center,double,3);

  // Description:
  // Set the normal vector to the plane of the arc.
  // By default it points in the positive Z direction.
  // Note: This is only used when UseNormalAndAngle is ON.
  vtkSetVector3Macro(Normal,double);
  vtkGetVectorMacro(Normal,double,3);

  // Description:
  // Set polar vector (starting point of the arc).
  // By default it is the unit vector in the positive X direction.
  // Note: This is only used when UseNormalAndAngle is ON.
  vtkSetVector3Macro(PolarVector,double);
  vtkGetVectorMacro(PolarVector,double,3);

  // Description:
  // Arc length (in degrees), beginning at the polar vector.
  // The direction is counterclockwise by default;
  // a negative value draws the arc in the clockwise direction.
  // Note: This is only used when UseNormalAndAngle is ON.
  vtkSetClampMacro(Angle,double,-360.0,360.0);
  vtkGetMacro(Angle,double);

  // Description:
  // Define the number of segments of the polyline that draws the arc.
  // Note: if the resolution is set to 1 (the default value),
  // the arc is drawn as a straight line.
  vtkSetClampMacro(Resolution,int,1,VTK_INT_MAX);
  vtkGetMacro(Resolution,int);

  // Description:
  // By default the arc spans the shortest angular sector point1 and point2.
  // By setting this to true, the longest angular sector is used instead
  // (i.e. the negative coterminal angle to the shortest one).
  // Note: This is only used when UseNormalAndAngle is OFF. False by default.
  vtkSetMacro(Negative, bool);
  vtkGetMacro(Negative, bool);
  vtkBooleanMacro(Negative, bool);

  // Description:
  // Activate the API based on a normal vector, a starting point
  // (polar vector) and an angle defining the arc length.
  // The previous API (which remains the default) allows for inputs that are
  // inconsistent (when Point1 and Point2 are not equidistant from Center)
  // or ambiguous (when Point1, Point2, and Center are aligned).
  // Note: false by default.
  vtkSetMacro(UseNormalAndAngle, bool);
  vtkGetMacro(UseNormalAndAngle, bool);
  vtkBooleanMacro(UseNormalAndAngle, bool);

  // Description:
  // Set/get the desired precision for the output points.
  // vtkAlgorithm::SINGLE_PRECISION - Output single-precision floating point.
  // vtkAlgorithm::DOUBLE_PRECISION - Output double-precision floating point.
  vtkSetMacro(OutputPointsPrecision,int);
  vtkGetMacro(OutputPointsPrecision,int);

protected:
  vtkArcSource(int res=1);
  ~vtkArcSource() {}

  int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *);
  int RequestInformation(vtkInformation *, vtkInformationVector **, vtkInformationVector *);
  double Point1[3];
  double Point2[3];
  double Center[3];
  double Normal[3];
  double PolarVector[3];
  double Angle;
  int Resolution;
  bool Negative;
  bool UseNormalAndAngle;
  int OutputPointsPrecision;

private:
  vtkArcSource(const vtkArcSource&) VTK_DELETE_FUNCTION;
  void operator=(const vtkArcSource&) VTK_DELETE_FUNCTION;
};

#endif


text:
typedef NS_ENUM(NSInteger, SYMLMarkdownParserLineType) {
	SYMLMarkdownParserLineTypeNormal,
	SYMLMarkdownParserLineTypeBlockquote,
	SYMLMarkdownParserLineTypeBlockcode,
	SYMLMarkdownParserLineTypeList,
	SYMLMarkdownParserLineTypeLink
};

struct SYMLMarkdownParserState {
	// Parse options
	NSInteger maximumRecursionDepth;
	BOOL shouldParseMarkdown;

	// Block elements
	BOOL shouldParseHeadings;
	BOOL shouldParseBlockquotes;
	BOOL shouldParseBlockcode;
	BOOL shouldParseHorizontalRule;
	BOOL shouldParseLists;

	// Inline elements
	BOOL shouldParseLinks;
	BOOL shouldParseEmphasisAndStrongTags;
	BOOL shouldParseHTMLTags;

	// Used internally to keep track of the parsing
	NSInteger textLength;
	NSRange searchRange;
	NSInteger currentRecursionDepth;

	// Cache respondToSelector: queries
	BOOL hasHeadingAttributes;
	BOOL hasHorizontalRuleAttributes;
	BOOL hasBlockquoteAttributes;
	BOOL hasListElementAttributes;
	BOOL hasListLineAttributes;
	BOOL hasEmphasisAttributes;
	BOOL hasStrongAttributes;
	BOOL hasLinkAttributes;
	BOOL hasLinkTitleAttributes;
	BOOL hasLinkTagAttributes;
	BOOL hasLinkURLAttributes;
	BOOL hasInvalidLinkAttributes;

	// The state that is passed on from state to state
	SYMLMarkdownParserLineType previousLineType;
};

typedef struct SYMLMarkdownParserState SYMLMarkdownParserState;

SYMLMarkdownParserState SYMLDefaultMarkdownParserState();
BOOL SYMLMarkdownParserStateInitialConditionsAreEqual(SYMLMarkdownParserState firstState, SYMLMarkdownParserState secondState);

// Returns the state after parsing has completed
SYMLMarkdownParserState SYMLParseMarkdown(NSString *inputString, id <SYMLAttributedObjectCollection> *result, SYMLMarkdownParserState parseState, id <SYMLMarkdownParserAttributes> attributes);


text:
import os

BOT_NAME = 'price_monitor'
SPIDER_MODULES = ['price_monitor.spiders']
NEWSPIDER_MODULE = 'price_monitor.spiders'

ROBOTSTXT_OBEY = True

SHUB_KEY = os.getenv('$SHUB_KEY')
# if you want to run it locally, replace '999999' by your Scrapy Cloud project ID below
SHUB_PROJ_ID = os.getenv('SHUB_JOBKEY', '999999').split('/')[0]

# settings for Amazon SES email service
AWS_ACCESS_KEY = os.getenv('$AWS_ACCESS_KEY')
AWS_SECRET_KEY = os.getenv('$AWS_SECRET_KEY')
EMAIL_ALERT_FROM = 'Price Monitor <SENDER_EMAIL@provider.com>'
EMAIL_ALERT_TO = ['RECEIVER_EMAIL@provider.com']

# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
    'price_monitor.pipelines.CollectionStoragePipeline': 400,
}

AUTOTHROTTLE_ENABLED = True
# HTTPCACHE_ENABLED = True


text:
import {
  Input,
  Component,
  OnChanges,
  OnInit,
  ChangeDetectionStrategy,
  ChangeDetectorRef
} from '@angular/core';
import { Store } from '@ngrx/store';
import { State } from '../../app.reducer';
import { getCalendarFilters, Filters } from '../calendar.reducer';
import {
  CALENDAR_ACTIONS
} from '../calendar.constants';
let template = require('./calendar-form.html');

@Component({
  selector: 'calendar-form',
  template: template,
  styleUrls: ['./calendar-form.css'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class CalendarForm implements OnInit, OnChanges {

  metricSelected: string;
  @Input() metric: string;
  @Input() year: number;
  years: any = [
    { value: '2016', name: '2016' },
    { value: '2017', name: '2017' },
    { value: '2018', name: '2018' },
    { value: '2019', name: '2019' }
  ];

  constructor(private store: Store<State>) { }

  ngOnInit() {
    this.metricSelected = this.metric;
  }

  ngOnChanges() {
    this.metricSelected = this.metric;
  }

  setMetric(value) {
    this.store.dispatch({
      type: CALENDAR_ACTIONS.SELECT_METRIC,
      payload: value
    });
  }

  setYear(value) {
    this.store.dispatch({
      type: CALENDAR_ACTIONS.SELECT_YEAR,
      payload: value
    });
  }
}


text:
<?php declare(strict_types=1);
/**
 * @license MIT
 * @author Samuel Adeshina <samueladeshina73@gmail.com>
 *
 * This file is part of the EmmetBlue project, please read the license document
 * available in the root level of the project
 */
namespace EmmetBlue\Plugins\Consultancy;

use EmmetBlue\Core\Builder\BuilderFactory as Builder;
use EmmetBlue\Core\Factory\DatabaseConnectionFactory as DBConnectionFactory;
use EmmetBlue\Core\Builder\QueryBuilder\QueryBuilder as QB;
use EmmetBlue\Core\Exception\SQLException;
use EmmetBlue\Core\Exception\UndefinedValueException;
use EmmetBlue\Core\Session\Session;
use EmmetBlue\Core\Logger\DatabaseLog;
use EmmetBlue\Core\Logger\ErrorLog;
use EmmetBlue\Core\Constant;

/**
 * class PatientonsultationSheet.
 *
 * Allergy Controller
 *
 * @author Samuel Adeshina <samueladeshina73@gmail.com>
 * @since v0.0.1 20/08/2016 03:29AM
 */
class Allergy
{
    /**
     * Creates a new Consultancy sheet
     *
     * @param $_POST
     */
    public static function newAllergy(array $data)
    {
        $result = Allergy\Allergy::create($data);

        return $result;
    }

    /**
     * Selects Allergy
     */
    public static function viewAllergy(int $resourceId=0)
    {
        $result = Allergy\Allergy::view($resourceId);

        return $result;
    }

    /**
     * edit Allergy
     */
    public static function editAllergy(int $resourceId=0, array $data)
    {
        $result = Allergy\Allergy::editAllergy($resourceId, $data);

        return $result;
    }

    /**
     * Deletes a Allergy
     */
    public static function deleteAllergy(int $resourceId)
    {
        $result = Allergy\Allergy::delete($resourceId);

        return $result;
    }
}


text:
package jme3test.post;

import com.jme3.input.InputManager;
import com.jme3.input.KeyInput;
import com.jme3.input.controls.ActionListener;
import com.jme3.input.controls.AnalogListener;
import com.jme3.input.controls.KeyTrigger;
import com.jme3.post.filters.LightScatteringFilter;

/**
 *
 * @author nehon
 */
public class LightScatteringUI {
    private LightScatteringFilter filter;
    public LightScatteringUI(InputManager inputManager, LightScatteringFilter proc) {
        filter=proc;

        System.out.println("----------------- LightScattering UI Debugger --------------------");
        System.out.println("-- Sample number : press Y to increase, H to decrease");
        System.out.println("-- blur start : press U to increase, J to decrease");
        System.out.println("-- blur width : press I to increase, K to decrease");
        System.out.println("-- Light density : press O to increase, P to decrease");
//        System.out.println("-- Toggle AO on/off : press space bar");
//        System.out.println("-- Use only AO : press Num pad 0");
//        System.out.println("-- Output config declaration : press P");
        System.out.println("-------------------------------------------------------");

        inputManager.addMapping("sampleUp", new KeyTrigger(KeyInput.KEY_Y));
        inputManager.addMapping("sampleDown", new KeyTrigger(KeyInput.KEY_H));
        inputManager.addMapping("blurStartUp", new KeyTrigger(KeyInput.KEY_U));
        inputManager.addMapping("blurStartDown", new KeyTrigger(KeyInput.KEY_J));
        inputManager.addMapping("blurWidthUp", new KeyTrigger(KeyInput.KEY_I));
        inputManager.addMapping("blurWidthDown", new KeyTrigger(KeyInput.KEY_K));
        inputManager.addMapping("lightDensityUp", new KeyTrigger(KeyInput.KEY_O));
        inputManager.addMapping("lightDensityDown", new KeyTrigger(KeyInput.KEY_L));
        inputManager.addMapping("outputConfig", new KeyTrigger(KeyInput.KEY_P));
//        inputManager.addMapping("toggleUseAO", new KeyTrigger(KeyInput.KEY_SPACE));
//        inputManager.addMapping("toggleUseOnlyAo", new KeyTrigger(KeyInput.KEY_NUMPAD0));

        ActionListener acl = new ActionListener() {

            public void onAction(String name, boolean keyPressed, float tpf) {

                if (name.equals("sampleUp")) {
                    filter.setNbSamples(filter.getNbSamples()+1);
                    System.out.println("Nb Samples : "+filter.getNbSamples());
                }
                if (name.equals("sampleDown")) {
                   filter.setNbSamples(filter.getNbSamples()-1);
                   System.out.println("Nb Samples : "+filter.getNbSamples());
                }
                if (name.equals("outputConfig") && keyPressed) {
                   System.out.println("lightScatteringFilter.setNbSamples("+filter.getNbSamples()+");");
                   System.out.println("lightScatteringFilter.setBlurStart("+filter.getBlurStart()+"f);");
                   System.out.println("lightScatteringFilter.setBlurWidth("+filter.getBlurWidth()+"f);");
                   System.out.println("lightScatteringFilter.setLightDensity("+filter.getLightDensity()+"f);");
                }

            }
        };

         AnalogListener anl = new AnalogListener() {

            public void onAnalog(String name, float value, float tpf) {

                if (name.equals("blurStartUp")) {
                    filter.setBlurStart(filter.getBlurStart()+0.001f);
                    System.out.println("Blur start : "+filter.getBlurStart());
                }
                if (name.equals("blurStartDown")) {
                    filter.setBlurStart(filter.getBlurStart()-0.001f);
                    System.out.println("Blur start : "+filter.getBlurStart());
                }
                 if (name.equals("blurWidthUp")) {
                    filter.setBlurWidth(filter.getBlurWidth()+0.001f);
                    System.out.println("Blur Width : "+filter.getBlurWidth());
                }
                if (name.equals("blurWidthDown")) {
                    filter.setBlurWidth(filter.getBlurWidth()-0.001f);
                    System.out.println("Blur Width : "+filter.getBlurWidth());
                }
                if (name.equals("lightDensityUp")) {
                    filter.setLightDensity(filter.getLightDensity()+0.001f);
                    System.out.println("light Density : "+filter.getLightDensity());
                }
                if (name.equals("lightDensityDown")) {
                     filter.setLightDensity(filter.getLightDensity()-0.001f);
                    System.out.println("light Density : "+filter.getLightDensity());
                }

            }
        };
        inputManager.addListener(acl,"sampleUp","sampleDown","outputConfig");

        inputManager.addListener(anl, "blurStartUp","blurStartDown","blurWidthUp", "blurWidthDown","lightDensityUp", "lightDensityDown");

    }

}


text:
typedef	unsigned int atypedef;
struct astruct{};
void afunction();
void aovlfunction();
void aovlfunction(int);
int avariable;

namespace foo {
  using ::atypedef;
  using ::astruct;
  using ::afunction;
  using ::aovlfunction;
  using ::avariable;
}


text:
This repo contains materials for a 90-minute introductory D3 guest lecture with the Spring Data Science Immersive at [General Assembly DC](https://generalassemb.ly/education/data-science-immersive).

# Getting Started
1. [Download Brackets](http://brackets.io/)
    > After installing: open --> click on brick on right --> search for 'Emmet' --> install

2. Create a folder for today's D3 project (i.e. documents/d3-intro)

# Session Goals
- Introducing key vocabulary and concepts of visualization library D3.js
- Identifying fundamentals of writing code for the web
- Creating an example visualization using D3
- Preparing to make use of the vast library of D3 resources and knowledge available to you

![header](https://github.com/ayrenay/d3-rough-sketches-class/blob/master/rough-sketches-cover.PNG)


text:
layout: post #
title: 205 Emocions # Generat automàticament
date: 2018-02-25 # Data
description:  # Argument
keywords: emocions # Paraules clau
coments:  # Comentaris
---

Els dos antídos

per superar

el **dubte** i

la **por**, son

el **valor** i

la **confiança**.

Bryan Traci


text:
#ifndef __SCENE_H__
#define __SCENE_H__

/** @ingroup game
 * @{
 */

/// Interface for scenes in the game, eg. title screen or in-game.
class Scene {
	public:
		/// Returned when the scene has ended. Defines what should be done next.
		/**
		* Sample usage:
		* \code{.cpp}
		* SceneEnd* ExampleScene::update(double time) {
		*     if (input::triggered(input::FORWARD))
		*         return new SceneEnd(SceneEnd::NEW_SCENE);
		*     return nullptr;
		* }
		* \endcode
		*/
		struct SceneEnd {
			public:
				/// Available commands.
				enum Command {
					/// Quit the game.
					QUIT = 0,
					/// Go to a new scene.
					NEW_SCENE
				};

				/// What to do next.
				Command command;

				/// Create a new SceneEnd and define what should be done next.
				/**
				 * @param command What to do.
				 */
				SceneEnd(Command command);

			private:
				SceneEnd();
		};

		/// Destructor
		virtual ~Scene() { }

		/// Update the scene.
		/**
		 * @param time Time since last frame (in seconds).
		 * @return SceneEnd-struct defining what to do next. nullptr if nothing should be done
		 */
		virtual SceneEnd* update(double time) = 0;

		/// Render the scene.
		/**
		 * @param width Width of the context.
		 * @param height Height of the context.
		 */
		virtual void render(int width, int height) = 0;
};

/** @} */

#endif


text:
<?php

namespace whm\Smoke\Rules\Html;

use Psr\Http\Message\ResponseInterface;
use whm\Html\Document;
use whm\Smoke\Rules\StandardRule;

abstract class CountRule extends StandardRule
{
    protected $maxCount;

    protected $contentTypes = array('text/html');

    protected $errorMessage;

    /**
     * @param int $maxCount The maximum number of css files that are allowed in one html document
     */
    public function init($maxCount)
    {
        $this->maxCount = $maxCount;
    }

    abstract protected function getFilesToCount(Document $document, ResponseInterface $response);

    protected function doValidation(ResponseInterface $response)
    {
        $document = new Document((string)$response->getBody());
        $files = $this->getFilesToCount($document, $response);

        $this->assert(count($files) <= $this->maxCount, sprintf($this->errorMessage, count($files)));
    }
}


text:
require 'spec_helper'

feature 'Project Activity RSS' do
  let(:project) { create(:empty_project, visibility_level: Gitlab::VisibilityLevel::PUBLIC) }
  let(:path) { activity_namespace_project_path(project.namespace, project) }

  before do
    create(:issue, project: project)
  end

  context 'when signed in' do
    before do
      user = create(:user)
      project.team << [user, :developer]
      login_as(user)
      visit path
    end

    it_behaves_like "it has an RSS button with current_user's private token"
  end

  context 'when signed out' do
    before do
      visit path
    end

    it_behaves_like "it has an RSS button without a private token"
  end
end


text:
<component name="libraryTable">
  <library name="SBT: org.apache.maven:maven-error-diagnostics:2.2.1:jar">
    <CLASSES>
      <root url="jar://$USER_HOME$/.ivy2/cache/org.apache.maven/maven-error-diagnostics/jars/maven-error-diagnostics-2.2.1.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://$USER_HOME$/.ivy2/cache/org.apache.maven/maven-error-diagnostics/docs/maven-error-diagnostics-2.2.1-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://$USER_HOME$/.ivy2/cache/org.apache.maven/maven-error-diagnostics/srcs/maven-error-diagnostics-2.2.1-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
package us.kbase.kbfastqc;

import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

/**
 *
Original spec-file type: FastQCParams

 *
 *
 */
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("com.googlecode.jsonschema2pojo")
@JsonPropertyOrder({
    "input_ws",
    "input_file",
    "input_file_ref"
})
public class FastQCParams {

    @JsonProperty("input_ws")
    private String inputWs;
    @JsonProperty("input_file")
    private String inputFile;
    @JsonProperty("input_file_ref")
    private String inputFileRef;
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    @JsonProperty("input_ws")
    public String getInputWs() {
        return inputWs;
    }

    @JsonProperty("input_ws")
    public void setInputWs(String inputWs) {
        this.inputWs = inputWs;
    }

    public FastQCParams withInputWs(String inputWs) {
        this.inputWs = inputWs;
        return this;
    }

    @JsonProperty("input_file")
    public String getInputFile() {
        return inputFile;
    }

    @JsonProperty("input_file")
    public void setInputFile(String inputFile) {
        this.inputFile = inputFile;
    }

    public FastQCParams withInputFile(String inputFile) {
        this.inputFile = inputFile;
        return this;
    }

    @JsonProperty("input_file_ref")
    public String getInputFileRef() {
        return inputFileRef;
    }

    @JsonProperty("input_file_ref")
    public void setInputFileRef(String inputFileRef) {
        this.inputFileRef = inputFileRef;
    }

    public FastQCParams withInputFileRef(String inputFileRef) {
        this.inputFileRef = inputFileRef;
        return this;
    }

    @JsonAnyGetter
    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }

    @JsonAnySetter
    public void setAdditionalProperties(String name, Object value) {
        this.additionalProperties.put(name, value);
    }

    @Override
    public String toString() {
        return ((((((((("FastQCParams"+" [inputWs=")+ inputWs)+", inputFile=")+ inputFile)+", inputFileRef=")+ inputFileRef)+", additionalProperties=")+ additionalProperties)+"]");
    }

}


text:
UPDATE [Customers$] SET
	Geocode_Location = '{Geocode_Location}'
WHERE
	CustID = '{CustID}'


text:
.. LetThereBe documentation master file, created by
   sphinx-quickstart on Wed Mar 29 09:35:31 2017.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to LetThereBe's documentation!
======================================

``LetThereBe`` automates the creation of a software project for collaborative development across any discipline to support best practice. It lowers the barrier for good practice development by providing an extension to `GitHub <https://github.com>`_ to generate an immediately usable project structure automatically.

.. toctree::
   :maxdepth: 1
   :caption: Contents:

   installation
   project_setup
   improve
   write_plugin
   contributing
   license


text:
"""Tests for Linux AtspiWrapper"""

import os
import sys
import unittest

if sys.platform.startswith("linux"):
    sys.path.append(".")
    from pywinauto.linux.atspi_element_info import AtspiElementInfo
    from pywinauto.linux.application import Application
    from pywinauto.controls.atspiwrapper import AtspiWrapper
    from pywinauto.linux.atspi_objects import IATSPI
    from pywinauto.linux.atspi_objects import POINT

app_name = r"gtk_example.py"

def _test_app():
    test_folder = os.path.join(os.path.dirname
                               (os.path.dirname
                                (os.path.dirname
                                 (os.path.abspath(__file__)))),
                               r"apps/Gtk_samples")
    sys.path.append(test_folder)
    return os.path.join(test_folder, app_name)

def print_tree(start_el_info, level_shifter=""):
    if level_shifter == "":
        print(start_el_info.control_type, "  ", start_el_info.control_id, "!")
        level_shifter += "-"

    for children in start_el_info.children():
        print(level_shifter, "  ", children.control_type, "    ", children.control_id, children.runtime_id, "!")
        print_tree(children, level_shifter + "-")

if sys.platform.startswith("linux"):
    class AtspiWrapperTests(unittest.TestCase):

        """Unit tests for the AtspiWrapper class"""

        def setUp(self):
            self.desktop_info = AtspiElementInfo()
            self.desktop_wrapper = AtspiWrapper(self.desktop_info)
            self.app = Application()
            self.app.start(_test_app())
            self.app_wrapper = self.app.gtk_example.find()
            self.app_frame = self.app.gtk_example.Frame

        def tearDown(self):
            self.app.kill()

        def test_set_focus(self):
            #TODO: make the app to be actually out focus
            states = self.app_frame.set_focus().get_states()
            self.assertIn("STATE_VISIBLE", states)
            self.assertIn("STATE_SHOWING", states)

        def test_top_level_parent_for_app_return_app(self):
            self.assertEqual(self.app_wrapper.top_level_parent().element_info.control_type, "Application")

        def test_top_level_parent_for_button_return_app(self):
            self.assertEqual(self.app_frame.Panel.top_level_parent().element_info.control_type,
                             "Application")

        def test_root_return_desktop(self):
            self.assertEqual(self.app_wrapper.root(), self.desktop_info)

        def test_class_name_return_element_info_class_name(self):
            self.assertEqual(self.app_wrapper.class_name(), "Application")

        def test_window_text(self):
            self.assertEqual(self.app_wrapper.window_text(), app_name)

        def test_control_id(self):
            self.assertEqual(self.app_wrapper.control_id(), IATSPI().known_control_types["Application"])

        def test_image(self):
            img_wrp = self.app_frame.Icon.find()
            self.assertEqual(img_wrp.description(), u'')
            self.assertEqual(img_wrp.class_name(), u"Icon")
            self.assertEqual(img_wrp.locale(), u'')
            self.assertEqual(img_wrp.size(), (48, 24))
            pos = img_wrp.position()
            self.assertAlmostEqual(pos.x, 408, delta=5)
            self.assertAlmostEqual(pos.y, 29, delta=5)
            bb = img_wrp.bounding_box()
            self.assertEqual(bb.left, pos.x)
            self.assertEqual(bb.top, pos.y)
            self.assertAlmostEqual(bb.right, 456, delta=5)
            self.assertAlmostEqual(bb.bottom, 53, delta=5)

        def test_can_get_rectangle(self):
            rect = self.app_frame.Panel.rectangle()
            self.assertEqual(rect.width(), 600)
            rect = self.app_frame.Icon.rectangle()
            self.assertAlmostEqual(rect.height(), 26, delta=2)

        def test_client_to_screen(self):
            rect = self.app_wrapper.rectangle()
            self.assertEqual(self.app_wrapper.client_to_screen((0, 0)),
                    (rect.left, rect.top))
            self.assertEqual(self.app_wrapper.client_to_screen(POINT(20, 20)),
                    (rect.left + 20, rect.top + 20))

        def test_can_get_process_id(self):
            self.assertEqual(self.app_wrapper.process_id(), self.app.process)

        def test_is_dialog_for_Application_is_true(self):
            self.assertTrue(self.app_wrapper.is_dialog())

        def test_is_dialog_for_button_is_false(self):
            self.assertFalse(self.app_frame.Panel.Click.is_dialog())

        def test_can_get_children(self):
            self.assertEqual(self.app_frame.control_id(), IATSPI().known_control_types["Frame"])

        def test_can_get_descendants(self):
            self.assertTrue(len(self.app_wrapper.descendants()) > len(self.app_wrapper.children()))

        def test_can_get_control_count(self):
            self.assertEqual(self.app_wrapper.control_count(), 1)

        def test_can_get_properties(self):
            props = self.app_wrapper.get_properties()
            self.assertEqual(props['class_name'], 'Application')
            self.assertEqual(props['friendly_class_name'], 'Application')
            self.assertEqual(props['control_id'], IATSPI().known_control_types["Application"])

        def test_app_is_child_of_desktop(self):
            self.assertTrue(self.app_wrapper.is_child(self.desktop_wrapper))

if __name__ == "__main__":
    unittest.main()


text:
module Locomotive
  module Liquid
    module Drops
      class Page < Base

        delegate :seo_title, :meta_keywords, :meta_description, :redirect_url, :handle, :layout, to: :@_source

        def title
          title =  @_source.templatized? ? @context['entry'].try(:_label) : nil
          title || @_source.title
        end

        def slug
          slug = @_source.templatized? ? @context['entry'].try(:_slug).try(:singularize) : nil
          slug || @_source.slug
        end

        def original_title
          @_source.title
        end

        def original_slug
          @_source.slug
        end

        def parent
          @parent ||= @_source.parent.to_liquid
        end

        def breadcrumbs
          @breadcrumbs ||= liquify(*@_source.ancestors_and_self)
        end

        def children
          @children ||= liquify(*@_source.children)
        end

        def fullpath
          @fullpath ||= @_source.fullpath
        end

        def depth
          @_source.depth
        end

        def listed?
          @_source.listed?
        end

        def published?
          @_source.published?
        end

        def redirect?
          @_source.redirect?
        end

        def is_layout?
          @_source.is_layout?
        end

        def templatized?
          @_source.templatized?
        end

        def content_type
          if @_source.content_type
            ContentTypeProxyCollection.new(@_source.content_type)
          else
            nil
          end
        end

        def editable_elements
          @editable_elements_hash ||= build_editable_elements_hash
        end

        def before_method(meth)
          # @deprecated
          @_source.editable_elements.where(slug: meth).try(:first).try(:content)
        end

        private

        def build_editable_elements_hash
            {}.tap do |hash|
              @_source.editable_elements.each do |el|
                safe_slug = el.slug.parameterize.underscore
                keys      = el.block.try(:split, '/').try(:compact) || []

                _hash = _build_editable_elements_hashes(hash, keys)

                _hash[safe_slug] = el.content
              end
            end
          end

          def _build_editable_elements_hashes(hash, keys)
            _hash = hash

            keys.each do |key|
              safe_key = key.parameterize.underscore

              _hash[safe_key] = {} if _hash[safe_key].nil?

              _hash = _hash[safe_key]
            end

            _hash
          end

      end
    end
  end
end


text:
using System.Collections.Generic;
using ContentPatcher.Framework.Conditions;
using ContentPatcher.Framework.Tokens;
using Pathoschild.Stardew.Common.Utilities;

namespace ContentPatcher.Framework
{
    /// A context which provides temporary tokens specific to the current patch or field.
    internal class LocalContext : IContext
    {
        /*********
        ** Fields
        *********/
        /// The mod namespace in which the token is accessible.
        private readonly string Scope;

        /// The parent context that provides non-patch-specific tokens.
        private IContext? LastParentContext;

        /// The local token values.
        private readonly InvariantDictionary<ManagedManualToken> LocalTokens = new();

        /*********
        ** Accessors
        *********/
        /// <inheritdoc />
        public int UpdateTick => this.LastParentContext?.UpdateTick ?? 0;

        /*********
        ** Public methods
        *********/
        /// Construct an instance.
        /// <param name="scope">The mod namespace in which the token is accessible.</param>
        /// <param name="parentContext">The initial parent context that provides non-patch-specific tokens, if any.</param>
        public LocalContext(string scope, IContext? parentContext = null)
        {
            this.Scope = scope;
            this.LastParentContext = parentContext;
        }

        /****
        ** IContext
        ****/
        /// Update the patch context.
        /// <param name="parentContext">The parent context that provides non-patch-specific tokens.</param>
        public void Update(IContext parentContext)
        {
            this.LastParentContext = parentContext;

            foreach (ManagedManualToken managed in this.LocalTokens.Values)
                managed.ValueProvider.SetReady(false);
        }

        /// <inheritdoc />
        public bool IsModInstalled(string id)
        {
            return this.LastParentContext?.IsModInstalled(id) ?? false;
        }

        /// <inheritdoc />
        public bool Contains(string name, bool enforceContext)
        {
            return this.GetToken(name, enforceContext) != null;
        }

        /// <inheritdoc />
        public IToken? GetToken(string name, bool enforceContext)
        {
            return this.LocalTokens.TryGetValue(name, out ManagedManualToken? managed)
                ? managed.Token
                : this.LastParentContext?.GetToken(name, enforceContext);
        }

        /// <inheritdoc />
        public IEnumerable<IToken> GetTokens(bool enforceContext)
        {
            foreach (ManagedManualToken managed in this.LocalTokens.Values)
                yield return managed.Token;

            if (this.LastParentContext != null)
            {
                foreach (IToken token in this.LastParentContext.GetTokens(enforceContext))
                    yield return token;
            }
        }

        /// <inheritdoc />
        public IInvariantSet GetValues(string name, IInputArguments input, bool enforceContext)
        {
            IToken? token = this.GetToken(name, enforceContext);
            return token?.GetValues(input) ?? InvariantSets.Empty;
        }

        /// Set a local token value.
        /// <param name="name">The token name.</param>
        /// <param name="value">The token value.</param>
        /// <param name="ready">Whether to mark the token ready.</param>
        public void SetLocalValue(string name, string? value, bool ready = true)
        {
            ITokenString str = new LiteralString(value, new LogPathBuilder(nameof(LocalContext), this.Scope, name));
            this.SetLocalValue(name, str, ready);
        }

        /// Set a local token value.
        /// <param name="name">The token name.</param>
        /// <param name="value">The token value.</param>
        /// <param name="ready">Whether to mark the token ready.</param>
        public void SetLocalValue(string name, ITokenString value, bool ready = true)
        {
            // get or create token
            ManagedManualToken? managed;
            {
                if (!this.LocalTokens.TryGetValue(name, out managed))
                    this.LocalTokens[name] = managed = new ManagedManualToken(name, isBounded: false, this.Scope);
            }

            // update values
            managed.ValueProvider.SetValue(value);
            managed.ValueProvider.SetReady(ready);
        }
    }
}


text:
<!doctype html>
<html>

<head>
    <title>Bar Chart Zoom</title>
    <script src="../node_modules/chart.js/dist/Chart.bundle.js"></script>
    <script src="../node_modules/hammerjs/hammer.min.js"></script>
    <script src="../Chart.Zoom.js"></script>
    <style>
    canvas {
        -moz-user-select: none;
        -webkit-user-select: none;
        -ms-user-select: none;
    }
    </style>
</head>

<body>
    <div id="container" style="width: 75%;">
        <canvas id="canvas"></canvas>
    </div>
    <script>
        var MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

        var randomScalingFactor = function() {
            return (Math.random() > 0.5 ? 1.0 : -1.0) * Math.round(Math.random() * 100);
        };
        var randomColorFactor = function() {
            return Math.round(Math.random() * 255);
        };
        var randomColor = function() {
            return 'rgba(' + randomColorFactor() + ',' + randomColorFactor() + ',' + randomColorFactor() + ',.7)';
        };

        var barChartData = {
            labels: ["January", "February", "March", "April", "May", "June", "July"],
            datasets: [{
                label: 'Dataset 1',
                backgroundColor: "rgba(220,220,220,0.5)",
                data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
            }, {
                hidden: true,
                label: 'Dataset 2',
                backgroundColor: "rgba(151,187,205,0.5)",
                data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
            }, {
                label: 'Dataset 3',
                backgroundColor: "rgba(151,187,205,0.5)",
                data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
            }]

        };

        window.onload = function() {
            var ctx = document.getElementById("canvas").getContext("2d");
            window.myBar = new Chart(ctx, {
                type: 'bar',
                data: barChartData,
                options: {
                    // Elements options apply to all of the options unless overridden in a dataset
                    // In this case, we are setting the border of each bar to be 2px wide and green
                    elements: {
                        rectangle: {
                            borderWidth: 2,
                            borderColor: 'rgb(0, 255, 0)',
                            borderSkipped: 'bottom'
                        }
                    },
                    responsive: true,
                    legend: {
                        position: 'top',
                    },
                    title: {
                        display: true,
                        text: 'Chart.js Bar Chart'
                    },
                    pan: {
                        enabled: true,
                        mode: 'y'
                    },
                    zoom: {
                        enabled: true,
                        mode: 'y',
                        limits: {
                            max: 10,
                            min: 0.5
                        }
                    },
                    scales: {
                        xAxes: [{
                            ticks: {
                                min: 'February',
                                max: 'June'
                            }
                        }]
                    }
                }
            });

        };
    </script>
</body>

</html>


text:
copyright:
  years: 2015, 2017
lastupdated: "2017-03-30"

---

{:new_window: target="_blank"}
{:codeblock: .codeblock}

# Dernières mises à jour apportées au pack de construction ASP.NET Core
{: #latest_updates}

Liste des dernières mises à jour apportées au pack de construction aspnet.

## 29 mars 2017 : pack de construction ASP.NET Core v1.0.13-20170330-1023 mis à jour

* Ajout de la prise en charge de .NET Core runtime 1.0.4
* Ajout de la prise en charge de .NET Core runtime 1.1.1
* Ajout de la prise en charge de .NET SDK 1.0.1
* Mise à jour de Node à la version 6.10.0
* Retrait du support de .NET Core SDK 1.0.0-preview2-003131
* Retrait du support de .NET Core SDK 1.0.0-preview3-004056

## 31 janvier 2017 : pack de construction ASP.NET Core v1.0.10-20170124-1145 mis à jour

* Ajout de la prise en charge de .NET Core 1.0.3
* Ajout de la prise en charge de l'outillage .NET Core MSBuild
* Ajout de la prise en charge des projets F#
* Retrait du support de .NET Core SDK 1.0.0-preview2-003121

## 9 décembre 2016 : pack de construction ASP.NET Core v1.0.6-20161205-0912 mis à jour

* Ajout de la prise en charge de .NET Core 1.1.0
* Retrait du support de .NET Core 1.0.0 RC2
* Ajout d'une option d'effacement du cache de packages NuGet

## 10 octobre 2016 : Pack de construction ASP.NET Core v1.0.1-20161005-1225 mis à jour

* Ajout de la prise en charge de .NET Core 1.0.1
* Correction d'un problème intermittent à l'origine de l'échec du déploiement lors de la mise en cache de packages NuGet

## 31 août 2016 : Pack de construction ASP.NET Core v1.0-20160826-1345 mis à jour

* Ajout d'une prise en charge pour l'exécution de scripts de pré-compilation ou de post-compilation via NPM et Bower afin d'installer des bibliothèques css et javascript frontales.
* Changement du statut du pack de construction (de Bêta à GA)

## 11 juillet 2016 : Pack de construction ASP.NET Core v0.9-20160706-1603 mis à jour

Cette version du pack de construction inclut les modifications suivantes :

* Cette version du pack de construction prend en charge .NET CLI 1.0 Preview 2 et .NET Core 1.0 RTM
* Le pack de construction continue de prendre en charge .NET CLI 1.0 Preview 1 et .NET Core 1.0 RC2
* La version .NET CLI par défaut à installer est désormais 1.0.0-preview2-003121

## 10 juin 2016 : Pack de construction ASP.NET Core v0.8.1-20160526-0957 mis à jour

Cette version du pack de construction inclut les modifications suivantes :

* Le nom de l'environnement d'exécution, ASP.NET 5, est devenu ASP.NET Core.
* Le numéro de version du pack de construction est inclus dans le script de sortie de détection.
* Cette version du pack de construction retire la prise en charge des applications basées sur DNX à l'aide de CoreCLR RC1 et version antérieure.
* Cette version du pack de construction prend en charge .NET CLI et .NET Core RC2.
* Le pack de construction détecte des projets avec un fichier project.json ou des fichiers *.runtimeconfig.json issus de la sortie de publication.

## 22 octobre 2105 : Pack de construction ASP.NET 5 v0.7-20151022-1257 mis à jour

* Cette version du pack de construction retire Mono et prend en charge la version bêta 8 de CoreCLR à la place.

## 18 septembre 2105 : Pack de construction ASP.NET 5 v0.6-20150916-1220 mis à jour

* Cette version du pack de construction prend en charge les modifications de l'environnement DNX 7 bêta. De plus, elle peut exécuter des applications
qui dépendent d'éditions bêta plus anciennes avec la commande de démarrage personnalisée suivante :

```
   dnx src/dotnetstarter kestrel --server.urls http://${VCAP_APP_HOST}:${PORT}
```
{: codeblock}

* L'utilisation du serveur Web Nowin a été retirée de ce pack de construction et le serveur Web [Kestrel]{https://github.com/aspnet/KestrelHttpServer} est utilisé à la place.

# rellinks
{: #rellinks notoc}
## general
{: #general notoc}
* [Environnement d'exécution Dotnet Core](index.html)


text:
package com.pme.exe.res.vi;

/**
 * @author yole
 */
public interface VersionInfoFactory {
  VersionInfoBin createChild(int index);
}


text:
package main;

import java.util.*;
import java.util.concurrent.*;

public class Tree {
    private TreeNode root;
    private int min_sample_split;
    private double min_child_weight;
    private int max_depth;
    private double colsample;
    private double rowsample;
    private double lambda;
    private double gamma;
    private int num_thread;
    private ArrayList<Integer> cat_features_cols;
    private Queue<TreeNode> alive_nodes = new LinkedList<>();
    //number of tree node of this tree
    public int nodes_cnt = 0;
    //number of nan tree node of this tree
    public int nan_nodes_cnt = 0;

    public Tree(TreeNode root){
        this.root = root;
        this.num_thread = Runtime.getRuntime().availableProcessors();
    }

    public Tree(int min_sample_split,
                double min_child_weight,
                int max_depth,
                double colsample,
                double rowsample,
                double lambda,
                double gamma,
                int num_thread,
                ArrayList<Integer> cat_features_cols){
        this.min_sample_split = min_sample_split;
        this.min_child_weight = min_child_weight;
        this.max_depth = max_depth;
        this.colsample = colsample;
        this.rowsample = rowsample;
        this.lambda = lambda;
        this.gamma = gamma;
        this.cat_features_cols = cat_features_cols;

        if(num_thread==-1){
            this.num_thread = Runtime.getRuntime().availableProcessors();
        }else {
            this.num_thread = num_thread;
        }
        //to avoid divide zero
        this.lambda = Math.max(this.lambda, 0.00001);
    }

    private double calculate_leaf_score(double G,double H){
        //According to xgboost, the leaf score is : - G / (H+lambda)
        return -G/(H+this.lambda);
    }

    private double[] calculate_split_gain(double G_left,double H_left,double G_nan,double H_nan,double G_total,double H_total){
        //According to xgboost, the scoring function is:
        //     gain = 0.5 * (GL^2/(HL+lambda) + GR^2/(HR+lambda) - (GL+GR)^2/(HL+HR+lambda)) - gamma
        //this gain is the loss reduction, We want it to be as large as possible.
        double G_right = G_total - G_left - G_nan;
        double H_right = H_total - H_left - H_nan;

        //if we let those with missing value go to a nan child
        double gain_1 = 0.5 * (
                Math.pow(G_left,2)/(H_left+lambda)
                        + Math.pow(G_right,2)/(H_right+lambda)
                        + Math.pow(G_nan,2)/(H_nan+lambda)
                        - Math.pow(G_total,2)/(H_total+lambda))-gamma;

        //uncomment this line, then we use xgboost's method to deal with missing value
        //gain_1 = -Double.MAX_VALUE;

        //if we let those with missing value go to left child
        double gain_2 = 0.5 * (
                Math.pow(G_left+G_nan,2)/(H_left+H_nan+lambda)
                        + Math.pow(G_right,2)/(H_right+lambda)
                        - Math.pow(G_total,2)/(H_total+lambda))-gamma;

        //if we let those with missing value go to right child
        double gain_3 = 0.5 * (
                Math.pow(G_left,2)/(H_left+lambda)
                        + Math.pow(G_right+G_nan,2)/(H_right+H_nan+lambda)
                        - Math.pow(G_total,2)/(H_total+lambda))-gamma;

        double nan_go_to;
        double gain = Math.max(gain_1,Math.max(gain_2,gain_3));
        if(gain_1==gain){
            nan_go_to = 0; //nan child
        }else if(gain_2==gain){
            nan_go_to = 1; //left child
        }else{
            nan_go_to = 2; //right child
        }

        //in this case, the trainset does not contains nan samples
        if(H_nan==0 && G_nan==0){
            nan_go_to = 3;
        }

        return new double[]{nan_go_to,gain};
    }

    public void fit(AttributeList attribute_list,
                    ClassList class_list,
                    RowSampler row_sampler,
                    ColumnSampler col_sampler){
        //when we start to fit a tree, we first conduct row and column sampling
        col_sampler.shuffle();
        row_sampler.shuffle();
        class_list.sampling(row_sampler.row_mask);

        //then we create the root node, initialize histogram(Gradient sum and Hessian sum)
        TreeNode root_node = new TreeNode(1,1,attribute_list.feature_dim,false);
        root_node.Grad_setter(sum(class_list.grad));
        root_node.Hess_setter(sum(class_list.hess));
        this.root = root_node;

        //put it into the alive_node, and fill the class_list, all data are assigned to root node initially
        alive_nodes.offer(root_node);

        for(int i=0;i<class_list.dataset_size;i++){
            class_list.corresponding_tree_node[i] = root_node;
        }

        //update Grad_missing Hess_missing for root node
        class_list.update_grad_hess_missing_for_tree_node(attribute_list.missing_value_attribute_list);

        //then build the tree util there is no alive tree_node to split
        build(attribute_list,class_list,col_sampler);
        clean_up();
    }

    class ProcessEachNumericFeature implements Runnable{
        public int col;
        public AttributeList attribute_list;
        public ClassList class_list;
        public ProcessEachNumericFeature(int col,AttributeList attribute_list,ClassList class_list){
            this.col = col;
            this.attribute_list = attribute_list;
            this.class_list = class_list;
        }

        @Override
        public void run(){
            for(int interval=0;interval<attribute_list.cutting_inds[col].length-1;interval++){
                //update the corresponding treenode's G_left,H_left with this inds's sample
                int[] inds = attribute_list.cutting_inds[col][interval];

                HashSet<TreeNode> nodes = new HashSet<>();
                for(int ind:inds){
                    TreeNode treenode = class_list.corresponding_tree_node[ind];
                    if(treenode.is_leaf) continue;

                    nodes.add(treenode);
                    treenode.G_left[col] += class_list.grad[ind];
                    treenode.H_left[col] += class_list.hess[ind];
                }
                //update each treenode's best split using this feature
                for(TreeNode node:nodes){
                    double G_left = node.G_left[col];
                    double H_left = node.H_left[col];
                    double G_total = node.Grad;
                    double H_total = node.Hess;
                    double G_nan = node.Grad_missing[col];
                    double H_nan = node.Hess_missing[col];
                    double[] ret = calculate_split_gain(G_left,H_left,G_nan,H_nan,G_total,H_total);
                    double nan_go_to = ret[0];
                    double gain = ret[1];
                    node.update_best_split(col,attribute_list.cutting_thresholds[col][interval],gain,nan_go_to);
                }
            }

        }
    }

    class ProcessEachCategoricalFeature implements Runnable{
        public int col;
        public AttributeList attribute_list;
        public ClassList class_list;

        public ProcessEachCategoricalFeature(int col,AttributeList attribute_list,ClassList class_list){
            this.col = col;
            this.attribute_list = attribute_list;
            this.class_list = class_list;
        }

        @Override
        public void run(){
            HashSet<TreeNode> nodes = new HashSet<>();
            for(int interval=0;interval<attribute_list.cutting_inds[col].length;interval++){
                //update the corresponding treenode's cat_feature_col_value_GH
                int[] inds = attribute_list.cutting_inds[col][interval];
                int cat_value = (int) attribute_list.cutting_thresholds[col][interval];
                for(int ind:inds){
                    TreeNode treenode = class_list.corresponding_tree_node[ind];
                    if(treenode.is_leaf) continue;

                    if(!nodes.contains(treenode)){
                        nodes.add(treenode);
                        treenode.cat_feature_col_value_GH.put(col,new HashMap<>());
                    }

                    if(treenode.cat_feature_col_value_GH.get(col).containsKey(cat_value)){
                        treenode.cat_feature_col_value_GH.get(col).get(cat_value)[0] += class_list.grad[ind];
                        treenode.cat_feature_col_value_GH.get(col).get(cat_value)[1] += class_list.hess[ind];
                    }else {
                        treenode.cat_feature_col_value_GH
                                .get(col).put(cat_value,new double[]{class_list.grad[ind],class_list.hess[ind]});
                    }
                }
            }

            for(TreeNode node:nodes){
                double[][] catvalue_GdivH = new double[node.cat_feature_col_value_GH.get(col).size()][4];
                int i=0;
                for(int catvalue:node.cat_feature_col_value_GH.get(col).keySet()){
                    catvalue_GdivH[i][0] = catvalue;
                    catvalue_GdivH[i][1] = node.cat_feature_col_value_GH.get(col).get(catvalue)[0];
                    catvalue_GdivH[i][2] = node.cat_feature_col_value_GH.get(col).get(catvalue)[1];
                    catvalue_GdivH[i][3] = catvalue_GdivH[i][1] / catvalue_GdivH[i][2];
                    i++;
                }
                Arrays.sort(catvalue_GdivH, new Comparator<double[]>() {
                    @Override
                    public int compare(double[] a, double[] b) {
                        return Double.compare(a[3],b[3]);
                    }
                });

                double G_total = node.Grad;
                double H_total = node.Hess;
                double G_nan = node.Grad_missing[col];
                double H_nan = node.Hess_missing[col];
                double G_left = 0;
                double H_left = 0;
                int best_split = -1;
                double best_gain = -Double.MAX_VALUE;
                double best_nan_go_to = -1;
                for(i=0;i<catvalue_GdivH.length;i++){
                    G_left += catvalue_GdivH[i][1];
                    H_left += catvalue_GdivH[i][2];
                    double[] ret = calculate_split_gain(G_left,H_left,G_nan,H_nan,G_total,H_total);
                    double nan_go_to = ret[0];
                    double gain = ret[1];
                    if(gain > best_gain){
                        best_gain = gain;
                        best_split = i;
                        best_nan_go_to = nan_go_to;
                    }
                }
                ArrayList<Integer> left_child_catvalue = new ArrayList<>();
                for(i=0;i<=best_split;i++){
                    left_child_catvalue.add((int) catvalue_GdivH[i][0]);
                }
                node.set_categorical_feature_best_split(col,left_child_catvalue,best_gain,best_nan_go_to);
            }

        }

    }

    private void build(AttributeList attribute_list,
                      ClassList class_list,
                      ColumnSampler col_sampler){
        while(!alive_nodes.isEmpty()){
            nodes_cnt += alive_nodes.size();

            //parallelly scan and process each selected attribute list
            ExecutorService pool = Executors.newFixedThreadPool(num_thread);
            for(int col:col_sampler.col_selected){
                if(attribute_list.cat_features_cols.contains(col)){
                    pool.execute(new ProcessEachCategoricalFeature(col,attribute_list,class_list));
                }else{
                    pool.execute(new ProcessEachNumericFeature(col,attribute_list,class_list));
                }
            }

            pool.shutdown();
            try {
                pool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            //once had scan all column, we can get the best (feature,threshold,gain) for each alive tree node
            int cur_level_node_size = alive_nodes.size();
            Queue<TreeNode> new_tree_nodes = new LinkedList<>();

            //time consumption: 0.0x ms
            for(int i=0;i<cur_level_node_size;i++){
                //pop each alive treenode
                TreeNode treenode = alive_nodes.poll();

                //consider categorical feature
                ArrayList<Double> ret = treenode.get_best_feature_threshold_gain();
                double best_feature = ret.get(0);
                double best_gain = ret.get(1);
                double best_nan_go_to = ret.get(2);
                double best_threshold = 0;
                ArrayList<Double> left_child_catvalue = new ArrayList<>();
                if(cat_features_cols.contains((int) best_feature)){
                    for(int j=3;j<ret.size();j++){
                        left_child_catvalue.add(ret.get(j));
                    }
                }else {
                    best_threshold = ret.get(3);
                }

                if(best_gain<=0){
                    //this node is leaf node
                    double leaf_score = calculate_leaf_score(treenode.Grad,treenode.Hess);
                    treenode.leaf_node_setter(leaf_score,true);
                }else {
                    //this node is internal node
                    TreeNode left_child = new TreeNode(3*treenode.index-1,treenode.depth+1,treenode.feature_dim,false);
                    TreeNode right_child = new TreeNode(3*treenode.index+1,treenode.depth+1,treenode.feature_dim,false);
                    TreeNode nan_child = null;
                    if(best_nan_go_to==0){
                        //this case we create the nan child
                        nan_child = new TreeNode(3*treenode.index,treenode.depth+1,treenode.feature_dim,false);
                        nan_nodes_cnt+=1;
                    }
                    //consider categorical feature
                    if(cat_features_cols.contains((int) best_feature)){
                        treenode.internal_node_setter(best_feature,left_child_catvalue,best_nan_go_to,nan_child,left_child,right_child,false);
                    }else {
                        treenode.internal_node_setter(best_feature,best_threshold,best_nan_go_to,nan_child,left_child,right_child,false);
                    }

                    new_tree_nodes.offer(left_child);
                    new_tree_nodes.offer(right_child);
                    if(nan_child != null){
                        new_tree_nodes.offer(nan_child);
                    }
                }
            }

            //update class_list.corresponding_tree_node
            class_list.update_corresponding_tree_node(attribute_list);

            //update (Grad,Hess,num_sample) for each new tree node
            class_list.update_Grad_Hess_numsample_for_tree_node();

            //update Grad_missing, Hess_missing for each new tree node
            //time consumption: 5ms
            class_list.update_grad_hess_missing_for_tree_node(attribute_list.missing_value_attribute_list);

            //process the new tree nodes
            //satisfy max_depth? min_child_weight? min_sample_split?
            //if yes, it is leaf node, calculate its leaf score
            //if no, put into self.alive_node
            while(new_tree_nodes.size()!=0){
                TreeNode treenode = new_tree_nodes.poll();
                if(treenode.depth>=max_depth || treenode.Hess<min_child_weight || treenode.num_sample<=min_sample_split){
                    treenode.leaf_node_setter(calculate_leaf_score(treenode.Grad,treenode.Hess),true);
                }else {
                    alive_nodes.offer(treenode);
                }
            }
        }
    }

    class PredictCallable implements Callable{
        private float[] feature;
        public PredictCallable(float[] feature){
            this.feature = feature;
        }
        @Override
        public Double call(){
            TreeNode cur_tree_node = root;
            while(!cur_tree_node.is_leaf){
                if(feature[cur_tree_node.split_feature]==Data.NULL){
                    //it is missing value
                    if(cur_tree_node.nan_go_to==0){
                        cur_tree_node = cur_tree_node.nan_child;
                    }else if(cur_tree_node.nan_go_to==1){
                        cur_tree_node = cur_tree_node.left_child;
                    }else if(cur_tree_node.nan_go_to==2){
                        cur_tree_node = cur_tree_node.right_child;
                    }else {
                        //trainset has not missing value for this feature,
                        // so we should decide which branch the testset's missing value go to
                        if(cur_tree_node.left_child.num_sample>cur_tree_node.right_child.num_sample){
                            cur_tree_node = cur_tree_node.left_child;
                        }else {
                            cur_tree_node = cur_tree_node.right_child;
                        }
                    }

                }else{
                    //not missing value
                    // consider split_feature categorical or numeric
                    if(cur_tree_node.split_left_child_catvalue!=null){
                        if(cur_tree_node.split_left_child_catvalue.contains((double) feature[cur_tree_node.split_feature])){
                            cur_tree_node = cur_tree_node.left_child;
                        }else {
                            cur_tree_node = cur_tree_node.right_child;
                        }
                    }else {
                        if(feature[cur_tree_node.split_feature]<=cur_tree_node.split_threshold){
                            cur_tree_node = cur_tree_node.left_child;
                        }else {
                            cur_tree_node = cur_tree_node.right_child;
                        }
                    }
                }
            }
            return cur_tree_node.leaf_score;
        }
    }

    public double[] predict(float[][] features){
        ExecutorService pool = Executors.newFixedThreadPool(num_thread);
        List<Future> list = new ArrayList<Future>();
        for(int i=0;i<features.length;i++){
            Callable c = new PredictCallable(features[i]);
            Future f = pool.submit(c);
            list.add(f);
        }

        pool.shutdown();
        try {
            pool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        double[] ret = new double[features.length];
        for(int i=0;i<ret.length;i++){
            try{
                ret[i] = (double) list.get(i).get();
            }catch (InterruptedException e){
                e.printStackTrace();
            }catch (ExecutionException e){
                e.printStackTrace();
            }
        }
        return ret;
    }

    private void clean_up(){
        this.alive_nodes = null;
    }

    private double sum(double[] vals){
        double s = 0;
        for(double v:vals) s+=v;
        return s;
    }

    public TreeNode getRoot() {
        return root;
    }
}


text:
<?php

namespace Admingenerator\DoctrineOrmDemoBundle\Form\Type\Category;

use Admingenerated\AdmingeneratorDoctrineOrmDemoBundle\Form\BaseCategoryType\EditType as BaseEditType;

/**
 * EditType
 */
class EditType extends BaseEditType
{
}


text:
require 'spec_helper'

describe SalesPagesController do
  describe "GET 'show'" do
    describe "for a Club owner with a verified PayPal account" do
      let!(:user)       { FactoryGirl.create :user, :verified => true }
      let!(:club)       { FactoryGirl.create :club, :user => user }
      let!(:sales_page) { club.sales_page }

      before :each do
        get 'show', :club_id => sales_page.club.id
      end

      it "returns http success" do
        response.should be_success
      end

      it "returns the club" do
        assigns(:club).should == sales_page.club
      end

      it "returns the sales_page" do
        assigns(:sales_page).should == sales_page
      end
    end

    describe "for a Club owner with an unverified PayPal account" do
      let!(:user)       { FactoryGirl.create :user, :verified => false }
      let!(:club)       { FactoryGirl.create :club, :user => user }
      let!(:sales_page) { club.sales_page }

      before :each do
        get 'show', :club_id => sales_page.club.id
      end

      it "redirects to the root path" do
        response.should redirect_to(root_path)
      end

      it "returns the club" do
        assigns(:club).should == sales_page.club
      end

      it "returns the sales_page" do
        assigns(:sales_page).should == sales_page
      end

      it "returns a flash error" do
        flash[:error].should_not be_blank
      end
    end
  end

  describe "GET 'edit'" do
    let!(:user)       { FactoryGirl.create :user }
    let!(:sales_page) { user.clubs.first.sales_page }

    before :each do
      @request.env["devise.mapping"] = Devise.mappings[:users]
      sign_in user
    end

    before :each do
      get "edit", :club_id => sales_page.club.id
    end

    it "returns http success" do
      response.should be_success
    end

    it "returns the club" do
      assigns(:club).should == sales_page.club
    end

    it "returns the sales_page" do
      assigns(:sales_page).should == sales_page
    end

    it "renders the mercury layout" do
      response.should render_template(:layout => "layouts/mercury")
    end
  end

  describe "PUT 'update'" do
    let!(:user)        { FactoryGirl.create :user }
    let!(:sales_page)  { user.clubs.first.sales_page }
    let!(:new_heading) { "Test Heading" }

    before :each do
      FakeWeb.clean_registry
      FakeWeb.register_uri(:head, "http://vimeo.com/22977143", :body => "", :status => [ "200", "OK" ])

      @request.env["devise.mapping"] = Devise.mappings[:users]
      sign_in user
    end

    describe "for valid attributes" do
      before :each do
        put 'update', :club_id => sales_page.club.id, :content => { :sales_page_heading        => { :value => new_heading },
                                                                    :sales_page_sub_heading    => { :value => "abc"  },
                                                                    :sales_page_call_to_action => { :value => "123"  },
                                                                    :sales_page_call_details   => { :value => "sgh"  },
                                                                    :sales_page_video_url      => { :value => "http://vimeo.com/22977143" },
                                                                    :sales_page_benefit1       => { :value => "abc"  },
                                                                    :sales_page_benefit2       => { :value => "abc"  },
                                                                    :sales_page_benefit3       => { :value => "abc"  },
                                                                    :sales_page_details        => { :value => "test" },
                                                                    :sales_page_about_owner    => { :value => "123"  } }
      end

      it "returns http success" do
        response.should be_success
      end

      it "returns the club" do
        assigns(:club).should_not be_nil
      end

      it "returns the sales_page" do
        assigns(:sales_page).should == sales_page
      end

      it "assigns the new attributes" do
        sales_page.reload
        sales_page.heading.should == new_heading
      end

      it "renders blank text as a response" do
        response.body.should == ""
      end
    end

    describe "for invalid attributes" do
      before :each do
        @old_heading = sales_page.heading
        put 'update', :club_id => sales_page.club.id, :content => { :sales_page_heading        => { :value => ""     },
                                                                    :sales_page_sub_heading    => { :value => "abc"  },
                                                                    :sales_page_call_to_action => { :value => "123"  },
                                                                    :sales_page_call_details   => { :value => "sgh"  },
                                                                    :sales_page_video_url      => { :value => "http://vimeo.com/22977143" },
                                                                    :sales_page_benefit1       => { :value => "abc"  },
                                                                    :sales_page_benefit2       => { :value => "abc"  },
                                                                    :sales_page_benefit3       => { :value => "abc"  },
                                                                    :sales_page_details        => { :value => "test" },
                                                                    :sales_page_about_owner    => { :value => "123"  } }
      end

      it "returns http unprocessable" do
        response.response_code.should == 422
      end

      it "returns the club" do
        assigns(:club).should_not be_nil
      end

      it "returns the sales_page" do
        assigns(:sales_page).should == sales_page
      end

      it "does not update the attributes" do
        sales_page.reload
        sales_page.heading.should == @old_heading
      end

      it "returns error about invalid sales_page attributes" do
        response.headers["X-Flash-Error"].should == "Heading for sales page can't be blank"
      end

      it "renders error text as a response" do
        response.body.should == "error"
      end
    end
  end
end


text:
using namespace DVGui;
using namespace TSyntax;

//=============================================================================

class ExpressionField::SyntaxHighlighter : public QSyntaxHighlighter
{
	const Grammar *m_grammar;

public:
	bool m_open;
	SyntaxHighlighter(QTextDocument *parent)
		: QSyntaxHighlighter(parent), m_grammar(0), m_open(true)
	{
	}
	~SyntaxHighlighter()
	{
	}

	void setGrammar(const Grammar *grammar) { m_grammar = grammar; }

	void highlightBlock(const QString &text)
	{
		Parser parser(m_grammar);
		std::vector<SyntaxToken> tokens;
		Parser::SyntaxStatus status = parser.checkSyntax(tokens, text.toStdString());

		int nextPos = 0;
		for (int i = 0; i < (int)tokens.size(); i++) {
			QTextCharFormat fmt;
			int pos = tokens[i].m_pos;
			int length = tokens[i].m_length;
			int type = tokens[i].m_type;
			nextPos = pos + length;
			switch (type) {
			case TSyntax::Unknown:
				fmt.setForeground(Qt::black);
				break;
			case TSyntax::Number:
				fmt.setForeground(QColor(0x50, 0x7d, 0x0));
				break; // number
			case TSyntax::Constant:
				fmt.setForeground(QColor(0x50, 0x7d, 0x0));
				break; // constant
			case TSyntax::Variable:
				fmt.setForeground(QColor(0x0, 0x88, 0xc8));
				break; // var
			case TSyntax::Operator:
				fmt.setForeground(QColor(50, 0, 255));
				break; // infix
			case TSyntax::Parenthesis:
				fmt.setForeground(QColor(50, 50, 255));
				break; // braket
			case TSyntax::Function:
				fmt.setForeground(QColor(0x0, 0x50, 0x7d));
				break; // fname
			case TSyntax::Comma:
				fmt.setForeground(QColor(50, 20, 255));
				break; // f ;

			case TSyntax::UnexpectedToken:
				fmt.setForeground(QColor(0xdc, 0x0, 0x0));
				break; // expression not found
			case TSyntax::Eos:
				fmt.setForeground(QColor(255, 127, 0));
				break; //  EOS
			case TSyntax::Mismatch:
				fmt.setForeground(QColor(255, 0, 0));
				break; // token mismatch

			default:
				fmt.setForeground(QColor(127, 127, 255));
				break;
			}
			if (type == 4)
				fmt.setToolTip("Infix");
			if (length == 0)
				length = 1;
			setFormat(pos, length, fmt);
		}
	}
};

//=============================================================================

class MyListView : public QListView
{
	QLabel *m_tooltip;

public:
	MyListView() : QListView()
	{
		setObjectName("SuggestionPopup");
		setStyleSheet("#SuggestionPopup {background-color:#FFFFFF; border:1px solid black;}");
		setWindowFlags(Qt::Popup);
		setMouseTracking(true);
		m_tooltip = new QLabel(0, Qt::ToolTip);
		//Stesso stile del popuop che lo contiene.
		m_tooltip->hide();

		m_tooltip->setObjectName("helpTooltip");
		m_tooltip->setAlignment(Qt::AlignLeft);
		m_tooltip->setIndent(1);
		m_tooltip->setWordWrap(false);
	}
	void showEvent(QShowEvent *)
	{
		showToolTip(currentIndex());
	}
	void hideEvent(QHideEvent *)
	{
		m_tooltip->hide();
	}
	void currentChanged(const QModelIndex &current, const QModelIndex &previous)
	{
		showToolTip(current);
		QListView::currentChanged(current, previous);
	}
	void showToolTip(const QModelIndex &index)
	{
		if (!index.isValid()) {
			m_tooltip->hide();
			return;
		}
		QVariant data = model()->data(index, Qt::ToolTipRole);
		if (!data.isValid()) {
			m_tooltip->hide();
			return;
		}
		QRect rect = visualRect(index);
		m_tooltip->setText(data.toString());
		QPoint pos = viewport()->mapToGlobal(QPoint(-m_tooltip->sizeHint().width(), rect.top()));
		m_tooltip->setGeometry(QRect(pos, m_tooltip->sizeHint()));
		m_tooltip->show();
	}

protected:
	void resizeEvent(QResizeEvent *e)
	{
		QListView::resizeEvent(e);
		if (m_tooltip->isVisible())
			showToolTip(currentIndex());
	}
};

//=============================================================================

ExpressionField::ExpressionField(QWidget *parent)
	: QTextEdit(parent), m_editing(false), m_grammar(0), m_syntaxHighlighter(0), m_completerPopup(0), m_completerStartPos(0)
{
	setFrameStyle(QFrame::StyledPanel);
	setObjectName("ExpressionField");
	setLineWrapMode(NoWrap);
	setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
	setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
	setTabChangesFocus(true);
	// setSizePolicy(QSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed));
	connect(this, SIGNAL(textChanged()), this, SLOT(onTextChanged()));

#ifdef MACOSX
	setFixedHeight(23);
#else
	setFixedHeight(20); // +40);
#endif

	m_completerPopup = new MyListView();
	QStandardItemModel *model = new QStandardItemModel();
	m_completerPopup->setModel(model);
	m_completerPopup->setFocusPolicy(Qt::NoFocus);
	m_completerPopup->setFocusProxy(this);
	m_completerPopup->installEventFilter(this);
	connect(
		m_completerPopup, SIGNAL(clicked(const QModelIndex &)),
		this, SLOT(insertCompletion(const QModelIndex &)));

	m_syntaxHighlighter = new SyntaxHighlighter(document());
}

ExpressionField::~ExpressionField()
{
	delete m_syntaxHighlighter;
}

void ExpressionField::showEvent(QShowEvent *e)
{
	QTextEdit::showEvent(e);
}

void ExpressionField::hideEvent(QHideEvent *e)
{
	QTextEdit::hideEvent(e);
}

void ExpressionField::setExpression(std::string expression)
{
	setPlainText(QString::fromStdString(expression));
}

std::string ExpressionField::getExpression() const
{
	return toPlainText().toStdString();
}

bool ExpressionField::event(QEvent *e)
{
	if (e->type() == QEvent::ToolTip) {
		QHelpEvent *helpEvent = static_cast<QHelpEvent *>(e);
		// openCompletionPopup();

	} else if (e->type() == QEvent::ShortcutOverride) {
		e->accept();
		return true;
	}
	//else
	return QTextEdit::event(e);
}

void ExpressionField::keyPressEvent(QKeyEvent *e)
{

	// setStyleSheet("background-color: cyan");
	if (e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter) {
		m_editing = false;
		emit expressionChanged();
	} else if (e->key() == Qt::Key_F10) {
		setAutoFillBackground(true);
		QPalette p = palette();
		p.setColor(QPalette::Base, Qt::cyan);
		p.setColor(QPalette::Background, Qt::cyan);
		setPalette(p);
		update();
		setStyleSheet("#ExpressionField {background-color:cyan;}");
	} else if (e->key() == Qt::Key_F11) {
		m_completerPopup->installEventFilter(this);
		QRect cr = cursorRect();
		QSize size(100, 200);
		QPoint pos = mapToGlobal(QPoint(cr.left(), cr.top() - size.height()));
		m_completerPopup->setGeometry(QRect(pos, size));
		m_completerPopup->show();
		QTextEdit::keyPressEvent(e);
	} else {
		QTextEdit::keyPressEvent(e);
		if (m_completerPopup->isVisible()) {
			updateCompleterPopup();
		} else if (Qt::Key_A <= e->key() && e->key() <= Qt::Key_Z || std::string("+&|!*/=?,:-").find(e->key()) != std::string::npos) {
			openCompleterPopup();
		}
		setFocus();
	}
}

bool ExpressionField::eventFilter(QObject *obj, QEvent *e)
{
	if (e->type() == QEvent::KeyPress) {
		QKeyEvent *keyEvent = static_cast<QKeyEvent *>(e);
		switch (keyEvent->key()) {
		case Qt::Key_Return:
		case Qt::Key_Enter:
			insertCompletion(m_completerPopup->currentIndex());
			return true;

		case Qt::Key_Left:
		case Qt::Key_Right:
			event(keyEvent);
			m_completerPopup->hide();
			return true;

		case Qt::Key_Escape:
			m_completerPopup->hide();
			return true;

		case Qt::Key_Down:
		case Qt::Key_Up:
			return false;

		default:
			event(e);
			return true;
		}
	} else if (e->type() == QEvent::MouseButtonPress) {
		m_completerPopup->hide();
		event(e);
		return true;
	} else if (e->type() == QEvent::ShortcutOverride) {
		e->accept();
		return true;
	}
	return QObject::eventFilter(obj, e);
}

void ExpressionField::onTextChanged()
{

	if (!m_editing) {
		m_editing = true;

		// setStyleSheet("background: rgb(250,200,200)");
	}
}

void ExpressionField::focusInEvent(QFocusEvent *e)
{
	m_syntaxHighlighter->m_open = true;
	m_syntaxHighlighter->rehighlight();
	QTextEdit::focusInEvent(e);
}

void ExpressionField::focusOutEvent(QFocusEvent *e)
{
	m_syntaxHighlighter->m_open = false;
	m_syntaxHighlighter->rehighlight();
	QTextEdit::focusOutEvent(e);
}

void ExpressionField::onCursorPositionChanged()
{
}

void ExpressionField::openCompleterPopup()
{
	int n = computeSuggestions();
	if (n < 2)
		return;
	if (updateCompleterPopup())
		m_completerPopup->show();
}

bool ExpressionField::updateCompleterPopup()
{
	int start = m_completerStartPos;
	int pos = textCursor().position();
	std::string text = getExpression();
	if (m_suggestions.empty() || start < 0 || start > pos || pos > (int)text.length()) {
		if (m_completerPopup->isVisible())
			m_completerPopup->hide();
		return false;
	}

	QStandardItemModel *model = new QStandardItemModel();
	std::string prefix = toLower(text.substr(start, pos - start));
	int prefixLength = prefix.length();
	int count = 0;
	for (int i = 0; i < (int)m_suggestions.size(); i++) {
		std::string item = m_suggestions[i].first;
		if ((int)item.length() >= prefixLength && toLower(item.substr(0, prefixLength)) == prefix) {
			QStandardItem *item = new QStandardItem();
			item->setData(QString::fromStdString(m_suggestions[i].first), Qt::EditRole);
			if (m_suggestions[i].second != "")
				item->setData(QString::fromStdString(m_suggestions[i].second), Qt::ToolTipRole);
			model->appendRow(item);
			count++;
		}
	}
	if (count == 0) {
		if (m_completerPopup->isVisible())
			m_completerPopup->hide();
		return false;
	}
	m_completerPopup->setModel(model);
	m_completerPopup->setCurrentIndex(model->index(0, 0));

	QTextCursor cursor(textCursor());
	cursor.setPosition(m_completerStartPos);
	QRect cr = cursorRect(cursor);

	int w = m_completerPopup->sizeHintForColumn(0) + m_completerPopup->verticalScrollBar()->sizeHint().width() + 5;
	int h = (m_completerPopup->sizeHintForRow(0) * qMin(7, model->rowCount()) + 3) + 3;

	QSize size(w, h);
	QPoint popupPos = mapToGlobal(QPoint(cr.left(), cr.bottom() + 3));
	m_completerPopup->setGeometry(QRect(popupPos, size));
	return true;
}

int ExpressionField::computeSuggestions()
{
	m_completerStartPos = -1;
	m_suggestions.clear();

	std::string text = getExpression();
	int pos = textCursor().position();
	int start = pos;
	if (start > 0) {
		start--;
		while (start > 0) {
			char c = text[start - 1];
			if (isascii(c) && isalpha(c) || c == '_' || c == '.' && (start - 2 < 0 || isascii(text[start - 2]) && isalpha(text[start - 2]))) {
			} else
				break;
			start--;
		}
	}
	if (start >= (int)text.length())
		return 0;
	m_completerStartPos = start;
	text = text.substr(0, start);
	TSyntax::Parser parser(m_grammar);
	parser.getSuggestions(m_suggestions, text);
	return (int)m_suggestions.size();
}

void ExpressionField::insertCompletion()
{
	if (!m_completerPopup->isVisible())
		return;
	QModelIndex index = m_completerPopup->currentIndex();
	if (!index.isValid())
		return;
	QString item = m_completerPopup->model()->data(index, Qt::EditRole).toString();
	QTextCursor tc = textCursor();
	int pos = tc.position();
	// tc.movePosition(m_completionStartPos, QTextCursor::KeepAnchor);
	tc.insertText(item);
	m_completerPopup->hide();
}

void ExpressionField::insertCompletion(const QModelIndex &index)
{
	if (index.isValid()) {
		QString item = m_completerPopup->model()->data(index, Qt::EditRole).toString();

		QTextCursor tc = textCursor();
		int pos = tc.position();
		if (pos - m_completerStartPos >= 1)
			tc.movePosition(QTextCursor::Left, QTextCursor::KeepAnchor, pos - m_completerStartPos);
		tc.insertText(item);
	}
	m_completerPopup->hide();
}

void ExpressionField::setGrammar(const Grammar *grammar)
{
	m_grammar = grammar;
	m_syntaxHighlighter->setGrammar(grammar);
};


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
angular.module('myApp.directive').directive('headerView', ['appConfig', function(appConfig){
    return {
        restrict: 'A',
        templateUrl: 'build/html/header-view.html',
        controller: 'HeaderViewController'
    };
}])
        .controller('HeaderViewController',['$scope', function($scope){

        }]);